diff --git a/apps/app/e2e/playwright.shell.config.ts b/apps/app/e2e/playwright.shell.config.ts index a05cad07..6bd70fa4 100644 --- a/apps/app/e2e/playwright.shell.config.ts +++ b/apps/app/e2e/playwright.shell.config.ts @@ -20,10 +20,13 @@ if (!anonKey) export default defineConfig({ testDir: './shell', + globalSetup: './support/warm-up.ts', outputDir: './test-results/shell', fullyParallel: true, forbidOnly: true, retries: 0, + // Eight workers share one sandbox stack: a read can take longer than the default 5 s. + expect: { timeout: 10_000 }, // No HTML report: its step titles would keep what the test typed, the // fictitious accounts' passwords included. The terminal and the failure // screenshots stay. diff --git a/apps/app/e2e/shell/admin.spec.ts b/apps/app/e2e/shell/admin.spec.ts index 5e3b6c38..21f526c7 100644 --- a/apps/app/e2e/shell/admin.spec.ts +++ b/apps/app/e2e/shell/admin.spec.ts @@ -515,7 +515,14 @@ for (const [locale, dict] of LANGUAGES) { .getByRole('button', { name: dict['admin.sheet_form.submit'] }) .click() - await expect(page).toHaveURL(/\/app\/admin\/sheets\/[0-9a-f-]{36}$/) + // V1-2.6: the creation opens the new draft in the editor; the overview follows. + await expect(page).toHaveURL( + /\/app\/admin\/sheets\/[0-9a-f-]{36}\/draft$/, + ) + await expect( + heading(page, dict['editor.draft.title'].replace('{number}', '1')), + ).toBeVisible() + await page.goto(new URL(page.url()).pathname.replace(/\/draft$/, '')) const name = locale === 'fr' ? `Fiche e2e ${tag}` : `E2E sheet ${tag}` await expect(heading(page, name)).toBeVisible() const versions = main(page) diff --git a/apps/app/e2e/shell/editor-access.spec.ts b/apps/app/e2e/shell/editor-access.spec.ts new file mode 100644 index 00000000..cca7e432 --- /dev/null +++ b/apps/app/e2e/shell/editor-access.spec.ts @@ -0,0 +1,201 @@ +import { fr } from '@/i18n/fr' +import type { Page, TestInfo } from '@playwright/test' +import { + expect, + expectAccessible, + expectNoHorizontalOverflow, + test, +} from '../support/browser' +import { stepUpAdmin } from '../support/admin' +import { dropLateReplays, routeToSandbox } from '../support/sandbox' +import { + draftPath, + draftTitle, + editorActor, + makeActor, + openEditor, + pointOf, + seedDraft, + selectTab, + shapeWith, + type Actor, +} from '../support/editor' +import { signIn } from '../support/shell' + +// V1-2.6 access, narrow screens and axe (contract C26, C31; plan « Modes, permissions, +// layout »): a reviewer-only account and an editor without the admin role read the draft +// without editing it, an account without a capability is refused, the editor is read-only +// at 320, 375 and 800 px and edits at 1 024 px, with no sideways scroll, and axe finds no +// serious violation on any tab, edit or read-only. + +const dict = fr + +const isPhone = (info: TestInfo) => info.project.name === 'chromium-375' +const TABS = [ + 'general', + 'views', + 'annotations', + 'findings', + 'references', + 'vertebrae', + 'verification', +] as const + +const seedShape = shapeWith( + pointOf('p1', 'main', { cx: 500, cy: 400, r: 40 }, 'Point un'), +) + +async function openAs(page: Page, actor: Actor, sheetId: string) { + await signIn(page, actor.account, dict) + await page.goto('/app/admin') + await stepUpAdmin(page, dict, actor.secret) + await page.goto(draftPath(sheetId)) +} + +async function expectReadOnly(page: Page) { + await expect( + page.getByRole('heading', { level: 1, name: draftTitle(dict) }), + ).toBeVisible() + await expect( + page.getByText(dict['editor.draft.read_only'], { exact: true }), + ).toBeVisible() + await expect( + page.getByRole('button', { name: dict['common.save'], exact: true }), + ).toHaveCount(0) + await selectTab(page, dict, 'annotations') + await expect( + page.getByRole('toolbar', { name: dict['editor.annotations.tools'] }), + ).toHaveCount(0) + await expect(page.getByRole('textbox')).toHaveCount(0) +} + +test.describe('editor access, narrow screens and axe', () => { + test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) + test.beforeEach(async ({ context }, info) => { + test.skip(isPhone(info), 'the widths are set by the tests themselves') + await routeToSandbox(context) + }) + test.afterEach(async ({ context }) => { + await dropLateReplays(context) + }) + + test('a reviewer-only account reads the draft, read-only', async ({ + page, + requests, + }) => { + const [editor, reviewer] = [ + await editorActor('fr'), + await makeActor('fr', null, ['sheet_reviewer']), + ] + requests.forbid(reviewer.account.email, reviewer.account.password) + const seed = await seedDraft(editor, { shape: seedShape }) + await openAs(page, reviewer, seed.sheetId) + await expectReadOnly(page) + await expect( + page.getByText(dict['editor.draft.mode.rights'], { exact: false }), + ).toBeVisible() + }) + + // The server answers « not found » to staff without the admin or owner role, so the + // page shows the not-found screen, not a read-only draft (the brief expected the latter). + const REFUSED = [ + ['an editor grant without the admin role', null, ['sheet_editor']], + ['an admin without any capability', 'admin', []], + ] as const + for (const [label, role, grants] of REFUSED) { + test(`${label} gets the not-found screen, no editor`, async ({ + page, + requests, + }) => { + const [editor, other] = [ + await editorActor('fr'), + await makeActor('fr', role, [...grants]), + ] + requests.forbid(other.account.email, other.account.password) + const seed = await seedDraft(editor, { shape: seedShape }) + await openAs(page, other, seed.sheetId) + await expect( + page.getByRole('heading', { + name: dict['admin.overview.not_found_title'], + }), + ).toBeVisible() + await expect(page.getByRole('tablist')).toHaveCount(0) + await expect( + page.getByRole('button', { name: dict['common.save'], exact: true }), + ).toHaveCount(0) + }) + } + + for (const width of [320, 375, 800]) { + test(`read-only at ${width} px, no horizontal scroll`, async ({ + page, + requests, + }) => { + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedDraft(actor, { shape: seedShape }) + await signIn(page, actor.account, dict) + await page.goto('/app/admin') + await stepUpAdmin(page, dict, actor.secret) + await page.setViewportSize({ width, height: 800 }) + await page.goto(draftPath(seed.sheetId)) + await expect( + page.getByRole('heading', { level: 1, name: draftTitle(dict) }), + ).toBeVisible() + await expect( + page.getByText(dict['editor.draft.mode.narrow'], { exact: false }), + ).toBeVisible() + await expect( + page.getByRole('button', { name: dict['common.save'], exact: true }), + ).toHaveCount(0) + await expectNoHorizontalOverflow(page, `the draft at ${width} px`) + await expectAccessible(page, `the draft at ${width} px`) + }) + } + + test('edit at 1 024 px, no horizontal scroll, axe on every tab', async ({ + page, + requests, + }) => { + test.setTimeout(120_000) + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedDraft(actor, { shape: seedShape }) + await page.setViewportSize({ width: 1024, height: 800 }) + await openEditor(page, dict, actor, seed.sheetId) + await expect( + page.getByRole('button', { name: dict['common.save'], exact: true }), + ).toBeVisible() + for (const tab of TABS) { + await selectTab(page, dict, tab) + await page.waitForLoadState('networkidle') + if (tab === 'annotations') + await expect( + page.getByRole('button', { + name: dict['editor.annotations.add.point'], + }), + ).toBeEnabled() + await expectNoHorizontalOverflow(page, `the ${tab} tab at 1 024 px`) + await expectAccessible(page, `the ${tab} tab (edit)`) + } + }) + + test('axe on every tab of a read-only draft', async ({ page, requests }) => { + test.setTimeout(120_000) + const [editor, reviewer] = [ + await editorActor('fr'), + await makeActor('fr', null, ['sheet_reviewer']), + ] + requests.forbid(reviewer.account.email, reviewer.account.password) + const seed = await seedDraft(editor, { shape: seedShape }) + await openAs(page, reviewer, seed.sheetId) + await expect( + page.getByRole('heading', { level: 1, name: draftTitle(dict) }), + ).toBeVisible() + for (const tab of TABS) { + await selectTab(page, dict, tab) + await page.waitForLoadState('networkidle') + await expectAccessible(page, `the ${tab} tab (read-only)`) + } + }) +}) diff --git a/apps/app/e2e/shell/editor-annotations.spec.ts b/apps/app/e2e/shell/editor-annotations.spec.ts new file mode 100644 index 00000000..e003add7 --- /dev/null +++ b/apps/app/e2e/shell/editor-annotations.spec.ts @@ -0,0 +1,302 @@ +import { fr } from '@/i18n/fr' +import type { Page, TestInfo } from '@playwright/test' +import { expect, expectAccessible, test } from '../support/browser' +import { dropLateReplays, routeToSandbox } from '../support/sandbox' +import { + clientOf, + clickDrawing, + editorActor, + geometryField, + openEditor, + saveDraft, + seedDraft, + selectTab, + serverDocument, + standardShape, +} from '../support/editor' + +// V1-2.6 A3 (contract C7, C8, C21): points, zones and links by clicks and by keyboard, +// move by drag, numeric edits, undo and redo, then the save that carries them. + +const dict = fr + +const isPhone = (info: TestInfo) => info.project.name === 'chromium-375' +const creation = (page: Page) => page.getByTestId('annotation-creation') +const properties = (page: Page) => page.getByTestId('annotation-properties') +const list = (page: Page) => + page.getByRole('list', { name: dict['editor.annotations.list'] }) + +const tool = (page: Page, id: string) => + page.getByRole('button', { + name: dict[`editor.annotations.tool.${id}`], + exact: true, + }) + +interface Names { + fr: string + en: string +} + +/** Fills the creation panel; the category keeps its first choice. */ +async function fillCreation(page: Page, names: Names, opens?: string) { + const panel = creation(page) + await panel.getByLabel(dict['editor.annotations.name_fr']).fill(names.fr) + await panel.getByLabel(dict['editor.annotations.name_en']).fill(names.en) + await panel + .getByLabel(dict['editor.annotations.laterality']) + .selectOption('unpaired') + if (opens) { + await panel.getByLabel(dict['editor.annotations.opens']).selectOption(opens) + } +} + +async function createFromPanel(page: Page) { + await creation(page) + .getByRole('button', { name: dict['editor.annotations.create'] }) + .click() + await expect(creation(page)).toHaveCount(0) +} + +async function openAnnotations(page: Page) { + const actor = await editorActor('fr') + const seed = await seedDraft(actor, { shape: standardShape }) + await openEditor(page, dict, actor, seed.sheetId) + await expect(tool(page, 'point')).toBeEnabled() + return { actor, seed } +} + +test.describe('editor annotations (A3)', () => { + test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) + test.beforeEach(async ({ context }, info) => { + test.skip(isPhone(info), 'editing needs 1 024 px') + await routeToSandbox(context) + }) + test.afterEach(async ({ context }) => { + await dropLateReplays(context) + }) + + test('point, zone and link by clicks; numeric edit; undo and redo; save', async ({ + page, + requests, + }) => { + const { actor, seed } = await openAnnotations(page).then((opened) => { + return opened + }) + requests.forbid(actor.account.email, actor.account.password) + + // A point: the tool, a click in the drawing, the fields the core requires. + await tool(page, 'point').click() + await clickDrawing(page, 300, 300) + await expect(creation(page)).toBeVisible() + await expectAccessible(page, 'the point creation panel') + await fillCreation(page, { fr: 'Point un', en: 'Point one' }) + await creation(page) + .getByLabel(dict['editor.annotations.zone']) + .selectOption('zone-a') + await createFromPanel(page) + await expect(list(page).getByText('Point un')).toBeVisible() + await expect(properties(page)).toBeVisible() + const placed = await geometryField(page, dict, 'cx').inputValue() + expect(Math.abs(Number(placed) - 300)).toBeLessThan(1) + + // A zone: three clicks, then « Fermer le tracé ». + await tool(page, 'zone').click() + for (const [x, y] of [ + [600, 200], + [800, 200], + [700, 400], + ]) + await clickDrawing(page, x, y) + await page + .getByRole('button', { name: dict['editor.annotations.trace_close'] }) + .click() + await fillCreation(page, { fr: 'Zone une', en: 'Zone one' }) + await createFromPanel(page) + await expect(list(page).getByText('Zone une')).toBeVisible() + + // A link to the detail view: the same tracing, the opened view chosen. + await tool(page, 'link').click() + for (const [x, y] of [ + [150, 500], + [350, 500], + [250, 700], + ]) + await clickDrawing(page, x, y) + await page + .getByRole('button', { name: dict['editor.annotations.trace_close'] }) + .click() + await fillCreation(page, { fr: 'Accès un', en: 'Access one' }, 'detail-a') + await createFromPanel(page) + await expect(list(page).getByText('Accès un')).toBeVisible() + await expect( + page.getByRole('button', { + name: dict['editor.annotations.undo'], + exact: true, + }), + ).toBeEnabled() + + // A numeric edit of the point, then undo and redo. + await list(page) + .getByRole('button', { name: /Point un/ }) + .click() + const cx = geometryField(page, dict, 'cx') + await cx.fill('420') + await cx.press('Enter') + await expect(cx).toHaveValue('420') + await page + .getByRole('button', { + name: dict['editor.annotations.undo'], + exact: true, + }) + .click() + await expect(geometryField(page, dict, 'cx')).toHaveValue(placed) + await page + .getByRole('button', { + name: dict['editor.annotations.redo'], + exact: true, + }) + .click() + await expect(geometryField(page, dict, 'cx')).toHaveValue('420') + + await saveDraft(page, dict, seed.revision + 1) + const saved = await serverDocument<{ + annotations: { kind: string; finding_zone_id?: string | null }[] + }>(seed.draftId) + expect(saved.annotations.map((a) => a.kind).sort()).toEqual([ + 'detail_trigger', + 'point', + 'zone', + ]) + expect( + saved.annotations.find((a) => a.kind === 'point')?.finding_zone_id, + ).toBe('zone-a') + }) + + test('a click with jitter never moves; a drag moves by the pointer delta', async ({ + page, + requests, + }) => { + const { actor } = await openAnnotations(page) + requests.forbid(actor.account.email, actor.account.password) + await tool(page, 'point').click() + await clickDrawing(page, 300, 300) + await fillCreation(page, { fr: 'Mobile', en: 'Movable' }) + await createFromPanel(page) + await tool(page, 'select').click() + const cx = geometryField(page, dict, 'cx') + const cy = geometryField(page, dict, 'cy') + const [x0, y0] = [await cx.inputValue(), await cy.inputValue()] + expect(Math.abs(Number(x0) - 300)).toBeLessThan(1) + + // Jitter under the 4 px threshold: pressed, moved by 3 px, released. + const from = await clientOf(page, 300, 300) + await page.mouse.move(from.x, from.y) + await page.mouse.down() + await page.mouse.move(from.x + 2, from.y + 2) + await page.mouse.up() + await expect(cx).toHaveValue(x0) + await expect(cy).toHaveValue(y0) + + // A real drag: the point follows to (400, 360) in drawing units. + const to = await clientOf(page, 400, 360) + await page.mouse.move(from.x, from.y) + await page.mouse.down() + await page.mouse.move((from.x + to.x) / 2, (from.y + to.y) / 2, { + steps: 5, + }) + await page.mouse.move(to.x, to.y, { steps: 5 }) + await page.mouse.up() + await expect(cx).not.toHaveValue(x0) + expect(Math.abs(Number(await cx.inputValue()) - 400)).toBeLessThan(2) + expect(Math.abs(Number(await cy.inputValue()) - 360)).toBeLessThan(2) + await page.keyboard.press('Control+z') + await expect(geometryField(page, dict, 'cx')).toHaveValue(x0) + }) + + test('keyboard only: creation by the add buttons, numeric position, numeric edit', async ({ + page, + requests, + }) => { + const { actor, seed } = await openAnnotations(page) + requests.forbid(actor.account.email, actor.account.password) + + const add = page.getByRole('button', { + name: dict['editor.annotations.add.point'], + }) + await add.focus() + await page.keyboard.press('Enter') + await expect(creation(page)).toBeVisible() + await fillCreation(page, { fr: 'Clavier', en: 'Keyboard' }) + const cx = creation(page).getByLabel(dict['editor.annotations.geometry.cx']) + await cx.fill('250') + await cx.press('Enter') + await expect(cx).toHaveValue('250') + await creation(page) + .getByRole('button', { name: dict['editor.annotations.create'] }) + .focus() + await page.keyboard.press('Enter') + await expect(creation(page)).toHaveCount(0) + await expect(list(page).getByText('Clavier')).toBeVisible() + await expect(geometryField(page, dict, 'cx')).toHaveValue('250') + + const cy = geometryField(page, dict, 'cy') + await cy.fill('510.5') + await cy.press('Enter') + await expect(cy).toHaveValue('510.5') + + // A polygon edit: the zone added by keyboard, a vertex typed. + await page + .getByRole('button', { name: dict['editor.annotations.add.zone'] }) + .focus() + await page.keyboard.press('Enter') + await fillCreation(page, { fr: 'Zone clavier', en: 'Keyboard zone' }) + await creation(page) + .getByRole('button', { name: dict['editor.annotations.create'] }) + .focus() + await page.keyboard.press('Enter') + await expect(list(page).getByText('Zone clavier')).toBeVisible() + const vertexX = page.getByLabel( + dict['editor.annotations.geometry.vertex_x'].replace('{n}', '1'), + ) + const before = Number(await vertexX.inputValue()) + await vertexX.fill(String(before + 10)) + await vertexX.press('Enter') + await expect(vertexX).toHaveValue(String(before + 10)) + await saveDraft(page, dict, seed.revision + 1) + }) + + test('the properties of an annotation: review state and deletion', async ({ + page, + requests, + }) => { + const { actor, seed } = await openAnnotations(page) + requests.forbid(actor.account.email, actor.account.password) + await tool(page, 'point').click() + await clickDrawing(page, 500, 400) + await fillCreation(page, { fr: 'A relire', en: 'To review' }) + await createFromPanel(page) + + await properties(page) + .getByRole('button', { name: dict['editor.annotations.mark_reviewed'] }) + .click() + await expect( + properties(page).getByRole('button', { + name: dict['editor.annotations.to_confirm'], + }), + ).toBeVisible() + await properties(page) + .getByRole('button', { name: dict['editor.action.delete'] }) + .click() + await page + .getByRole('dialog') + .getByRole('button', { name: dict['editor.delete.confirm'] }) + .click() + await expect(list(page)).toHaveCount(0) + await expect( + page.getByText(dict['editor.annotations.list_empty']), + ).toBeVisible() + await selectTab(page, dict, 'verification') + await expectAccessible(page, 'the verification tab after a deletion') + expect(seed.draftId).toBeTruthy() + }) +}) diff --git a/apps/app/e2e/shell/editor-drawings.spec.ts b/apps/app/e2e/shell/editor-drawings.spec.ts new file mode 100644 index 00000000..999f9248 --- /dev/null +++ b/apps/app/e2e/shell/editor-drawings.spec.ts @@ -0,0 +1,174 @@ +import { fr } from '@/i18n/fr' +import type { Page, TestInfo } from '@playwright/test' +import { expect, expectAccessible, test } from '../support/browser' +import { dropLateReplays, routeToSandbox } from '../support/sandbox' +import { + DRAWING_SVG, + editorActor, + openEditor, + seedDraft, + selectTab, + standardShape, + serverDocument, + saveDraft, +} from '../support/editor' + +// V1-2.6 A2 (contract C16, C20): a drawing imported into a view. A hostile file is +// refused, an Inkscape export is cleaned after a preview, a valid file is attached, a +// detail view shows the drawing by crop. Both upload outcomes (the object is new, or the +// same bytes are already stored) end on the same screen. + +const dict = fr + +const INKSCAPE_SVG = + '' + + '' + + '' + + '' + + '' + +const HOSTILE_SVG = + '' + + '' + +const file = (svg: string, name = 'dessin.svg') => ({ + name, + mimeType: 'image/svg+xml', + buffer: Buffer.from(svg), +}) + +const isPhone = (info: TestInfo) => info.project.name === 'chromium-375' + +const mainFile = (page: Page) => page.getByTestId('view-main-file') +const mainDrawing = (page: Page) => page.getByTestId('view-main-drawing') + +test.describe('editor drawings (A2)', () => { + test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) + test.beforeEach(async ({ context }, info) => { + test.skip(isPhone(info), 'editing needs 1 024 px') + await routeToSandbox(context) + }) + test.afterEach(async ({ context }) => { + await dropLateReplays(context) + }) + + test('hostile file refused, nothing added, no cleaning box', async ({ + page, + requests, + }) => { + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedDraft(actor, { drawing: null }) + await openEditor(page, dict, actor, seed.sheetId) + await selectTab(page, dict, 'views') + await expect( + mainDrawing(page).getByText(dict['editor.views.drawing.none']), + ).toBeVisible() + + await mainFile(page).setInputFiles(file(HOSTILE_SVG, 'hostile.svg')) + await expect( + page.getByText(dict['editor.upload.err.svg_active_content']), + ).toBeVisible() + await expect( + page.getByRole('dialog', { name: dict['editor.cleaning.title'] }), + ).toHaveCount(0) + await expect( + mainDrawing(page).getByText(dict['editor.views.drawing.none']), + ).toBeVisible() + await expect(page.getByText(dict['editor.upload.done'])).toHaveCount(0) + await expectAccessible(page, 'the refused drawing') + }) + + test('Inkscape export: preview, cancel adds nothing, confirm cleans and attaches', async ({ + page, + requests, + }) => { + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedDraft(actor, { drawing: null }) + await openEditor(page, dict, actor, seed.sheetId) + await selectTab(page, dict, 'views') + + await mainFile(page).setInputFiles(file(INKSCAPE_SVG, 'inkscape.svg')) + const dialog = page.getByRole('dialog', { + name: dict['editor.cleaning.title'], + }) + await expect(dialog).toBeVisible() + await expect( + dialog.getByTestId('cleaning-preview').locator('svg'), + ).toBeVisible() + await expect(dialog.getByText(dict['editor.cleaning.style'])).toBeVisible() + await expectAccessible(page, 'the cleaning box') + await dialog + .getByRole('button', { name: dict['editor.cleaning.cancel'] }) + .click() + await expect(dialog).toBeHidden() + await expect( + mainDrawing(page).getByText(dict['editor.views.drawing.none']), + ).toBeVisible() + + await mainFile(page).setInputFiles(file(INKSCAPE_SVG, 'inkscape.svg')) + await dialog + .getByRole('button', { name: dict['editor.cleaning.confirm'] }) + .click() + await expect(page.getByText(dict['editor.upload.done'])).toBeVisible() + await expect( + mainDrawing(page).getByText(dict['editor.views.drawing.ok']), + ).toBeVisible() + await saveDraft(page, dict, seed.revision + 1) + const saved = await serverDocument<{ + views: { svg_asset_id: string | null }[] + }>(seed.draftId) + expect(saved.views[0].svg_asset_id).not.toBeNull() + }) + + test('valid file attached; a detail view shows it by crop; the same bytes attach twice', async ({ + page, + requests, + }) => { + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedDraft(actor, { drawing: null, shape: standardShape }) + await openEditor(page, dict, actor, seed.sheetId) + await selectTab(page, dict, 'views') + + await mainFile(page).setInputFiles(file(DRAWING_SVG, 'valide.svg')) + await expect(page.getByText(dict['editor.upload.done'])).toBeVisible() + await expect( + mainDrawing(page).getByText(dict['editor.views.drawing.ok']), + ).toBeVisible() + + // The detail view crops the main drawing: its own drawing line says it is inherited. + const detail = page.getByRole('listitem', { name: 'Détail A' }) + await expect( + detail.getByText(dict['editor.views.drawing.inherited']), + ).toBeVisible() + + // The same bytes attached to the detail view: the stored object already exists. + await detail + .getByTestId('view-detail-a-file') + .setInputFiles(file(DRAWING_SVG)) + await expect( + detail.getByText(dict['editor.views.drawing.ok']), + ).toBeVisible() + await detail + .getByRole('button', { name: dict['editor.views.drawing.use_parent'] }) + .click() + await expect( + detail.getByText(dict['editor.views.drawing.inherited']), + ).toBeVisible() + + await selectTab(page, dict, 'annotations') + await page + .getByRole('group', { name: dict['editor.annotations.views'] }) + .getByRole('button', { name: 'Détail A' }) + .click() + await expect( + page.getByTestId('annotation-canvas-drawing').locator('svg').first(), + ).toBeVisible() + await expect(page.getByTestId('annotation-overlay')).toBeAttached() + }) +}) diff --git a/apps/app/e2e/shell/editor-equine.spec.ts b/apps/app/e2e/shell/editor-equine.spec.ts new file mode 100644 index 00000000..bfbb811c --- /dev/null +++ b/apps/app/e2e/shell/editor-equine.spec.ts @@ -0,0 +1,375 @@ +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { fr } from '@/i18n/fr' +import type { Locator, Page, TestInfo } from '@playwright/test' +import { + rpc, + sql, + stack, +} from '../../../../packages/supabase/tests/sandbox/stack' +import { stepUpAdmin } from '../support/admin' +import { expect, expectAccessible, test } from '../support/browser' +import { dropLateReplays, routeToSandbox } from '../support/sandbox' +import { + editorActor, + openEditor, + seedDraft, + selectTab, + serverDocument, + standardShape, + toolButton, + type Actor, +} from '../support/editor' +import { signIn } from '../support/shell' + +// V1-2.6 equine working copy and commit latency (contract C31, plan « Edge cases »): the +// historical equine sheet opened as a working copy in the editor (a copy left active by +// an earlier run is set aside first, as sheets-concurrency.sandbox.ts does), the commit +// latency measured on it and on a synthetic document near 2 MiB. The numbers are +// reported (console, test annotations); the budget is 500 ms per commit on the equine copy. + +const dict = fr +const HISTORICAL = '503dc301-a8b1-50d4-9e44-0919b2fc2916' +const REPO = join(__dirname, '../../../..') +const BUDGET_MS = 500 +const SAMPLES = 15 + +const isPhone = (info: TestInfo) => info.project.name === 'chromium-375' + +interface Sample { + handler: number + paint: number +} + +/** Time from the Enter or click that commits to the end of its task, and to the 2nd frame. */ +async function startProbe(page: Page) { + await page.evaluate(() => { + const w = window as unknown as { __latency?: Sample[] } + if (w.__latency) { + w.__latency.length = 0 + return + } + const samples: Sample[] = [] + w.__latency = samples + const mark = (event: Event) => { + const start = performance.now() + setTimeout(() => { + const handler = performance.now() - start + requestAnimationFrame(() => + requestAnimationFrame(() => + samples.push({ handler, paint: performance.now() - start }), + ), + ) + }, 0) + void event + } + window.addEventListener( + 'keydown', + (e) => e.key === 'Enter' && mark(e), + true, + ) + window.addEventListener('click', mark, true) + }) +} + +function takeSamples(page: Page): Promise { + return page.evaluate(() => { + const w = window as unknown as { __latency: Sample[] } + return w.__latency.splice(0) + }) +} + +function stats(values: number[]) { + const sorted = [...values].sort((a, b) => a - b) + const at = (share: number) => sorted[Math.floor(share * (sorted.length - 1))] + return { + n: sorted.length, + median: Math.round(at(0.5)), + p95: Math.round(at(0.95)), + max: Math.round(sorted[sorted.length - 1]), + } +} + +function report(label: string, samples: Sample[]) { + const line = { + label, + handler: stats(samples.map((s) => s.handler)), + paint: stats(samples.map((s) => s.paint)), + } + console.log(`LATENCY ${JSON.stringify(line)}`) + test.info().annotations.push({ + type: 'latency', + description: JSON.stringify(line), + }) + return line +} + +async function commitName(field: Locator, round: number) { + await field.fill(`Nom mesuré ${round}`) + await field.press('Enter') +} + +/** SAMPLES commits of the sheet's French name, one probe entry each (after a warm-up). */ +async function measureRenames(page: Page, label: string) { + await selectTab(page, dict, 'general') + const field = page.getByLabel(dict['editor.general.name_fr'], { exact: true }) + await startProbe(page) + await commitName(field, 0) + await takeSamples(page) + for (let round = 1; round <= SAMPLES; round++) await commitName(field, round) + await expect(field).toHaveValue(`Nom mesuré ${SAMPLES}`) + await page.waitForTimeout(200) + return report(label, await takeSamples(page)) +} + +async function measureAdditions(page: Page, label: string) { + await selectTab(page, dict, 'general') + await startProbe(page) + for (let round = 0; round <= SAMPLES; round++) { + await page.locator('#category-new-fr').fill(`Catégorie ${round}`) + await page.locator('#category-new-en').fill(`Category ${round}`) + await page.locator('#category-new-fr').press('Tab') + await page + .getByRole('button', { name: dict['editor.general.category_add'] }) + .click() + await expect(page.locator('#category-new-fr')).toHaveValue('') + } + await page.waitForTimeout(200) + // The first round is the warm-up. + return report(label, (await takeSamples(page)).slice(1)) +} + +async function confirmHistoricalDrawing() { + const row = ( + await sql(`select id || ' ' || sha256 || ' ' || (uploaded_at is null)::text + from public.anatomical_sheet_assets where sheet_id = '${HISTORICAL}'`) + ).split(' ') + if (row[2] !== 'true') return + const bytes = await readFile( + join(REPO, 'supabase/seed/anatomical-sheets/equine/draft/assets/horse.svg'), + ) + const stored = await fetch( + `${stack.storageUrl}/object/anatomical-sheet-assets/${row[1]}.svg`, + { + method: 'POST', + headers: { + Authorization: `Bearer ${stack.serviceKey}`, + 'Content-Type': 'image/svg+xml', + }, + body: new Uint8Array(bytes), + }, + ) + await stored.arrayBuffer() + const confirmed = await rpc( + 'confirm_sheet_asset_upload', + { asset_id: row[0] }, + stack.serviceKey, + ) + expect(confirmed.status).toBe(200) +} + +/** Finding nodes with long descriptions, up to about 1.9 MiB of document text. */ +function nearCapShape(document: Record) { + standardShape(document) + const filler = (letter: string) => letter.repeat(260) + const zones = [] + for (let z = 0; z < 20; z++) { + const categories = [] + for (let c = 0; c < 10; c++) { + const children = [] + for (let n = 0; n < 12; n++) { + children.push({ + id: `node-${z}-${c}-${n}`, + name: { fr: `Constat ${z}.${c}.${n}`, en: `Finding ${z}.${c}.${n}` }, + description: { fr: filler('a'), en: filler('b') }, + requires_vet_referral: false, + reference_ids: [], + review_status: 'reviewed', + children: [], + }) + } + categories.push({ + id: `fcat-${z}-${c}`, + kind: 'dysfunction', + name: { fr: `Catégorie ${z}.${c}`, en: `Category ${z}.${c}` }, + description: {}, + reference_ids: [], + review_status: 'reviewed', + children, + }) + } + zones.push({ + id: `zone-${z}`, + name: { fr: `Zone ${z}`, en: `Zone ${z}` }, + categories, + }) + } + document.finding_zones = zones +} + +test.describe.configure({ mode: 'serial' }) + +test.describe('equine working copy and commit latency', () => { + test.use({ locale: 'fr-FR', actionTimeout: 30_000 }) + let actor: Actor + let setAside: string[] = [] + let copyId = '' + + test.beforeAll(async () => { + actor = await editorActor('fr') + await confirmHistoricalDrawing() + // A copy left active by an earlier run is set aside and put back after. + setAside = ( + await sql(`update public.anatomical_sheets set status = 'archived', archived_at = now() + where status = 'active' and private.is_historical_working_copy(id) returning id`) + ) + .split('\n') + .filter(Boolean) + }) + + test.afterAll(async () => { + // Archived as postgres, like the set-aside below: the sheet is a fixture of this run. + if (copyId) + await sql(`update public.anatomical_sheets set status = 'archived', archived_at = now() + where id = '${copyId}'`) + if (setAside.length > 0) + await sql(`update public.anatomical_sheets set status = 'active', archived_at = null + where id in (${setAside.map((id) => `'${id}'`).join(', ')})`) + }) + + test.beforeEach(async ({ context }, info) => { + test.skip(isPhone(info), 'editing needs 1 024 px') + await routeToSandbox(context) + }) + test.afterEach(async ({ context }) => { + await dropLateReplays(context) + }) + + test('the historical equine sheet opens as a working copy in the editor', async ({ + page, + requests, + }) => { + test.setTimeout(120_000) + requests.forbid(actor.account.email, actor.account.password) + const errors: string[] = [] + page.on('pageerror', (error) => errors.push(error.message)) + await signIn(page, actor.account, dict) + await page.goto('/app/admin') + await stepUpAdmin(page, dict, actor.secret) + await page.goto(`/app/admin/sheets/${HISTORICAL}`) + await page + .getByRole('button', { name: dict['admin.working_copy.create'] }) + .first() + .click() + const dialog = page.getByRole('dialog', { + name: dict['admin.working_copy.create'], + }) + // The proposed slug is taken by the copies of earlier runs: one of its own. + await dialog + .getByLabel(dict['admin.sheet_form.slug']) + .fill(`e2e-copie-${actor.account.id.slice(0, 8)}`) + await dialog + .getByRole('button', { name: dict['admin.working_copy.confirm'] }) + .click() + await expect(page).toHaveURL(/\/app\/admin\/sheets\/[0-9a-f-]{36}\/draft$/) + copyId = new URL(page.url()).pathname.split('/')[4] + await expect( + page.getByText(dict['admin.badge.working_copy'], { exact: true }), + ).toBeVisible() + await expect(toolButton(page, dict, 'point')).toBeEnabled() + const rows = page + .getByRole('list', { name: dict['editor.annotations.list'] }) + .getByRole('listitem') + await expect(rows.first()).toBeVisible() + expect(await rows.count()).toBeGreaterThan(5) + await expectAccessible(page, 'the equine working copy') + // Every tab opens on the real equine data without a page error (the findings tree + // once blanked the page on nodes that omit their defaulted fields). + await selectTab(page, dict, 'findings') + await expect(page.getByTestId('finding-item').first()).toBeVisible() + for (const tab of [ + 'general', + 'views', + 'references', + 'vertebrae', + 'verification', + ]) + await selectTab(page, dict, tab) + expect(errors, 'page errors on the equine copy').toEqual([]) + }) + + test('commit latency on the equine copy', async ({ page, requests }) => { + test.setTimeout(180_000) + expect(copyId).not.toBe('') + requests.forbid(actor.account.email, actor.account.password) + await signIn(page, actor.account, dict) + await page.goto('/app/admin') + await stepUpAdmin(page, dict, actor.secret) + await page.goto(`/app/admin/sheets/${copyId}/draft`) + await expect(toolButton(page, dict, 'point')).toBeEnabled() + + const renames = await measureRenames(page, 'equine: rename (update)') + const additions = await measureAdditions( + page, + 'equine: add category (insert)', + ) + // A geometry edit: the first annotation's centre, through the geometry group. + await selectTab(page, dict, 'annotations') + await page + .getByRole('list', { name: dict['editor.annotations.list'] }) + .getByRole('button') + .first() + .click() + const cx = page.getByLabel(dict['editor.annotations.geometry.cx'], { + exact: true, + }) + const base = Number(await cx.inputValue()) + await startProbe(page) + for (let round = 0; round <= SAMPLES; round++) { + await cx.fill(String(base + ((round % 2) + 1) * 0.5)) + await cx.press('Enter') + } + await page.waitForTimeout(200) + const moves = report( + 'equine: geometry edit', + (await takeSamples(page)).slice(1), + ) + for (const line of [renames, additions, moves]) + expect(line.handler.max, line.handler.max + ' ms').toBeLessThan(BUDGET_MS) + }) + + test('commit latency on a synthetic document near 2 MiB', async ({ + page, + requests, + }) => { + test.setTimeout(180_000) + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedDraft(actor, { shape: nearCapShape }) + const bytes = Number( + await sql( + `select octet_length(content::text) from public.anatomical_sheet_versions where id = '${seed.draftId}'`, + ), + ) + console.log(`SYNTHETIC document ${bytes} bytes`) + expect(bytes).toBeGreaterThan(1_800_000) + expect(bytes).toBeLessThanOrEqual(2_097_152) + expect( + Object.keys(await serverDocument(seed.draftId)).length, + ).toBeGreaterThan(5) + await openEditor(page, dict, actor, seed.sheetId) + const renames = await measureRenames( + page, + `synthetic ${bytes} B: rename (update)`, + ) + const additions = await measureAdditions( + page, + `synthetic ${bytes} B: add category (insert)`, + ) + test.info().annotations.push({ + type: 'synthetic-bytes', + description: String(bytes), + }) + expect(renames.handler.n).toBeGreaterThan(0) + expect(additions.handler.n).toBeGreaterThan(0) + }) +}) diff --git a/apps/app/e2e/shell/editor-geometry.spec.ts b/apps/app/e2e/shell/editor-geometry.spec.ts new file mode 100644 index 00000000..cd0f3429 --- /dev/null +++ b/apps/app/e2e/shell/editor-geometry.spec.ts @@ -0,0 +1,303 @@ +import { fr } from '@/i18n/fr' +import type { Page, TestInfo } from '@playwright/test' +import { expect, expectAccessible, test } from '../support/browser' +import { dropLateReplays, routeToSandbox } from '../support/sandbox' +import { + clickDrawing, + clientOf, + editorActor, + geometryField, + openEditor, + pointOf, + seedDraft, + selectTab, + shapeWith, + standardShape, +} from '../support/editor' + +// V1-2.6 geometry and adversarial cases (contract C7, C8, C21; owner 2026-11-04): a click +// near the edge of a frame (the corrected position shown, confirmed and cancelled), a +// point inherited out of its frame repaired through the geometry group, a crop change +// refused when it would invalidate a point, an unmeasured view with its tools disabled, +// and the touch path (touch-action, pointer capture) in a real browser. + +const dict = fr + +const isPhone = (info: TestInfo) => info.project.name === 'chromium-375' +const creation = (page: Page) => page.getByTestId('annotation-creation') +const notice = (page: Page) => page.getByTestId('correction-notice') +const list = (page: Page) => + page.getByRole('list', { name: dict['editor.annotations.list'] }) + +const tool = (page: Page, id: string) => + page.getByRole('button', { + name: dict[`editor.annotations.tool.${id}`], + exact: true, + }) + +const viewChip = (page: Page, name: string) => + page + .getByRole('group', { name: dict['editor.annotations.views'] }) + .getByRole('button', { name }) + +/** The x and y a correction notice proposes, read from its sentence. */ +async function proposed(page: Page): Promise<{ x: string; y: string }> { + const text = (await notice(page).innerText()).replace(/\s+/g, ' ') + const found = /x = (-?\d+(?:\.\d+)?), y = (-?\d+(?:\.\d+)?)/.exec(text) + if (!found) throw new Error('no proposed position in the notice') + return { x: found[1], y: found[2] } +} + +async function fillNames(page: Page, fr: string, en: string) { + await creation(page).getByLabel(dict['editor.annotations.name_fr']).fill(fr) + await creation(page).getByLabel(dict['editor.annotations.name_en']).fill(en) + await creation(page) + .getByLabel(dict['editor.annotations.laterality']) + .selectOption('unpaired') +} + +async function open(page: Page, ...annotations: unknown[]) { + const actor = await editorActor('fr') + const seed = await seedDraft(actor, { shape: shapeWith(...annotations) }) + await openEditor(page, dict, actor, seed.sheetId) + await expect(tool(page, 'point')).toBeEnabled() + return { actor, seed } +} + +test.describe('editor geometry (adversarial)', () => { + test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) + test.beforeEach(async ({ context }, info) => { + test.skip(isPhone(info), 'editing needs 1 024 px') + await routeToSandbox(context) + }) + test.afterEach(async ({ context }) => { + await dropLateReplays(context) + }) + + test('a click near the edge: corrected position shown, cancelled, then confirmed', async ({ + page, + requests, + }) => { + const { actor } = await open(page) + requests.forbid(actor.account.email, actor.account.password) + await tool(page, 'point').click() + await clickDrawing(page, 3, 3) + await fillNames(page, 'Bord', 'Edge') + await creation(page) + .getByRole('button', { name: dict['editor.annotations.create'] }) + .click() + await expect(notice(page)).toBeVisible() + await expect(page.getByTestId('overlay-click-cross')).toBeAttached() + const shown = await proposed(page) + await expect(list(page)).toHaveCount(0) + + // Cancelled: the notice goes, nothing was inserted. + await notice(page) + .getByRole('button', { + name: dict['editor.annotations.correction_cancel'], + }) + .click() + await expect(notice(page)).toHaveCount(0) + await expect(list(page)).toHaveCount(0) + + // Confirmed: the same attempt again, the corrected position inserted. + await creation(page) + .getByRole('button', { name: dict['editor.annotations.create'] }) + .click() + await expect(notice(page)).toBeVisible() + expect(await proposed(page)).toEqual(shown) + await notice(page) + .getByRole('button', { name: dict['editor.annotations.correction_use'] }) + .click() + await expect(creation(page)).toHaveCount(0) + await expect(list(page).getByText('Bord')).toBeVisible() + await expect(geometryField(page, dict, 'cx')).toHaveValue(shown.x) + await expect(geometryField(page, dict, 'cy')).toHaveValue(shown.y) + }) + + test('a click near the edge of a detail crop is corrected inside the crop', async ({ + page, + requests, + }) => { + const { actor } = await open(page) + requests.forbid(actor.account.email, actor.account.password) + await viewChip(page, 'Détail A').click() + await tool(page, 'point').click() + await clickDrawing(page, 102, 102) + await fillNames(page, 'Bord détail', 'Detail edge') + await creation(page) + .getByRole('button', { name: dict['editor.annotations.create'] }) + .click() + await expect(notice(page)).toBeVisible() + const shown = await proposed(page) + expect(Number(shown.x)).toBeGreaterThan(100) + expect(Number(shown.y)).toBeGreaterThan(100) + await notice(page) + .getByRole('button', { name: dict['editor.annotations.correction_use'] }) + .click() + await expect(list(page).getByText('Bord détail')).toBeVisible() + }) + + test('a point inherited out of its frame is repaired through the geometry group', async ({ + page, + requests, + }) => { + const { actor } = await open( + page, + pointOf('out', 'detail-a', { cx: 110, cy: 110, r: 30 }, 'Hors cadre'), + ) + requests.forbid(actor.account.email, actor.account.password) + await viewChip(page, 'Détail A').click() + await list(page) + .getByRole('button', { name: /Hors cadre/ }) + .click() + const issues = page.getByTestId('annotation-geometry-issues') + await expect(issues).toBeVisible() + const verification = page.getByRole('tab', { + name: dict['editor.tab.verification'], + }) + const errorsBefore = Number( + (await verification.innerText()).replace(/\D/g, ''), + ) + expect(errorsBefore).toBeGreaterThan(0) + + const cx = geometryField(page, dict, 'cx') + await cx.fill('200') + await cx.press('Enter') + const cy = geometryField(page, dict, 'cy') + await cy.fill('200') + await cy.press('Enter') + await expect(issues).toHaveCount(0) + const after = (await verification.innerText()).replace(/\D/g, '') + expect(Number(after || 0)).toBeLessThan(errorsBefore) + }) + + test('a crop change that would invalidate a point is refused, then reverted', async ({ + page, + requests, + }) => { + const { actor } = await open( + page, + pointOf( + 'inside', + 'detail-a', + { cx: 350, cy: 300, r: 20 }, + 'Dans le cadre', + ), + ) + requests.forbid(actor.account.email, actor.account.password) + await selectTab(page, dict, 'views') + const detail = page.getByRole('listitem', { name: 'Détail A' }) + await detail + .getByRole('button', { name: dict['editor.views.crop.toggle'] }) + .click() + const width = detail.getByLabel(dict['editor.views.crop.width'], { + exact: true, + }) + await expect(width).toHaveValue('300') + await width.fill('100') + await width.press('Enter') + const refusal = detail.getByRole('alert') + await expect( + refusal.getByText(dict['editor.views.crop.not_applied']), + ).toBeVisible() + await expect(refusal).toContainText('Dans le cadre') + await refusal + .getByRole('button', { name: dict['editor.views.crop.revert'] }) + .click() + await expect(width).toHaveValue('300') + }) + + test('an unmeasured view: drawing tools and add buttons disabled, the hint shown', async ({ + page, + requests, + }) => { + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedDraft(actor, { drawing: null, shape: standardShape }) + await openEditor(page, dict, actor, seed.sheetId) + await expect( + page.getByText(dict['editor.annotations.unmeasured.hint'], { + exact: false, + }), + ).toBeVisible() + for (const id of ['point', 'zone', 'link']) + await expect(tool(page, id)).toBeDisabled() + for (const kind of ['point', 'zone', 'detail_trigger']) + await expect( + page.getByRole('button', { + name: dict[`editor.annotations.add.${kind}`], + }), + ).toBeDisabled() + await expect(tool(page, 'select')).toBeEnabled() + await expectAccessible(page, 'an unmeasured view with its tools disabled') + }) +}) + +test.describe('editor touch path (real browser)', () => { + test.use({ + locale: 'fr-FR', + actionTimeout: 15_000, + hasTouch: true, + viewport: { width: 1280, height: 800 }, + }) + test.beforeEach(async ({ context }, info) => { + test.skip( + isPhone(info), + 'a 1 024 px touch screen runs on the desktop project', + ) + await routeToSandbox(context) + }) + test.afterEach(async ({ context }) => { + await dropLateReplays(context) + }) + + test('touch-action follows the tool; a touch drag moves the selected marker', async ({ + page, + context, + requests, + }) => { + const { actor } = await open( + page, + pointOf('moving', 'main', { cx: 500, cy: 400, r: 60 }, 'Tactile'), + ) + requests.forbid(actor.account.email, actor.account.password) + const box = page.getByTestId('annotation-canvas') + const touchAction = () => + box.evaluate((el) => getComputedStyle(el).touchAction) + expect(await touchAction()).toBe('pan-x pan-y') + await tool(page, 'point').click() + expect(await touchAction()).toBe('none') + await tool(page, 'select').click() + expect(await touchAction()).toBe('pan-x pan-y') + + // A movable selection needs the touch itself: the browser reads touch-action at + // touchstart, so a drag of the selected marker must not be left to the pan. + await list(page) + .getByRole('button', { name: /Tactile/ }) + .click() + expect(await touchAction()).toBe('none') + const cx = geometryField(page, dict, 'cx') + await expect(cx).toHaveValue('500') + const from = await clientOf(page, 500, 400) + const to = await clientOf(page, 620, 400) + const cdp = await context.newCDPSession(page) + const touch = ( + type: 'touchStart' | 'touchMove' | 'touchEnd', + at: { x: number; y: number } | null, + ) => + cdp.send('Input.dispatchTouchEvent', { + type, + touchPoints: at ? [{ x: at.x, y: at.y }] : [], + }) + await touch('touchStart', from) + for (let step = 1; step <= 8; step++) + await touch('touchMove', { + x: from.x + ((to.x - from.x) * step) / 8, + y: from.y, + }) + await touch('touchEnd', null) + await expect(cx).not.toHaveValue('500') + expect(Math.abs(Number(await cx.inputValue()) - 620)).toBeLessThan(3) + }) +}) diff --git a/apps/app/e2e/shell/editor-journey.spec.ts b/apps/app/e2e/shell/editor-journey.spec.ts new file mode 100644 index 00000000..6c84579e --- /dev/null +++ b/apps/app/e2e/shell/editor-journey.spec.ts @@ -0,0 +1,376 @@ +import { fr } from '@/i18n/fr' +import type { Locator, Page, TestInfo } from '@playwright/test' +import { sql } from '../../../../packages/supabase/tests/sandbox/stack' +import { stepUpAdmin } from '../support/admin' +import { expect, expectAccessible, test } from '../support/browser' +import { dropLateReplays, routeToSandbox } from '../support/sandbox' +import { + annotationList, + clickDrawing, + createFromPanel, + creationPanel, + DRAWING_SVG, + editorActor, + fillCreation, + geometryField, + saveDraft, + secondSession, + selectTab, + toolButton, + openDraft, +} from '../support/editor' +import { signIn } from '../support/shell' + +// V1-2.6 journey (contract C26 to C30; the steps of docs/development/V1-2-6_OWNER_TRIAL.md +// §4, with two editor accounts): a non-equine sheet created from the administration, +// a drawing, a detail view, findings, categories, points, zones and a link, the save, +// a reload with the beforeunload dialog and the recovery offer, a conflict with the +// other account, the submission and the round read back in SQL. + +const dict = fr + +const isPhone = (info: TestInfo) => info.project.name === 'chromium-375' +const main = (page: Page) => page.getByRole('main') + +async function commitText(field: Locator, value: string) { + await field.fill(value) + await field.press('Enter') +} + +const clickDialog = (dialog: Locator, name: string) => + dialog.getByRole('button', { name, exact: true }).click() + +const clickButton = (page: Page, name: string) => + page.getByRole('button', { name, exact: true }).click() + +async function createSheetFromAdmin(page: Page, tag: string): Promise { + await page + .locator('section[aria-labelledby="admin-sheets-title"]') + .getByRole('link', { name: dict['admin.home.all_sheets'] }) + .click() + await main(page).getByRole('link', { name: dict['admin.sheets.new'] }).click() + await page.getByLabel(dict['admin.sheet_form.name_fr']).fill(`Chien ${tag}`) + await page.getByLabel(dict['admin.sheet_form.name_en']).fill(`Dog ${tag}`) + // The form is briefly replaced while the page re-reads the account's rights: a + // choice made in that instant is lost, so the species is chosen last. + const species = page.getByLabel(dict['admin.sheet_form.species'], { + exact: true, + }) + await expect(species.locator('option[value="canine"]')).toHaveCount(1) + await species.selectOption('canine') + await expect(species).toHaveValue('canine') + await page + .getByRole('button', { name: dict['admin.sheet_form.submit'] }) + .click() + // The creation opens the new draft in the editor directly (the guide's 4.1 says the + // sheet « apparaît » and is « ouvrable dans l'éditeur »: no overview step). + await expect(page).toHaveURL(/\/app\/admin\/sheets\/[0-9a-f-]{36}\/draft$/) + const id = new URL(page.url()).pathname.split('/')[4] ?? '' + await expect( + page.getByRole('heading', { level: 1, name: 'Brouillon, version 1' }), + ).toBeVisible() + return id +} + +async function importDrawing(page: Page) { + await selectTab(page, dict, 'views') + await page.getByTestId('view-view-main-file').setInputFiles({ + name: 'valide.svg', + mimeType: 'image/svg+xml', + buffer: Buffer.from(DRAWING_SVG), + }) + await expect(page.getByText(dict['editor.upload.done'])).toBeVisible() + await page.locator('#view-new-fr').fill('Détail essai') + await page.locator('#view-new-en').fill('Trial detail') + const crop = { min_x: '100', min_y: '100', width: '300', height: '240' } + for (const [key, value] of Object.entries(crop)) + await page.locator(`#view-new-crop-${key}`).fill(value) + await clickButton(page, dict['editor.views.add']) + await expect( + page.getByRole('listitem', { name: 'Détail essai' }), + ).toBeVisible() +} + +async function createFindings(page: Page) { + await selectTab(page, dict, 'general') + await page.locator('#category-new-fr').fill('Catégorie essai') + await page.locator('#category-new-en').fill('Trial category') + await clickButton(page, dict['editor.general.category_add']) + await selectTab(page, dict, 'findings') + const create = () => clickButton(page, dict['editor.findings.create']) + const names = async (frName: string, enName: string) => { + await page.locator('#finding-new-name-fr').fill(frName) + await page.locator('#finding-new-name-en').fill(enName) + } + await clickButton(page, dict['editor.findings.add_zone']) + await names('Zone essai', 'Trial zone') + await create() + await clickButton(page, dict['editor.findings.add_category']) + await page.locator('#finding-new-kind').selectOption('dysfunction') + await names('Dysfonction essai', 'Trial dysfunction') + await create() + await clickButton(page, dict['editor.findings.add_node']) + await names('Constat essai', 'Trial finding') + await create() + await expect( + page.getByTestId('finding-item').filter({ hasText: 'Constat essai' }), + ).toBeVisible() +} + +async function createAnnotations(page: Page) { + await selectTab(page, dict, 'annotations') + const trace = async (points: number[][]) => { + for (const [x, y] of points) await clickDrawing(page, x, y) + await clickButton(page, dict['editor.annotations.trace_close']) + } + await toolButton(page, dict, 'point').click() + await clickDrawing(page, 300, 300) + await fillCreation(page, dict, { fr: 'Point essai', en: 'Trial point' }) + await creationPanel(page) + .getByLabel(dict['editor.annotations.zone']) + .selectOption({ label: 'Zone essai' }) + await createFromPanel(page, dict) + await toolButton(page, dict, 'zone').click() + await trace([ + [600, 200], + [800, 200], + [700, 400], + ]) + await fillCreation(page, dict, { fr: 'Zone dessinée', en: 'Drawn zone' }) + await creationPanel(page) + .getByLabel(dict['editor.annotations.zone']) + .selectOption({ label: 'Zone essai' }) + await createFromPanel(page, dict) + await toolButton(page, dict, 'link').click() + await trace([ + [150, 500], + [350, 500], + [250, 700], + ]) + await fillCreation(page, dict, { fr: 'Accès essai', en: 'Trial access' }) + await creationPanel(page) + .getByLabel(dict['editor.annotations.opens']) + .selectOption({ label: 'Détail essai' }) + await createFromPanel(page, dict) +} + +/** Guide 4.4: a click near the edge proposes a position; a far value is refused. */ +async function repairGeometry(page: Page) { + await toolButton(page, dict, 'point').click() + await clickDrawing(page, 3, 3) + await fillCreation(page, dict, { fr: 'Point de bord', en: 'Edge point' }) + await creationPanel(page) + .getByRole('button', { name: dict['editor.annotations.create'] }) + .click() + const correction = page.getByTestId('correction-notice') + await expect(correction).toBeVisible() + await correction + .getByRole('button', { name: dict['editor.annotations.correction_use'] }) + .click() + await expect( + annotationList(page, dict).getByText('Point de bord'), + ).toBeVisible() + const cx = geometryField(page, dict, 'cx') + await cx.fill('9999') + await cx.press('Enter') + await expect( + page.getByText(dict['editor.annotations.geometry.unapplied']), + ).toBeVisible() + await clickButton(page, dict['editor.annotations.geometry.revert']) + await expect( + page.getByText(dict['editor.annotations.geometry.unapplied']), + ).toHaveCount(0) +} + +/** Guide 4.5: an unsaved change, a reload (beforeunload accepted), the offer, a restore. */ +async function reloadAndRestore(page: Page, sheetId: string) { + const kinds: string[] = [] + page.on('dialog', (dialog) => { + kinds.push(dialog.type()) + void dialog.accept() + }) + await page.reload() + expect(kinds).toContain('beforeunload') + await expect( + page.getByText(dict['editor.draft.recovery.restore'], { exact: true }), + ).toBeVisible() + await expect( + page.getByText('Une copie locale temporaire de ce brouillon existe', { + exact: false, + }), + ).toBeVisible() + expect(page.url()).toContain(sheetId) + await clickButton(page, dict['editor.draft.recovery.restore']) + await expect( + page.getByText(dict['editor.draft.status.unsaved'], { exact: false }), + ).toBeVisible() +} + +test.describe('editor journey (owner trial steps)', () => { + test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) + test.beforeEach(async ({ context }, info) => { + test.skip(isPhone(info), 'editing needs 1 024 px') + await routeToSandbox(context) + }) + test.afterEach(async ({ context }) => { + await dropLateReplays(context) + }) + + test('creation to submission with two editor accounts', async ({ + page, + browser, + baseURL, + requests, + }) => { + test.setTimeout(240_000) + const [a, b] = [await editorActor('fr'), await editorActor('fr')] + for (const actor of [a, b]) + requests.forbid(actor.account.email, actor.account.password) + const tag = a.account.id.slice(0, 8) + await signIn(page, a.account, dict) + await page.goto('/app/admin') + await stepUpAdmin(page, dict, a.secret) + + const sheetId = await createSheetFromAdmin(page, tag) + await importDrawing(page) + await createFindings(page) + await createAnnotations(page) + await repairGeometry(page) + // Undo and redo the numeric repair path's last creation. + await page + .getByRole('button', { + name: dict['editor.annotations.undo'], + exact: true, + }) + .click() + await page + .getByRole('button', { + name: dict['editor.annotations.redo'], + exact: true, + }) + .click() + await expectAccessible(page, 'the editor with annotations') + await saveDraft(page, dict, 1) + + // 4.5: a rename left unsaved survives a reload through the recovery copy. + await selectTab(page, dict, 'general') + const name = page.getByLabel(dict['editor.general.name_fr'], { + exact: true, + }) + await commitText(name, `Chien révisé ${tag}`) + await reloadAndRestore(page, sheetId) + await saveDraft(page, dict, 2) + + // 4.6: the other account saves first; the conflict names its revision. + const second = await secondSession(browser, baseURL ?? '', 'fr-FR') + await signIn(second.page, b.account, dict) + await second.page.goto('/app/admin') + await stepUpAdmin(second.page, dict, b.secret) + await openDraft(second.page, dict, sheetId) + await selectTab(second.page, dict, 'general') + await commitText( + second.page.getByLabel(dict['editor.general.name_en'], { exact: true }), + `Dog by B ${tag}`, + ) + await saveDraft(second.page, dict, 3) + await selectTab(page, dict, 'general') + await commitText( + page.getByLabel(dict['editor.general.name_en'], { exact: true }), + `Dog by A ${tag}`, + ) + await clickButton(page, dict['common.save']) + const conflict = page.getByRole('dialog', { + name: dict['editor.draft.conflict.known'].replace('{revision}', '3'), + }) + await expect(conflict).toBeVisible() + await expectAccessible(page, 'the conflict dialog') + await clickDialog(conflict, dict['editor.draft.conflict.reload']) + await expect(conflict).toContainText('révision 3') + await clickDialog(conflict, dict['editor.draft.conflict.reload']) + await expect(conflict).toBeHidden() + await expect( + page.getByText( + dict['editor.draft.status.revision'].replace('{revision}', '3'), + { + exact: true, + }, + ), + ).toBeVisible() + + // The conflict again, resolved by keeping this version after the confirmation. + await commitText( + second.page.getByLabel(dict['editor.general.name_en'], { exact: true }), + `Dog by B again ${tag}`, + ) + await saveDraft(second.page, dict, 4) + await commitText( + page.getByLabel(dict['editor.general.name_en'], { exact: true }), + `Dog by A ${tag}`, + ) + await clickButton(page, dict['common.save']) + const again = page.getByRole('dialog', { + name: dict['editor.draft.conflict.known'].replace('{revision}', '4'), + }) + await clickDialog(again, dict['editor.draft.conflict.keep']) + await expect(again).toContainText('Remplacer la révision 4') + await clickDialog(again, dict['editor.draft.conflict.keep']) + await expect(again).toBeHidden() + await expect( + page.getByText( + dict['editor.draft.status.revision'].replace('{revision}', '5'), + { + exact: true, + }, + ), + ).toBeVisible() + await second.context.close() + + await selectTab(page, dict, 'verification') + + // 4.7: elements to confirm are information, never an error; « Aller à » selects. + const verification = page.getByTestId('editor-tab-verification') + await expect( + verification.getByText( + dict['editor.verification.errors'].replace('{count}', '0'), + ), + ).toBeVisible() + await expect( + verification.getByText(dict['editor.verification.to_confirm_info']), + ).toBeVisible() + await expect( + page.getByRole('tab', { name: dict['editor.tab.verification'] }), + ).not.toContainText(/\d/) + await expectAccessible(page, 'the verification tab') + await verification + .getByRole('button', { + name: dict['editor.verification.goto'].replace( + '{tab}', + 'Point de bord', + ), + }) + .click() + await expect(page.getByTestId('annotation-selection-tag')).toContainText( + 'Point de bord', + ) + await selectTab(page, dict, 'verification') + await page + .getByLabel(dict['editor.verification.note']) + .fill('Premier jet complet, éléments à confirmer.') + await clickButton(page, dict['editor.verification.submit']) + await expect( + page.getByText(dict['editor.draft.read_only'], { exact: true }), + ).toBeVisible() + await expect( + page.getByText('vérification en cours', { exact: false }), + ).toBeVisible() + const draftId = await sql( + `select id from public.anatomical_sheet_versions where sheet_id = '${sheetId}' and status = 'draft'`, + ) + expect( + await sql( + `select status from public.anatomical_sheet_reviews where version_id = '${draftId}'`, + ), + ).toBe('verifying') + await expectAccessible(page, 'the frozen draft') + }) +}) diff --git a/apps/app/e2e/shell/editor-recovery.spec.ts b/apps/app/e2e/shell/editor-recovery.spec.ts new file mode 100644 index 00000000..6d73ace2 --- /dev/null +++ b/apps/app/e2e/shell/editor-recovery.spec.ts @@ -0,0 +1,377 @@ +import { fr } from '@/i18n/fr' +import type { Locator, Page, TestInfo } from '@playwright/test' +import { rpc } from '../../../../packages/supabase/tests/sandbox/stack' +import { expect, expectAccessible, test } from '../support/browser' +import { dropLateReplays, routeToSandbox } from '../support/sandbox' +import { + copyKeyOf, + editorActor, + expiringEditor, + grantIdOf, + openDraft, + openEditor, + ownerActor, + reloadAccepting, + saveDraft, + seedDraft, + selectTab, + serverDocument, + serverRevision, + standardShape, + storedCopy, + type Actor, +} from '../support/editor' +import { stepUpAdmin } from '../support/admin' +import { secondSession } from '../support/editor' +import { signIn } from '../support/shell' + +// V1-2.6 recovery and concurrency (contract C27 to C30, owner 2026-11-04): two sessions +// saving one draft, an older local copy restored then saved over a newer server revision, +// a pending offer that blocks editing until answered, an unreadable copy kept until +// « Ignorer », the conflict read that can be left with Escape, and the rights that change +// under an open editing session. + +const dict = fr + +const isPhone = (info: TestInfo) => info.project.name === 'chromium-375' + +const nameFr = (page: Page) => + page.getByLabel(dict['editor.general.name_fr'], { exact: true }) + +async function commitText(field: Locator, value: string) { + await field.fill(value) + await field.press('Enter') +} + +const button = (scope: Page | Locator, name: string) => + scope.getByRole('button', { name, exact: true }) + +async function openGeneral(page: Page, actor: Actor, sheetId: string) { + await openEditor(page, dict, actor, sheetId) + await selectTab(page, dict, 'general') +} + +async function signInAgain( + page: Page, + actor: Actor, + sheetId: string, +): Promise { + await signIn(page, actor.account, dict) + await page.goto('/app/admin') + await stepUpAdmin(page, dict, actor.secret) + await openDraft(page, dict, sheetId) + await selectTab(page, dict, 'general') +} + +/** Moves the server draft on as another session would (same account, aal2). */ +async function advanceServer(actor: Actor, draftId: string, revision: number) { + const document = await serverDocument>(draftId) + document.description = { fr: `Serveur ${revision}`, en: `Server ${revision}` } + const saved = await rpc( + 'save_sheet_draft', + { + version_id: draftId, + expected_revision: revision, + document, + change_note: 'e2e', + }, + actor.aal2, + ) + expect(saved.status).toBe(200) +} + +test.describe('editor recovery and concurrency', () => { + test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) + test.beforeEach(async ({ context }, info) => { + test.skip(isPhone(info), 'editing needs 1 024 px') + await routeToSandbox(context) + }) + test.afterEach(async ({ context }) => { + await dropLateReplays(context) + }) + + test('two sessions of one account: the second save meets the conflict, reload keeps the server', async ({ + page, + browser, + baseURL, + requests, + }) => { + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedDraft(actor, { shape: standardShape }) + await openGeneral(page, actor, seed.sheetId) + const other = await secondSession(browser, baseURL ?? '', 'fr-FR') + await signInAgain(other.page, actor, seed.sheetId) + + await commitText(nameFr(page), 'Première session') + await saveDraft(page, dict, 2) + await commitText(nameFr(other.page), 'Seconde session') + await button(other.page, dict['common.save']).click() + const conflict = other.page.getByRole('dialog', { + name: dict['editor.draft.conflict.known'].replace('{revision}', '2'), + }) + await expect(conflict).toBeVisible() + await expect( + conflict.getByText( + dict['editor.draft.conflict.by_you'].split('{date}')[0], + { + exact: false, + }, + ), + ).toBeVisible() + await button(conflict, dict['editor.draft.conflict.reload']).click() + await button(conflict, dict['editor.draft.conflict.reload']).click() + await expect(conflict).toBeHidden() + await expect(nameFr(other.page)).toHaveValue('Première session') + expect(await serverRevision(seed.draftId)).toBe(2) + + // The reloaded session then saves without a conflict. + await commitText(nameFr(other.page), 'Seconde session, reprise') + await saveDraft(other.page, dict, 3) + await other.context.close() + }) + + test('an older copy restored then saved: conflict, then « Garder ma version » after the confirmation', async ({ + page, + requests, + }) => { + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedDraft(actor, { shape: standardShape }) + await openGeneral(page, actor, seed.sheetId) + await commitText(nameFr(page), 'Mon travail local') + await expect( + page.getByText(dict['editor.draft.status.unsaved'], { exact: false }), + ).toBeVisible() + await advanceServer(actor, seed.draftId, 1) + + expect(await reloadAccepting(page)).toContain('beforeunload') + await expect( + page.getByText( + dict['editor.draft.recovery.older'] + .replace('{revision}', '1') + .replace('{server}', '2'), + { exact: false }, + ), + ).toBeVisible() + await expectAccessible(page, 'the recovery offer') + await button(page, dict['editor.draft.recovery.restore']).click() + await button(page, dict['common.save']).click() + const conflict = page.getByRole('dialog', { + name: dict['editor.draft.conflict.known'].replace('{revision}', '2'), + }) + await expect(conflict).toBeVisible() + await button(conflict, dict['editor.draft.conflict.keep']).click() + await expect(conflict).toContainText('Remplacer la révision 2') + await button(conflict, dict['editor.draft.conflict.keep']).click() + await expect(conflict).toBeHidden() + await expect( + page.getByText( + dict['editor.draft.status.revision'].replace('{revision}', '3'), + { + exact: true, + }, + ), + ).toBeVisible() + const saved = await serverDocument<{ name: { fr: string } }>(seed.draftId) + expect(saved.name.fr).toBe('Mon travail local') + }) + + test('a pending offer blocks editing until answered; ignoring it removes the copy', async ({ + page, + requests, + }) => { + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedDraft(actor, { shape: standardShape }) + const key = copyKeyOf(actor.account.id, seed.draftId) + await openGeneral(page, actor, seed.sheetId) + await commitText(nameFr(page), 'À conserver') + expect(await storedCopy(page, key)).not.toBeNull() + + await reloadAccepting(page) + await expect( + button(page, dict['editor.draft.recovery.restore']), + ).toBeVisible() + await expect(button(page, dict['common.save'])).toBeDisabled() + await expect(button(page, dict['editor.draft.discard'])).toBeDisabled() + await selectTab(page, dict, 'general') + await expect( + page.getByTestId('editor-tab-general').getByRole('textbox'), + ).toHaveCount(0) + await selectTab(page, dict, 'annotations') + await expect( + page.getByRole('toolbar', { name: dict['editor.annotations.tools'] }), + ).toHaveCount(0) + + await button(page, dict['editor.draft.recovery.ignore']).click() + await button( + page.getByRole('dialog'), + dict['editor.draft.recovery.ignore_confirm'], + ).click() + await expect( + button(page, dict['editor.draft.recovery.restore']), + ).toHaveCount(0) + expect(await storedCopy(page, key)).toBeNull() + await selectTab(page, dict, 'general') + await expect(nameFr(page)).toBeEditable() + }) + + test('an unreadable copy is kept, offers only « Ignorer », and goes when ignored', async ({ + page, + requests, + }) => { + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedDraft(actor, { shape: standardShape }) + const key = copyKeyOf(actor.account.id, seed.draftId) + await openGeneral(page, actor, seed.sheetId) + await page.evaluate( + ([name]) => sessionStorage.setItem(name, '{not json'), + [key], + ) + await page.reload() + await expect( + page.getByText(dict['editor.draft.recovery.unreadable'], { + exact: false, + }), + ).toBeVisible() + await expect( + button(page, dict['editor.draft.recovery.restore']), + ).toHaveCount(0) + await selectTab(page, dict, 'verification') + await selectTab(page, dict, 'general') + expect(await storedCopy(page, key)).toBe('{not json') + + await button(page, dict['editor.draft.recovery.ignore']).click() + await expect( + page + .getByRole('dialog') + .getByText(dict['editor.draft.recovery.ignore_unreadable_body']), + ).toBeVisible() + await button( + page.getByRole('dialog'), + dict['editor.draft.recovery.ignore_confirm'], + ).click() + expect(await storedCopy(page, key)).toBeNull() + await expect(nameFr(page)).toBeEditable() + }) + + test('the conflict read in progress can be left with Escape', async ({ + page, + browser, + baseURL, + requests, + }) => { + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedDraft(actor, { shape: standardShape }) + await openGeneral(page, actor, seed.sheetId) + const other = await secondSession(browser, baseURL ?? '', 'fr-FR') + await signInAgain(other.page, actor, seed.sheetId) + await commitText(nameFr(other.page), 'Devant') + await saveDraft(other.page, dict, 2) + await other.context.close() + + let release = () => {} + const gate = new Promise((resolve) => (release = resolve)) + await page.route('**/rpc/get_official_sheet_admin*', async (route) => { + await gate + await route.fallback() + }) + await commitText(nameFr(page), 'Derrière') + await button(page, dict['common.save']).click() + const reading = page.getByRole('dialog', { + name: dict['editor.draft.conflict.reading_title'], + }) + await expect(reading).toBeVisible() + await expect( + reading.getByText(dict['editor.draft.conflict.reading']), + ).toBeVisible() + await page.keyboard.press('Escape') + await expect(reading).toBeHidden() + release() + // The late answer of the dismissed read is dropped: no dialog comes back. + await page.waitForTimeout(500) + await expect( + page.getByRole('dialog', { name: /enregistré la révision/ }), + ).toHaveCount(0) + await expect(button(page, dict['common.save'])).toBeEnabled() + await expect(nameFr(page)).toHaveValue('Derrière') + }) +}) + +test.describe('rights changing under an open editing session', () => { + test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) + test.beforeEach(async ({ context }, info) => { + test.skip(isPhone(info), 'editing needs 1 024 px') + await routeToSandbox(context) + }) + test.afterEach(async ({ context }) => { + await dropLateReplays(context) + }) + + /** The save after the change: refused, read-only, the copy wording true. */ + async function expectRefusedSave(page: Page, key: string) { + await commitText(nameFr(page), 'Après le retrait') + await button(page, dict['common.save']).click() + await expect( + page.getByText(dict['editor.draft.read_only'], { exact: true }), + ).toBeVisible() + await expect( + page.getByText(dict['editor.draft.copy_kept'], { exact: false }), + ).toBeVisible() + expect(await storedCopy(page, key)).not.toBeNull() + await expect(button(page, dict['common.save'])).toHaveCount(0) + } + + test('the editor grant revoked by the owner: the next save is refused', async ({ + page, + requests, + }) => { + const [actor, owner] = [await editorActor('fr'), await ownerActor('fr')] + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedDraft(actor, { shape: standardShape }) + await openGeneral(page, actor, seed.sheetId) + const revoked = await rpc( + 'revoke_catalog_right', + { + grant_id: await grantIdOf(actor.account, 'sheet_editor'), + reason: 'e2e', + }, + owner.aal2, + ) + expect(revoked.status).toBe(200) + await expectRefusedSave(page, copyKeyOf(actor.account.id, seed.draftId)) + }) + + test('the admin role removed by the owner: the next save is refused', async ({ + page, + requests, + }) => { + const [actor, owner] = [await editorActor('fr'), await ownerActor('fr')] + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedDraft(actor, { shape: standardShape }) + await openGeneral(page, actor, seed.sheetId) + const revoked = await rpc( + 'revoke_platform_role', + { target_user_id: actor.account.id, role: 'admin', reason: 'e2e' }, + owner.aal2, + ) + expect(revoked.status).toBe(200) + await expectRefusedSave(page, copyKeyOf(actor.account.id, seed.draftId)) + }) + + test('the editor grant expired while editing: the next save is refused', async ({ + page, + requests, + }) => { + test.setTimeout(90_000) + const actor = await expiringEditor('fr', 25) + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedDraft(actor, { shape: standardShape }) + await openGeneral(page, actor, seed.sheetId) + await page.waitForTimeout(26_000) + await expectRefusedSave(page, copyKeyOf(actor.account.id, seed.draftId)) + }) +}) diff --git a/apps/app/e2e/shell/editor-structures.spec.ts b/apps/app/e2e/shell/editor-structures.spec.ts new file mode 100644 index 00000000..801ca733 --- /dev/null +++ b/apps/app/e2e/shell/editor-structures.spec.ts @@ -0,0 +1,277 @@ +import { fr } from '@/i18n/fr' +import type { Locator, Page, TestInfo } from '@playwright/test' +import { expect, expectAccessible, test } from '../support/browser' +import { dropLateReplays, routeToSandbox } from '../support/sandbox' +import { + editorActor, + openEditor, + pointOf, + saveDraft, + seedDraft, + selectTab, + serverDocument, + shapeWith, +} from '../support/editor' + +// V1-2.6 A4 (contract C9 to C12, C19): the structures around the drawing. Annotation +// categories, references, vertebral regions, then the findings tree (zones, categories, +// nodes): add, edit, reorder, mark reviewed, delete with and without dependents. + +const dict = fr + +const isPhone = (info: TestInfo) => info.project.name === 'chromium-375' +const dialog = (page: Page) => page.getByRole('dialog') + +async function open(page: Page, ...annotations: unknown[]) { + const actor = await editorActor('fr') + const seed = await seedDraft(actor, { shape: shapeWith(...annotations) }) + await openEditor(page, dict, actor, seed.sheetId) + return { actor, seed } +} + +async function commitText(field: Locator, value: string) { + await field.fill(value) + await field.press('Enter') +} + +test.describe('editor structures (A4)', () => { + test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) + test.beforeEach(async ({ context }, info) => { + test.skip(isPhone(info), 'editing needs 1 024 px') + await routeToSandbox(context) + }) + test.afterEach(async ({ context }) => { + await dropLateReplays(context) + }) + + test('categories, references and regions: add, edit, reorder, delete', async ({ + page, + requests, + }) => { + const { actor, seed } = await open(page) + requests.forbid(actor.account.email, actor.account.password) + + // A category added, then renamed in place. + await selectTab(page, dict, 'general') + await page.locator('#category-new-fr').fill('Catégorie B') + await page.locator('#category-new-en').fill('Category B') + await page + .getByRole('button', { name: dict['editor.general.category_add'] }) + .click() + const names = page.locator('[id^="category-"][id$="-name-fr"]') + await expect(page.locator('#category-new-fr')).toHaveValue('') + await expect(names).toHaveCount(2) + await commitText(names.nth(1), 'Catégorie B bis') + await expect(names.nth(1)).toHaveValue('Catégorie B bis') + await expectAccessible(page, 'the general tab') + + // Two references, the second moved up. + await selectTab(page, dict, 'references') + for (const citation of ['Première référence', 'Seconde référence']) { + await page.locator('#reference-new-type').selectOption('book') + await page.locator('#reference-new-citation').fill(citation) + await page + .getByRole('button', { name: dict['editor.reference.add'] }) + .click() + await expect(page.getByText(citation)).toBeVisible() + } + const citations = page.locator( + '[id^="reference-"][id$="-citation"]:not(#reference-new-citation)', + ) + await expect(citations).toHaveCount(2) + await page + .getByRole('listitem') + .filter({ hasText: 'Seconde référence' }) + .getByRole('button', { name: dict['editor.action.move_up'] }) + .click() + await expect(citations.first()).toHaveValue('Seconde référence') + await page + .getByRole('listitem') + .filter({ hasText: 'Première référence' }) + .getByRole('button', { name: dict['editor.action.delete'] }) + .click() + await dialog(page) + .getByRole('button', { name: dict['editor.delete.confirm'] }) + .click() + await expect(citations).toHaveCount(1) + + // A region with its count. + await selectTab(page, dict, 'vertebrae') + await page.locator('#region-new-code').fill('T') + await page.locator('#region-new-fr').fill('Thoracique') + await page.locator('#region-new-en').fill('Thoracic') + await page.locator('#region-new-count').fill('18') + await page + .getByRole('button', { name: dict['editor.vertebra.add'] }) + .click() + await commitText(page.locator('#region-T-count'), '17') + await expect(page.locator('#region-T-count')).toHaveValue('17') + + await saveDraft(page, dict, seed.revision + 1) + const saved = await serverDocument<{ + categories: { name: { fr: string } }[] + references: { citation: string }[] + vertebral_config: { regions: { code: string; count: number }[] } + }>(seed.draftId) + expect(saved.categories.map((c) => c.name.fr)).toEqual([ + 'Catégorie A', + 'Catégorie B bis', + ]) + expect(saved.references.map((r) => r.citation)).toEqual([ + 'Seconde référence', + ]) + expect(saved.vertebral_config.regions).toEqual([ + expect.objectContaining({ code: 'T', count: 17 }), + ]) + }) + + test('the findings tree: add zone, category and node, review, reorder', async ({ + page, + requests, + }) => { + const { actor, seed } = await open(page) + requests.forbid(actor.account.email, actor.account.password) + await selectTab(page, dict, 'findings') + const items = page.getByTestId('finding-item') + // The seeded zone is open: the zone and its category show, the node is folded. + await expect(items).toHaveCount(2) + + await page + .getByRole('button', { name: dict['editor.findings.add_zone'] }) + .click() + await page.locator('#finding-new-name-fr').fill('Zone B') + await page.locator('#finding-new-name-en').fill('Zone B en') + await page + .getByRole('button', { name: dict['editor.findings.create'] }) + .click() + await expect(items.filter({ hasText: 'Zone B' })).toBeVisible() + + await page + .getByRole('button', { name: dict['editor.findings.add_category'] }) + .click() + await page.locator('#finding-new-kind').selectOption('anamnesis') + await page.locator('#finding-new-name-fr').fill('Anamnèse B') + await page.locator('#finding-new-name-en').fill('History B') + await page + .getByRole('button', { name: dict['editor.findings.create'] }) + .click() + const category = items.filter({ hasText: 'Anamnèse B' }) + await expect(category).toBeVisible() + await expect( + category.getByText(dict['editor.findings.status.to_confirm']), + ).toBeVisible() + + await page + .getByRole('button', { name: dict['editor.findings.add_node'] }) + .click() + await page.locator('#finding-new-name-fr').fill('Constat B1') + await page.locator('#finding-new-name-en').fill('Finding B1') + await page + .getByRole('button', { name: dict['editor.findings.create'] }) + .click() + const node = items.filter({ hasText: 'Constat B1' }) + await expect(node).toBeVisible() + + // Marked reviewed: the badge of the row follows. + await page + .getByRole('button', { name: dict['editor.findings.mark_reviewed'] }) + .click() + await expect( + node.getByText(dict['editor.findings.status.reviewed']), + ).toBeVisible() + await expectAccessible(page, 'the findings tree') + + // Reorder: the new zone moves above the seeded one. + await items.filter({ hasText: 'Zone B' }).first().click() + await page + .getByRole('button', { name: dict['editor.action.move_up'] }) + .click() + await expect(items.first()).toContainText('Zone B') + + await saveDraft(page, dict, seed.revision + 1) + const saved = await serverDocument<{ + finding_zones: { name: { fr: string } }[] + }>(seed.draftId) + expect(saved.finding_zones.map((z) => z.name.fr)).toEqual([ + 'Zone B', + 'Zone A', + ]) + }) + + test('delete with dependents: refused with the list; without, descendants named', async ({ + page, + requests, + }) => { + const { actor } = await open( + page, + pointOf('p1', 'main', { cx: 500, cy: 400, r: 40 }, 'Point lié'), + ) + requests.forbid(actor.account.email, actor.account.password) + + // The category is used by the point: the dialog lists it and offers no deletion. + await selectTab(page, dict, 'general') + await page + .getByRole('listitem') + .filter({ has: page.locator('#category-cat-a-name-fr') }) + .getByRole('button', { name: dict['editor.action.delete'] }) + .click() + await expect( + dialog(page).getByText( + dict['editor.delete.blocked'].replace('{name}', 'Catégorie A'), + ), + ).toBeVisible() + await expect(dialog(page).getByText('Point lié')).toBeVisible() + await expect( + dialog(page).getByRole('button', { name: dict['editor.delete.confirm'] }), + ).toHaveCount(0) + await dialog(page) + .getByRole('button', { name: dict['editor.delete.close'], exact: true }) + .last() + .click() + + // The zone is linked by the point as well: refused. + await selectTab(page, dict, 'findings') + const zone = page.getByTestId('finding-item').filter({ hasText: 'Zone A' }) + await zone.first().click() + await page + .getByRole('button', { name: dict['editor.action.delete'] }) + .click() + await expect( + dialog(page).getByText( + dict['editor.delete.blocked'].replace('{name}', 'Zone A'), + ), + ).toBeVisible() + await dialog(page) + .getByRole('button', { name: dict['editor.delete.close'], exact: true }) + .last() + .click() + + // The point goes first; the zone then deletes with its descendants named. + await selectTab(page, dict, 'annotations') + await page + .getByRole('list', { name: dict['editor.annotations.list'] }) + .getByRole('button', { name: /Point lié/ }) + .click() + await page + .getByTestId('annotation-properties') + .getByRole('button', { name: dict['editor.action.delete'] }) + .click() + await dialog(page) + .getByRole('button', { name: dict['editor.delete.confirm'] }) + .click() + await selectTab(page, dict, 'findings') + await zone.first().click() + await page + .getByRole('button', { name: dict['editor.action.delete'] }) + .click() + await expect( + dialog(page).getByText(dict['editor.delete.descendants']), + ).toBeVisible() + await expect(dialog(page).getByText('Dysfonction A')).toBeVisible() + await dialog(page) + .getByRole('button', { name: dict['editor.delete.confirm'] }) + .click() + await expect(page.getByTestId('finding-item')).toHaveCount(0) + await expect(page.getByText(dict['editor.findings.empty'])).toBeVisible() + }) +}) diff --git a/apps/app/e2e/support/admin.ts b/apps/app/e2e/support/admin.ts index 0b7e9501..a664e409 100644 --- a/apps/app/e2e/support/admin.ts +++ b/apps/app/e2e/support/admin.ts @@ -47,7 +47,7 @@ export async function seedGrant( } /** A password session of the account on GoTrue: always aal1. */ -async function passwordToken(account: SandboxAccount): Promise { +export async function passwordToken(account: SandboxAccount): Promise { const response = await fetch(`${stack.authUrl}/token?grant_type=password`, { method: 'POST', headers: { apikey: stack.anonKey, 'Content-Type': 'application/json' }, diff --git a/apps/app/e2e/support/catalogue.ts b/apps/app/e2e/support/catalogue.ts index 48059062..ebd4604b 100644 --- a/apps/app/e2e/support/catalogue.ts +++ b/apps/app/e2e/support/catalogue.ts @@ -59,7 +59,8 @@ async function loadCore(): Promise { } let runtime: Promise | null = null -const core = () => (runtime ??= loadCore()) +/** Loaded once per worker process; also used by the editor fixtures. */ +export const core = () => (runtime ??= loadCore()) async function seedFiles() { const [drawing, document] = await Promise.all([ diff --git a/apps/app/e2e/support/editor.ts b/apps/app/e2e/support/editor.ts new file mode 100644 index 00000000..60cc6b5f --- /dev/null +++ b/apps/app/e2e/support/editor.ts @@ -0,0 +1,498 @@ +/** + * V1-2.6 setup of the editor suites (Lot K): editor accounts with a verified factor and an + * aal2 token of their own, draft sheets written the way the sandbox suites do (RPC with + * that token, the drawing through the Storage policy), and the page-side helpers the + * editor specs share (opening the draft, tabs, drawing coordinates, save). What a test + * proves goes through the page; fixtures only prepare what a person did earlier. + */ +import { createHash, randomUUID } from 'node:crypto' +import type { Dict } from '@/i18n/types' +import type { Browser, BrowserContext, Page } from '@playwright/test' +import { + enrolTotp, + verifyTotp, +} from '../../../../packages/supabase/tests/sandbox/mfa' +import { + rpc, + sql, + stack, +} from '../../../../packages/supabase/tests/sandbox/stack' +import { assignRole, passwordToken, seedGrant, stepUpAdmin } from './admin' +import type { GrantKind } from './admin' +import { expect } from './browser' +import { core } from './catalogue' +import { parseOutcome } from '@faunosteo/core-wasm' +import { + createAccount, + FAKE_SUPABASE_ORIGIN, + routeToSandbox, + type SandboxAccount, +} from './sandbox' +import { signIn } from './shell' + +export interface Actor { + account: SandboxAccount + secret: string + /** An aal2 access token for the sandbox REST and Storage calls of fixtures. */ + aal2: string +} + +/** An account with its role and grants and one verified factor; the secret serves the page. */ +export async function makeActor( + locale: 'fr' | 'en', + role: 'owner' | 'admin' | null, + grants: GrantKind[], +): Promise { + const account = await createAccount(locale, false) + if (role) await assignRole(account, role) + for (const kind of grants) await seedGrant(account, kind) + const token = await passwordToken(account) + const enrolment = await enrolTotp(token, 'Téléphone') + if (!enrolment.factor) throw new Error('editor fixture: enrol refused') + const verified = await verifyTotp(token, enrolment.factor) + const aal2 = verified.body.access_token + if (typeof aal2 !== 'string') throw new Error('editor fixture: no aal2') + return { account, secret: enrolment.factor.secret, aal2 } +} + +export const editorActor = (locale: 'fr' | 'en') => + makeActor(locale, 'admin', ['sheet_editor']) + +/** An admin whose editor grant ends soon (the grant is written by hand, not seeded). */ +export async function expiringEditor( + locale: 'fr' | 'en', + seconds: number, +): Promise { + const actor = await makeActor(locale, 'admin', []) + await seedExpiringGrant(actor.account, 'sheet_editor', seconds) + return actor +} + +/** The drawing of the fixtures: a 1000 × 800 box with a body shape. */ +export const DRAWING_SVG = + '' + + '' + + '' + +const text = (fr: string) => ({ fr, en: fr }) + +export interface DraftSeed { + sheetId: string + draftId: string + names: { fr: string; en: string } + assetId: string | null + /** The revision the server holds once seeded (0 for a blank draft). */ + revision: number +} + +export interface SeedOptions { + /** SVG bytes of the main view's drawing; null leaves the blank starting document. */ + drawing?: string | null + species?: string + /** Adjusts the document before it is saved (categories, detail views, findings). */ + shape?: (document: Record) => void +} + +const sha256 = (bytes: Buffer) => + createHash('sha256').update(bytes).digest('hex') + +function blankDocument(species: string, name: string) { + return { + schema_version: 2, + species_id: species, + name: text(name), + description: {}, + scope_disclaimer: {}, + attribution: { authors: [], license: null, notes: null }, + vertebral_config: { regions: [] }, + references: [], + categories: [], + views: [ + { + id: 'main', + kind: 'main', + name: { fr: 'Vue principale', en: 'Main view' }, + svg_asset_id: null as string | null, + view_box: null, + }, + ], + annotations: [], + finding_zones: [], + } +} + +function succeeded(result: { status: number; text: string }, what: string) { + if (result.status !== 200) + throw new Error(`editor fixture ${what}: HTTP ${result.status}`) + return result +} + +/** The drawing as the core stores it: the form the page uploads after its own cleaning. */ +async function storedForm(svg: string): Promise { + const loaded = await core() + const outcome = loaded.invoke<{ stored: string | null }>((glue) => + parseOutcome<{ stored: string | null }>( + glue.clean_svg(new TextEncoder().encode(svg)), + ), + ) + if (!outcome.ok || !outcome.value.stored) + throw new Error('editor fixture: the core refused the drawing') + return outcome.value.stored +} + +async function attachDrawing( + actor: Actor, + sheetId: string, + svg: string, +): Promise { + const bytes = Buffer.from(await storedForm(svg)) + const registered = succeeded( + await rpc( + 'register_sheet_asset', + { + sheet_id: sheetId, + sha256: sha256(bytes), + byte_size: bytes.length, + file_name: 'fixture.svg', + }, + actor.aal2, + ), + 'register', + ) + const response = await fetch( + `${stack.storageUrl}/object/anatomical-sheet-assets/${sha256(bytes)}.svg`, + { + method: 'POST', + headers: { + Authorization: `Bearer ${actor.aal2}`, + 'Content-Type': 'image/svg+xml', + }, + body: new Uint8Array(bytes), + }, + ) + await response.arrayBuffer() + if (response.status !== 200 && response.status !== 400) + throw new Error(`editor fixture upload: HTTP ${response.status}`) + const assetId = JSON.parse(registered.text) as string + succeeded( + await rpc('confirm_sheet_asset_upload', { asset_id: assetId }, actor.aal2), + 'confirm', + ) + return assetId +} + +/** A non-equine draft sheet by `actor`, its drawing and content saved as revision 1. */ +export async function seedDraft( + actor: Actor, + options: SeedOptions = {}, +): Promise { + const tag = randomUUID().slice(0, 8) + const names = { fr: `Fiche e2e ${tag}`, en: `E2E sheet ${tag}` } + const document = blankDocument(options.species ?? 'canine', names.fr) + document.name = names + const created = succeeded( + await rpc( + 'create_official_sheet', + { slug: `e2e-${tag}`, document }, + actor.aal2, + ), + 'create', + ) + const sheetId = JSON.parse(created.text) as string + const draftId = await sql( + `select id from public.anatomical_sheet_versions where sheet_id = '${sheetId}' and status = 'draft'`, + ) + const drawing = options.drawing === undefined ? DRAWING_SVG : options.drawing + const assetId = drawing ? await attachDrawing(actor, sheetId, drawing) : null + if (assetId) document.views[0].svg_asset_id = assetId + options.shape?.(document as unknown as Record) + const changed = assetId !== null || options.shape !== undefined + if (changed) { + succeeded( + await rpc( + 'save_sheet_draft', + { + version_id: draftId, + expected_revision: 0, + document, + change_note: 'fixture', + }, + actor.aal2, + ), + 'save', + ) + } + const revision = changed ? 1 : 0 + return { sheetId, draftId, names, assetId, revision } +} + +/** + * The categories, zone and detail view most editor specs start from. Every defaulted + * field is written out, as the core writes a document: the page reads the stored text + * as it is (an omitted `reference_ids` breaks the findings tree, see the report). + */ +export function standardShape(document: Record) { + document.categories = [ + { id: 'cat-a', name: text('Catégorie A'), color: null }, + ] + document.finding_zones = [ + { + id: 'zone-a', + name: text('Zone A'), + categories: [ + { + id: 'fcat-a', + kind: 'dysfunction', + name: text('Dysfonction A'), + description: {}, + reference_ids: [], + review_status: 'reviewed', + children: [ + { + id: 'node-a', + name: text('Constat A'), + description: {}, + requires_vet_referral: false, + reference_ids: [], + review_status: 'reviewed', + children: [], + }, + ], + }, + ], + }, + ] + ;(document.views as unknown[]).push({ + id: 'detail-a', + kind: 'detail', + name: text('Détail A'), + svg_asset_id: null, + view_box: { min_x: 100, min_y: 100, width: 300, height: 240 }, + parent_view_id: 'main', + }) +} + +export const draftPath = (sheetId: string) => + `/app/admin/sheets/${sheetId}/draft` + +export const draftTitle = (dict: Dict, number = 1) => + dict['editor.draft.title'].replace('{number}', String(number)) + +/** Signs in, steps up and opens the draft editor of `sheetId`; resolves once it is ready. */ +export async function openEditor( + page: Page, + dict: Dict, + actor: Actor, + sheetId: string, +): Promise { + await signIn(page, actor.account, dict) + await page.goto('/app/admin') + await stepUpAdmin(page, dict, actor.secret) + await openDraft(page, dict, sheetId) +} + +/** Opens the draft page (already signed in and stepped up). */ +export async function openDraft(page: Page, dict: Dict, sheetId: string) { + await page.goto(draftPath(sheetId)) + await expect( + page.getByRole('heading', { level: 1, name: draftTitle(dict) }), + ).toBeVisible() + await expect(page.getByRole('tablist')).toBeVisible() +} + +export async function selectTab(page: Page, dict: Dict, tab: string) { + await page + .getByRole('tab', { name: dict[`editor.tab.${tab}`], exact: true }) + .click() +} + +/** The revision the server holds for the draft. */ +export async function serverRevision(draftId: string): Promise { + return Number( + await sql( + `select revision from public.anatomical_sheet_versions where id = '${draftId}'`, + ), + ) +} + +export async function serverDocument>( + draftId: string, +): Promise { + return JSON.parse( + await sql( + `select content::text from public.anatomical_sheet_versions where id = '${draftId}'`, + ), + ) as T +} + +/** Saves through « Enregistrer » and waits until the server revision line moves. */ +export async function saveDraft(page: Page, dict: Dict, revision: number) { + await page.getByRole('button', { name: dict['common.save'] }).click() + await expect( + page.getByText( + dict['editor.draft.status.revision'].replace( + '{revision}', + String(revision), + ), + { exact: true }, + ), + ).toBeVisible() +} + +/** Client coordinates of a drawing point, through the overlay's own matrix. */ +export async function clientOf( + page: Page, + x: number, + y: number, +): Promise<{ x: number; y: number }> { + return page.getByTestId('annotation-overlay').evaluate( + (svg, at) => { + const root = svg as unknown as SVGSVGElement + const point = root.createSVGPoint() + point.x = at.x + point.y = at.y + const mapped = point.matrixTransform(root.getScreenCTM()!) + return { x: mapped.x, y: mapped.y } + }, + { x, y }, + ) +} + +/** A click at a drawing point on the annotation canvas. */ +export async function clickDrawing(page: Page, x: number, y: number) { + const at = await clientOf(page, x, y) + await page.mouse.click(at.x, at.y) +} + +/** The geometry fields of the open creation panel or properties panel. */ +export const geometryField = (page: Page, dict: Dict, key: string) => + page.getByLabel(dict[`editor.annotations.geometry.${key}`], { exact: true }) + +/** A point annotation of the fixtures (a circle in drawing units, reviewed). */ +export function pointOf( + id: string, + viewId: string, + circle: { cx: number; cy: number; r: number }, + name = id, +) { + return { + id, + kind: 'point', + view_id: viewId, + category_id: 'cat-a', + laterality: 'unpaired', + geometry: { type: 'circle', ...circle }, + review_status: 'reviewed', + name: text(name), + finding_zone_id: 'zone-a', + vertebral_region_code: null, + } +} + +/** The standard shape plus the given annotations. */ +export function shapeWith(...annotations: unknown[]) { + return (document: Record) => { + standardShape(document) + document.annotations = annotations + } +} + +export const creationPanel = (page: Page) => + page.getByTestId('annotation-creation') + +export const annotationList = (page: Page, dict: Dict) => + page.getByRole('list', { name: dict['editor.annotations.list'] }) + +export const toolButton = (page: Page, dict: Dict, id: string) => + page.getByRole('button', { + name: dict[`editor.annotations.tool.${id}`], + exact: true, + }) + +/** Fills the creation panel; the category keeps its first choice. */ +export async function fillCreation( + page: Page, + dict: Dict, + names: { fr: string; en: string }, + opens?: string, +) { + const panel = creationPanel(page) + await panel.getByLabel(dict['editor.annotations.name_fr']).fill(names.fr) + await panel.getByLabel(dict['editor.annotations.name_en']).fill(names.en) + await panel + .getByLabel(dict['editor.annotations.laterality']) + .selectOption('unpaired') + if (opens) + await panel.getByLabel(dict['editor.annotations.opens']).selectOption(opens) +} + +export async function createFromPanel(page: Page, dict: Dict) { + await creationPanel(page) + .getByRole('button', { name: dict['editor.annotations.create'] }) + .click() + await expect(creationPanel(page)).toHaveCount(0) +} + +/** + * A second signed-in session of `actor` or another account in a fresh browser context, + * under the same replay and the same request allowlist as the suite's pages. + */ +export async function secondSession( + browser: Browser, + baseURL: string, + locale: string, +): Promise<{ context: BrowserContext; page: Page }> { + const context = await browser.newContext({ baseURL, locale }) + await routeToSandbox(context) + const allowed = [new URL(baseURL).origin, FAKE_SUPABASE_ORIGIN] + await context.route( + (url) => !allowed.includes(url.origin), + (route) => route.abort('blockedbyclient'), + ) + return { context, page: await context.newPage() } +} + +/** The storage key of the tab's recovery copy of a draft (state/recovery.ts). */ +export const copyKeyOf = (userId: string, versionId: string) => + `osteo:sheet-draft:${userId}:${versionId}` + +export function storedCopy(page: Page, key: string): Promise { + return page.evaluate((name) => sessionStorage.getItem(name), key) +} + +/** Reloads with the beforeunload dialog of a page holding unsaved changes accepted. */ +export async function reloadAccepting(page: Page): Promise { + const kinds: string[] = [] + const accept = (dialog: import('@playwright/test').Dialog) => { + kinds.push(dialog.type()) + void dialog.accept() + } + page.on('dialog', accept) + await page.reload() + page.off('dialog', accept) + return kinds +} + +/** An aal2 owner, for the calls that change another account's rights. */ +export const ownerActor = (locale: 'fr' | 'en') => + makeActor(locale, 'owner', []) + +/** The id of the account's active grant of `kind`. */ +export function grantIdOf(account: SandboxAccount, kind: string) { + return sql( + `select id from public.anatomical_catalog_grants where user_id = '${account.id}' + and grant_kind = '${kind}' and revoked_at is null`, + ) +} + +/** A grant that ends `seconds` from now (granted earlier, so the expiry check holds). */ +export async function seedExpiringGrant( + account: SandboxAccount, + kind: GrantKind, + seconds: number, +): Promise { + await sql(`insert into public.anatomical_catalog_grants + (user_id, grant_kind, reason, verification_note, granted_by, granted_at, expires_at) + values ('${account.id}', '${kind}', 'sandbox', 'sandbox', '${account.id}', + now() - interval '1 hour', now() + interval '${seconds} seconds')`) +} diff --git a/apps/app/e2e/support/warm-up.ts b/apps/app/e2e/support/warm-up.ts new file mode 100644 index 00000000..1287f8fe --- /dev/null +++ b/apps/app/e2e/support/warm-up.ts @@ -0,0 +1,49 @@ +/** + * Global setup of the shell suite (V1-2.6): the Vite dev server discovers some + * dependencies only when a route first loads them and answers with a full page + * reload, which wiped a form a test had begun to fill. One throwaway session + * visits the editor routes and every tab once before the tests start, so the + * reload happens here and not in a test. + */ +import { chromium, type FullConfig } from '@playwright/test' +import { fr } from '@/i18n/fr' +import { stepUpAdmin } from './admin' +import { draftPath, editorActor, seedDraft, standardShape } from './editor' +import { routeToSandbox } from './sandbox' +import { signIn } from './shell' + +const TABS = [ + 'general', + 'views', + 'annotations', + 'findings', + 'references', + 'vertebrae', + 'verification', +] as const + +export default async function warmUp(config: FullConfig): Promise { + const baseURL = config.projects[0].use.baseURL ?? '' + const actor = await editorActor('fr') + const seed = await seedDraft(actor, { shape: standardShape }) + const browser = await chromium.launch() + const context = await browser.newContext({ baseURL, locale: 'fr-FR' }) + await routeToSandbox(context) + const page = await context.newPage() + await signIn(page, actor.account, fr) + await page.goto('/app/admin') + await stepUpAdmin(page, fr, actor.secret) + for (const path of ['/app/admin/sheets/new', draftPath(seed.sheetId)]) { + await page.goto(path) + await page.waitForLoadState('networkidle') + } + for (const tab of TABS) { + await page + .getByRole('tab', { name: fr[`editor.tab.${tab}`], exact: true }) + .click() + await page.waitForLoadState('networkidle') + } + await page.goto('/app/admin/sheets/new') + await page.waitForLoadState('networkidle') + await browser.close() +} diff --git a/apps/app/src/editor/annotations/useCanvasGestures.ts b/apps/app/src/editor/annotations/useCanvasGestures.ts index 6964b106..261208a8 100644 --- a/apps/app/src/editor/annotations/useCanvasGestures.ts +++ b/apps/app/src/editor/annotations/useCanvasGestures.ts @@ -68,13 +68,18 @@ function clickHandler(input: GestureInput, framing: Framing) { } } -/** `touch-action: none` only while a drawing tool, a drag or a zoom is active. */ +/** + * `touch-action: none` while a drawing tool, a drag, a zoom or a movable selection is + * active: the browser reads it at touchstart, so a touch drag of the selected marker + * would otherwise be taken as a pan and cancelled before the drag is armed. + */ function touchStyle( tool: ToolId, armed: boolean, scale: number, + movable: boolean, ): CSSProperties { - const none = tool !== 'select' || armed || scale !== 1 + const none = tool !== 'select' || armed || scale !== 1 || movable return { touchAction: none ? 'none' : 'pan-x pan-y' } } @@ -103,7 +108,12 @@ export function useCanvasGestures(input: GestureInput) { ...composedPointer(framing, move), onKeyDown, onClick: clickHandler(input, framing), - style: touchStyle(input.tool, move.armed, framing.framing.scale), + style: touchStyle( + input.tool, + move.armed, + framing.framing.scale, + input.moveTarget !== null, + ), }, } } diff --git a/apps/app/src/editor/findings/tree.ts b/apps/app/src/editor/findings/tree.ts index dd332d30..ea54ab7f 100644 --- a/apps/app/src/editor/findings/tree.ts +++ b/apps/app/src/editor/findings/tree.ts @@ -157,9 +157,34 @@ function categoryItems(zone: FindingZone, zoneItemId: string): FindingItem[] { }) } +// shortcut: the serde defaults of the core's FindingNode and FindingCategory (schema.rs), +// applied here because the page reads the stored text and the equine import omits them +// (a node without `children` or `reference_ids` blanked the Constats tab). Upgrade path: +// the loader hands the page the core's canonical document and this goes away. +const filledNode = (node: FindingNode): FindingNode => ({ + ...node, + description: node.description ?? {}, + requires_vet_referral: node.requires_vet_referral ?? false, + reference_ids: node.reference_ids ?? [], + review_status: node.review_status ?? 'inherited', + children: (node.children ?? []).map(filledNode), +}) + +const filledCategory = (category: FindingCategory): FindingCategory => ({ + ...category, + description: category.description ?? {}, + reference_ids: category.reference_ids ?? [], + review_status: category.review_status ?? 'inherited', + children: (category.children ?? []).map(filledNode), +}) + /** Every element of the findings tree in document order, collapsed or not. */ export function buildItems(doc: AnatomicalSheetDocument): FindingItem[] { - return doc.finding_zones.flatMap((zone, index) => { + return doc.finding_zones.flatMap((stored, index) => { + const zone: FindingZone = { + ...stored, + categories: (stored.categories ?? []).map(filledCategory), + } const id = itemId(zone.id, []) const self: FindingItem = { id, diff --git a/apps/app/tests/unit/editor-findings.test.tsx b/apps/app/tests/unit/editor-findings.test.tsx index 004512a8..53be30ca 100644 --- a/apps/app/tests/unit/editor-findings.test.tsx +++ b/apps/app/tests/unit/editor-findings.test.tsx @@ -96,6 +96,30 @@ describe('findings tree model', () => { expect(shown.map((i) => i.kind)).toEqual(['zone', 'category', 'zone']) }) + it('reads nodes that omit their defaulted fields (the equine import)', () => { + const bare = { + id: 'n1', + name: name('N1'), + children: [{ id: 'n2', name: name('N2') }], + } + const stored = { + finding_zones: [ + { + id: 'z', + name: name('Z'), + categories: [ + { id: 'c', kind: 'dysfunction', name: name('C'), children: [bare] }, + ], + }, + ], + } as unknown as AnatomicalSheetDocument + const all = buildItems(stored) + expect(all.map((i) => i.level)).toEqual([1, 2, 3, 4]) + expect(all[3].element).toMatchObject({ + value: { reference_ids: [], children: [], review_status: 'inherited' }, + }) + }) + it('maps the WAI-ARIA keys', async () => { await openReady({ text: treeText() }) const all = buildItems(doc()) diff --git a/docs/development/BROWSER_TESTS.md b/docs/development/BROWSER_TESTS.md index 479d4de5..cfb066f0 100644 --- a/docs/development/BROWSER_TESTS.md +++ b/docs/development/BROWSER_TESTS.md @@ -10,7 +10,7 @@ engines are installed. The suites live in `apps/app/e2e`. | Command | Backend | Dev server | Content | |---|---|---|---| | `pnpm e2e:ui` | none | Vite on `127.0.0.1:5191` | `e2e/ui/dialog.spec.ts`: the D13 contract of the shared Dialog on a test page; `e2e/ui/local-tool.spec.ts`: the disclaimer, edit and replace dialogs on the real local-tool routes | -| `pnpm e2e:shell` | the isolated stack of `pnpm db:sandbox` | Vite on `127.0.0.1:5192` | `e2e/shell/shell.spec.ts`: sign-in, dashboard, the account photo confirmation, the phone drawer; `e2e/shell/clients.spec.ts`: the client journeys (V1-1.5); `e2e/shell/animals.spec.ts`: the animal and relation journeys (V1-1.6, contract §11.8); `e2e/shell/responsive.spec.ts`: no sideways scroll on nine shell pages, the archive confirmations and the drawer at 320, 360, 375, 390 and 430 px (phone project) and 1280 px, long values, the dashboard e-mail shown whole (RESP-01); `e2e/shell/admin.spec.ts` (V1-2.5): A0 the owner's bootstrap (two TOTP factors from Sécurité, the step-up at `/app/admin` and inside a factor action, no second factor from `aal1`, refresh keeping `aal1` and `aal2`, rights granted and revoked with their reason), A1 a sheet created by an editor on a new inactive species, S1 a species created inactive then activated by the owner, the creation page when the own-grants read fails (« Impossible de vérifier vos autorisations » and « Réessayer », never the form; Retry brings the form back), access per right (a reviewer-only account refused on the creation page), axe and no sideways scroll on every admin page; `e2e/shell/catalogue.spec.ts` (V1-2.5): P1 a reader searches, opens a sheet, picks a zone, reads a retired version, drafts and archived sheets never listed, the same refusal for an existing and an unknown sheet without access, 320, 375 and 430 px with the whole drawing in the box at opening; at 320 and 375 px the zone panel's live region present before a pick and naming the picked zone, the « Références » card starting at or below the drawing's bottom | +| `pnpm e2e:shell` | the isolated stack of `pnpm db:sandbox` | Vite on `127.0.0.1:5192` | `e2e/shell/shell.spec.ts`: sign-in, dashboard, the account photo confirmation, the phone drawer; `e2e/shell/clients.spec.ts`: the client journeys (V1-1.5); `e2e/shell/animals.spec.ts`: the animal and relation journeys (V1-1.6, contract §11.8); `e2e/shell/responsive.spec.ts`: no sideways scroll on nine shell pages, the archive confirmations and the drawer at 320, 360, 375, 390 and 430 px (phone project) and 1280 px, long values, the dashboard e-mail shown whole (RESP-01); `e2e/shell/admin.spec.ts` (V1-2.5): A0 the owner's bootstrap (two TOTP factors from Sécurité, the step-up at `/app/admin` and inside a factor action, no second factor from `aal1`, refresh keeping `aal1` and `aal2`, rights granted and revoked with their reason), A1 a sheet created by an editor on a new inactive species, S1 a species created inactive then activated by the owner, the creation page when the own-grants read fails (« Impossible de vérifier vos autorisations » and « Réessayer », never the form; Retry brings the form back), access per right (a reviewer-only account refused on the creation page), axe and no sideways scroll on every admin page; `e2e/shell/catalogue.spec.ts` (V1-2.5): P1 a reader searches, opens a sheet, picks a zone, reads a retired version, drafts and archived sheets never listed, the same refusal for an existing and an unknown sheet without access, 320, 375 and 430 px with the whole drawing in the box at opening; at 320 and 375 px the zone panel's live region present before a pick and naming the picked zone, the « Références » card starting at or below the drawing's bottom; `e2e/shell/editor-*.spec.ts` (V1-2.6, the draft editor level 1, contract C16 to C34): `editor-drawings` (A2: a hostile file refused with no cleaning box, an Inkscape export cleaned after its preview, a valid file attached, a detail view by crop, the same bytes attached twice), `editor-annotations` (A3: points, zones and links by clicks and by keyboard only, move by drag, a click with jitter never moves, numeric edits, undo and redo, review and delete), `editor-geometry` (a click near a frame edge with the corrected position confirmed and cancelled, an inherited out-of-frame point repaired through the geometry group, a crop change refused when it would invalidate a point, an unmeasured view with its tools disabled, touch-action and a touch drag in real Chromium), `editor-structures` (A4: categories, references, regions, findings tree, reorder, mark reviewed, delete with dependents), `editor-journey` (the steps of `V1-2-6_OWNER_TRIAL.md` §4 with two editor accounts: creation, drawing, findings, annotations, save, reload with the beforeunload dialog and the recovery offer, conflict, submission, the round read back in SQL), `editor-recovery` (two sessions, an older local copy restored then saved over a newer revision, a pending offer blocking edits, an unreadable copy kept until « Ignorer », Escape on the conflict read, the editor grant revoked, the admin role removed and the grant expired under an open session), `editor-access` (a reviewer-only account read-only, the not-found screen for an editor without the admin role and for an admin without a capability, 320, 375 and 800 px read-only, 1 024 px editing, axe on every tab edit and read-only), `editor-equine` (the historical equine sheet opened as a working copy, a copy left active by an earlier run set aside and put back; commit latency on it and on a synthetic document near 2 MiB, printed as `LATENCY` lines and kept as test annotations, budget 500 ms per commit on the equine copy). Editor accounts, drafts and drawings are prepared by `e2e/support/editor.ts` (a drawing in its stored form, written by the core); `e2e/support/warm-up.ts` is the suite's global setup (the dev server reloads the page once when a route first loads a dependency, so one throwaway session visits the editor routes before the tests). Editing needs 1 024 px: these specs skip the 375 px project | Each suite runs on two Chromium projects: `chromium-desktop` (1280 × 800) and `chromium-375` (375 × 667, mobile viewport, touch). A test tagged `@phone`