diff --git a/apps/app/e2e/harness/access-labels.html b/apps/app/e2e/harness/access-labels.html new file mode 100644 index 00000000..22b8a342 --- /dev/null +++ b/apps/app/e2e/harness/access-labels.html @@ -0,0 +1,12 @@ + + + + + + Access labels harness + + +
+ + + diff --git a/apps/app/e2e/harness/access-labels.tsx b/apps/app/e2e/harness/access-labels.tsx new file mode 100644 index 00000000..27877480 --- /dev/null +++ b/apps/app/e2e/harness/access-labels.tsx @@ -0,0 +1,119 @@ +/** + * Test page for the bilan's access labels and detail window in a real browser + * (e2e/ui/access-labels.spec.ts): the real application, started at its home route, on the + * bundled equine sheet given what the draft lacks: an access over the hock's point (a point + * under an access), a 7:1 view and a view nested in the head view, reached by an access inside it. Served + * by the Vite dev server only (`/e2e/harness/access-labels.html`); the build has a single + * entry, index.html, so this page never ships. The address is reset to `/` before the + * router mounts, so the local tool's own navigation works from there. + */ +import { StrictMode } from 'react' +import { createRoot } from 'react-dom/client' +import '@/styles/index.css' +import App from '@/app/App' +import { bundledSheetProvider } from '@/sheets/provider' +import { setSheetProvider } from '@/sheets/useSheet' + +type Json = Record + +/** A rectangle access of `view` over `[x, y, w, h]`, in the internal category. */ +function access( + id: string, + view: string, + [x, y, w, h]: number[], + name: string, + opens: string, +): Json { + return { + id, + kind: 'detail_trigger', + view_id: view, + category_id: 'cat-access', + laterality: 'unpaired', + geometry: { + type: 'polygon', + points: [ + [x, y], + [x + w, y], + [x + w, y + h], + [x, y + h], + ], + }, + review_status: 'reviewed', + name: { fr: name, en: name }, + opens_view_id: opens, + } +} + +function withNestedViews(document: Json): Json { + const views = document.views as Json[] + const detail = (id: string, name: string, parent: string, box: Json) => + views.push({ + id, + kind: 'detail', + name: { fr: name, en: name }, + svg_asset_id: null, + view_box: box, + parent_view_id: parent, + }) + detail('muzzle', 'Museau', 'head', { + min_x: 100, + min_y: 280, + width: 220, + height: 170, + }) + detail('hock-view', 'Vue du jarret', 'main', { + min_x: 1400, + min_y: 1050, + width: 300, + height: 220, + }) + detail('wide', 'Vue large', 'main', { + min_x: 900, + min_y: 800, + width: 700, + height: 100, + }) + ;(document.categories as Json[]).push({ + id: 'cat-access', + name: { fr: 'Accès aux vues détaillées', en: 'Access to detail views' }, + color: null, + }) + ;(document.annotations as Json[]).push( + access('muzzle-access', 'head', [130, 330, 120, 80], 'Museau', 'muzzle'), + access('wide-access', 'main', [1000, 300, 200, 100], 'Vue large', 'wide'), + access( + 'hock-access', + 'main', + [1480, 1100, 130, 130], + 'Jarret', + 'hock-view', + ), + ) + return document +} + +setSheetProvider({ + async getReferenceSheet(speciesId) { + const sheet = await bundledSheetProvider.getReferenceSheet(speciesId) + if (!sheet) return sheet + const document = structuredClone(sheet.document) as Json + // The edited document no longer matches the declared fingerprint: without that block the + // reference reads as a historical one, unverified, which this page does not mind. + const ref = { ...(sheet.ref as Json) } + delete ref.fingerprint + return { + ...sheet, + ref: ref as unknown as typeof sheet.ref, + document: withNestedViews(document), + } + }, +}) + +history.replaceState(null, '', '/') + +createRoot(document.getElementById('root') as HTMLElement).render( + + + , +) diff --git a/apps/app/e2e/shell/catalogue.spec.ts b/apps/app/e2e/shell/catalogue.spec.ts index 8b5d1a0c..eff65ac2 100644 --- a/apps/app/e2e/shell/catalogue.spec.ts +++ b/apps/app/e2e/shell/catalogue.spec.ts @@ -1,4 +1,5 @@ import { randomUUID } from 'node:crypto' +import { join } from 'node:path' import { en } from '@/i18n/en' import { fr } from '@/i18n/fr' import type { Dict } from '@/i18n/types' @@ -10,7 +11,13 @@ import { test, } from '../support/browser' import { seedGrant } from '../support/admin' -import { seedOfficialSheet, type FixtureSheet } from '../support/catalogue' +import { + archiveOwnSheet, + revokeOwnGrant, + seedOfficialSheet, + type FixtureSheet, +} from '../support/catalogue' +import { distinctColours } from '../support/pixels' import { createAccount, dropLateReplays, @@ -334,3 +341,223 @@ for (const [locale, dict] of LANGUAGES) { }) }) } + +// V1-2.6 U2 Task 29a: the access labels of the catalogue (D12, D25, A8) on a published sheet +// that carries what the equine draft does not: five close accesses on the fore limb, an +// access drawn over the hock's point and a 7:1 detail view. The sheet and the reader's grant +// are the test's own, cleaned by id after a name read-back. + +/** Screenshots kept for the owner's review (not committed: `.superpowers` is ignored). */ +const SHOTS = join( + __dirname, + '../../../../.superpowers/sdd/2026-11-22-detail-views-graphic-crop/task-29a-shots', +) + +const WIDE = { min_x: 900, min_y: 800, width: 700, height: 100 } + +/** A rectangle access over `box` on the main view, opening `opens`, in the internal category. */ +function accessOver( + id: string, + box: [number, number, number, number], + opens: string, +) { + const [x, y, w, h] = box + return { + id, + kind: 'detail_trigger', + view_id: 'main', + category_id: 'cat-access', + laterality: 'unpaired', + geometry: { + type: 'polygon', + points: [ + [x, y], + [x + w, y], + [x + w, y + h], + [x, y + h], + ], + }, + review_status: 'reviewed', + name: { fr: `Accès ${id}`, en: `Access ${id}` }, + opens_view_id: opens, + } +} + +/** Five close fore-limb accesses, an access over the hock (a point), a 7:1 view and its access. */ +function labelledShape(document: Record) { + const views = document.views as unknown[] + const annotations = document.annotations as unknown[] + ;(document.categories as unknown[]).push({ + id: 'cat-access', + name: { fr: 'Accès aux vues détaillées', en: 'Access to detail views' }, + color: null, + }) + const crop = { min_x: 600, min_y: 1000, width: 400, height: 300 } + const detail = (id: string, view_box: unknown) => + views.push({ + id, + kind: 'detail', + name: { fr: `Vue ${id}`, en: `View ${id}` }, + svg_asset_id: null, + view_box, + parent_view_id: 'main', + }) + ;['f1', 'f2', 'f3', 'f4', 'f5'].forEach((id, i) => { + detail(`v-${id}`, crop) + annotations.push( + accessOver(id, [690 + i * 18, 1150 + i * 40, 90, 90], `v-${id}`), + ) + }) + detail('v-hock', { min_x: 1400, min_y: 1050, width: 300, height: 220 }) + annotations.push(accessOver('hock-access', [1480, 1100, 130, 130], 'v-hock')) + detail('v-wide', WIDE) + annotations.push(accessOver('wide-access', [1000, 300, 200, 100], 'v-wide')) +} + +test.describe('catalogue access labels (29a, fr)', () => { + test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) + test.beforeEach(async ({ context }, info) => { + test.skip(isPhone(info), 'the desktop widths are set by the test') // floor-guard: allow the catalogue labels have their own 375 px proof in editor-detail-views + await routeToSandbox(context) + }) + test.afterEach(async ({ context }) => { + await dropLateReplays(context) + }) + + test('12. labels show the view, a point under an access wins, bands, zoom buttons stay free (A8)', async ({ + page, + requests, + }) => { + test.setTimeout(240_000) + const tag = tagOf() + const sheet = await seedOfficialSheet( + namesOf(tag, 'étiquettes'), + 'listed', + { shape: labelledShape }, + ) + const reader = await createAccount('fr', false) + const grantId = await seedGrant(reader, 'catalog_reader') + try { + requests.forbid(reader.email, reader.password, reader.displayName, tag) + await signIn(page, reader, fr) + await page.setViewportSize({ width: 1280, height: 800 }) + await openSheet(page, `/app/anatomy/${sheet.id}`, sheet.names.fr) + const box = page.getByTestId('catalogue-canvas').locator('xpath=..') + const labels = box.getByTestId('access-labels') + const named = labels.getByRole('button', { name: /^Ouvrir la vue/ }) + const more = labels.getByRole('button', { name: /^Autres vues/ }) + const zoom = box.getByRole('button', { name: fr['catalogue.zoom.fit'] }) + await expect(named.first()).toBeVisible() + + // With five close accesses, nothing of the labels overlaps the zoom buttons. + const zoomBox = await zoomButtonsBox(page) + const shown = [...(await named.all()), ...(await more.all())] + expect(shown.length).toBeGreaterThan(0) + for (const element of shown) { + const rect = (await element.boundingBox())! + expect(overlaps(rect, zoomBox), await element.innerText()).toBe(false) + } + + // With « Autres vues » open the zoom buttons stay visible, answer, and zoom the drawing. + await expect(more).toBeVisible() + await more.click() + await expect(more).toHaveAttribute('aria-expanded', 'true') + await expect(zoom).toBeVisible() + const list = (await labels.getByRole('list').boundingBox())! + expect(overlaps(list, zoomBox), 'the open list over the zoom buttons').toBe(false) + const before = await framingScale(page) + await box.getByRole('button', { name: fr['catalogue.zoom.in'] }).click() + expect(await framingScale(page)).toBeGreaterThan(before) + await box.getByRole('button', { name: fr['catalogue.zoom.fit'] }).click() + expect(await framingScale(page)).toBeCloseTo(before, 2) + + // A point under an access wins the click: the zone is picked, the view stays. + const hock = page + .getByTestId('catalogue-canvas-drawing') + .locator('circle[data-anno-id="hock"][pointer-events="visiblePainted"]') + .first() + const spot = (await hock.boundingBox())! + await page.mouse.click(spot.x + spot.width / 2, spot.y + spot.height / 2) + await expect( + page.getByRole('combobox', { name: fr['catalogue.zone.choose'] }), + ).toHaveValue('hock') + await expect( + page.getByRole('tab', { selected: true }), + ).toHaveText(/Vue latérale gauche|Left lateral view/) + + // A label shows its view, and a 7:1 view sits between neutral bands. + await box + .getByRole('button', { name: 'Ouvrir la vue « Accès wide-access »' }) + .click() + await expect(page.getByRole('tab', { selected: true })).toHaveText( + 'Vue v-wide', + ) + const svg = page.getByTestId('catalogue-canvas-drawing').locator('> svg') + const clip = await svg.evaluate((e) => (e as SVGElement).style.clipPath) + const insets = (clip.match(/[\d.]+/g) ?? []).map(Number) + expect(insets[0], `clip ${clip}`).toBeGreaterThan(20) + const frame = (await svg.boundingBox())! + expect( + await distinctColours(page, { + // Left of the zoom buttons, which sit over the top band. + x: frame.x + 16, + y: frame.y + 2, + width: frame.width - 260, + height: insets[0] - 4, + }), + ).toEqual(['#ece7df']) + await page.screenshot({ path: join(SHOTS, 'case12-catalogue-bands.png') }) + } finally { + const status = await archiveOwnSheet(sheet.id, sheet.names.fr).catch( + (e: Error) => e.message, + ) + const revoked = await revokeOwnGrant(grantId, reader.id).catch( + (e: Error) => ({ returned: e.message, readBack: '' }), + ) + expect([status, revoked.returned, revoked.readBack]).toEqual([ + 'archived', + grantId, + grantId, + ]) + } + }) +}) + +type Rect = { x: number; y: number; width: number; height: number } + +const overlaps = (a: Rect, b: Rect) => + a.x < b.x + b.width && + b.x < a.x + a.width && + a.y < b.y + b.height && + b.y < a.y + a.height + +/** The box holding the three zoom buttons: their union. */ +async function zoomButtonsBox(page: Page): Promise { + const boxes = await Promise.all( + [fr['catalogue.zoom.out'], fr['catalogue.zoom.in'], fr['catalogue.zoom.fit']].map( + (name) => + page + .getByTestId('catalogue-canvas') + .locator('xpath=..') + .getByRole('button', { name }) + .boundingBox(), + ), + ) + const found = boxes.filter((b): b is Rect => b !== null) + const x = Math.min(...found.map((b) => b.x)) + const y = Math.min(...found.map((b) => b.y)) + return { + x, + y, + width: Math.max(...found.map((b) => b.x + b.width)) - x, + height: Math.max(...found.map((b) => b.y + b.height)) - y, + } +} + +/** The drawing layer's scale: `translate(x, y) scale(s)`. */ +async function framingScale(page: Page): Promise { + const transform = await page + .getByTestId('catalogue-canvas-drawing') + .evaluate((el) => (el as HTMLElement).style.transform) + return Number((transform.match(/-?[\d.]+/g) ?? [])[2] ?? 1) +} diff --git a/apps/app/e2e/shell/editor-annotations.spec.ts b/apps/app/e2e/shell/editor-annotations.spec.ts index d42c54e1..9dc0c2d8 100644 --- a/apps/app/e2e/shell/editor-annotations.spec.ts +++ b/apps/app/e2e/shell/editor-annotations.spec.ts @@ -235,6 +235,11 @@ test.describe('editor annotations (A3)', () => { // A link to the detail view: the same tracing, the opened view chosen. await tool(page, 'link').click() + // The access tool defaults to the rectangle (D5): the polygon is chosen to trace one. + await page + .getByTestId('access-shape') + .getByText(dict['editor.annotations.shape.polygon'], { exact: true }) + .click() for (const [x, y] of [ [150, 500], [350, 500], diff --git a/apps/app/e2e/shell/editor-detail-views.spec.ts b/apps/app/e2e/shell/editor-detail-views.spec.ts new file mode 100644 index 00000000..89f2e8d9 --- /dev/null +++ b/apps/app/e2e/shell/editor-detail-views.spec.ts @@ -0,0 +1,796 @@ +import { join } from 'node:path' +import { fr } from '@/i18n/fr' +import type { Locator, Page } from '@playwright/test' +import { expect, expectAccessible, test } from '../support/browser' +import { archiveOwnSheet } from '../support/catalogue' +import { guardAgainst, preExistingRows } from '../support/dataGuard' +import { stepUpAdmin } from '../support/admin' +import { distinctColours } from '../support/pixels' +import { dropLateReplays, routeToSandbox } from '../support/sandbox' +import { + clickDrawing, + clientOf, + createFromPanel, + draftPath, + draftTitle, + editorActor, + fillCreation, + openEditor, + saveDraft, + seedDraft, + selectionTag, + selectTab, + serverDocument, + pointOf, + shapeWith, + shownNumber, + shownPoints, + standardShape, + toolButton, + type DraftSeed, +} from '../support/editor' +import { between, move, touch } from '../support/touch' +import { signIn } from '../support/shell' + +// V1-2.6 U2 Task 29a: the detail views drawn on the drawing, in a real browser against the +// sandbox. Every test seeds its own draft and archives it by captured id after a name +// read-back (LRN-143); the data guard proves no pre-existing sheet or version changed. + +const dict = fr + +const ownSheets: { id: string; name: string }[] = [] +let before: string[] = [] + +test.beforeAll(async () => { + before = await preExistingRows() +}) + +test.afterAll(async () => { + const failures: string[] = [] + for (const { id, name } of ownSheets.splice(0)) { + const status = await archiveOwnSheet(id, name).catch( + (e: Error) => e.message, + ) + if (status !== 'archived') failures.push(`sheet ${id}: ${status}`) + } + expect(failures, 'cleanup of the run').toEqual([]) + const result = await guardAgainst(before) + console.log( + `data guard: ${result.compared} pre-existing rows compared, ` + + `${result.changed.length} changed, ${result.missing.length} missing`, + ) + expect(result.changed, 'pre-existing rows changed').toEqual([]) + expect(result.missing, 'pre-existing rows missing').toEqual([]) +}) + +/** Seeds a draft of the test's own and remembers it for the cleanup. */ +async function seedOwn( + actor: Awaited>, + shape: Parameters[1], +): Promise { + const seed = await seedDraft(actor, shape) + ownSheets.push({ id: seed.sheetId, name: seed.names.fr }) + return seed +} + +/** The access tool, then a drag from `from` to `to` in drawing units. */ +async function dragDrawing( + page: Page, + from: { x: number; y: number }, + to: { x: number; y: number }, +) { + const [a, b] = [ + await clientOf(page, from.x, from.y), + await clientOf(page, to.x, to.y), + ] + await page.mouse.move(a.x, a.y) + await page.mouse.down() + await page.mouse.move((a.x + b.x) / 2, (a.y + b.y) / 2, { steps: 4 }) + await page.mouse.move(b.x, b.y, { steps: 4 }) + await page.mouse.up() +} + +/** The access tool, with the shape chosen when it is not the default rectangle. */ +async function armAccess(page: Page, shape?: 'circle' | 'polygon') { + await toolButton(page, dict, 'link').click() + if (shape) + await page + .getByTestId('access-shape') + .getByText(dict[`editor.annotations.shape.${shape}`], { exact: true }) + .click() +} + +/** The creation dialog of an access: its names, the view it opens, then « Créer ». */ +async function createAccess(page: Page, name: string, opens: string) { + await fillCreation(page, dict, { fr: name, en: name }, opens) + await createFromPanel(page, dict) +} + +/** An access of the draft's shape: a rectangle on the main view, in the internal category. */ +function accessOf( + id: string, + box: { x: number; y: number; w: number; h: number }, + opens: string, + viewId = 'main', +) { + const { x, y, w, h } = box + return { + id, + kind: 'detail_trigger', + view_id: viewId, + category_id: 'cat-access', + laterality: 'unpaired', + geometry: { + type: 'polygon', + points: [ + [x, y], + [x + w, y], + [x + w, y + h], + [x, y + h], + ], + }, + review_status: 'reviewed', + name: { fr: `Accès ${id}`, en: `Access ${id}` }, + opens_view_id: opens, + } +} + +/** The internal category a document needs once it holds an access. */ +const withAccessCategory = (document: Record) => + (document.categories as unknown[]).push({ + id: 'cat-access', + name: { fr: 'Accès aux vues détaillées', en: 'Access to detail views' }, + color: null, + }) + +/** Panel 15's setup: five accesses close together on the fore limb, each opening a view. */ +function closeAccesses(document: Record) { + const ids = ['f1', 'f2', 'f3', 'f4', 'f5'] + views(...ids.map((id) => `view-${id}`))(document) + withAccessCategory(document) + document.annotations = ids.map((id, i) => + accessOf( + id, + { x: 300 + i * 22, y: 300 + i * 12, w: 70, h: 70 }, + `view-${id}`, + ), + ) +} + +/** One access on the main view, opening « Détail A ». */ +function oneAccess(document: Record) { + views()(document) + withAccessCategory(document) + document.annotations = [ + accessOf('a1', { x: 400, y: 300, w: 300, h: 200 }, 'detail-a'), + ] +} + +const views = + (...ids: string[]) => + (document: Record) => { + standardShape(document) + for (const id of ids) + (document.views as unknown[]).push({ + id, + kind: 'detail', + name: { fr: `Détail ${id}`, en: `Detail ${id}` }, + svg_asset_id: null, + view_box: { min_x: 100, min_y: 100, width: 300, height: 240 }, + parent_view_id: 'main', + }) + } + +test.describe('detail views drawn on the drawing (29a)', () => { + test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) + test.beforeEach(async ({ context }, info) => { + test.skip(info.project.name === 'chromium-375', 'editing needs 1 024 px') // floor-guard: allow C16 editing needs >= 1024 px; the 375 px reading has its own test + await routeToSandbox(context) + }) + test.afterEach(async ({ context }) => { + await dropLateReplays(context) + }) + + test('6. shapes: a rectangle and a circle by dragging, a polygon by clicks', async ({ + page, + requests, + }) => { + test.setTimeout(180_000) + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedOwn(actor, { shape: views('detail-b', 'detail-c') }) + await openEditor(page, dict, actor, seed.sheetId) + await expect(toolButton(page, dict, 'link')).toBeEnabled() + + // A rectangle by dragging (the default shape): four vertices, the access selected. + await armAccess(page) + await dragDrawing(page, { x: 600, y: 500 }, { x: 800, y: 650 }) + await createAccess(page, 'Rect', 'detail-a') + await expect(selectionTag(page)).toContainText('Rect') + expect(await shownPoints(page)).toEqual([ + [600, 500], + [800, 500], + [800, 650], + [600, 650], + ]) + + // A circle by dragging from the centre to the edge. + await armAccess(page, 'circle') + await dragDrawing(page, { x: 700, y: 250 }, { x: 760, y: 250 }) + await createAccess(page, 'Cercle', 'detail-b') + await expect(selectionTag(page)).toContainText('Cercle') + expect(await shownNumber(page, 'r')).toBeCloseTo(60, 0) + + // Its radius handle, by dragging, then by keys (one Enter commits the series). + const handle = page.getByTestId('radius-handle') + await expect(handle).toBeVisible() + const edge = await clientOf(page, 760, 250) + await page.mouse.move(edge.x, edge.y) + await page.mouse.down() + await page.mouse.move(edge.x + 15, edge.y, { steps: 4 }) + await page.mouse.up() + const dragged = await shownNumber(page, 'r') + expect(dragged).toBeGreaterThan(60) + await handle.focus() + await page.keyboard.press('ArrowRight') + const stepped = await shownNumber(page, 'r') + expect(stepped).toBeGreaterThan(dragged) + await page.keyboard.press('ArrowRight') + await page.keyboard.press('ArrowRight') + expect(await shownNumber(page, 'r')).toBeCloseTo( + dragged + 3 * (stepped - dragged), + 1, + ) + await page.keyboard.press('Enter') + + // A polygon by clicks, closed by « Fermer le tracé ». + await armAccess(page, 'polygon') + for (const [x, y] of [ + [150, 550], + [350, 550], + [250, 700], + ]) + await clickDrawing(page, x, y) + await page + .getByRole('button', { name: dict['editor.annotations.trace_close'] }) + .click() + await createAccess(page, 'Poly', 'detail-c') + await expect(selectionTag(page)).toContainText('Poly') + + // Each is committed in the internal category once saved. + await saveDraft(page, dict, seed.revision + 1) + const document = await serverDocument<{ + annotations: { + name: { fr: string } + kind: string + category_id: string + geometry: { type: string } + }[] + }>(seed.draftId) + const accesses = document.annotations.filter( + (a) => a.kind === 'detail_trigger', + ) + expect( + accesses.map((a) => [a.name.fr, a.geometry.type, a.category_id]), + ).toEqual([ + ['Rect', 'polygon', 'cat-access'], + ['Cercle', 'circle', 'cat-access'], + ['Poly', 'polygon', 'cat-access'], + ]) + }) + + test('7. priority (D11): a point wins over an access, the label picks the access', async ({ + page, + requests, + }) => { + test.setTimeout(180_000) + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedOwn(actor, { + shape: (document) => { + shapeWith( + pointOf('p1', 'main', { cx: 500, cy: 400, r: 40 }, 'Point un'), + accessOf('a1', { x: 400, y: 300, w: 300, h: 200 }, 'detail-a'), + )(document) + withAccessCategory(document) + }, + }) + await openEditor(page, dict, actor, seed.sheetId) + await expect(toolButton(page, dict, 'point')).toBeEnabled() + // The ring between the disc and the hit circle lies inside the access: the point wins. + await clickDrawing(page, 534, 400) + await expect(selectionTag(page)).toContainText('Point un') + // Inside the access and off the point, the access is what is there. + await clickDrawing(page, 650, 470) + await expect(selectionTag(page)).toContainText('Accès a1') + await clickDrawing(page, 534, 400) + await expect(selectionTag(page)).toContainText('Point un') + // The access answers where no point is: its label selects it, « Ouvrir la vue » opens it. + const label = page.getByRole('button', { + name: 'Ouvrir la vue « Accès a1 »', + }) + await label.click() + await expect(selectionTag(page)).toContainText('Accès a1') + const parent = page.getByRole('button', { + name: dict['editor.annotations.view.parent'], + }) + await expect(parent).toHaveCount(0) + await page + .getByTestId('edit-strip') + .getByRole('button', { name: dict['editor.annotations.view.open'] }) + .click() + await expect(parent).toBeVisible() + await expect(label).toHaveCount(0) + await parent.click() + await expect(parent).toHaveCount(0) + await expect(label).toBeVisible() + }) + + test('8. labels at 375 px, read-only: two labels, « Autres vues (3) », axe', async ({ + page, + requests, + }) => { + test.setTimeout(180_000) + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedOwn(actor, { shape: closeAccesses }) + await signIn(page, actor.account, dict) + await page.goto('/app/admin') + await stepUpAdmin(page, dict, actor.secret) + await page.setViewportSize({ width: 375, height: 667 }) + await page.goto(draftPath(seed.sheetId)) + await expect( + page.getByRole('heading', { level: 1, name: draftTitle(dict) }), + ).toBeVisible() + await selectTab(page, dict, 'annotations') + const labels = page.getByTestId('access-labels') + const named = labels.getByRole('button', { name: /^Ouvrir la vue/ }) + const more = labels.getByRole('button', { name: 'Autres vues (3)' }) + await expect(named).toHaveCount(2) + await expect(more).toBeVisible() + // The list opens and Escape closes it, the focus back on the button. + await more.click() + await expect(more).toHaveAttribute('aria-expanded', 'true') + await expect(labels.getByRole('listitem')).toHaveCount(3) + await expectAccessible(page, 'the labels with the list open at 375 px') + await page.keyboard.press('Escape') + await expect(more).toHaveAttribute('aria-expanded', 'false') + await expect(more).toBeFocused() + // Tab order: the labels in the document's order, then the button. + await named.first().focus() + await page.keyboard.press('Tab') + await expect(named.nth(1)).toBeFocused() + await page.keyboard.press('Tab') + await expect(more).toBeFocused() + await expectAccessible(page, 'the read-only draft with labels at 375 px') + }) + + test('9. bands: a 7:1 view shows neutral bands and nothing outside the frame', async ({ + page, + requests, + }) => { + test.setTimeout(180_000) + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedOwn(actor, { + shape: (document) => { + views('wide')(document) + withAccessCategory(document) + const wide = ( + document.views as { id: string; view_box: unknown }[] + ).find((v) => v.id === 'wide')! + wide.view_box = { min_x: 100, min_y: 380, width: 700, height: 100 } + document.annotations = [ + accessOf('a1', { x: 120, y: 400, w: 200, h: 60 }, 'wide'), + ] + }, + }) + await openEditor(page, dict, actor, seed.sheetId) + await expect(toolButton(page, dict, 'point')).toBeEnabled() + await page + .getByRole('button', { name: 'Ouvrir la vue « Accès a1 »' }) + .click() + await page + .getByTestId('edit-strip') + .getByRole('button', { name: dict['editor.annotations.view.open'] }) + .click() + const parent = page.getByRole('button', { + name: dict['editor.annotations.view.parent'], + }) + await expect(parent).toBeVisible() + const svg = page.locator('[data-testid="annotation-canvas-drawing"] > svg') + await expect(svg).toBeVisible() + const clip = await svg.evaluate((e) => (e as SVGElement).style.clipPath) + // `inset(T R)` or `inset(T R B L)`: the top and bottom insets, whichever the form. + const insets = (clip.match(/[\d.]+/g) ?? []).map(Number) + const [top, bottom] = [insets[0], insets[2] ?? insets[0]] + expect(top, `clip ${clip}`).toBeGreaterThan(20) + const box = (await svg.boundingBox())! + // Every pixel of both bands (clear of the box's rounded corners) is the band's colour. + for (const [y, height] of [ + [box.y + 2, top - 4], + [box.y + box.height - bottom + 2, bottom - 4], + ]) + expect( + await distinctColours(page, { + x: box.x + 16, + y, + width: box.width - 32, + height, + }), + ).toEqual(['#ece7df']) + await page.screenshot({ + path: `${SHOTS}/case9-bands.png`, + clip: box, + }) + }) + + for (const width of [1024, 1280]) { + test(`10. strip at ${width} px: hint, adjust commands, move bar, shape choice`, async ({ + page, + requests, + }) => { + test.setTimeout(180_000) + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedOwn(actor, { shape: views() }) + await page.setViewportSize({ width, height: 800 }) + await openEditor(page, dict, actor, seed.sheetId) + await expect(toolButton(page, dict, 'link')).toBeEnabled() + const idle = (await stripBox(page))! + const detail = page.getByTestId('edit-strip-detail') + + // Drawing phase: the hint in the 256 px lead (measurement 1). + await page + .getByTestId('edit-strip') + .getByRole('button', { name: dict['editor.annotations.view.new'] }) + .click() + await expect(detail).toHaveText( + dict['editor.annotations.frame.draw_hint'], + ) + measured(`1 hint truncated at ${width}`, { + truncated: await truncated(detail), + scrollWidth: await detail.evaluate((e) => e.scrollWidth), + clientWidth: await detail.evaluate((e) => e.clientWidth), + }) + await expectControlsInside(page, 'the drawing phase') + + // Adjust phase (measurement 2): every command inside the strip. + await dragDrawing(page, { x: 150, y: 150 }, { x: 450, y: 350 }) + await expect(page.getByTestId('frame-commands')).toBeVisible() + const adjust = await stripControls(page) + const lead = (await page.getByTestId('edit-strip-lead').boundingBox())! + measured(`2 adjust controls at ${width}`, { + lead: Math.round(lead.width), + strip: Math.round(idle.width), + controls: adjust.map((i) => [ + i.name, + Math.round(i.x - idle.x), + Math.round(i.width), + ]), + formatInStrip: adjust.some((i) => i.name.startsWith('Format')), + }) + measured(`2 adjust controls cut at ${width}`, await clippedControls(page)) + const commandsBox = async (testId: string) => + (await page.getByTestId(testId).locator('xpath=..').boundingBox())! + const adjustBox = await commandsBox('frame-commands') + expect(await stripBox(page)).toEqual(idle) + + // The move bar takes the same commands box: no layout shift (A6). + await page + .getByTestId('edit-strip') + .getByRole('button', { + name: dict['editor.annotations.frame.move'], + exact: true, + }) + .click() + await expect(page.getByTestId('move-mode-bar')).toBeVisible() + await expectControlsInside(page, 'the move bar') + const moveBox = await commandsBox('move-mode-bar') + const bar = (await page.getByTestId('move-mode-bar').boundingBox())! + measured(`2 move bar at ${width}`, { + barHeight: bar.height, + commandsBoxHeight: moveBox.height, + adjustBoxHeight: adjustBox.height, + stripHeight: idle.height, + }) + expect(moveBox.height).toBe(adjustBox.height) + expect(await stripBox(page)).toEqual(idle) + await page + .getByTestId('move-mode-bar') + .getByRole('button', { name: dict['editor.annotations.move.cancel'] }) + .click() + + // The access tool's shape choice keeps the strip's fixed height (measurement 3). + await page + .getByTestId('edit-strip') + .getByRole('button', { name: dict['editor.annotations.frame.abandon'] }) + .click() + await page + .getByTestId('dialog-panel') + .getByRole('button', { name: dict['editor.annotations.guard.discard'] }) + .click() + await expect(page.getByTestId('frame-commands')).toHaveCount(0) + await armAccess(page) + await expect(page.getByTestId('access-shape')).toBeVisible() + await expectControlsInside(page, 'the access tool') + const armed = (await stripBox(page))! + measured(`3 strip height with the shape choice at ${width}`, { + armed: armed.height, + fixed: idle.height, + }) + expect(armed.height).toBe(idle.height) + }) + } + + // Finding of the 29a run: the adjust commands are 54 px wider than the strip, « Valider le + // cadre » is cut (measurement 2). The proof stays here, expected to fail until the strip + // gives the « Format » chip to the lead's detail line, as the plan allows. + for (const width of [1024, 1280]) { + test(`10. adjust commands inside the strip at ${width} px`, async ({ + page, + requests, + }) => { + test.fail(true, 'finding 29a-2: « Valider le cadre » is cut by the strip') + test.setTimeout(180_000) + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedOwn(actor, { shape: views() }) + await page.setViewportSize({ width, height: 800 }) + await openEditor(page, dict, actor, seed.sheetId) + await expect(toolButton(page, dict, 'link')).toBeEnabled() + await page + .getByTestId('edit-strip') + .getByRole('button', { name: dict['editor.annotations.view.new'] }) + .click() + await dragDrawing(page, { x: 150, y: 150 }, { x: 450, y: 350 }) + await expect(page.getByTestId('frame-commands')).toBeVisible() + await expectControlsInside(page, 'the adjust phase') + }) + } + + test('10. a kept selection and the access tool: the lead names the selection (measurement 6)', async ({ + page, + requests, + }) => { + test.setTimeout(180_000) + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedOwn(actor, { + shape: shapeWith( + pointOf('p1', 'main', { cx: 500, cy: 400, r: 40 }, 'Point un'), + ), + }) + await openEditor(page, dict, actor, seed.sheetId) + await expect(toolButton(page, dict, 'link')).toBeEnabled() + await clickDrawing(page, 534, 400) + await expect(selectionTag(page)).toContainText('Point un') + await armAccess(page) + await expect(page.getByTestId('access-shape')).toBeVisible() + const title = await page.getByTestId('edit-strip-title').textContent() + const detail = await page.getByTestId('edit-strip-detail').textContent() + measured('6 lead with the access tool armed over a selection', { + title, + detail, + shapeChoiceShown: true, + }) + await page.getByTestId('edit-strip').screenshot({ + path: `${SHOTS}/measure6-strip-selection-access-tool.png`, + }) + await page.screenshot({ path: `${SHOTS}/measure6-page.png` }) + await expectControlsInside(page, 'the access tool over a selection') + }) + + // Finding of the 29a run: with an access selected the five commands are wider than the + // strip, « Désélectionner » is cut (measurement 4). Expected to fail until the strip fits. + test('10. the selected access commands fit the strip at 1024 px', async ({ + page, + requests, + }) => { + test.fail(true, 'finding 29a-4: « Désélectionner » is cut by the strip') + test.setTimeout(180_000) + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedOwn(actor, { shape: oneAccess }) + await page.setViewportSize({ width: 1024, height: 800 }) + await openEditor(page, dict, actor, seed.sheetId) + await expect(toolButton(page, dict, 'point')).toBeEnabled() + await page + .getByRole('button', { name: 'Ouvrir la vue « Accès a1 »' }) + .click() + await expect(selectionTag(page)).toContainText('Accès a1') + measured( + '4 access commands at 1024', + (await stripControls(page)).map((i) => [i.name, Math.round(i.width)]), + ) + await expectControlsInside(page, 'the selected access at 1024 px') + }) + + test('10. at 375 px read-only there is no strip, a label opens its view (measurement 4)', async ({ + page, + requests, + }) => { + test.setTimeout(180_000) + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedOwn(actor, { shape: oneAccess }) + await signIn(page, actor.account, dict) + await page.goto('/app/admin') + await stepUpAdmin(page, dict, actor.secret) + await page.setViewportSize({ width: 375, height: 667 }) + await page.goto(draftPath(seed.sheetId)) + await selectTab(page, dict, 'annotations') + // No strip below 1 024 px: the label opens the view straight away, nothing to measure. + await page + .getByRole('button', { name: 'Ouvrir la vue « Accès a1 »' }) + .click() + await expect(page.getByTestId('edit-strip')).toHaveCount(0) + await expect( + page.getByRole('button', { + name: dict['editor.annotations.view.parent'], + }), + ).toHaveCount(0) + measured('4 at 375', 'read-only: no edit strip, the label opens the view') + await page.screenshot({ + path: `${SHOTS}/measure4-375-label-opens-view.png`, + }) + }) + + test.describe('by finger (11)', () => { + test.use({ hasTouch: true }) + + /** The frame tool started from the strip, the canvas box and the framing read. */ + async function startFrame(page: Page) { + await page + .getByTestId('edit-strip') + .getByRole('button', { name: dict['editor.annotations.view.new'] }) + .click() + await expect(page.getByTestId('edit-strip-detail')).toHaveText( + dict['editor.annotations.frame.draw_hint'], + ) + } + + const scaleOf = async (page: Page) => { + const transform = await page + .getByTestId('annotation-canvas-drawing') + .evaluate((el) => (el.parentElement as HTMLElement).style.transform) + return Number((transform.match(/-?[\d.]+/g) ?? [])[2]) + } + + test('11. one finger draws a frame, a second finger cancels it and zooms, a corner shows the loupe', async ({ + page, + context, + requests, + }) => { + test.setTimeout(180_000) + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedOwn(actor, { shape: views() }) + await page.setViewportSize({ width: 1280, height: 800 }) + await openEditor(page, dict, actor, seed.sheetId) + await expect(toolButton(page, dict, 'link')).toBeEnabled() + const cdp = await context.newCDPSession(page) + const [a, b] = [ + await clientOf(page, 150, 150), + await clientOf(page, 450, 350), + ] + + // A second finger during a drag: the frame is cancelled, the drawing zooms. + await startFrame(page) + expect(await scaleOf(page)).toBeCloseTo(1, 2) + await touch(cdp, 'touchStart', [a]) + await move(cdp, [a], [between(a, b, 1, 2)], 3) + const first = between(a, b, 1, 2) + const second = { x: first.x + 60, y: first.y } + await touch(cdp, 'touchStart', [first, second]) + await move( + cdp, + [first, second], + [ + { x: first.x - 60, y: first.y }, + { x: second.x + 60, y: second.y }, + ], + ) + await touch(cdp, 'touchEnd', []) + await expect(page.getByTestId('frame-commands')).toHaveCount(0) + await expect(page.getByTestId('edit-strip-detail')).toHaveText( + dict['editor.annotations.frame.draw_hint'], + ) + expect(await scaleOf(page)).toBeGreaterThan(1) + + // A one-finger drag draws the frame (the whole drawing first, the tool still armed). + await page + .getByRole('button', { name: dict['catalogue.zoom.fit'], exact: true }) + .click() + expect(await scaleOf(page)).toBeCloseTo(1, 2) + await touch(cdp, 'touchStart', [a]) + await move(cdp, [a], [b]) + await touch(cdp, 'touchEnd', []) + await expect(page.getByTestId('frame-commands')).toBeVisible() + + // A one-finger drag on a corner handle shows the loupe, inside the canvas box. + const corner = await clientOf(page, 450, 350) + await touch(cdp, 'touchStart', [corner]) + await move(cdp, [corner], [{ x: corner.x + 30, y: corner.y + 20 }], 4) + const loupe = page.getByTestId('loupe') + await expect(loupe).toBeVisible() + const [disc, canvas] = [ + (await loupe.boundingBox())!, + (await page.getByTestId('annotation-canvas').boundingBox())!, + ] + expect(disc.x).toBeGreaterThanOrEqual(canvas.x - 1) + expect(disc.y).toBeGreaterThanOrEqual(canvas.y - 1) + expect(disc.x + disc.width).toBeLessThanOrEqual( + canvas.x + canvas.width + 1, + ) + expect(disc.y + disc.height).toBeLessThanOrEqual( + canvas.y + canvas.height + 1, + ) + await touch(cdp, 'touchEnd', []) + await expect(loupe).toHaveCount(0) + }) + }) +}) + +/** Records a measurement of the task: printed, and kept as an annotation of the test. */ +function measured(name: string, value: unknown) { + const text = typeof value === 'string' ? value : JSON.stringify(value) + console.log(`MEASURE ${name}: ${text}`) + test.info().annotations.push({ type: `measure ${name}`, description: text }) +} + +const stripBox = (page: Page) => page.getByTestId('edit-strip').boundingBox() + +/** Every visible control of the strip's commands, its box and a name, left to right. */ +async function stripControls(page: Page) { + return page.getByTestId('edit-strip').evaluate((strip) => { + const lead = strip.querySelector('[data-testid="edit-strip-lead"]')! + const notice = strip.querySelector('[data-testid="edit-strip-notice"]')! + const items = [ + ...strip.querySelectorAll( + 'button, label, [data-testid="frame-format"], fieldset', + ), + ].filter((el) => !lead.contains(el) && !notice.contains(el)) + return items.map((el) => { + const r = el.getBoundingClientRect() + return { + name: (el.getAttribute('aria-label') ?? el.textContent ?? '').trim(), + x: r.x, + y: r.y, + width: r.width, + height: r.height, + } + }) + }) +} + +/** The names of the strip's controls that reach outside it (cut by its overflow). */ +async function clippedControls(page: Page): Promise { + const strip = (await stripBox(page))! + const items = await stripControls(page) + expect(items.length, 'controls in the strip').toBeGreaterThan(0) + return items + .filter( + (item) => + item.x < strip.x - 0.5 || + item.y < strip.y - 0.5 || + item.x + item.width > strip.x + strip.width + 0.5 || + item.y + item.height > strip.y + strip.height + 0.5, + ) + .map((item) => item.name) +} + +/** The strip's controls all lie inside the strip (nothing clipped by its overflow). */ +async function expectControlsInside(page: Page, state: string) { + expect(await clippedControls(page), `controls cut in ${state}`).toEqual([]) +} + +/** Whether a strip text is cut by its ellipsis. */ +const truncated = (locator: Locator) => + locator.evaluate((el) => el.scrollWidth > el.clientWidth) + +/** Screenshots kept for the owner's review (not committed: `.superpowers` is ignored). */ +const SHOTS = join( + __dirname, + '../../../../.superpowers/sdd/2026-11-22-detail-views-graphic-crop/task-29a-shots', +) diff --git a/apps/app/e2e/support/catalogue.ts b/apps/app/e2e/support/catalogue.ts index 7d09f623..8127d537 100644 --- a/apps/app/e2e/support/catalogue.ts +++ b/apps/app/e2e/support/catalogue.ts @@ -44,6 +44,8 @@ export interface FixtureSheet { export interface SeedOptions { /** Stored on the published and retired versions in place of the core's (an altered record). */ storedFingerprint?: string + /** Adjusts the parsed document before it is written and fingerprinted (views, accesses). */ + shape?: (document: Record) => void } /** @@ -82,12 +84,18 @@ async function seedFiles() { } /** The equine draft renamed, its drawing re-pointed at the fixture's asset row. */ -function documentFor(text: string, asset: string, names: SheetNames): string { +function documentFor( + text: string, + asset: string, + names: SheetNames, + shape?: SeedOptions['shape'], +): string { const document = JSON.parse(text.replaceAll(SEED_ASSET, asset)) as Record< string, unknown > document.name = names + shape?.(document) return JSON.stringify(document) } @@ -155,7 +163,7 @@ export async function seedOfficialSheet( const id = randomUUID() const asset = randomUUID() const [v1, v2] = [randomUUID(), randomUUID()] - const document = documentFor(text, asset, names) + const document = documentFor(text, asset, names, options.shape) const fingerprint = shape === 'draft' ? null diff --git a/apps/app/e2e/support/dataGuard.ts b/apps/app/e2e/support/dataGuard.ts new file mode 100644 index 00000000..c9918b3b --- /dev/null +++ b/apps/app/e2e/support/dataGuard.ts @@ -0,0 +1,48 @@ +/** + * The data guard of the browser proofs that seed their own sheets: an archive is a status + * update, which a row count cannot see. The pre-existing rows of `anatomical_sheets` (id, + * status, updated_at) and of `anatomical_sheet_versions` (id, status, updated_at, the md5 + * of the content) are read before the first test and after the last; the two readings must + * be equal. "Pre-existing" means created before the run started (the Playwright runner, + * the parent of every worker), so a draft another worker seeds and archives meanwhile is + * never compared. + */ +import { statSync } from 'node:fs' +import { sql } from '../../../../packages/supabase/tests/sandbox/stack' + +/** Start of the Playwright runner, in epoch seconds (Linux: the age of its /proc entry). */ +function runStart(): number { + return Math.floor(statSync(`/proc/${process.ppid}`).ctimeMs / 1000) +} + +/** One line per pre-existing sheet and version, sorted; the cut-off is a number, never text. */ +export async function preExistingRows(): Promise { + const cutoff = Number(runStart()) + if (!Number.isFinite(cutoff)) throw new Error('data guard: no run start') + const out = await sql(`select line from ( + select 's ' || id || ' ' || status || ' ' || updated_at::text as line + from public.anatomical_sheets where created_at < to_timestamp(${cutoff}) + union all + select 'v ' || id || ' ' || status || ' ' || updated_at::text || ' ' || md5(content::text) + from public.anatomical_sheet_versions where created_at < to_timestamp(${cutoff}) + ) rows order by line`) + return out === '' ? [] : out.split('\n') +} + +export interface GuardResult { + compared: number + changed: string[] + missing: string[] +} + +/** The rows of `before` against the rows read now: changed or missing ones, by id. */ +export async function guardAgainst(before: string[]): Promise { + const after = new Set(await preExistingRows()) + const idOf = (line: string) => line.split(' ')[1] + const ids = new Set([...after].map(idOf)) + return { + compared: before.length, + changed: before.filter((line) => !after.has(line) && ids.has(idOf(line))), + missing: before.filter((line) => !ids.has(idOf(line))), + } +} diff --git a/apps/app/e2e/support/pixels.ts b/apps/app/e2e/support/pixels.ts new file mode 100644 index 00000000..29164ee7 --- /dev/null +++ b/apps/app/e2e/support/pixels.ts @@ -0,0 +1,30 @@ +/** Pixel reads of a screen rectangle, for the browser proofs of neutral bands. */ +import type { Page } from '@playwright/test' + +/** The distinct colours (hex) of a screen rectangle, read from a screenshot of it. */ +export async function distinctColours( + page: Page, + clip: { x: number; y: number; width: number; height: number }, +): Promise { + const png = await page.screenshot({ clip }) + return page.evaluate(async (base64) => { + const image = new Image() + image.src = `data:image/png;base64,${base64}` + await image.decode() + const canvas = document.createElement('canvas') + canvas.width = image.width + canvas.height = image.height + const context = canvas.getContext('2d')! + context.drawImage(image, 0, 0) + const { data } = context.getImageData(0, 0, canvas.width, canvas.height) + const seen = new Set() + for (let i = 0; i < data.length; i += 4) + seen.add( + '#' + + [data[i], data[i + 1], data[i + 2]] + .map((v) => v.toString(16).padStart(2, '0')) + .join(''), + ) + return [...seen] + }, png.toString('base64')) +} diff --git a/apps/app/e2e/support/touch.ts b/apps/app/e2e/support/touch.ts new file mode 100644 index 00000000..57056137 --- /dev/null +++ b/apps/app/e2e/support/touch.ts @@ -0,0 +1,29 @@ +/** CDP touch points for the browser proofs (the way editor-touch.spec.ts drives a finger). */ +import type { CDPSession } from '@playwright/test' + +export type XY = { x: number; y: number } + +export const touch = ( + cdp: CDPSession, + type: 'touchStart' | 'touchMove' | 'touchEnd', + points: XY[], +) => + cdp.send('Input.dispatchTouchEvent', { + type, + touchPoints: points.map((p, id) => ({ x: p.x, y: p.y, id })), + }) + +export const between = (from: XY, to: XY, step: number, steps: number) => ({ + x: from.x + ((to.x - from.x) * step) / steps, + y: from.y + ((to.y - from.y) * step) / steps, +}) + +/** Fingers moved together from `from` to `to` in `steps` moves (no touchEnd). */ +export async function move(cdp: CDPSession, from: XY[], to: XY[], steps = 6) { + for (let step = 1; step <= steps; step++) + await touch( + cdp, + 'touchMove', + from.map((f, i) => between(f, to[i], step, steps)), + ) +} diff --git a/apps/app/e2e/ui/access-labels.spec.ts b/apps/app/e2e/ui/access-labels.spec.ts new file mode 100644 index 00000000..9eda8ee1 --- /dev/null +++ b/apps/app/e2e/ui/access-labels.spec.ts @@ -0,0 +1,158 @@ +import { join } from 'node:path' +import { fr } from '@/i18n/fr' +import type { Page } from '@playwright/test' +import { expect, expectAccessible, test } from '../support/browser' + +// V1-2.6 U2 Task 29a: the bilan canvas and its detail window in a real browser, on the +// application's own local tool with the bundled equine sheet given an access over the hock's +// point and a view nested in the head (e2e/harness/access-labels.tsx). No backend, fictitious +// names only. + +const dict = fr +const SHOTS = join( + __dirname, + '../../../../.superpowers/sdd/2026-11-22-detail-views-graphic-crop/task-29a-shots', +) + +const label = (key: string) => dict[key].replace(/\s*\*$/, '') + +async function startReport(page: Page) { + await page.goto('/e2e/harness/access-labels.html') + await page.getByRole('button', { name: dict['home.new_report.cta'] }).click() + await page + .getByLabel(label('form.practitioner.name')) + .fill('Praticien Fictif') + await page.getByLabel(label('form.animal.name')).fill('Fictif Alezan') + await page.getByLabel(label('form.owner.name')).fill('Propriétaire Fictif') + await page.getByRole('button', { name: dict['new_report.submit'] }).click() + await expect(page).toHaveURL(/\/editor$/) + const disclaimer = page.getByRole('dialog', { + name: dict['editor.disclaimer_title'], + }) + await expect(disclaimer).toBeVisible() + await page.keyboard.press('Escape') + await expect(disclaimer).toBeHidden() +} + +const openLabel = (page: Page, name: string | RegExp) => + page + .getByTestId('anatomy-canvas') + .first() + .getByRole('button', { + name: typeof name === 'string' ? `Ouvrir la vue « ${name} »` : name, + }) + +test.describe('bilan access labels and detail window (13)', () => { + test.use({ locale: 'fr-FR', forbiddenInUrls: ['Fictif'] }) + test.skip(({ isMobile }) => isMobile, 'desktop journey') // floor-guard: allow the 375 px reading of labels is proved in the shell suite + + test('a click on the point ring adds the point, even under an access', async ({ + page, + }) => { + await startReport(page) + const markers = page.locator( + '[data-testid="anatomy-canvas"] [data-anno-id="hock"]', + ) + await markers.first().scrollIntoViewIfNeeded() + const [hit, disc] = [ + (await markers.nth(0).boundingBox())!, + (await markers.nth(1).boundingBox())!, + ] + const [outer, inner] = [ + Math.max(hit.width, disc.width), + Math.min(hit.width, disc.width), + ] + // Between the visible disc and the hit circle: inside the access, on the point's ring. + const ring = { + x: hit.x + hit.width / 2 + (outer + inner) / 4, + y: hit.y + hit.height / 2, + } + await page.mouse.click(ring.x, ring.y) + // The point answered (its side question), not the access (its view window). + const sides = page.getByRole('dialog', { name: /^Jarret \(tarso/ }) + await expect(sides).toBeVisible() + await sides.getByRole('button', { name: 'Gauche' }).click() + await expect(page.getByText('1 zone · 0 constat')).toBeVisible() + await expect( + page.getByRole('dialog', { name: 'Vue du jarret' }), + ).toHaveCount(0) + await page.screenshot({ path: join(SHOTS, 'case13-ring-click.png') }) + }) + + test('Enter on a label opens the window, a nested label pushes, back returns, Escape closes', async ({ + page, + }) => { + await startReport(page) + const head = openLabel(page, /^Ouvrir la vue « Tête/) + await head.focus() + await page.keyboard.press('Enter') + const window = page.getByRole('dialog', { name: /^Tête/ }) + await expect(window).toBeVisible() + await expectAccessible(page, 'the bilan detail window on the head') + + // Measurement 5: the drawing is vertically centred in the window's area. + const canvas = window.getByTestId('anatomy-canvas') + const area = (await canvas.locator('xpath=..').boundingBox())! + const drawing = (await canvas + .locator('> div:first-child > svg') + .boundingBox())! + const [above, below] = [ + drawing.y - area.y, + area.y + area.height - (drawing.y + drawing.height), + ] + console.log( + `MEASURE 5 bilan window centring: ${JSON.stringify({ area, drawing, above, below })}`, + ) + expect( + Math.abs(above - below), + 'space above and below the drawing', + ).toBeLessThanOrEqual(2) + await page.screenshot({ path: join(SHOTS, 'measure5-bilan-window.png') }) + + // A nested label pushes the view; the back button names the one it returns to. + await window + .getByRole('button', { name: 'Ouvrir la vue « Museau »' }) + .click() + await expect(page.getByRole('dialog', { name: 'Museau' })).toBeVisible() + const back = page.getByRole('button', { + name: /^Revenir à la vue « Tête/, + }) + await expect(back).toBeVisible() + await expectAccessible(page, 'the bilan detail window on a nested view') + await back.click() + await expect(page.getByRole('dialog', { name: /^Tête/ })).toBeVisible() + await expect(back).toHaveCount(0) + + await page.keyboard.press('Escape') + await expect(page.getByRole('dialog', { name: /^Tête/ })).toHaveCount(0) + }) + + test('a 7:1 view in the window sits in the middle of its area', async ({ + page, + }) => { + await startReport(page) + await openLabel(page, 'Vue large').click() + const window = page.getByRole('dialog', { name: 'Vue large' }) + await expect(window).toBeVisible() + const canvas = window.getByTestId('anatomy-canvas') + const area = (await canvas.locator('xpath=..').boundingBox())! + const drawing = (await canvas + .locator('> div:first-child > svg') + .boundingBox())! + const [above, below] = [ + drawing.y - area.y, + area.y + area.height - (drawing.y + drawing.height), + ] + console.log( + `MEASURE 5 bilan window centring, 7:1 view: ${JSON.stringify({ area, drawing, above, below })}`, + ) + expect(above, 'a band above the drawing').toBeGreaterThan(20) + expect( + Math.abs(above - below), + 'space above and below', + ).toBeLessThanOrEqual(2) + await page.screenshot({ + path: join(SHOTS, 'measure5-bilan-window-wide.png'), + }) + }) +})