Files
faunosteo/apps/app/e2e/ui/canvas-clicks.spec.ts
T
bchanot 9c606aa567 fix(anatomy): V1-2.2 the visible wins on the editor canvas
Owner decision 2026-11-01. The canvas paints and hits every point hitbox,
then every zone and trigger, then every visible twin, which captures on
what it paints; a junction's disc is no longer taken by the zone drawn
after it. The PDF view keeps the document order and its bytes. Click
spec: the five fixme run unmarked, six projects incl. a 320 px phone.
2026-11-01 00:56:11 +01:00

340 lines
12 KiB
TypeScript

import { expect, test } from '../support/browser'
import type { Page } from '@playwright/test'
// V1-2.2 owner brief 2026-10-30, defect 2: a click on the editor canvas records the marker
// under the pointer, never another one, whatever stroke the drawing's root sets. Real
// clicks (taps on the phone project) on the bundled equine sheet in AnatomyCanvas
// (e2e/harness/canvas.tsx); run on Chromium, Firefox and WebKit when installed.
/** The points of the equine main view, in document order. */
const POINTS = [
'hind-fetlock',
'hock',
'stifle',
'hip',
'sacroiliac',
'shoulder',
'elbow',
'carpus',
'fore-fetlock',
'fore-sesamoids',
]
/**
* The vertebral junctions sit on the edge of a zone. Until the canvas painted its markers in
* three passes (« the visible wins », owner decision 2026-11-01) the zone, drawn after them,
* took up to half of their disc.
*/
const JUNCTIONS = ['l6-s1', 't18-l1', 'c7-t1']
const DRAWINGS = ['plain', 'giant-stroke', 'invisible-stroke', 'hidden-stroke']
type Point = { x: number; y: number }
async function open(page: Page, drawing: string) {
await page.goto(`/e2e/harness/canvas.html?drawing=${drawing}`)
await expect(
page
.locator('[data-testid="anatomy-canvas"] [data-anno-id="hock"]')
.first(),
).toBeAttached()
}
/** The centre of a marker's visible shape on screen (a point's twin shares its hitbox's). */
async function centreOf(page: Page, id: string): Promise<Point> {
const box = await page
.locator(`[data-testid="anatomy-canvas"] [data-anno-id="${id}"]`)
.last()
.boundingBox()
if (!box) throw new Error(`${id} has no box`)
return { x: box.x + box.width / 2, y: box.y + box.height / 2 }
}
async function press(page: Page, at: Point, touch: boolean) {
if (touch) await page.touchscreen.tap(at.x, at.y)
else await page.mouse.click(at.x, at.y)
}
/** The ids recorded by the clicks so far. */
async function recorded(page: Page): Promise<string[]> {
const text = (await page.getByTestId('clicks').textContent()) ?? ''
return text.split(' ').filter(Boolean)
}
async function clickRecords(page: Page, at: Point, touch = false) {
const before = (await recorded(page)).length
await press(page, at, touch)
// A click that records nothing leaves the list as it was; wait out the handler.
await page.waitForTimeout(50)
return (await recorded(page)).slice(before)
}
test.describe('canvas clicks', () => {
for (const drawing of DRAWINGS) {
test(`a click on the hock records the hock (${drawing})`, async ({
page,
}, info) => {
await open(page, drawing)
const touch = info.project.use.hasTouch === true
expect(
await clickRecords(page, await centreOf(page, 'hock'), touch),
).toEqual(['hock'])
})
test(`every point clear of the zones records itself (${drawing})`, async ({
page,
}) => {
await open(page, drawing)
for (const id of POINTS) {
expect(await clickRecords(page, await centreOf(page, id)), id).toEqual([
id,
])
}
})
test(`a click on the drawing away from the markers records nothing (${drawing})`, async ({
page,
}) => {
await open(page, drawing)
const box = await page.getByTestId('anatomy-canvas').boundingBox()
if (!box) throw new Error('no canvas')
// The top left corner and the middle of the belly hold no marker.
for (const [fx, fy] of [
[0.03, 0.05],
[0.5, 0.55],
] as const) {
const at = { x: box.x + box.width * fx, y: box.y + box.height * fy }
expect(await clickRecords(page, at), `${fx},${fy}`).toEqual([])
}
})
}
test('two close points each record themselves, the gap between their discs goes to the later hitbox', async ({
page,
}) => {
await open(page, 'giant-stroke')
const fetlock = await centreOf(page, 'fore-fetlock')
const sesamoids = await centreOf(page, 'fore-sesamoids')
expect(await clickRecords(page, fetlock)).toEqual(['fore-fetlock'])
expect(await clickRecords(page, sesamoids)).toEqual(['fore-sesamoids'])
// On the perpendicular bisector, halfway between the visible discs' edge and the
// hitboxes' edge: outside both discs, inside both hitboxes, the later hitbox on top.
const twin = await page
.locator('[data-anno-id="fore-fetlock"]')
.last()
.boundingBox()
const hitbox = await page
.locator('[data-anno-id="fore-fetlock"]')
.first()
.boundingBox()
if (!twin || !hitbox) throw new Error('fore-fetlock has no box')
const [disc, ring] = [twin.width / 2, hitbox.width / 2]
const span = { x: sesamoids.x - fetlock.x, y: sesamoids.y - fetlock.y }
const half = Math.hypot(span.x, span.y) / 2
const reach = Math.sqrt(((disc + ring) / 2) ** 2 - half ** 2)
const at = {
x: (fetlock.x + sesamoids.x) / 2 - (span.y / (2 * half)) * reach,
y: (fetlock.y + sesamoids.y) / 2 + (span.x / (2 * half)) * reach,
}
// WebKit snaps a real press to whole pixels: below 1.5 px of margin on each side the
// browser's own hit test answers, at the exact point. One id, never two.
if ((ring - disc) / 2 >= 1.5) {
expect(await clickRecords(page, at)).toEqual(['fore-sesamoids'])
} else {
const hit = await page.evaluate(
({ x, y }) =>
document
.elementFromPoint(x, y)
?.closest('[data-anno-id]')
?.getAttribute('data-anno-id'),
at,
)
expect(hit).toBe('fore-sesamoids')
}
})
test('a click on a vertebral junction records the junction', async ({
page,
}, info) => {
await open(page, 'plain')
const touch = info.project.use.hasTouch === true
for (const id of [...JUNCTIONS, 'fore-fetlock']) {
const centre = await centreOf(page, id)
expect(await clickRecords(page, centre, touch), id).toEqual([id])
// Four points towards the edge of the visible disc, on the zone side and the other ones.
const box = await page
.locator(`[data-testid="anatomy-canvas"] [data-anno-id="${id}"]`)
.last()
.boundingBox()
if (!box) throw new Error(`${id} has no box`)
// A real press is snapped to whole pixels by WebKit (taps and clicks, measured
// 2026-11-01): 80 % of the radius, at most the radius less 1.5 px.
const radius = box.width / 2
const reach = Math.min(radius * 0.8, radius - 1.5)
for (const [dx, dy] of [
[0, -1],
[1, 0],
[0, 1],
[-1, 0],
] as const) {
const at = { x: centre.x + dx * reach, y: centre.y + dy * reach }
expect(
await clickRecords(page, at, touch),
`${id} ${dx},${dy}`,
).toEqual([id])
}
}
})
test('every visible disc records its point on its whole surface', async ({
page,
}) => {
await open(page, 'plain')
expect(await page.evaluate(sampleDiscs), 'main').toEqual({})
await page.goto('/e2e/harness/canvas.html?view=head')
await expect(
page
.locator('[data-testid="anatomy-canvas"] [data-anno-id="atm"]')
.first(),
).toBeAttached()
expect(await page.evaluate(sampleDiscs), 'head').toEqual({})
})
test('every zone records itself wherever no disc covers it', async ({
page,
}) => {
await open(page, 'plain')
const missed = await page.evaluate(sampleZones)
expect(missed).toEqual({})
})
// @phone: the desktop projects leave it out (grepInvert), the touch projects run it.
test('a tap on the hock records the hock @phone', async ({ page }) => {
for (const drawing of DRAWINGS) {
await open(page, drawing)
expect(
await clickRecords(page, await centreOf(page, 'hock'), true),
drawing,
).toEqual(['hock'])
}
})
})
/**
* In the page: the topmost visible disc decides. Samples every visible twin of the layer
* inside 95 % of its radius (anti-aliasing aside), every 2 units; the expected id is the last
* twin in document order whose disc holds the sample. Answers the twins that missed, with
* their counts.
*/
function sampleDiscs(): Record<string, string> {
const svg = document.querySelector(
'[data-testid="anatomy-canvas"] svg',
) as SVGSVGElement
const ctm = svg.getScreenCTM()
if (!ctm) throw new Error('no CTM')
const layer = svg.lastElementChild as SVGGElement
const twins = Array.from(layer.children).filter(
(k) => k.tagName === 'circle' && k.getAttribute('fill') !== 'transparent',
) as SVGCircleElement[]
const disc = (t: SVGCircleElement) => ({
id: t.getAttribute('data-anno-id') ?? '',
cx: t.cx.baseVal.value,
cy: t.cy.baseVal.value,
r: t.r.baseVal.value,
})
const discs = twins.map(disc)
const who = (x: number, y: number) => {
const p = new DOMPoint(x, y).matrixTransform(ctm)
return document
.elementFromPoint(p.x, p.y)
?.closest('[data-anno-id]')
?.getAttribute('data-anno-id')
}
const missed: Record<string, string> = {}
for (const d of discs) {
let n = 0
let own = 0
const reach = d.r * 0.95
for (let dx = -reach; dx <= reach; dx += 2) {
for (let dy = -reach; dy <= reach; dy += 2) {
if (Math.hypot(dx, dy) > reach) continue
const x = d.cx + dx
const y = d.cy + dy
const top = discs
.filter((o) => Math.hypot(x - o.cx, y - o.cy) <= o.r)
.pop()
n++
if (who(x, y) === top?.id) own++
}
}
if (own < n) missed[d.id] = `${own}/${n}`
}
return missed
}
/**
* In the page: every filled shape of the layer (zones, trigger), sampled every 4 units inside
* its fill, 2 CSS pixels from its edges; a sample counts where no visible disc lies within 2 CSS
* pixels and no later shape holds it in its fill or its stroke. Answers the shapes that missed, with their counts.
*/
function sampleZones(): Record<string, string> {
const svg = document.querySelector(
'[data-testid="anatomy-canvas"] svg',
) as SVGSVGElement
const ctm = svg.getScreenCTM()
if (!ctm) throw new Error('no CTM')
const margin = 2 / ctm.a
const layer = svg.lastElementChild as SVGGElement
const kids = Array.from(layer.children) as SVGGeometryElement[]
const twins = kids.filter(
(k) =>
k.tagName === 'circle' &&
k.getAttribute('pointer-events') === 'visiblePainted',
) as SVGCircleElement[]
const shapes = kids.filter(
(k) => k.tagName !== 'circle' || k.getAttribute('pointer-events') === 'all',
)
const nearDisc = (x: number, y: number) =>
twins.some(
(t) =>
Math.hypot(x - t.cx.baseVal.value, y - t.cy.baseVal.value) <=
t.r.baseVal.value + 0.75 + margin,
)
const who = (x: number, y: number) => {
const p = new DOMPoint(x, y).matrixTransform(ctm)
return document
.elementFromPoint(p.x, p.y)
?.closest('[data-anno-id]')
?.getAttribute('data-anno-id')
}
const missed: Record<string, string> = {}
shapes.forEach((shape, at) => {
const id = shape.getAttribute('data-anno-id') ?? ''
const later = shapes.slice(at + 1)
const b = shape.getBBox()
let n = 0
let own = 0
for (let x = b.x; x <= b.x + b.width; x += 4) {
for (let y = b.y; y <= b.y + b.height; y += 4) {
const point = new DOMPoint(x, y)
// Edges and vertices aside: a sample 2 CSS pixels inside the fill in each direction.
const inside = [
[margin, 0],
[-margin, 0],
[0, margin],
[0, -margin],
].every(([dx, dy]) => shape.isPointInFill(new DOMPoint(x + dx, y + dy)))
if (!shape.isPointInFill(point) || !inside || nearDisc(x, y)) continue
if (
later.some((o) => o.isPointInFill(point) || o.isPointInStroke(point))
)
continue
n++
const got = who(x, y)
if (got === id) own++
else missed[`${id} first miss`] ??= `${x},${y}: ${String(got)}`
}
}
if (own < n) missed[id] = `${own}/${n}`
})
return missed
}