From 4731a3376a2dc98e58d08b72ca661ce835be3580 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 13 Nov 2026 19:03:21 +0100 Subject: [PATCH] feat(editor): sheet landings, history and e2e for the finding layers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit « Tout afficher » clears the search and keeps the sort. A landing waits for the dialogs a move closed and for their focus restore. Helpers and shell specs move to the dialog and sheet flow; new finding dialog spec (entries, guards, flip, gone rule, Back and Forward over the layers). --- apps/app/e2e/shell/editor-access.spec.ts | 27 +- apps/app/e2e/shell/editor-citations.spec.ts | 264 ++++++++----- apps/app/e2e/shell/editor-deselect.spec.ts | 10 +- apps/app/e2e/shell/editor-equine.spec.ts | 6 +- .../e2e/shell/editor-finding-dialog.spec.ts | 315 +++++++++++++++ apps/app/e2e/shell/editor-journey.spec.ts | 7 +- .../e2e/shell/editor-shell-crossing.spec.ts | 50 ++- .../app/e2e/shell/editor-shell-layout.spec.ts | 360 ++++-------------- apps/app/e2e/shell/editor-shell.spec.ts | 29 +- apps/app/e2e/shell/editor-structures.spec.ts | 49 ++- apps/app/e2e/support/editor.ts | 83 +++- apps/app/e2e/support/warm-up.ts | 2 + .../editor/findings/FindingTree.tsx | 4 +- .../editor/references/useReferenceView.ts | 5 +- .../src/components/ui/afterModalsClosed.ts | 9 + apps/app/src/editor/focusRequest.ts | 4 +- .../src/editor/history/useEditorHistory.ts | 4 +- apps/app/src/editor/useEditorNavigation.ts | 7 +- .../tests/unit/editor-focus-request.test.tsx | 13 +- .../unit/editor-references-panel.test.tsx | 4 +- .../unit/editor-references-view.test.tsx | 4 +- 21 files changed, 782 insertions(+), 474 deletions(-) create mode 100644 apps/app/e2e/shell/editor-finding-dialog.spec.ts diff --git a/apps/app/e2e/shell/editor-access.spec.ts b/apps/app/e2e/shell/editor-access.spec.ts index 4671ad93..b7ce65f3 100644 --- a/apps/app/e2e/shell/editor-access.spec.ts +++ b/apps/app/e2e/shell/editor-access.spec.ts @@ -12,17 +12,19 @@ import { SECTIONS, TABS, closeCitations, + closeFinding, draftPath, draftTitle, editorActor, makeActor, openEditor, - openCitations, + openFinding, openSection, pointOf, seedDraft, selectTab, shapeWith, + showCitations, type Actor, } from '../support/editor' import { signIn } from '../support/shell' @@ -146,9 +148,11 @@ test.describe('editor access, narrow screens and axe', () => { ).toHaveCount(0) await expectNoHorizontalOverflow(page, `the draft at ${width} px`) await expectAccessible(page, `the draft at ${width} px`) - await openCitations(page, dict, 'Constat A') - await expectNoHorizontalOverflow(page, `the panel at ${width} px`) - await expectAccessible(page, `the citations panel at ${width} px`) + await openFinding(page, dict, 'Constat A') + await expectAccessible(page, `the finding dialog at ${width} px`) + await showCitations(page) + await expectNoHorizontalOverflow(page, `the sheet at ${width} px`) + await expectAccessible(page, `the citations sheet at ${width} px`) }) } @@ -186,10 +190,13 @@ test.describe('editor access, narrow screens and axe', () => { ) await expectAccessible(page, `the ${section} section (edit)`) } - await openCitations(page, dict, 'Constat A') - await expectNoHorizontalOverflow(page, 'the citations panel at 1 024 px') - await expectAccessible(page, 'the citations panel (edit)') + await openFinding(page, dict, 'Constat A') + await expectAccessible(page, 'the finding dialog (edit)') + await showCitations(page) + await expectNoHorizontalOverflow(page, 'the citations sheet at 1 024 px') + await expectAccessible(page, 'the citations sheet (edit)') await closeCitations(page, dict) + await closeFinding(page, dict) }) test('axe on every tab of a read-only draft', async ({ page, requests }) => { @@ -213,7 +220,9 @@ test.describe('editor access, narrow screens and axe', () => { await openSection(page, dict, section) await expectAccessible(page, `the ${section} section (read-only)`) } - await openCitations(page, dict, 'Constat A') - await expectAccessible(page, 'the citations panel (read-only)') + await openFinding(page, dict, 'Constat A') + await expectAccessible(page, 'the finding dialog (read-only)') + await showCitations(page) + await expectAccessible(page, 'the citations sheet (read-only)') }) }) diff --git a/apps/app/e2e/shell/editor-citations.spec.ts b/apps/app/e2e/shell/editor-citations.spec.ts index a3dc8644..ac1bbb47 100644 --- a/apps/app/e2e/shell/editor-citations.spec.ts +++ b/apps/app/e2e/shell/editor-citations.spec.ts @@ -9,23 +9,29 @@ import { import { dropLateReplays, routeToSandbox } from '../support/sandbox' import { closeCitations, + closeFinding, editorActor, + expectNoDialog, + findingDialog, libraryRoot, openCitations, openEditor, + openFinding, openTab, place, saveDraft, seedDraft, serverDocument, + showCitations, standardShape, } from '../support/editor' -// V1-2.6 R2.4: the contextual citations panel of one finding (board 25): its contents, -// « Retirer de ce constat » and « Défaire », « Tout afficher », every close path with the -// focus checked after the exit (motion and reduced motion), Escape in a tile field, the -// inert page during the exit sampled in the page, axe open (edit, read-only at 375 px). -// The spec seeds its own sheet and never touches another. +// V1-2.6 R2 finish: the citations of one finding as a modal side sheet over its dialog +// (R2F-4): its contents, « Retirer de ce constat » and « Défaire », « Tout afficher », +// every close path with the focus checked after the exit (motion and reduced motion), +// Escape in a tile field, the exiting sheet inert, the keyboard and touch proofs, axe open +// (edit, read-only at 375 px), Back and Forward over the layers. The spec seeds its own +// sheet and never touches another. const dict = fr @@ -84,9 +90,12 @@ async function open(page: Page, seedShape = shape) { } const panel = (page: Page) => page.getByTestId('editor-citations-panel') +/** The sheet's own dialog (the finding dialog under it is the other one). */ +const sheet = (page: Page) => + page.locator('dialog[open]').filter({ has: panel(page) }) const heads = (page: Page) => panel(page).locator('button[aria-controls][id$="-header"]') -const trigger = (page: Page) => page.locator('[data-citations-trigger]:visible') +const trigger = (page: Page) => page.locator('[data-citations-trigger]') const link = (page: Page) => panel(page).getByRole('button', { name: dict['editor.references.panel_show_all'], @@ -103,7 +112,7 @@ const nodeOf = (document: Record) => }[] )[0].categories[0].children[0] -test.describe('citations panel, editing', () => { +test.describe('citations sheet, editing', () => { test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) test.beforeEach(async ({ context }, info) => { test.skip( @@ -116,7 +125,7 @@ test.describe('citations panel, editing', () => { await dropLateReplays(context) }) - test('opens filtered on its finding, « Retirer » and one « Défaire », saved status', async ({ + test('opens over its finding dialog, « Retirer » then one « Défaire », saved status', async ({ page, requests, }) => { @@ -137,7 +146,7 @@ test.describe('citations panel, editing', () => { await expect(heads(page)).toHaveCount(3) await expect(panel(page).getByText('Source libre')).toHaveCount(0) await expect(panel(page).getByRole('searchbox')).toHaveCount(0) - await expectAccessible(page, 'the citations panel, closed tiles') + await expectAccessible(page, 'the citations sheet, closed tiles') await heads(page).nth(1).click() const tile = heads(page).nth(1).locator('xpath=ancestor::li[1]') @@ -151,20 +160,25 @@ test.describe('citations panel, editing', () => { ]) { await expect(panel(page).getByRole('button', { name })).toHaveCount(0) } - await expectAccessible(page, 'the citations panel, an open tile') + await expectAccessible(page, 'the citations sheet, an open tile') - // « Retirer » then one « Défaire » restores the citation and the status together. + // « Retirer » takes the citation out at once; the next tile takes the focus (P20). await retire(tile).click() await expect(heads(page)).toHaveCount(2) - // The next tile (« Source C », now second) takes the focus (P20). await expect(heads(page).nth(1)).toBeFocused() await expect(heads(page).nth(1)).toContainText('Source C') + // « Défaire » is out of reach under the dialogs: close them, then one undo restores + // the citation and the status together. + await closeCitations(page, dict) + await closeFinding(page, dict) await undo(page).click() + await openCitations(page, dict, 'Constat A') await expect(heads(page)).toHaveCount(3) - // The tile that came back is closed (its open state went with it): open it again. await heads(page).nth(1).click() await retire(tile).click() await expect(heads(page)).toHaveCount(2) + await closeCitations(page, dict) + await closeFinding(page, dict) await saveDraft(page, dict, seed.revision + 1) const saved = await serverDocument>(seed.draftId) expect(nodeOf(saved).reference_ids).toEqual(['ref-a', 'ref-c']) @@ -172,7 +186,7 @@ test.describe('citations panel, editing', () => { expect((saved.references as unknown[]).length).toBe(4) }) - test('a long list scrolls inside the panel: the last tile is reachable from scroll 0, the page never moves', async ({ + test('a long list scrolls inside the sheet: the last tile is reachable from scroll 0, the page never moves', async ({ page, }) => { test.setTimeout(150_000) @@ -194,7 +208,7 @@ test.describe('citations panel, editing', () => { await expect(last).toHaveAttribute('aria-expanded', 'true') }) - test('the last citations gone: the panel stays with its line, then closes on the tab', async ({ + test('the last citations gone: the sheet stays with its line, Escape closes it, the dialog stays', async ({ page, }) => { test.setTimeout(150_000) @@ -212,13 +226,12 @@ test.describe('citations panel, editing', () => { await expect(page.locator('#editor-citations-title')).toBeFocused() await page.keyboard.press('Escape') await expect(panel(page)).toHaveCount(0) - // The trigger went with the last citation: the active tab takes the focus (P6). - await expect( - page.getByRole('tab', { name: dict['editor.tab.findings'] }), - ).toBeFocused() + // The trigger went with the last citation: the focus stays in the dialog. + await expect(findingDialog(page)).toBeVisible() + await expect(findingDialog(page).locator(':focus')).toHaveCount(1) }) - test('« Tout afficher » closes it, resets search and sort, keeps open tiles, focuses the tab heading', async ({ + test('« Tout afficher » closes both layers, clears the search, keeps the sort and the open tiles; Back returns to the sheet', async ({ page, }) => { test.setTimeout(150_000) @@ -232,21 +245,29 @@ test.describe('citations panel, editing', () => { await root.getByRole('button', { name: /Source B/ }).click() await openCitations(page, dict, 'Constat A') await link(page).click() - await expect(panel(page)).toHaveCount(0) + await expectNoDialog(page) await expect(page.locator('#editor-references-title')).toBeFocused() await expect(root.getByRole('searchbox')).toHaveValue('') await expect( root.getByLabel(dict['editor.references.sort_by']), - ).toHaveValue('sheet') + ).toHaveValue('citation') await expect( root.getByRole('button', { name: /Source B/ }), ).toHaveAttribute('aria-expanded', 'true') await expect( root.locator('button[aria-controls][id$="-header"]'), ).toHaveCount(4) + // The move is an entry of its own: Back returns to the finding with its sheet on top. + await page.goBack() + await expect(place(page, 'citations')).toBeVisible() + await expect(findingDialog(page)).toBeVisible() + await expect(page.locator('dialog[open]')).toHaveCount(2) + await page.goForward() + await expectNoDialog(page) + await expect(place(page, 'references')).toBeVisible() }) - test('Escape in a field of a tile neither closes the panel nor commits; ✕ then commits', async ({ + test('Escape in a field of a tile neither closes the sheet nor commits; ✕ then commits', async ({ page, }) => { test.setTimeout(150_000) @@ -261,12 +282,13 @@ test.describe('citations panel, editing', () => { await field.press('Escape') await expect(panel(page)).toBeVisible() await expect(field).toHaveValue('Référence A, révisée') - await expect(undo(page)).toBeDisabled() - // A user close applies a valid draft first (P22''), then the panel exits. + // A user close applies a valid draft first (P22''), then the sheet exits. await panel(page) .getByRole('button', { name: dict['editor.references.close'] }) .click() await expect(panel(page)).toHaveCount(0) + await closeFinding(page, dict) + await expect(undo(page)).toBeEnabled() await saveDraft(page, dict, seed.revision + 1) const saved = await serverDocument<{ references: { citation: string }[] }>( seed.draftId, @@ -274,7 +296,7 @@ test.describe('citations panel, editing', () => { expect(saved.references[0].citation).toBe('Référence A, révisée') }) - test('a refused draft cancels the close: panel open, field focused, message shown', async ({ + test('a refused draft cancels every move that unmounts the sheet: ✕, scrim, Back, « Tout afficher »', async ({ page, }) => { test.setTimeout(150_000) @@ -286,67 +308,91 @@ test.describe('citations panel, editing', () => { .click() const field = panel(page).getByLabel(dict['editor.reference.citation']) await field.fill('') - await page - .getByRole('tab', { - name: new RegExp(`^${dict['editor.tab.verification']}`), - }) + await panel(page) + .getByRole('button', { name: dict['editor.references.close'] }) .click() await expect(panel(page)).toBeVisible() await expect(field).toBeFocused() await expect(panel(page).getByRole('alert')).toBeVisible() + await page + .getByTestId('references-scrim') + .click({ position: { x: 4, y: 40 } }) + await expect(panel(page)).toBeVisible() + await link(page).click() + await expect(panel(page)).toBeVisible() await expect(page.getByRole('tab', { selected: true })).toHaveText( new RegExp(`^${dict['editor.tab.findings']}`), ) + // Back: the page stays, the view is pushed again, the refusal shows. + await page.goBack() + await expect(panel(page)).toBeVisible() + await expect(findingDialog(page)).toBeVisible() + await expect(panel(page).getByRole('alert')).toBeVisible() }) - test('the page and the panel are inert through the exit (sampled in the page)', async ({ + test('the exiting sheet is inert, and a second close finds nothing to close', async ({ page, }) => { test.setTimeout(150_000) await open(page) await openCitations(page, dict, 'Constat A') await page.evaluate(() => { - const samples: { panel: boolean; page: boolean; inert: boolean }[] = [] + const samples: boolean[] = [] Object.assign(window, { samples }) const tick = () => { const layer = document.querySelector('[data-place="citations"]') - const body = document.querySelector('[data-place="findings"]') - samples.push({ - panel: layer !== null, - page: body?.closest('[inert]') !== null, - inert: layer?.hasAttribute('inert') ?? false, - }) - if (layer !== null) requestAnimationFrame(tick) + if (layer === null) return + samples.push(layer.closest('dialog')?.hasAttribute('inert') ?? false) + requestAnimationFrame(tick) } tick() }) - await panel(page) - .getByRole('button', { name: dict['editor.references.close'] }) - .click() + const closeButton = panel(page).getByRole('button', { + name: dict['editor.references.close'], + }) + await closeButton.dispatchEvent('click') + await closeButton.dispatchEvent('click').catch(() => undefined) await expect(panel(page)).toHaveCount(0) const samples = await page.evaluate( - () => - ( - window as unknown as { - samples: { panel: boolean; page: boolean; inert: boolean }[] - } - ).samples, + () => (window as unknown as { samples: boolean[] }).samples, ) - const leaving = samples.filter((sample) => sample.panel && sample.inert) - expect(leaving.length).toBeGreaterThan(0) - expect(leaving.every((sample) => sample.page)).toBe(true) - await expect(page.locator('[data-place="findings"]')).toBeVisible() - expect( - await page - .locator('[data-place="findings"]') - .evaluate((body) => body.closest('[inert]') === null), - ).toBe(true) + expect(samples.some((inert) => inert)).toBe(true) + // The dialog under the sheet is still open: the second click closed nothing more. + await expect(findingDialog(page)).toBeVisible() + await expect(page.locator('dialog[open]')).toHaveCount(1) + }) + + test('keyboard: Tab stays in the sheet, Escape closes only it, the trigger holds the focus', async ({ + page, + }) => { + test.setTimeout(150_000) + await open(page) + await openCitations(page, dict, 'Constat A') + const controls = await panel(page) + .locator('button, [href], input, select, textarea') + .count() + for (let step = 0; step < controls + 2; step++) { + await page.keyboard.press('Tab') + const where = await page.evaluate(() => { + const active = document.activeElement + if (!active || active === document.body) return 'outside' + return active.closest('[data-place="citations"]') ? 'sheet' : 'page' + }) + // Past the last control the focus leaves for the browser's own interface + // (body): it never reaches the dialog under the sheet or the page. + expect(where, `Tab ${step + 1}`).not.toBe('page') + } + await sheet(page).evaluate((node) => (node as HTMLElement).focus()) + await page.keyboard.press('Escape') + await expect(panel(page)).toHaveCount(0) + await expect(findingDialog(page)).toBeVisible() + await expect(trigger(page)).toBeFocused() }) }) -/** Every way out of the panel, the focus read from the document after the exit. */ +/** Every way out of the sheet, the focus read from the document after the exit. */ for (const reduced of [false, true]) { - test.describe(`citations panel closes, ${reduced ? 'reduced motion' : 'motion'}`, () => { + test.describe(`citations sheet closes, ${reduced ? 'reduced motion' : 'motion'}`, () => { test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) test.beforeEach(async ({ context, page }, info) => { test.skip(isPhone(info), 'the paths are walked on desktop') // floor-guard: allow C16 editing needs >= 1 024 px @@ -359,7 +405,7 @@ for (const reduced of [false, true]) { await dropLateReplays(context) }) - test('✕, Escape and the scrim give the focus back to the trigger', async ({ + test('✕, Escape, the scrim and Back give the focus back to the trigger', async ({ page, }) => { test.setTimeout(150_000) @@ -368,28 +414,34 @@ for (const reduced of [false, true]) { await closeCitations(page, dict) await expect(trigger(page)).toBeFocused() await expect(trigger(page)).toHaveAttribute('aria-expanded', 'false') - await trigger(page).click() - await expect(page.locator('#editor-citations-title')).toBeFocused() + await showCitations(page) await page.keyboard.press('Escape') await expect(panel(page)).toHaveCount(0) await expect(trigger(page)).toBeFocused() - await trigger(page).click() - await expect(page.locator('#editor-citations-title')).toBeFocused() + await showCitations(page) await page .getByTestId('references-scrim') .click({ position: { x: 12, y: 40 } }) await expect(panel(page)).toHaveCount(0) await expect(trigger(page)).toBeFocused() + await showCitations(page) + await page.goBack() + await expect(panel(page)).toHaveCount(0) + await expect(findingDialog(page)).toBeVisible() + await expect(trigger(page)).toBeFocused() + await page.goForward() + await expect(panel(page)).toBeVisible() + await expect(page.locator('dialog[open]')).toHaveCount(2) }) - test('« Tout afficher », « Aller à » and a tab choice land where the pending move says', async ({ + test('« Tout afficher » and « Aller à » land where the pending move says', async ({ page, }) => { test.setTimeout(150_000) await open(page) await openCitations(page, dict, 'Constat A') await link(page).click() - await expect(panel(page)).toHaveCount(0) + await expectNoDialog(page) await expect(page.locator('#editor-references-title')).toBeFocused() await openCitations(page, dict, 'Constat A') @@ -398,35 +450,23 @@ for (const reduced of [false, true]) { .getByRole('button', { name: dict['editor.references.go_to'] }) .first() .click() - await expect(panel(page)).toHaveCount(0) + await expectNoDialog(page) await expect( page.getByRole('treeitem', { name: /Dysfonction A/ }), ).toBeFocused() - - await openCitations(page, dict, 'Constat A') - const verification = page.getByRole('tab', { - name: new RegExp(`^${dict['editor.tab.verification']}`), - }) - await verification.click() - await expect(panel(page)).toHaveCount(0) - await expect(verification).toBeFocused() }) - test('the panel slides only when motion is allowed', async ({ page }) => { + test('the sheet slides only when motion is allowed', async ({ page }) => { test.setTimeout(150_000) await open(page) - await page.getByRole('tab', { name: dict['editor.tab.findings'] }).click() - await page - .getByRole('treeitem', { expanded: false }) - .first() - .press('ArrowRight') - await page.getByRole('treeitem', { name: 'Constat A' }).click() + await openFinding(page, dict, 'Constat A') await page.evaluate(() => { const seen: string[] = [] Object.assign(window, { seen }) new MutationObserver(() => { - const layer = document.querySelector('[data-place="citations"]') - const slider = layer?.firstElementChild as HTMLElement | null + const slider = document.querySelector( + '[data-place="citations"]', + ) as HTMLElement | null if (slider) seen.push(slider.style.transform) }).observe(document.body, { subtree: true, @@ -436,7 +476,8 @@ for (const reduced of [false, true]) { }) }) await trigger(page).click() - await expect(page.locator('#editor-citations-title')).toBeFocused() + await expect(place(page, 'citations')).toBeVisible() + await expect(page.locator('dialog[open]')).toHaveCount(2) const seen = await page.evaluate( () => (window as unknown as { seen: string[] }).seen, ) @@ -446,7 +487,7 @@ for (const reduced of [false, true]) { }) } -test.describe('citations panel, read-only at 375 px', () => { +test.describe('citations sheet, read-only at 375 px', () => { test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) test.beforeEach(async ({ context }, info) => { test.skip(!isPhone(info), 'the read-only twin runs at 375 px only') @@ -462,14 +503,13 @@ test.describe('citations panel, read-only at 375 px', () => { test.setTimeout(150_000) await open(page) await openCitations(page, dict, 'Constat A') - // Full width: the whole content area (the page's side gutters stay). + // Full width: the sheet is min(34 rem, 100 vw), so the whole phone screen. const layer = page.locator('[data-place="citations"]') const box = await layer.boundingBox() - const area = await layer.locator('xpath=..').boundingBox() expect(box?.width ?? 0).toBeLessThanOrEqual(375) - expect(Math.abs((box?.width ?? 0) - (area?.width ?? 0))).toBeLessThan(1) + expect(Math.abs((box?.width ?? 0) - 375)).toBeLessThan(1) await expect(heads(page)).toHaveCount(3) - await expectNoHorizontalOverflow(page, 'the panel at 375 px') + await expectNoHorizontalOverflow(page, 'the sheet at 375 px') await heads(page).first().click() for (const name of [ dict['editor.references.edit'], @@ -483,9 +523,51 @@ test.describe('citations panel, read-only at 375 px', () => { .boundingBox() expect(close?.width ?? 0).toBeGreaterThanOrEqual(44) expect(close?.height ?? 0).toBeGreaterThanOrEqual(44) - await expectAccessible(page, 'the citations panel, read-only at 375 px') + await expectAccessible(page, 'the citations sheet, read-only at 375 px') await closeCitations(page, dict) await expect(trigger(page)).toBeFocused() + await closeFinding(page, dict) await expect(place(page, 'findings')).toBeVisible() }) + + test('by touch: taps act on the sheet only, the dialog under it is never activated @phone', async ({ + page, + }) => { + test.setTimeout(150_000) + await open(page) + await openFinding(page, dict, 'Constat A') + const center = async (target: Locator) => { + const box = await target.boundingBox() + return { x: box!.x + box!.width / 2, y: box!.y + box!.height / 2 } + } + const tap = async (target: Locator) => { + const at = await center(target) + await page.touchscreen.tap(at.x, at.y) + } + await tap(trigger(page)) + await expect(place(page, 'citations')).toBeVisible() + // A tile opens by a tap; the dialog's own controls underneath stay as they were. + await tap(heads(page).first()) + await expect(heads(page).first()).toHaveAttribute('aria-expanded', 'true') + await expect(trigger(page)).toHaveAttribute('aria-expanded', 'true') + // A tap where the dialog's close button lies (it is under the sheet) hits the sheet. + const under = await center( + findingDialog(page).getByRole('button', { name: dict['common.close'] }), + ) + await page.touchscreen.tap(under.x, under.y) + await expect(findingDialog(page)).toBeVisible() + // The sheet's ✕ closes the sheet only; the trigger holds the focus. + await tap( + panel(page).getByRole('button', { + name: dict['editor.references.close'], + }), + ) + await expect(panel(page)).toHaveCount(0) + await expect(findingDialog(page)).toBeVisible() + await expect(trigger(page)).toBeFocused() + await tap( + findingDialog(page).getByRole('button', { name: dict['common.close'] }), + ) + await expectNoDialog(page) + }) }) diff --git a/apps/app/e2e/shell/editor-deselect.spec.ts b/apps/app/e2e/shell/editor-deselect.spec.ts index 259637b8..3c79a9cd 100644 --- a/apps/app/e2e/shell/editor-deselect.spec.ts +++ b/apps/app/e2e/shell/editor-deselect.spec.ts @@ -11,6 +11,8 @@ import { geometryField, historyButton, openEditor, + expectNoDialog, + findingDialog, openCitations, pickAnnotation, place, @@ -223,11 +225,15 @@ test.describe('deselect and D6b (editor, mouse and keyboard)', () => { await expect(dialog).toHaveCount(0) await expectKept(page, POINT) - // The citations panel (over Constats): it closes, the selection stays, back on - // Annotations a second Escape deselects. + // The citations sheet (over the finding dialog over Constats): Escape closes the + // sheet only, a second one the dialog, the selection stays, back on Annotations a + // third Escape deselects. await openCitations(page, dict, 'Constat A') await page.keyboard.press('Escape') await expect(place(page, 'citations')).toHaveCount(0) + await expect(findingDialog(page)).toBeVisible() + await page.keyboard.press('Escape') + await expectNoDialog(page) await selectTab(page, dict, 'annotations') await expectKept(page, POINT) await box(page).focus() diff --git a/apps/app/e2e/shell/editor-equine.spec.ts b/apps/app/e2e/shell/editor-equine.spec.ts index 25bd4f47..76afaeb3 100644 --- a/apps/app/e2e/shell/editor-equine.spec.ts +++ b/apps/app/e2e/shell/editor-equine.spec.ts @@ -15,6 +15,8 @@ import { type Actor, annotationList, editorActor, + closeCitations, + closeFinding, openCitations, openEditor, openTab, @@ -396,7 +398,7 @@ test.describe('equine working copy and commit latency', () => { await stepUpAdmin(page, dict, actor.secret) await page.goto(`/app/admin/sheets/${copyId}/draft`) await expect(toolButton(page, dict, 'point')).toBeEnabled() - // Every tab, section and the citations panel mounted once: all of them stay mounted (B2a). + // Every tab, section and the citations sheet mounted once: all of them stay mounted (B2a). for (const tab of ['general', 'findings', 'verification']) await selectTab(page, dict, tab) for (const section of SECTIONS) await openSection(page, dict, section) @@ -408,6 +410,8 @@ test.describe('equine working copy and commit latency', () => { 'Suture sagittale (entre les deux pariétaux)', 5, ) + await closeCitations(page, dict) + await closeFinding(page, dict) const renames = await measureRenames(page, 'equine, all places: rename') const additions = await measureAdditions(page, 'equine, all places: add') for (const line of [renames, additions]) diff --git a/apps/app/e2e/shell/editor-finding-dialog.spec.ts b/apps/app/e2e/shell/editor-finding-dialog.spec.ts new file mode 100644 index 00000000..70baae23 --- /dev/null +++ b/apps/app/e2e/shell/editor-finding-dialog.spec.ts @@ -0,0 +1,315 @@ +import { fr } from '@/i18n/fr' +import type { Page, TestInfo } from '@playwright/test' +import { expect, test } from '../support/browser' +import { dropLateReplays, routeToSandbox } from '../support/sandbox' +import { + closeFinding, + editorActor, + expectNoDialog, + findingDialog, + historyButton, + openEditor, + openFinding, + openTab, + place, + revealFinding, + seedDraft, + serverDocument, + showCitations, + standardShape, +} from '../support/editor' + +// R2 UX finish, task 2 (R2F-3, R2F-4): the finding dialog (view, edit, creation), its +// browser-history entries, its guards, the read-only flip and the gone rule, and the +// layers' order after Back and Forward. The top-layer, focus and history rules are the +// browser's, so they are proved here and not in happy-dom. + +const dict = fr + +const isPhone = (info: TestInfo) => info.project.name === 'chromium-375' +const dialog = (page: Page) => findingDialog(page) +const inDialog = (page: Page, name: string) => + dialog(page).getByRole('button', { name, exact: true }) +const edit = (page: Page) => inDialog(page, dict['editor.findings.edit']) +const save = (page: Page) => inDialog(page, dict['editor.findings.save']) +const nameFr = (page: Page) => + dialog(page).getByLabel(dict['editor.general.name_fr']) +const confirmText = (page: Page) => + dialog(page).getByText(dict['editor.findings.discard_ask']) +const undo = (page: Page) => historyButton(page, dict, 'undo') +const rows = (page: Page) => page.getByTestId('finding-item') + +async function open(page: Page) { + const actor = await editorActor('fr') + const seed = await seedDraft(actor, { shape: standardShape }) + await openEditor(page, dict, actor, seed.sheetId) + return seed +} + +/** The history entry on top names a finding layer (the adapter writes a moment after a click). */ +async function layerWritten(page: Page, layer: 'finding' | 'none') { + await page.waitForFunction((wanted) => { + const view = history.state?.usr?.editorEntry?.view + return wanted === 'none' ? view?.finding === null : !!view?.finding + }, layer) +} + +/** Whether the sheet is the dialog on top at the right edge of the viewport. */ +const sheetOnTop = (page: Page) => + page.evaluate(() => { + const top = document.elementFromPoint(window.innerWidth - 40, 100) + return !!top?.closest('dialog')?.querySelector('[data-place="citations"]') + }) + +test.describe('finding dialog', () => { + test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) + test.beforeEach(async ({ context }, info) => { + test.skip(isPhone(info), 'editing needs 1 024 px') // floor-guard: allow C16 editing needs >= 1024 px; phone read-only covered in editor-citations + await routeToSandbox(context) + }) + test.afterEach(async ({ context }) => { + await dropLateReplays(context) + }) + + test('a click, Enter and Space open the dialog; the tree, its expansion and the scroll stay; the row holds the focus', async ({ + page, + }) => { + test.setTimeout(150_000) + await open(page) + await openTab(page, dict, 'findings') + const row = await revealFinding(page, 'Constat A') + await expect(row).toBeVisible() + await page.evaluate(() => { + const spacer = document.createElement('div') + spacer.style.height = '4000px' + document.body.append(spacer) + window.scrollTo(0, 250) + }) + const before = { + rows: await rows(page).count(), + y: await page.evaluate(() => window.scrollY), + } + await row.focus({ preventScroll: true }) + await page.keyboard.press('Enter') + await expect(dialog(page)).toBeVisible() + await page.keyboard.press('Escape') + await expectNoDialog(page) + await expect(row).toBeFocused() + await page.keyboard.press('Space') + await expect(dialog(page)).toBeVisible() + await closeFinding(page, dict) + await expect(row).toBeFocused() + await row.click() + await expect(dialog(page)).toBeVisible() + await page.keyboard.press('Escape') + await expectNoDialog(page) + expect(await rows(page).count()).toBe(before.rows) + expect( + Math.abs((await page.evaluate(() => window.scrollY)) - before.y), + ).toBeLessThanOrEqual(2) + await expect(row).toBeFocused() + }) + + test('a pristine « Enregistrer » writes nothing, a changed one writes one entry', async ({ + page, + }) => { + test.setTimeout(150_000) + const seed = await open(page) + await openFinding(page, dict, 'Dysfonction A') + await edit(page).click() + await save(page).click() + await expect(edit(page)).toBeFocused() + await closeFinding(page, dict) + await expect(undo(page)).toHaveAttribute('aria-disabled', 'true') + await openFinding(page, dict, 'Dysfonction A') + await edit(page).click() + await nameFr(page).fill('Dysfonction renommée') + await save(page).click() + await expect(dialog(page).getByRole('status')).toHaveText( + dict['editor.findings.saved'], + ) + await closeFinding(page, dict) + await expect(undo(page)).toHaveAttribute('aria-disabled', 'false') + await undo(page).click() + await expect(rows(page).filter({ hasText: 'Dysfonction A' })).toBeVisible() + await expect(undo(page)).toHaveAttribute('aria-disabled', 'true') + expect( + ( + await serverDocument<{ + finding_zones: { categories: { name: { fr: string } }[] }[] + }>(seed.draftId) + ).finding_zones[0].categories[0].name.fr, + ).toBe('Dysfonction A') + }) + + test('« Abandonner » and a width flip commit nothing; 1280, 900, 1280 keeps the draft and the focus', async ({ + page, + }) => { + test.setTimeout(150_000) + await open(page) + await openFinding(page, dict, 'Dysfonction A') + await edit(page).click() + await nameFr(page).fill('Dysfonction brouillon') + await expect(nameFr(page)).toBeFocused() + await page.setViewportSize({ width: 900, height: 800 }) + await expect(nameFr(page)).toHaveAttribute('readonly', '') + await expect(nameFr(page)).toHaveAttribute('aria-readonly', 'true') + await expect(nameFr(page)).toBeFocused() + await expect( + page.getByText(dict['editor.findings.flip_narrow']), + ).toBeVisible() + await expect(save(page)).toBeDisabled() + await page.setViewportSize({ width: 1280, height: 800 }) + await expect(nameFr(page)).not.toHaveAttribute('readonly', '') + await expect(nameFr(page)).toHaveValue('Dysfonction brouillon') + await expect(nameFr(page)).toBeFocused() + await inDialog(page, dict['editor.findings.cancel']).click() + await expect(confirmText(page)).toBeVisible() + await expect( + inDialog(page, dict['editor.findings.keep_typing']), + ).toBeFocused() + await inDialog(page, dict['editor.findings.discard']).click() + await expect(edit(page)).toBeVisible() + await closeFinding(page, dict) + await expect(undo(page)).toHaveAttribute('aria-disabled', 'true') + await expect(rows(page).filter({ hasText: 'Dysfonction A' })).toBeVisible() + }) + + test('a dirty Escape and a dirty Back ask, the dialog and the draft stay; « Abandonner » pops one entry', async ({ + page, + }) => { + test.setTimeout(150_000) + await open(page) + await openFinding(page, dict, 'Dysfonction A') + await layerWritten(page, 'finding') + await edit(page).click() + await nameFr(page).fill('Dysfonction brouillon') + await page.keyboard.press('Escape') + await expect(confirmText(page)).toBeVisible() + await expect(dialog(page)).toBeVisible() + await inDialog(page, dict['editor.findings.keep_typing']).click() + await expect(nameFr(page)).toHaveValue('Dysfonction brouillon') + await page.goBack() + await expect(confirmText(page)).toBeVisible() + await expect(dialog(page)).toBeVisible() + await inDialog(page, dict['editor.findings.keep_typing']).click() + await expect(nameFr(page)).toHaveValue('Dysfonction brouillon') + await page.keyboard.press('Escape') + await inDialog(page, dict['editor.findings.discard']).click() + await expectNoDialog(page) + await layerWritten(page, 'none') + // One entry went: the next Back leaves the tab, no orphan entry of the dialog is left. + await page.goBack() + await expect(page.getByRole('tab', { selected: true })).toHaveText( + new RegExp(`^${dict['editor.tab.annotations']}`), + ) + }) + + test('deleting from the dialog closes it and lands on the nearest row', async ({ + page, + }) => { + test.setTimeout(150_000) + await open(page) + await openFinding(page, dict, 'Constat A') + await inDialog(page, dict['editor.action.delete']).click() + await page + .locator('dialog[open]') + .last() + .getByRole('button', { name: dict['editor.delete.confirm'] }) + .click() + await expectNoDialog(page) + const parent = page.getByRole('treeitem', { name: /Dysfonction A/ }) + await expect(parent).toBeFocused() + await expect(parent).toHaveAttribute('aria-selected', 'true') + }) + + test('a creation is a layer: « Créer » shows the new element, a Back goes to the tree', async ({ + page, + }) => { + test.setTimeout(150_000) + await open(page) + await openTab(page, dict, 'findings') + await page + .getByRole('button', { name: dict['editor.findings.add_zone'] }) + .click() + await layerWritten(page, 'finding') + 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( + dialog(page).getByRole('heading', { name: 'Zone B' }), + ).toBeVisible() + await expect(edit(page)).toBeVisible() + await page.goBack() + await expectNoDialog(page) + await expect(rows(page).filter({ hasText: 'Zone B' })).toBeVisible() + }) + + test('an element that vanished under a restored entry closes its dialog and says so', async ({ + page, + }) => { + test.setTimeout(150_000) + await open(page) + await openTab(page, dict, 'findings') + 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(edit(page)).toBeVisible() + await closeFinding(page, dict) + await undo(page).click() + await expect(rows(page).filter({ hasText: 'Zone B' })).toHaveCount(0) + // Forward restores the entry of the dead zone: its dialog closes at once. + await page.goForward() + await expectNoDialog(page) + await expect(page.locator('p[aria-live="polite"]')).toHaveText( + dict['editor.findings.gone'], + ) + }) + + test('Back and Forward walk the layers, the sheet is on top each time (owner steps 1 to 4)', async ({ + page, + }) => { + test.setTimeout(150_000) + await open(page) + // 1. the finding dialog, 2. its sheet, 3. « Tout afficher », 4. the references tab. + await openFinding(page, dict, 'Constat A') + await layerWritten(page, 'finding') + await showCitations(page) + expect(await sheetOnTop(page)).toBe(true) + await page + .getByRole('button', { name: dict['editor.references.panel_show_all'] }) + .click() + await expectNoDialog(page) + await expect(place(page, 'references')).toBeVisible() + await page.waitForFunction( + () => history.state?.usr?.editorEntry?.view?.tab === 'references', + ) + await page.goBack() + await expect(page.locator('dialog[open]')).toHaveCount(2) + expect(await sheetOnTop(page)).toBe(true) + await page.goBack() + await expect(page.locator('dialog[open]')).toHaveCount(1) + await expect(dialog(page)).toBeVisible() + await expect(page.locator('[data-citations-trigger]')).toBeFocused() + await page.goBack() + await expectNoDialog(page) + await expect( + page.getByRole('treeitem', { name: 'Constat A' }), + ).toBeFocused() + await page.goForward() + await expect(page.locator('dialog[open]')).toHaveCount(1) + await page.goForward() + await expect(page.locator('dialog[open]')).toHaveCount(2) + expect(await sheetOnTop(page)).toBe(true) + await page.goForward() + await expectNoDialog(page) + await expect(place(page, 'references')).toBeVisible() + }) +}) diff --git a/apps/app/e2e/shell/editor-journey.spec.ts b/apps/app/e2e/shell/editor-journey.spec.ts index 3a9934a2..62816544 100644 --- a/apps/app/e2e/shell/editor-journey.spec.ts +++ b/apps/app/e2e/shell/editor-journey.spec.ts @@ -6,6 +6,7 @@ import { expect, expectAccessible, test } from '../support/browser' import { dropLateReplays, routeToSandbox } from '../support/sandbox' import { clickDrawing, + closeFinding, createFromPanel, creationPanel, editorActor, @@ -119,7 +120,11 @@ async function createFindings(page: Page) { 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']) + // « Créer » turns the dialog into the new element's view: close it before the next add. + const create = async () => { + await clickButton(page, dict['editor.findings.create']) + await closeFinding(page, dict) + } 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) diff --git a/apps/app/e2e/shell/editor-shell-crossing.spec.ts b/apps/app/e2e/shell/editor-shell-crossing.spec.ts index a4787f01..b135f17d 100644 --- a/apps/app/e2e/shell/editor-shell-crossing.spec.ts +++ b/apps/app/e2e/shell/editor-shell-crossing.spec.ts @@ -5,6 +5,7 @@ import { dropLateReplays, routeToSandbox } from '../support/sandbox' import { clientOf, closeCitations, + closeFinding, copyKeyOf, editorActor, geometryField, @@ -168,7 +169,7 @@ test.describe('editor shell, width crossing (H)', () => { expect(ids).toEqual([]) }) - test('the findings creation form and the submission note keep their typed text', async ({ + test('the findings creation form stays in its dialog while narrow: draft, focus and a notice kept', async ({ page, }) => { await open(page) @@ -176,12 +177,36 @@ test.describe('editor shell, width crossing (H)', () => { await page .getByRole('button', { name: dict['editor.findings.add_zone'] }) .click() - await keepsTypedValue( - page, - page.locator('#finding-new-name-fr'), - dict['editor.findings.add_zone'], - 'findings', - ) + const field = page.locator('#finding-new-name-fr') + await field.fill('Saisie') + await expect(field).toBeFocused() + // The dialog is a part the flip keeps: no edit control leaves, nothing is written. + await page.setViewportSize(NARROW) + await expect(field).toBeVisible() + await expect(field).toHaveAttribute('readonly', '') + await expect(field).toHaveAttribute('aria-readonly', 'true') + await expect(field).toHaveValue('Saisie') + await expect(field).toBeFocused() + await expect( + page.getByText(dict['editor.findings.flip_narrow']), + ).toBeVisible() + await expect( + page.getByRole('button', { name: dict['editor.findings.create'] }), + ).toBeDisabled() + await page.setViewportSize(WIDE) + await expect(field).not.toHaveAttribute('readonly', '') + await expect(field).toHaveValue('Saisie') + await expect(field).toBeFocused() + await expect(saveLine(page)).not.toHaveText(UNSAVED_LINE) + await page.keyboard.press('Escape') + await page + .getByRole('button', { name: dict['editor.findings.discard'] }) + .click() + await expect(dialogs(page)).toHaveCount(0) + }) + + test('the submission note keeps its typed text', async ({ page }) => { + await open(page) await selectTab(page, dict, 'verification') await keepsTypedValue( page, @@ -262,21 +287,22 @@ test.describe('editor shell, width crossing (H)', () => { await expect(saveLine(page)).toHaveText(UNSAVED_LINE) }) - test('the citations panel open: read-only below the threshold, unsaved work kept, edit back on widening', async ({ + test('the citations sheet open: read-only below the threshold, unsaved work kept, edit back on widening', async ({ page, }) => { await open(page) await commitName(page, 'Nom conservé') await openCitations(page, dict, 'Constat A') - await cross(page, NARROW) - await expectReadOnly(page) + await page.setViewportSize(NARROW) await expect(place(page, 'citations')).toBeVisible() + await expect(page.locator('dialog[open]')).toHaveCount(2) + await page.setViewportSize(WIDE) + await closeCitations(page, dict) + await closeFinding(page, dict) await expect(saveLine(page)).toHaveText(UNSAVED_LINE) - await cross(page, WIDE) await expect( page.getByRole('button', { name: dict['common.save'], exact: true }), ).toBeEnabled() - await closeCitations(page, dict) }) test('text typed without a blur is unsaved after the crossing and the copy is written', async ({ diff --git a/apps/app/e2e/shell/editor-shell-layout.spec.ts b/apps/app/e2e/shell/editor-shell-layout.spec.ts index 9dadb334..92d4f4d9 100644 --- a/apps/app/e2e/shell/editor-shell-layout.spec.ts +++ b/apps/app/e2e/shell/editor-shell-layout.spec.ts @@ -1,5 +1,5 @@ import { fr } from '@/i18n/fr' -import type { CDPSession, Locator, Page, TestInfo } from '@playwright/test' +import type { Page, TestInfo } from '@playwright/test' import { stepUpAdmin } from '../support/admin' import { expect, @@ -12,12 +12,15 @@ import { SECTIONS, TABS, closeCitations, + closeFinding, draftPath, + expectNoDialog, draftTitle, editorActor, historyButton, openEditor, openCitations, + openFinding, openTab, openSection, pickAnnotation, @@ -26,6 +29,7 @@ import { seedDraft, selectTab, shapeWith, + showCitations, showDrawing, } from '../support/editor' import { signIn } from '../support/shell' @@ -52,18 +56,6 @@ async function open(page: Page) { return { ...seed, actor } } -/** Selects a finding in the tree of Constats (expanding down to it), the panel closed. */ -async function selectFinding(page: Page, name: string) { - await openTab(page, dict, 'findings') - const item = page.getByRole('treeitem', { name }) - for (let depth = 0; depth < 4 && (await item.count()) === 0; depth++) { - const closed = page.getByRole('treeitem', { expanded: false }).first() - await closed.focus() - await closed.press('ArrowRight') - } - await item.click() -} - /** * Samples the document's size on every frame until stopped (the click that opens or * closes the panel is inside the window): the distinct sizes seen come back. @@ -92,58 +84,28 @@ async function watchDocumentSize(page: Page) { } const REM = 16 -/** The panel's own padding (`p-4` top and bottom): its box cannot be shorter than this. */ -const PANEL_PADDING_PX = 32 /** - * The panel is at most 34 rem and no wider than the viewport, and at scroll 0, halfway and - * at the end of the page its bottom is the nearer of the viewport's bottom and its - * container's bottom (its visible height is kept right on scroll). + * The sheet is a modal at the right edge: at most 34 rem and no wider than the viewport, + * as tall as the window whatever the page's scroll (it is in the top layer). */ -async function expectPanelWithin( - page: Page, - viewportWidth: number, - cramped = false, -) { +async function expectSheetWithin(page: Page, viewportWidth: number) { const layer = page.locator('[data-place="citations"]') const box = await layer.boundingBox() expect(box!.width).toBeLessThanOrEqual(34 * REM + 0.5) expect(box!.width).toBeLessThanOrEqual(viewportWidth) - for (const at of [0, 0.5, 1]) { - await page.evaluate((share) => { - const root = document.documentElement - window.scrollTo(0, (root.scrollHeight - window.innerHeight) * share) - }, at) - await page.evaluate( - () => new Promise((done) => requestAnimationFrame(() => done(null))), - ) - const edges = await page.evaluate(() => { - const container = document.querySelector('[data-place="citations"]')! - const panel = document.querySelector('#editor-citations-panel')! - const outer = container.getBoundingClientRect() - const inner = panel.getBoundingClientRect() - const viewport = window.visualViewport?.height ?? window.innerHeight - return { - panelBottom: inner.bottom, - expected: Math.min(viewport, outer.bottom), - panelTop: inner.top, - } - }) - if (edges.expected - edges.panelTop < PANEL_PADDING_PX) { - // Only the landscape phone at scroll 0 may leave less room than the padding. - expect( - cramped && at === 0, - `panel room below its padding at scroll share ${at}`, - ).toBe(true) - continue - } - expect( - Math.abs(edges.panelBottom - edges.expected), - `panel bottom at scroll share ${at}`, - ).toBeLessThanOrEqual(1) - expect(edges.panelBottom).toBeGreaterThan(edges.panelTop) - } - await page.evaluate(() => window.scrollTo(0, 0)) + const edges = await page.evaluate(() => { + const sheet = document.querySelector('[data-place="citations"]')! + const rect = sheet.getBoundingClientRect() + return { top: rect.top, bottom: rect.bottom, right: rect.right } + }) + expect(edges.top, 'sheet top').toBeLessThanOrEqual(1) + expect( + Math.abs(edges.right - viewportWidth), + 'sheet right edge', + ).toBeLessThan(1) + const height = await page.evaluate(() => window.innerHeight) + expect(Math.abs(edges.bottom - height), 'sheet bottom').toBeLessThanOrEqual(1) } async function settle(page: Page) { @@ -155,160 +117,6 @@ async function settle(page: Page) { ) } -/** Opens the finding by taps only: the caret of a closed row opens the branch. */ -async function tapFinding(page: Page, name: string) { - await openTab(page, dict, 'findings') - const item = page.getByRole('treeitem', { name }) - for (let depth = 0; depth < 4 && (await item.count()) === 0; depth++) { - const closed = page.getByRole('treeitem', { expanded: false }).first() - await closed.locator('span').first().tap() - } - await item.tap() -} - -/** The window's scrollY once two animation frames in a row agree (no fling left). */ -async function stableScrollY(page: Page) { - let last = -1 - for (let tries = 0; tries < 60; tries++) { - await settle(page) - const now = await page.evaluate(() => window.scrollY) - if (now === last) return now - last = now - } - throw new Error('the scroll never settled') -} - -/** The trigger's box; `gap` is the room between its bottom and the viewport bottom. */ -function triggerRect(trigger: Locator) { - return trigger.evaluate((el) => { - const box = el.getBoundingClientRect() - return { - top: box.top, - bottom: box.bottom, - gap: window.innerHeight - box.bottom, - } - }) -} - -/** One finger swipe on the page: `travel` > 0 moves the finger up (the page goes down). */ -async function touchSwipe(page: Page, cdp: CDPSession, travel: number) { - const from = 340 - const point = (y: number) => [{ x: 200, y }] - await cdp.send('Input.dispatchTouchEvent', { - type: 'touchStart', - touchPoints: point(from), - }) - for (let step = 1; step <= 10; step++) { - const y = from - (travel * step) / 10 - await cdp.send('Input.dispatchTouchEvent', { - type: 'touchMove', - touchPoints: point(y), - }) - } - await cdp.send('Input.dispatchTouchEvent', { - type: 'touchEnd', - touchPoints: [], - }) - return stableScrollY(page) -} - -/** Finger travel of each reach swipe, well above the touch slop (a swipe <= ~60 px moves 0). */ -const REACH_TRAVEL = 200 -const REACH_MAX_SWIPES = 12 - -/** - * Swipes by touch only until the trigger is wholly on screen and hit-testable. Answers the - * swipe count; throws with the scrollY trace after REACH_MAX_SWIPES swipes. - */ -async function swipeUntilReached( - page: Page, - cdp: CDPSession, - trigger: Locator, -) { - const trace: number[] = [] - for (let swipes = 0; swipes <= REACH_MAX_SWIPES; swipes++) { - const view = await probeInView(trigger) - if (view.inside && view.hit) return swipes - if (swipes < REACH_MAX_SWIPES) - trace.push(await touchSwipe(page, cdp, REACH_TRAVEL)) - } - throw new Error( - `the trigger never came into view: scrollY after each swipe ${trace.join(' ')}`, - ) -} - -/** Scrolls at once so the trigger's bottom sits on the viewport bottom (clamped to the page). */ -async function scrollToWorstCase(page: Page, trigger: Locator) { - await trigger.evaluate((el) => { - const max = document.documentElement.scrollHeight - window.innerHeight - const want = - window.scrollY + el.getBoundingClientRect().bottom - window.innerHeight - window.scrollTo({ - top: Math.min(Math.max(Math.ceil(want), 0), max), - behavior: 'instant', - }) - }) - return stableScrollY(page) -} - -/** Taps the trigger: the panel opens with heading and close in view, the page does not scroll. */ -async function tapOpensInPlace(page: Page, trigger: Locator, scrollY: number) { - expect(await probeInView(trigger), 'trigger in view').toEqual({ - inside: true, - hit: true, - }) - await trigger.tap() - await expect(page.locator('#editor-citations-title')).toBeFocused() - expect(await stableScrollY(page), 'no scroll once the panel is open').toBe( - scrollY, - ) - await expectPanelReachable(page) -} - -/** Whether the element is wholly on screen and the topmost thing at its centre. */ -function probeInView(target: Locator) { - return target.evaluate((el) => { - const box = el.getBoundingClientRect() - const at = document.elementFromPoint( - box.x + box.width / 2, - box.y + box.height / 2, - ) - const inside = - box.top >= 0 && - box.left >= 0 && - box.bottom <= window.innerHeight && - box.right <= window.innerWidth - return { inside, hit: !!at && el.contains(at) } - }) -} - -/** The open panel's heading and close button, in view and hit-testable, no scroll needed. */ -async function expectPanelReachable(page: Page) { - const panel = page.locator('#editor-citations-panel') - const heading = page.locator('#editor-citations-title') - const close = panel.getByRole('button', { - name: dict['editor.references.close'], - }) - const visible = await panel.evaluate( - (el) => - Math.min(el.getBoundingClientRect().bottom, window.innerHeight) - - Math.max(el.getBoundingClientRect().top, 0), - ) - test.info().annotations.push({ - type: 'c4-measure', - description: `panel visible ${visible}`, - }) - expect(visible).toBeGreaterThan(0) - expect(await probeInView(heading), 'heading').toEqual({ - inside: true, - hit: true, - }) - expect(await probeInView(close), 'close button').toEqual({ - inside: true, - hit: true, - }) -} - test.describe('editor shell layout (H)', () => { test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) test.beforeEach(async ({ context }, info) => { @@ -319,7 +127,7 @@ test.describe('editor shell layout (H)', () => { await dropLateReplays(context) }) - test('no horizontal scroll from 1 024 to 1 280 px on the five tabs, the three sections and the open citations panel', async ({ + test('no horizontal scroll from 1 024 to 1 280 px on the five tabs, the three sections and the open citations sheet', async ({ page, }) => { test.setTimeout(150_000) @@ -335,25 +143,26 @@ test.describe('editor shell layout (H)', () => { await expectNoHorizontalOverflow(page, `${section} at ${width} px`) } await openCitations(page, dict, 'Constat A') - await expectNoHorizontalOverflow(page, `the panel at ${width} px`) + await expectNoHorizontalOverflow(page, `the sheet at ${width} px`) await closeCitations(page, dict) + await closeFinding(page, dict) } }) - test('the open panel is at most 34 rem and the viewport wide, and the document never changes size, before, during and after', async ({ + test('the open sheet is at most 34 rem and the viewport wide, and the document never changes size, before, during and after', async ({ page, }) => { test.setTimeout(150_000) await open(page) for (const width of WIDTHS) { await page.setViewportSize({ width, height: 800 }) - await selectFinding(page, 'Constat A') + await openFinding(page, dict, 'Constat A') const stop = await watchDocumentSize(page) - await page.locator('[data-citations-trigger]:visible').click() - await expect(page.locator('#editor-citations-title')).toBeFocused() - await expectPanelWithin(page, width) - await expectNoHorizontalOverflow(page, `the open panel at ${width} px`) + await showCitations(page) + await expectSheetWithin(page, width) + await expectNoHorizontalOverflow(page, `the open sheet at ${width} px`) await closeCitations(page, dict) + await closeFinding(page, dict) const sizes = await stop() expect( sizes, @@ -396,7 +205,7 @@ test.describe('editor shell layout (H)', () => { } }) - test('the canvas width is the same before the citations panel opens and after a tab switch closes it', async ({ + test('the canvas width is the same before the citations sheet opens and after both layers close', async ({ page, }) => { test.setTimeout(150_000) @@ -413,7 +222,9 @@ test.describe('editor shell layout (H)', () => { description: `${before}px at ${width}px`, }) await openCitations(page, dict, 'Constat A') - // The panel exists on Constats only: leaving for Annotations closes it (P21). + await page.keyboard.press('Escape') + await page.keyboard.press('Escape') + await expectNoDialog(page) await selectTab(page, dict, 'annotations') await expect(place(page, 'citations')).toHaveCount(0) await expect(page.getByTestId('annotation-canvas')).toBeVisible() @@ -421,7 +232,7 @@ test.describe('editor shell layout (H)', () => { } }) - test('axe from the top on the five tabs, each section and the open citations panel', async ({ + test('axe from the top on the five tabs, each section and the open dialog and sheet', async ({ page, }) => { test.setTimeout(150_000) @@ -442,12 +253,14 @@ test.describe('editor shell layout (H)', () => { await expect(page.locator('dialog[open]')).toHaveCount(0) await expectAccessible(page, `${name} at ${width} px`) } - await openCitations(page, dict, 'Constat A') + await openFinding(page, dict, 'Constat A') await settle(page) - await page.evaluate(() => window.scrollTo(0, 0)) - await expect(page.locator('dialog[open]')).toHaveCount(0) - await expectAccessible(page, `the open panel at ${width} px`) + await expectAccessible(page, `the finding dialog at ${width} px`) + await showCitations(page) + await settle(page) + await expectAccessible(page, `the open sheet at ${width} px`) await closeCitations(page, dict) + await closeFinding(page, dict) } }) @@ -546,21 +359,31 @@ test.describe('editor shell keyboard order (H)', () => { expect(order).toEqual(['tab', 'undo', 'redo', 'tools', 'canvas', 'side']) }) - test('with the panel open: tab list, Défaire, Refaire, the panel, then the page content', async ({ + test('with the sheet open: Tab stays in the sheet; closed, the order is the page again', async ({ page, }) => { await open(page) await openCitations(page, dict, 'Constat A') - const order = await walk(page, 'panel') - test.info().annotations.push({ - type: 'keyboard-order-panel', - description: order.join(' > '), - }) - expect(order).toEqual(['tab', 'undo', 'redo', 'panel']) + const met = new Set() + for (let step = 0; step < 12; step++) { + await page.keyboard.press('Tab') + met.add(await focusKind(page)) + } + // The page behind the dialogs is inert: the tab row, Défaire and Refaire are out of reach. + for (const kind of [ + 'tab', + 'undo', + 'redo', + 'tools', + 'canvas', + 'side', + ] as const) { + expect(met.has(kind), `Tab reached ${kind}`).toBe(false) + } + expect(met.has('panel')).toBe(true) await page.keyboard.press('Escape') - await expect(page.locator('[data-place="citations"]:visible')).toHaveCount( - 0, - ) + await page.keyboard.press('Escape') + await expectNoDialog(page) await selectTab(page, dict, 'annotations') const after = await walk(page, 'side') expect(after.slice(0, 3)).toEqual(['tab', 'undo', 'redo']) @@ -569,7 +392,7 @@ test.describe('editor shell keyboard order (H)', () => { }) }) -test.describe('citations panel at 375 px, read-only (O4-2)', () => { +test.describe('citations sheet at 375 px, read-only (O4-2)', () => { test.use({ locale: 'fr-FR', actionTimeout: 15_000 }) test.beforeEach(async ({ context }, info) => { test.skip(!isPhone(info), 'the phone sizes are set by the test itself') @@ -579,7 +402,7 @@ test.describe('citations panel at 375 px, read-only (O4-2)', () => { await dropLateReplays(context) }) - test('full width, never wider than the screen, bottom on the viewport bottom through a height change and a rotation, the drawing box unchanged @phone', async ({ + test('the whole screen, never wider than it, as tall as the window through a height change and a rotation, the drawing box unchanged @phone', async ({ page, }) => { test.setTimeout(150_000) @@ -588,9 +411,7 @@ test.describe('citations panel at 375 px, read-only (O4-2)', () => { const drawingBox = () => place(page, 'annotations.drawing').boundingBox() await expect(place(page, 'annotations.drawing')).toBeVisible() const drawing = await drawingBox() - await selectFinding(page, 'Constat A') - await page.locator('[data-citations-trigger]:visible').click() - await expect(page.locator('#editor-citations-title')).toBeFocused() + await openCitations(page, dict, 'Constat A') for (const size of [ { width: 375, height: 667 }, { width: 375, height: 560 }, @@ -600,71 +421,30 @@ test.describe('citations panel at 375 px, read-only (O4-2)', () => { await page.evaluate( () => new Promise((done) => requestAnimationFrame(() => done(null))), ) - await expectPanelWithin(page, size.width, size.width === 667) + await expectSheetWithin(page, size.width) await expectNoHorizontalOverflow( page, - `the panel at ${size.width} x ${size.height}`, + `the sheet at ${size.width} x ${size.height}`, ) } await page.setViewportSize({ width: 375, height: 667 }) await closeCitations(page, dict) + await closeFinding(page, dict) await openTab(page, dict, 'annotations') await expect(place(page, 'annotations.drawing')).toBeVisible() expect(await drawingBox()).toEqual(drawing) }) - test('667 x 375: reached by touch; at the worst case the panel stays in view @phone', async ({ + test('the document size does not change while the dialog and the sheet open and close @phone', async ({ page, }) => { test.setTimeout(150_000) await open(page) - await page.setViewportSize({ width: 667, height: 375 }) - await tapFinding(page, 'Constat A') - const trigger = page.locator('[data-citations-trigger]:visible') - await expect(trigger).toBeVisible() - await page.evaluate(() => window.scrollTo(0, 0)) - expect(await stableScrollY(page), 'start at the top').toBe(0) - const start = await triggerRect(trigger) - // A. Reachability by touch swipes only (CDP touch events, no keyboard, no programmatic scroll). - const cdp = await page.context().newCDPSession(page) - const swipes = await swipeUntilReached(page, cdp, trigger) - const reached = await stableScrollY(page) - expect(reached, 'the page scrolled by touch').toBeGreaterThan(0) - await tapOpensInPlace(page, trigger, reached) - const close = page.getByRole('button', { - name: dict['editor.references.close'], - }) - await close.tap() - await expect(place(page, 'citations')).toHaveCount(0) - // B. Worst case: the trigger's bottom exactly on the viewport bottom. Set by window.scrollTo - // because touch has a slop floor and a load-dependent gain, so a pixel-exact touch landing - // is not deterministic; A already proves the trigger is reachable by touch. - const worst = await scrollToWorstCase(page, trigger) - const end = await triggerRect(trigger) - test.info().annotations.push({ - type: 'c4-measure', - description: - `top=${start.top} bottom=${start.bottom}; A swipes=${swipes} y=${reached}; ` + - `B gap=${end.gap} y=${worst}`, - }) - expect( - end.gap, - 'trigger gap to the viewport bottom', - ).toBeGreaterThanOrEqual(0) - expect(end.gap, 'trigger gap to the viewport bottom').toBeLessThanOrEqual(1) - await tapOpensInPlace(page, trigger, worst) - }) - - test('the document size does not change while the panel opens and closes @phone', async ({ - page, - }) => { - test.setTimeout(150_000) - await open(page) - await selectFinding(page, 'Constat A') + await openFinding(page, dict, 'Constat A') const stop = await watchDocumentSize(page) - await page.locator('[data-citations-trigger]:visible').click() - await expect(page.locator('#editor-citations-title')).toBeFocused() + await showCitations(page) await closeCitations(page, dict) + await closeFinding(page, dict) expect(await stop()).toHaveLength(1) }) }) diff --git a/apps/app/e2e/shell/editor-shell.spec.ts b/apps/app/e2e/shell/editor-shell.spec.ts index 43c02ad3..2a4b6d66 100644 --- a/apps/app/e2e/shell/editor-shell.spec.ts +++ b/apps/app/e2e/shell/editor-shell.spec.ts @@ -7,6 +7,7 @@ import { copyKeyOf, storedCopy, closeCitations, + closeFinding, editorActor, openEditor, openCitations, @@ -121,10 +122,11 @@ test.describe('editor shell, kept places (B2a)', () => { }) expect(repeated).toEqual([]) await closeCitations(page, dict) + await closeFinding(page, dict) }) for (const width of [1024, 1280]) { - test(`the open citations panel leaves the header and the tab row clickable at ${width} px`, async ({ + test(`the open citations sheet is modal: the header and the tab row are out of reach at ${width} px`, async ({ page, }) => { await page.setViewportSize({ width, height: 800 }) @@ -140,29 +142,20 @@ test.describe('editor shell, kept places (B2a)', () => { .getByRole('button', { name: dict['editor.reference.add'] }) .click() await openCitations(page, dict, 'Constat A') - const header = page.locator('main header').first() - const tabs = page.getByRole('tablist') - const panel = place(page, 'citations') const targets = [ page.getByRole('button', { name: dict['common.save'], exact: true }), page.getByRole('tab', { name: new RegExp(`^${dict['editor.tab.findings']}`), }), + historyButton(page, dict, 'undo'), ] - for (const scrolled of [false, true]) { - await page.evaluate((y) => window.scrollTo(0, y), scrolled ? 400 : 0) - for (const target of targets) await target.click({ trial: true }) - // « Défaire » / « Refaire » may be aria-disabled (a trial click would wait). - for (const kind of ['undo', 'redo'] as const) { - const button = historyButton(page, dict, kind) - await button.scrollIntoViewIfNeeded() - expect(await hitsItself(button)).toBe(true) - } - const box = await panel.boundingBox() - for (const above of [header, tabs]) { - const other = await above.boundingBox() - expect(box!.y).toBeGreaterThanOrEqual(other!.y + other!.height - 1) - } + for (const target of targets) { + expect(await hitsItself(target)).toBe(false) + } + await closeCitations(page, dict) + await closeFinding(page, dict) + for (const target of targets) { + expect(await hitsItself(target)).toBe(true) } }) } diff --git a/apps/app/e2e/shell/editor-structures.spec.ts b/apps/app/e2e/shell/editor-structures.spec.ts index 7f5e5670..2096e12d 100644 --- a/apps/app/e2e/shell/editor-structures.spec.ts +++ b/apps/app/e2e/shell/editor-structures.spec.ts @@ -4,7 +4,10 @@ import { expect, expectAccessible, test } from '../support/browser' import { dropLateReplays, routeToSandbox } from '../support/sandbox' import { bareShape, + closeFinding, editorActor, + expectNoDialog, + findingDialog, libraryRoot, openEditor, openTab, @@ -30,6 +33,8 @@ const dict = fr const isPhone = (info: TestInfo) => info.project.name === 'chromium-375' const dialog = (page: Page) => page.getByRole('dialog') +/** The deletion dialog over the finding dialog: the last dialog open. */ +const deleteDialog = (page: Page) => page.locator('dialog[open]').last() const button = (page: Page, name: string) => page.getByRole('button', { name, exact: true }) @@ -176,6 +181,8 @@ test.describe('editor structures (A4)', () => { await page .getByRole('button', { name: dict['editor.findings.create'] }) .click() + // « Créer » turns the dialog into the new zone's view: close it. + await closeFinding(page, dict) await expect(items.filter({ hasText: 'Zone B' })).toBeVisible() await page @@ -188,6 +195,7 @@ test.describe('editor structures (A4)', () => { await page .getByRole('button', { name: dict['editor.findings.create'] }) .click() + await closeFinding(page, dict) const category = items.filter({ hasText: 'Anamnèse B' }) await expect(category).toBeVisible() await expect( @@ -203,12 +211,12 @@ test.describe('editor structures (A4)', () => { .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 + // The dialog shows the new node: marked reviewed there, the badge of the row follows. + await findingDialog(page) .getByRole('button', { name: dict['editor.findings.mark_reviewed'] }) .click() + await closeFinding(page, dict) + await expect(node).toBeVisible() await expect( node.getByText(dict['editor.findings.status.reviewed']), ).toBeVisible() @@ -217,11 +225,12 @@ test.describe('editor structures (A4)', () => { await page.evaluate(() => window.scrollTo(0, 0)) await expectAccessible(page, 'the findings tree') - // Reorder: the new zone moves above the seeded one. + // Reorder: the new zone moves above the seeded one, from its dialog. await items.filter({ hasText: 'Zone B' }).first().click() - await page + await findingDialog(page) .getByRole('button', { name: dict['editor.action.move_up'] }) .click() + await closeFinding(page, dict) await expect(items.first()).toContainText('Zone B') await saveDraft(page, dict, seed.revision + 1) @@ -245,7 +254,14 @@ test.describe('editor structures (A4)', () => { await selectTab(page, dict, 'findings') const items = page.getByTestId('finding-item') await items.filter({ hasText: 'Catégorie nue' }).click() - await commitText(page.locator('#finding-name-fr'), 'Catégorie renommée') + await findingDialog(page) + .getByRole('button', { name: dict['editor.findings.edit'] }) + .click() + await page.locator('#finding-edit-name-fr').fill('Catégorie renommée') + await findingDialog(page) + .getByRole('button', { name: dict['editor.findings.save'] }) + .click() + await closeFinding(page, dict) await saveDraft(page, dict, seed.revision + 1) const saved = await serverDocument<{ @@ -300,18 +316,19 @@ test.describe('editor structures (A4)', () => { await selectTab(page, dict, 'findings') const zone = page.getByTestId('finding-item').filter({ hasText: 'Zone A' }) await zone.first().click() - await page + await findingDialog(page) .getByRole('button', { name: dict['editor.action.delete'] }) .click() await expect( - dialog(page).getByText( + deleteDialog(page).getByText( dict['editor.delete.blocked'].replace('{name}', 'Zone A'), ), ).toBeVisible() - await dialog(page) + await deleteDialog(page) .getByRole('button', { name: dict['editor.delete.close'], exact: true }) - .last() .click() + await expect(page.locator('dialog[open]')).toHaveCount(1) + await closeFinding(page, dict) // The point goes first; the zone then deletes with its descendants named. await showDrawing(page, dict) @@ -325,16 +342,18 @@ test.describe('editor structures (A4)', () => { .click() await selectTab(page, dict, 'findings') await zone.first().click() - await page + await findingDialog(page) .getByRole('button', { name: dict['editor.action.delete'] }) .click() await expect( - dialog(page).getByText(dict['editor.delete.descendants']), + deleteDialog(page).getByText(dict['editor.delete.descendants']), ).toBeVisible() - await expect(dialog(page).getByText('Dysfonction A')).toBeVisible() - await dialog(page) + await expect(deleteDialog(page).getByText('Dysfonction A')).toBeVisible() + await deleteDialog(page) .getByRole('button', { name: dict['editor.delete.confirm'] }) .click() + // The deletion closes both dialogs at once. + await expectNoDialog(page) await expect(page.getByTestId('finding-item')).toHaveCount(0) await expect(page.getByText(dict['editor.findings.empty'])).toBeVisible() }) diff --git a/apps/app/e2e/support/editor.ts b/apps/app/e2e/support/editor.ts index 50003dca..023ec5b1 100644 --- a/apps/app/e2e/support/editor.ts +++ b/apps/app/e2e/support/editor.ts @@ -421,11 +421,62 @@ export async function openTab(page: Page, dict: Dict, tab: string) { ).toBeVisible() } +/** The open finding dialog: the layer dialog that is not the citations sheet. */ +export const findingDialog = (page: Page): Locator => + page + .locator('dialog[open][data-layer]') + .filter({ hasNot: page.locator('[data-place="citations"]') }) + +/** Waits until no modal dialog is open: nothing is typed or pressed before (LRN-111/116). */ +export const expectNoDialog = (page: Page) => + expect(page.locator('dialog[open]')).toHaveCount(0) + /** - * Opens the citations panel of the finding named `element`: the Constats tab, the tree - * expanded down to it, the element selected, its « n références » trigger pressed, the - * slide over (the heading holds the focus). Expansion goes depth-first from the first - * zone, one node per step, at most `expansions` steps (4 is enough for a small fixture). + * The tree expanded down to the row named `element`, from the keyboard (a click on a row + * opens its dialog): depth-first from the first zone, one node per step, at most + * `expansions` steps (4 is enough for a small fixture). + */ +export async function revealFinding( + page: Page, + element: string, + expansions = 4, +): Promise { + const item = page.getByRole('treeitem', { name: element }) + for (let step = 0; step < expansions && (await item.count()) === 0; step++) { + const closed = page.getByRole('treeitem', { expanded: false }).first() + await closed.focus() + await closed.press('ArrowRight') + } + return item +} + +/** + * Opens the dialog of the finding named `element`: the Constats tab, the tree expanded + * down to it, its row activated (a click), the dialog open. + */ +export async function openFinding( + page: Page, + dict: Dict, + element: string, + expansions = 4, +) { + await openTab(page, dict, 'findings') + const item = await revealFinding(page, element, expansions) + await item.click() + await expect(findingDialog(page)).toBeVisible() +} + +/** Closes the finding dialog with its ✕ and waits until no dialog is left. */ +export async function closeFinding(page: Page, dict: Dict) { + await findingDialog(page) + .getByRole('button', { name: dict['common.close'], exact: true }) + .click() + await expectNoDialog(page) +} + +/** + * Opens the citations sheet of the finding named `element`: its dialog, then its + * « n références » trigger. The sheet lies over the dialog and holds the focus. */ export async function openCitations( page: Page, @@ -433,26 +484,24 @@ export async function openCitations( element: string, expansions = 4, ) { - await openTab(page, dict, 'findings') - const item = page.getByRole('treeitem', { name: element }) - for (let step = 0; step < expansions && (await item.count()) === 0; step++) { - const closed = page.getByRole('treeitem', { expanded: false }).first() - await closed.focus() - await closed.press('ArrowRight') - } - await item.click() - await page.locator('[data-citations-trigger]:visible').click() - await expect(place(page, 'citations')).toBeVisible() - // The slide is over when the panel's heading takes the focus (P9). - await expect(page.locator('#editor-citations-title')).toBeFocused() + await openFinding(page, dict, element, expansions) + await showCitations(page) } -/** Closes the citations panel with its ✕ button. */ +/** From the open finding dialog: « n références » opens the sheet over it. */ +export async function showCitations(page: Page) { + await page.locator('[data-citations-trigger]:visible').click() + await expect(place(page, 'citations')).toBeVisible() + await expect(page.locator('dialog[open]')).toHaveCount(2) +} + +/** Closes the citations sheet with its ✕: the finding dialog under it stays open. */ export async function closeCitations(page: Page, dict: Dict) { await page .getByRole('button', { name: dict['editor.references.close'] }) .click() await expect(place(page, 'citations')).toHaveCount(0) + await expect(page.locator('dialog[open]')).toHaveCount(1) } /** The revision the server holds for the draft. */ diff --git a/apps/app/e2e/support/warm-up.ts b/apps/app/e2e/support/warm-up.ts index a88c9c96..2bebcf42 100644 --- a/apps/app/e2e/support/warm-up.ts +++ b/apps/app/e2e/support/warm-up.ts @@ -11,6 +11,7 @@ import { stepUpAdmin } from './admin' import { TABS, closeCitations, + closeFinding, draftPath, editorActor, openCitations, @@ -49,6 +50,7 @@ export default async function warmUp(config: FullConfig): Promise { } await openCitations(page, fr, 'Constat A') await closeCitations(page, fr) + await closeFinding(page, fr) await page.goto('/app/admin/sheets/new') await page.waitForLoadState('networkidle') await browser.close() diff --git a/apps/app/src/components/editor/findings/FindingTree.tsx b/apps/app/src/components/editor/findings/FindingTree.tsx index a369abce..13f7dfd3 100644 --- a/apps/app/src/components/editor/findings/FindingTree.tsx +++ b/apps/app/src/components/editor/findings/FindingTree.tsx @@ -1,5 +1,5 @@ import { useEffect, useRef, type KeyboardEvent } from 'react' -import { afterModalsClosed } from '@/components/ui/afterModalsClosed' +import { landAfterModalsClosed } from '@/components/ui/afterModalsClosed' import StatusBadge from '@/components/editor/findings/StatusBadge' import { keyMove, type FindingItem } from '@/editor/findings/tree' import { useT } from '@/i18n/useT' @@ -38,7 +38,7 @@ export default function FindingTree(props: FindingTreeProps) { useEffect(() => { if (!focusId) return // After the dialogs a move closed: the page behind them is inert until then. - afterModalsClosed(() => refs.current.get(focusId.id)?.focus()) + landAfterModalsClosed(() => refs.current.get(focusId.id)?.focus()) onFocused() }, [focusId, onFocused]) const current = visible.find((item) => item.id === selectedId) ?? visible[0] diff --git a/apps/app/src/components/editor/references/useReferenceView.ts b/apps/app/src/components/editor/references/useReferenceView.ts index 176c3474..feed1168 100644 --- a/apps/app/src/components/editor/references/useReferenceView.ts +++ b/apps/app/src/components/editor/references/useReferenceView.ts @@ -27,7 +27,8 @@ interface Shown { /** * The search, the sort and the resulting tile order of the Références tab. All three are * display state: nothing here reaches the document (BDR-114). `resetSignal` (« Tout - * afficher ») empties the search and the sort once per bump; the tab stays mounted (A2). + * afficher ») empties the search once per bump and keeps the sort (R2F-4); the tab stays + * mounted (A2). * The tile that entered edit is pinned at the index it was shown at, whatever the search * or the sort, and stays pinned after « Terminer » until the next search or sort change, * so the tile the user just edited never vanishes under their focus (P23, I1). A @@ -50,7 +51,7 @@ export function useReferenceView( : { key, index: keys.indexOf(key) } if (seen !== resetSignal) { setSeen(resetSignal) - setView(INITIAL) + setView({ ...view, query: '' }) setPinned(pinEdited(editingKey)) } const pinAt = pinned === null ? -1 : keys.indexOf(pinned.key) diff --git a/apps/app/src/components/ui/afterModalsClosed.ts b/apps/app/src/components/ui/afterModalsClosed.ts index d5ff2b9e..cb564924 100644 --- a/apps/app/src/components/ui/afterModalsClosed.ts +++ b/apps/app/src/components/ui/afterModalsClosed.ts @@ -28,3 +28,12 @@ export function flushAfterModals(): void { waiting.clear() ready.forEach((fn) => fn()) } + +/** + * `afterModalsClosed` for a focus landing: a dialog closed in the same commit restores + * its own focus in a microtask queued before this call, so the landing waits one more + * microtask and is never undone by it. + */ +export function landAfterModalsClosed(fn: () => void): () => void { + return afterModalsClosed(() => queueMicrotask(fn)) +} diff --git a/apps/app/src/editor/focusRequest.ts b/apps/app/src/editor/focusRequest.ts index 2077824e..e6562e1f 100644 --- a/apps/app/src/editor/focusRequest.ts +++ b/apps/app/src/editor/focusRequest.ts @@ -1,6 +1,6 @@ import { createContext, useContext, useEffect, useRef } from 'react' import type { ElementKey } from '@faunosteo/core-wasm/types' -import { afterModalsClosed } from '@/components/ui/afterModalsClosed' +import { landAfterModalsClosed } from '@/components/ui/afterModalsClosed' import type { AnnotationSection, EditorTarget, @@ -107,7 +107,7 @@ export function focusRow(key: ElementKey): boolean { */ export function focusRowLater(key: ElementKey): boolean { if (!rowOf(key)) return false - afterModalsClosed(() => void focusRow(key)) + landAfterModalsClosed(() => void focusRow(key)) return true } diff --git a/apps/app/src/editor/history/useEditorHistory.ts b/apps/app/src/editor/history/useEditorHistory.ts index 68c6c2e0..6ac135ac 100644 --- a/apps/app/src/editor/history/useEditorHistory.ts +++ b/apps/app/src/editor/history/useEditorHistory.ts @@ -1,6 +1,6 @@ import { useEffect, useMemo, useRef, useState } from 'react' import { useLocation, useNavigate, useNavigationType } from 'react-router-dom' -import { afterModalsClosed } from '@/components/ui/afterModalsClosed' +import { landAfterModalsClosed } from '@/components/ui/afterModalsClosed' import { focusActiveTab } from '../focusRequest' import { sameView, type EditorView } from '../navigation' import { @@ -248,7 +248,7 @@ function useLanding( if (!landing || landed.current === landing) return landed.current = landing const { id, view } = landing.entry - return afterModalsClosed(() => { + return landAfterModalsClosed(() => { window.scrollTo(0, book.scrolls.get(id) ?? 0) landFocus(landing) if (landing.layerChanged && !landing.tabChanged) return diff --git a/apps/app/src/editor/useEditorNavigation.ts b/apps/app/src/editor/useEditorNavigation.ts index 3a062f60..f0146358 100644 --- a/apps/app/src/editor/useEditorNavigation.ts +++ b/apps/app/src/editor/useEditorNavigation.ts @@ -9,7 +9,10 @@ import { type RefObject, } from 'react' import type { ElementKey } from '@faunosteo/core-wasm/types' -import { afterModalsClosed } from '@/components/ui/afterModalsClosed' +import { + afterModalsClosed, + landAfterModalsClosed, +} from '@/components/ui/afterModalsClosed' import { useT } from '@/i18n/useT' import { commitFocusedField, @@ -393,7 +396,7 @@ function useMoveFocus( if (outcome === 'found' || outcome === 'kept') return dispatch({ type: 'focus_consumed', serial }) } - afterModalsClosed(() => { + landAfterModalsClosed(() => { if (move.kind === 'back') backTarget(openers.section.current)?.focus() else landingOf(move, state)?.focus() }) diff --git a/apps/app/tests/unit/editor-focus-request.test.tsx b/apps/app/tests/unit/editor-focus-request.test.tsx index 177ba50b..73f71a45 100644 --- a/apps/app/tests/unit/editor-focus-request.test.tsx +++ b/apps/app/tests/unit/editor-focus-request.test.tsx @@ -167,8 +167,11 @@ describe('focus requests', () => { focus={request({ kind: 'reference', id: 'ref-a' })} />, ) - expect(document.activeElement?.getAttribute('data-focus-key')).toContain( - 'ref-a', + // The landing waits for any dialog a move closed: one microtask when none is open. + await waitFor(() => + expect(document.activeElement?.getAttribute('data-focus-key')).toContain( + 'ref-a', + ), ) cleanup() render( @@ -434,8 +437,10 @@ describe('a consumed request', () => { await openReady({ text }) const user = userEvent.setup() render() - expect(document.activeElement?.getAttribute('data-focus-key')).toContain( - 'ref-a', + await waitFor(() => + expect(document.activeElement?.getAttribute('data-focus-key')).toContain( + 'ref-a', + ), ) await user.click(screen.getByText('switch')) await user.click(screen.getByText('switch')) diff --git a/apps/app/tests/unit/editor-references-panel.test.tsx b/apps/app/tests/unit/editor-references-panel.test.tsx index f6cffa41..c4ec722e 100644 --- a/apps/app/tests/unit/editor-references-panel.test.tsx +++ b/apps/app/tests/unit/editor-references-panel.test.tsx @@ -421,7 +421,7 @@ describe('the exit', () => { }) describe('the library and the history around the panel', () => { - it('« Tout afficher » resets the search and the sort of the tab, open tiles kept (P4)', async () => { + it('« Tout afficher » clears the search of the tab and keeps its sort, open tiles kept (P4)', async () => { const user = await mount() await user.click(screen.getByRole('tab', { name: 'Références' })) const tab = () => screen.getByRole('tabpanel', { name: 'Références' }) @@ -435,7 +435,7 @@ describe('the library and the history around the panel', () => { await user.click(link()) await closed() expect(within(tab()).getByRole('searchbox')).toHaveValue('') - expect(within(tab()).getByLabelText('Trier par')).toHaveValue('sheet') + expect(within(tab()).getByLabelText('Trier par')).toHaveValue('citation') expect(within(tab()).getAllByRole('listitem').length).toBeGreaterThan(2) expect( within(tab()).getByRole('button', { name: /^Barone/ }), diff --git a/apps/app/tests/unit/editor-references-view.test.tsx b/apps/app/tests/unit/editor-references-view.test.tsx index 3e769d96..8238c9f1 100644 --- a/apps/app/tests/unit/editor-references-view.test.tsx +++ b/apps/app/tests/unit/editor-references-view.test.tsx @@ -584,7 +584,7 @@ describe('adding (P24)', () => { }) describe('the reset path (« Tout afficher »)', () => { - it('empties the search and the sort, keeping open tiles and the tile in edit', async () => { + it('empties the search and keeps the sort, keeping open tiles and the tile in edit (R2F-4)', async () => { await openReady({ text: sortText() }) const user = userEvent.setup() const view = render(lib(false, { libraryReset: 0 })) @@ -594,7 +594,7 @@ describe('the reset path (« Tout afficher »)', () => { await user.type(search(), 'e') view.rerender(lib(false, { libraryReset: 1 })) expect(search()).toHaveValue('') - expect(sortBox()).toHaveValue('sheet') + expect(sortBox()).toHaveValue('citation') expect(order()).toHaveLength(5) expect(header('r2')).toHaveAttribute('aria-expanded', 'true') expect(within(item).getByLabelText('Citation')).toBeInTheDocument()