From 6bf9290da714628e18b5fd3cc5cd65a9424a0b6d Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 13 Nov 2026 23:42:32 +0100 Subject: [PATCH] fix(editor): final review round, history, dialogs, Plus and limits I1 scroll restored at once on a Back into layers; I2 Aller a opens the target dialog in one push; M1-M9, criteria 8 and 17 (left-draft notice), entry caps, no exhaustive-deps disables, locals within 5. --- apps/app/e2e/shell/editor-citations.spec.ts | 13 +- .../shell/editor-reference-journey.spec.ts | 36 ++++ .../src/components/editor/EditorWorkspace.tsx | 69 ++++-- .../editor/findings/FindingCreateForm.tsx | 70 ++++--- .../editor/references/ReferenceDialog.tsx | 36 +++- .../editor/references/useReferenceLibrary.ts | 9 +- .../components/editor/tabs/FindingsTab.tsx | 43 ++-- apps/app/src/components/editor/useMoreMenu.ts | 20 ++ apps/app/src/components/ui/ModalDialog.tsx | 105 ++++++---- .../src/components/ui/afterModalsClosed.ts | 28 ++- apps/app/src/editor/focusRequest.ts | 5 +- apps/app/src/editor/history/entry.ts | 43 ++-- .../src/editor/history/useEditorHistory.ts | 198 +++++++++++++----- apps/app/src/editor/leftDraft.ts | 88 ++++++++ apps/app/src/editor/navigation.ts | 21 +- apps/app/src/editor/useEditorNavigation.ts | 19 +- apps/app/src/editor/useReferenceMoves.ts | 19 +- apps/app/src/i18n/en.ts | 3 + apps/app/src/i18n/fr.ts | 2 + .../tests/unit/editor-finding-dialog.test.tsx | 91 ++++++++ .../tests/unit/editor-history-entry.test.ts | 54 +++++ .../tests/unit/editor-history-guards.test.tsx | 161 +++++++++++++- apps/app/tests/unit/editor-more-menu.test.tsx | 15 ++ apps/app/tests/unit/editor-navigation.test.ts | 29 ++- .../unit/editor-reference-dialog.test.tsx | 27 +++ 25 files changed, 1002 insertions(+), 202 deletions(-) create mode 100644 apps/app/src/editor/leftDraft.ts diff --git a/apps/app/e2e/shell/editor-citations.spec.ts b/apps/app/e2e/shell/editor-citations.spec.ts index 76ca2bd0..4d21deb1 100644 --- a/apps/app/e2e/shell/editor-citations.spec.ts +++ b/apps/app/e2e/shell/editor-citations.spec.ts @@ -491,9 +491,20 @@ for (const reduced of [false, true]) { // The sheet closes and the family opens in the dialog (view mode); closed, the // row holds the focus. await expect(place(page, 'citations')).toHaveCount(0) + const family = findingDialog(page).getByRole('heading', { + name: 'Dysfonction A', + }) + await expect(family).toBeVisible() + // Back returns to the place « Aller à » left: Constat A with its sheet open. + await page.goBack() + await expect(page.locator('dialog[open]')).toHaveCount(2) + await expect(place(page, 'citations')).toBeVisible() await expect( - findingDialog(page).getByRole('heading', { name: 'Dysfonction A' }), + findingDialog(page).getByRole('heading', { name: 'Constat A' }), ).toBeVisible() + await page.goForward() + await expect(place(page, 'citations')).toHaveCount(0) + await expect(family).toBeVisible() await closeFinding(page, dict) await expect( page.getByRole('treeitem', { name: /Dysfonction A/ }), diff --git a/apps/app/e2e/shell/editor-reference-journey.spec.ts b/apps/app/e2e/shell/editor-reference-journey.spec.ts index 4382fed4..6c4d1fe2 100644 --- a/apps/app/e2e/shell/editor-reference-journey.spec.ts +++ b/apps/app/e2e/shell/editor-reference-journey.spec.ts @@ -80,6 +80,31 @@ async function entryHolds(page: Page, test: string) { ) } +/** A Back restores the page offset within this many pixels. */ +const SCROLL_SLACK = 4 + +const scrollY = (page: Page) => page.evaluate(() => window.scrollY) + +/** + * Pads the page so it can scroll whatever the viewport, then moves it to `y` (a page + * behind a modal still scrolls by script). Answers the offset reached. + */ +async function scrollTreeTo(page: Page, y: number): Promise { + await page.evaluate((top) => { + document.body.style.paddingBottom = '3000px' + window.scrollTo(0, top) + }, y) + const reached = await scrollY(page) + expect(reached).toBeGreaterThan(0) + return reached +} + +async function expectScrollNear(page: Page, y: number) { + await expect + .poll(async () => Math.abs((await scrollY(page)) - y)) + .toBeLessThanOrEqual(SCROLL_SLACK) +} + /** Whether the sheet is the dialog on top at the right edge of the viewport. */ const sheetOnTop = (page: Page) => page.evaluate(() => { @@ -127,6 +152,9 @@ test.describe('the owner journey through the history', () => { await expect(place(page, 'citations')).toBeVisible() await expect(sheetHeaders(page)).toHaveCount(2) await entryHolds(page, 'view.finding && view.finding.citations') + // The tree behind the dialogs sits at an offset of its own (the page is padded so it + // can scroll whatever the viewport): Back must return to it. + const left = await scrollTreeTo(page, 400) // 5. « Tout afficher dans l'onglet Références »; 6. the tab filtered on A's two references. await panel(page) .getByRole('button', { name: dict['editor.references.panel_show_all'] }) @@ -141,6 +169,7 @@ test.describe('the owner journey through the history', () => { await expect( libraryRoot(page).getByText('2 références', { exact: true }), ).toBeVisible() + expect(Math.abs((await scrollY(page)) - left)).toBeGreaterThan(SCROLL_SLACK) // 7. browser Back; 8. finding A with its sheet on top, as left. await page.goBack() await expect(dialogs(page)).toHaveCount(2) @@ -148,6 +177,13 @@ test.describe('the owner journey through the history', () => { await expect(findingDialog(page)).toContainText('Constat A') expect(await sheetOnTop(page)).toBe(true) await expect(sheetHeaders(page)).toHaveCount(2) + await expectScrollNear(page, left) + // Closed by Escape (sheet, then dialog): the tree stays where it was left. + await page.keyboard.press('Escape') + await expect(dialogs(page)).toHaveCount(1) + await page.keyboard.press('Escape') + await expectNoDialog(page) + await expectScrollNear(page, left) }) test('eight steps: finding, sheet, filter, edit, Back, Forward, Revenir au constat, every Back', async ({ diff --git a/apps/app/src/components/editor/EditorWorkspace.tsx b/apps/app/src/components/editor/EditorWorkspace.tsx index cd51a9b7..fb494704 100644 --- a/apps/app/src/components/editor/EditorWorkspace.tsx +++ b/apps/app/src/components/editor/EditorWorkspace.tsx @@ -7,8 +7,13 @@ import { AnnounceContext, FocusConsumedContext } from '@/editor/focusRequest' import { saveFailureMessage } from '@/editor/messages' import type { EditorMode } from '@/editor/mode' import { useEditorStore } from '@/editor/state/editorStore' -import { ownedEntry, withoutForms } from '@/editor/history/entry' +import { + ownedEntry, + withoutForms, + type HistoryOwner, +} from '@/editor/history/entry' import useEditorHistory from '@/editor/history/useEditorHistory' +import { useLeftDraft } from '@/editor/leftDraft' import { citationsOfView, defaultView } from '@/editor/navigation' import { findingLayerOf, referenceLayerOf } from '@/editor/findingLayer' import { initialTab } from '@/editor/tabs' @@ -119,44 +124,72 @@ function Places({ nav, readOnly, reloadSheet }: PlacesProps) { ) } -/** - * The draft page once the version is ready: header, notices, tab row, the citations - * panel and the shown place. Owns the navigation state, so the first tab is known at - * mount (`initialTab`) and later edits never move the user off their tab. - */ -export default function EditorWorkspace(props: Props) { - const { sheet, mode, readOnly, tier, reloadSheet } = props - const previewState = useEditorStore((s) => s.previewState) - const tab = previewState ? initialTab(previewState, tier) : 'annotations' +/** The sheet and the account the history entries of this editor belong to. */ +function useOwner(sheetId: string): HistoryOwner { const userId = useAuthStore((s) => s.user?.id ?? '') - const owner = useMemo( - () => ({ sheetId: sheet.sheet_id, userId }), - [sheet.sheet_id, userId], - ) - // A reload or a reopened entry shows the view the history kept, never a layer. + return useMemo(() => ({ sheetId, userId }), [sheetId, userId]) +} + +/** A reload or a reopened entry shows the view the history kept, never a layer. */ +function useRestoredView(owner: HistoryOwner) { const { state } = useLocation() const [view] = useState(() => { const entry = ownedEntry(state, owner) return entry && withoutForms(entry.view) }) - const nav = useEditorNavigation(tab, view) + return view +} + +/** + * The navigation of this sheet for this account: the first tab known at mount + * (`initialTab`), the view a kept entry holds, the browser history in step with it, and + * whether the last editor left a dirty dialog behind. + */ +function useWorkspaceNavigation(sheetId: string, tier: TabTier) { + const previewState = useEditorStore((s) => s.previewState) + const tab = previewState ? initialTab(previewState, tier) : 'annotations' + const owner = useOwner(sheetId) + const nav = useEditorNavigation(tab, useRestoredView(owner)) useEditorHistory(nav, owner, defaultView(tab)) + return { nav, left: useLeftDraft(nav, owner) } +} + +/** The last editor of this sheet was left with a dirty dialog: said once. */ +function LeftDraftNotice({ shown }: { shown: boolean }) { + const t = useT() + if (!shown) return null + return {t('editor.leave.draft_dropped')} +} + +/** + * The draft page once the version is ready: header, notices, tab row, the citations + * panel and the shown place. Owns the navigation state, so the first tab is known at + * mount and later edits never move the user off their tab. + */ +export default function EditorWorkspace(props: Props) { + const { sheet, mode, readOnly } = props + const { nav, left } = useWorkspaceNavigation(sheet.sheet_id, props.tier) return (
+ - +

diff --git a/apps/app/src/components/editor/findings/FindingCreateForm.tsx b/apps/app/src/components/editor/findings/FindingCreateForm.tsx index a2b73a35..3dd51946 100644 --- a/apps/app/src/components/editor/findings/FindingCreateForm.tsx +++ b/apps/app/src/components/editor/findings/FindingCreateForm.tsx @@ -1,4 +1,3 @@ -import { useState } from 'react' import type { EditCommand, FindingCategoryKind, @@ -44,15 +43,17 @@ export interface FindingCreateFormProps { onClose: (forced: boolean) => void } +/** What the form holds before « Créer »; the zone of a category is part of it. */ interface Draft { fr: string en: string kind: string + zone: string } -const EMPTY: Draft = { fr: '', en: '', kind: '' } +const EMPTY: Draft = { fr: '', en: '', kind: '', zone: '' } const sameDraft = (a: Draft, b: Draft) => - a.fr === b.fr && a.en === b.en && a.kind === b.kind + a.fr === b.fr && a.en === b.en && a.kind === b.kind && a.zone === b.zone /** What the core requires before an insert: both names, a zone and a kind for a category. */ function isComplete(draft: Draft, pending: PendingFinding, parent: unknown) { @@ -76,14 +77,23 @@ function insertNew( return added ? createdId : null } +/** With exactly one zone it is preselected: the form starts on it, nothing typed yet. */ +const preselected = (zones: readonly FindingItem[]) => + zones.length === 1 ? zones[0].zoneId : '' + /** The form's state and its one `insert` (« Créer »), refused on a missing field. */ function useCreateForm(props: FindingCreateFormProps) { const edit = useEditCommand() - const zones = useZoneChoice() - const form = useFormDraft(EMPTY, props.guards, sameDraft) + const zones = useZones() + const form = useFormDraft( + { ...EMPTY, zone: preselected(zones) }, + props.guards, + sameDraft, + ) + const chosen = zones.find((zone) => zone.zoneId === form.draft.zone) ?? null const create = () => { const { pending } = props - const parent = pending.kind === 'category' ? zones.chosen : pending.parent + const parent = pending.kind === 'category' ? chosen : pending.parent if (!isComplete(form.draft, pending, parent)) { edit.reject('form', 'editor.findings.required') return @@ -91,7 +101,7 @@ function useCreateForm(props: FindingCreateFormProps) { const id = insertNew(edit, pending, parent, form.draft) if (id !== null) props.onCreated(id, parent) } - return { ...form, zones, create, error: edit.fieldError('form') } + return { ...form, zones, chosen, create, error: edit.fieldError('form') } } /** The kind choice of a category and its two names, as draft fields. */ @@ -108,7 +118,14 @@ function CreateFields(props: { })) return (

- {category && } + {category && ( + form.set({ zone })} + /> + )} {category && ( {props.readOnly && } - {category && form.zones.chosen && } + {category && form.chosen && } {form.error && (

@@ -172,30 +189,17 @@ export default function FindingCreateForm(props: FindingCreateFormProps) { ) } -interface ZoneChoice { - zones: readonly FindingItem[] - zoneId: string - setZoneId: (id: string) => void - chosen: FindingItem | null -} - -/** The zones to choose from; with exactly one, it is preselected, otherwise nothing is. */ -function useZoneChoice(): ZoneChoice { +/** The zones a new category can go in. */ +function useZones(): readonly FindingItem[] { const doc = useSheetDocument() - const zones = doc ? buildItems(doc).filter((i) => i.kind === 'zone') : [] - const [zoneId, setZoneId] = useState( - zones.length === 1 ? zones[0].zoneId : '', - ) - const chosen = zones.find((zone) => zone.zoneId === zoneId) ?? null - return { zones, zoneId, setZoneId, chosen } + return doc ? buildItems(doc).filter((i) => i.kind === 'zone') : [] } -function ZoneSelect({ - zones, - readOnly, -}: { - zones: ZoneChoice +function ZoneSelect(props: { + zones: readonly FindingItem[] + value: string readOnly: boolean + onCommit: (zoneId: string) => void }) { const t = useT() const locale = useLocaleStore((s) => s.locale) @@ -203,16 +207,16 @@ function ZoneSelect({ ({ + ...props.zones.map((zone) => ({ value: zone.zoneId, label: zone.name[locale], })), ]} - onCommit={zones.setZoneId} + onCommit={props.onCommit} /> ) } diff --git a/apps/app/src/components/editor/references/ReferenceDialog.tsx b/apps/app/src/components/editor/references/ReferenceDialog.tsx index 42b42238..b2f5b315 100644 --- a/apps/app/src/components/editor/references/ReferenceDialog.tsx +++ b/apps/app/src/components/editor/references/ReferenceDialog.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef } from 'react' +import { useCallback, useEffect, useRef, useState } from 'react' import type { Reference } from '@faunosteo/core-wasm/types' import Dialog from '@/components/ui/Dialog' import { visibleElement } from '@/editor/focusRequest' @@ -60,12 +60,28 @@ function useReturnTarget(layer: ReferenceLayer) { }, [opener]) } +/** + * The reference a creation just handed its entry over to (`layer.created`): the dialog + * still shows the creation while it closes, never « Modifier la référence ». Forgotten + * once the layer is closed. + */ +function useHandOver(layer: ReferenceLayer) { + const [handed, setHanded] = useState(null) + if (handed !== null && !layer.view) setHanded(null) + return { handed, handOver: setHanded } +} + +/** A creation, or the reference a creation was just handed over to. */ +function isCreation(view: View, handed: string | null): boolean { + return !!view && ('create' in view || view.edit === handed) +} + /** What the layer shows: a creation, or the reference it edits (null once it is gone). */ -function useShownReference(layer: ReferenceLayer) { +function useShownReference(layer: ReferenceLayer, handed: string | null) { const t = useT() const doc = useSheetDocument() - const creating = !!layer.view && 'create' in layer.view - const edited = editedIn(layer.view, doc?.references) + const creating = isCreation(layer.view, handed) + const edited = creating ? null : editedIn(layer.view, doc?.references) const title = creating ? 'editor.reference.new' : 'editor.references.edit_title' @@ -73,10 +89,15 @@ function useShownReference(layer: ReferenceLayer) { } /** What a save does: a creation is announced, then handed over; an edit closes the layer. */ -function useOnSaved(layer: ReferenceLayer, creating: boolean) { +function useOnSaved( + layer: ReferenceLayer, + creating: boolean, + handOver: (id: string) => void, +) { const t = useT() return (id: string, citation: string) => { if (!creating) return void layer.close(true) + handOver(id) layer.announce(t('editor.references.added').replace('{citation}', citation)) layer.created(id) } @@ -92,9 +113,10 @@ export default function ReferenceDialog({ layer, readOnly, }: ReferenceDialogProps) { - const shown = useShownReference(layer) + const creation = useHandOver(layer) + const shown = useShownReference(layer, creation.handed) const returnFocus = useReturnTarget(layer) - const onSaved = useOnSaved(layer, shown.creating) + const onSaved = useOnSaved(layer, shown.creating, creation.handOver) useGoneRule(layer) return (

void>(() => undefined) + clear.current = () => layer.clearFilter(t('editor.references.filter_gone')) useEffect(() => { - if (gone) layer.clearFilter(t('editor.references.filter_gone')) - // The wording and the move are stable per render; the vanished finding is the trigger. - // eslint-disable-next-line react-hooks/exhaustive-deps + if (gone) clear.current() }, [gone]) return { finding, cited: finding ? new Set(citedIds(finding)) : null } } diff --git a/apps/app/src/components/editor/tabs/FindingsTab.tsx b/apps/app/src/components/editor/tabs/FindingsTab.tsx index c4f778d8..74e010a7 100644 --- a/apps/app/src/components/editor/tabs/FindingsTab.tsx +++ b/apps/app/src/components/editor/tabs/FindingsTab.tsx @@ -6,7 +6,7 @@ import AddBar from '@/components/editor/findings/AddBar' import FindingDialog from '@/components/editor/findings/FindingDialog' import type { PendingFinding } from '@/components/editor/findings/FindingCreateForm' import FindingTree from '@/components/editor/findings/FindingTree' -import { afterModalsClosed } from '@/components/ui/afterModalsClosed' +import { landAfterModalsClosed } from '@/components/ui/afterModalsClosed' import { buildItems, createdItemId, @@ -62,13 +62,14 @@ function useFindingDeletion( setAsk({ target, fallback: fallbackAfterRemoval(items, item) }) } // The element is gone: its dialog closes in the same move (replace, no Back step) and - // the focus lands on the nearest row once every dialog is closed. + // the focus lands on the nearest row once every dialog is closed, unless a newer + // landing supersedes it. const closeDelete = () => { setAsk(null) if (!ask || currentItems().some((item) => item.id === selectedId)) return actions.select(ask.fallback) actions.closeLayer() - afterModalsClosed(() => actions.focusItem(ask.fallback)) + landAfterModalsClosed(() => actions.focusItem(ask.fallback)) } return { deleting: ask?.target ?? null, askDelete, closeDelete } } @@ -81,17 +82,18 @@ function useSelectionOfLayer( ) { const { view } = layer const wanted = view && 'key' in view ? JSON.stringify(view.key) : null + // `show` only sets state: the layer's key and the tree are what the effect follows. + const reveal = useRef(show) + reveal.current = show useEffect(() => { const found = wanted && itemForKey(items, JSON.parse(wanted)) - if (found) show(found) - // `show` only sets state; the layer's key and the tree are what it follows. - // eslint-disable-next-line react-hooks/exhaustive-deps + if (found) reveal.current(found) }, [wanted, items]) } /** - * The element the dialog shows vanished (a reload after a conflict): the layer closes by - * replace and says so; a creation whose parent vanished closes silently. + * The element the dialog shows, or the parent of a creation, vanished (a reload after a + * conflict): the layer closes by replace and says so, with the dropped entry if any. */ function useGoneRule(layer: FindingLayer, loaded: boolean) { const t = useT() @@ -100,8 +102,7 @@ function useGoneRule(layer: FindingLayer, loaded: boolean) { useEffect(() => { if (!view) handled.current = null if (!loaded || !view) return - const named = 'key' in view - const key = named ? view.key : view.create.parent + const key = 'key' in view ? view.key : view.create.parent const stamp = JSON.stringify(view) const present = (i: FindingItem) => key !== null && sameKey(i.key, key) if (key === null || currentItems().some(present)) return @@ -109,9 +110,7 @@ function useGoneRule(layer: FindingLayer, loaded: boolean) { handled.current = stamp // After this commit's effects: a tile in edit re-registers its guard in them, and the // forced close below must still be able to ask it. - queueMicrotask(() => - layer.replace(null, named ? t('editor.findings.gone') : undefined), - ) + queueMicrotask(() => layer.replace(null, t('editor.findings.gone'))) }, [loaded, view, layer, t]) } @@ -261,6 +260,11 @@ function useFindingsData() { return { doc, items } } +/** The element the layer's dialog shows, read from the tree; null for none or a creation. */ +function shownOf(view: FindingLayer['view'], items: readonly FindingItem[]) { + return view && 'key' in view ? itemForKey(items, view.key) : null +} + /** Everything the tab shows and does, so the component only lays it out. */ function useFindingsTab(focus: EditorPlaceProps['focus'], layer: FindingLayer) { const data = useFindingsData() @@ -269,11 +273,14 @@ function useFindingsTab(focus: EditorPlaceProps['focus'], layer: FindingLayer) { const ctx = { layer, items: data.items, sel, land: landing.land } useLayerFollow(focus, ctx) useGoneRule(layer, data.doc !== null) - const actions = useFindingActions(ctx) - const returnFocus = useReturnTarget(layer.view) - const { view } = layer - const shown = view && 'key' in view ? itemForKey(data.items, view.key) : null - return { ...data, sel, landing, actions, returnFocus, shown } + return { + ...data, + sel, + landing, + actions: useFindingActions(ctx), + returnFocus: useReturnTarget(layer.view), + shown: shownOf(layer.view, data.items), + } } /** Constats: the tree zones → categories → nodes; each element opens in a dialog. */ diff --git a/apps/app/src/components/editor/useMoreMenu.ts b/apps/app/src/components/editor/useMoreMenu.ts index eb0f152f..d14d6172 100644 --- a/apps/app/src/components/editor/useMoreMenu.ts +++ b/apps/app/src/components/editor/useMoreMenu.ts @@ -110,9 +110,29 @@ function useBackRequest(open: boolean, close: () => void) { }, [open, close]) } +/** + * Keyboard focus that leaves the trigger and the list closes « Plus »: the open overlay + * would cover the control the focus reached (WCAG 2.4.11). A focus that goes nowhere in + * the page (the browser's own interface) leaves it open. + */ +function useFocusLeave(open: boolean, close: () => void) { + useEffect(() => { + if (!open) return + const onOut = (event: FocusEvent) => { + const from = event.target instanceof Element ? event.target : null + const to = event.relatedTarget + if (!from?.closest(MENU_PARTS) || !(to instanceof Element)) return + if (!to.closest(MENU_PARTS)) close() + } + document.addEventListener('focusout', onOut, true) + return () => document.removeEventListener('focusout', onOut, true) + }, [open, close]) +} + /** Every way « Plus » closes besides a selection and a tab change. */ export function useMoreDismiss(open: boolean, close: () => void) { useMoreEscape(open, close) useOutsidePress(open, close) useBackRequest(open, close) + useFocusLeave(open, close) } diff --git a/apps/app/src/components/ui/ModalDialog.tsx b/apps/app/src/components/ui/ModalDialog.tsx index a924181b..2270e384 100644 --- a/apps/app/src/components/ui/ModalDialog.tsx +++ b/apps/app/src/components/ui/ModalDialog.tsx @@ -1,9 +1,11 @@ import { useIsPresent } from 'motion/react' import { + useCallback, useLayoutEffect, useRef, type KeyboardEvent, type ReactNode, + type RefObject, type SyntheticEvent, } from 'react' import { flushAfterModals } from './afterModalsClosed' @@ -89,34 +91,27 @@ function restoreFocus( } } -/** - * Native modal `` shown while mounted (D13): `showModal()` makes the - * rest of the page inert and keeps focus in the top layer. The dialog never - * closes itself: Escape and close requests call `onClose`, and it leaves the - * screen when the consumer unmounts it. Focus starts on the first control and - * then returns to the opener. Tab past the last control reaches the browser's - * own interface, never the page, as the platform intends. - */ -export default function ModalDialog({ - onClose, - returnFocus, - layer, - labelledBy, - label, - describedBy, - className = '', - children, -}: ModalDialogProps) { - const ref = useRef(null) - const latest = useRef({ returnFocus, onClose }) - latest.current = { returnFocus, onClose } - const isPresent = useIsPresent() - const present = useRef(true) - present.current = isPresent - // The `close` event of the cleanup's own `close()` is no request (a DOM that fires it - // at once, as the test DOM does, would otherwise reach the consumer). - const closingSelf = useRef(false) +/** What the dialog's handlers read at the time they run, never a stale render's. */ +type Latest = () => Pick +/** A stable reader of the props the last render passed. */ +function useLatest(props: ReturnType): Latest { + const box = useRef(props) + box.current = props + return useCallback(() => box.current, []) +} + +/** + * Shows the dialog on mount and closes it on unmount, focus in then back to the opener. + * Answers whether the dialog is closing itself: the `close` event of the cleanup's own + * `close()` is no request (a DOM that fires it at once, as the test DOM does, would + * otherwise reach the consumer). + */ +function useShowModal( + ref: RefObject, + latest: Latest, +) { + const closingSelf = useRef(false) useLayoutEffect(() => { const dialog = ref.current if (!dialog) return @@ -137,7 +132,7 @@ export default function ModalDialog({ // After the commit: the render that closes the dialog may remove the opener // too. A dialog still on screen was only remounted (React StrictMode). queueMicrotask(() => { - const resolve = latest.current.returnFocus + const resolve = latest().returnFocus if (!dialog.isConnected && resolve !== null) { restoreFocus(resolve?.() ?? null, opener, ancestors) } @@ -146,8 +141,20 @@ export default function ModalDialog({ queueMicrotask(flushAfterModals) }) } - }, []) + // Shown once per mount: the ref and the latest props are read when it runs. + }, [ref, latest]) + return closingSelf +} +/** Escape, the platform's cancel and a close the platform made anyway: each asks. */ +function useCloseRequests( + ref: RefObject, + latest: Latest, + isPresent: boolean, + closingSelf: RefObject, +) { + const present = useRef(true) + present.current = isPresent const onKeyDown = (event: KeyboardEvent) => { if (event.key !== 'Escape' || event.nativeEvent.isComposing) return // A cancelled keydown is no close request: Chromium would otherwise close the @@ -156,21 +163,47 @@ export default function ModalDialog({ event.stopPropagation() // A held key repeats: only the first press asks. if (event.repeat) return - onClose() + latest().onClose() } const onCancel = (event: SyntheticEvent) => { event.preventDefault() - onClose() + latest().onClose() } // Closed by the platform anyway: keep the consumer's state in step. The check // ignores the `close` event queued by a cleanup the dialog has since reopened from. // A refused close shows the dialog again, never during an exit or once it is gone. - const onClosed = () => { + const onClose = () => { const dialog = ref.current if (!dialog || dialog.open || closingSelf.current) return - const refused = latest.current.onClose() === 'kept' + const refused = latest().onClose() === 'kept' if (refused && present.current && dialog.isConnected) dialog.showModal() } + return { onKeyDown, onCancel, onClose } +} + +/** + * Native modal `` shown while mounted (D13): `showModal()` makes the + * rest of the page inert and keeps focus in the top layer. The dialog never + * closes itself: Escape and close requests call `onClose`, and it leaves the + * screen when the consumer unmounts it. Focus starts on the first control and + * then returns to the opener. Tab past the last control reaches the browser's + * own interface, never the page, as the platform intends. + */ +export default function ModalDialog({ + onClose, + returnFocus, + layer, + labelledBy, + label, + describedBy, + className = '', + children, +}: ModalDialogProps) { + const ref = useRef(null) + const latest = useLatest({ returnFocus, onClose }) + const isPresent = useIsPresent() + const closingSelf = useShowModal(ref, latest) + const requests = useCloseRequests(ref, latest, isPresent, closingSelf) return ( {children} diff --git a/apps/app/src/components/ui/afterModalsClosed.ts b/apps/app/src/components/ui/afterModalsClosed.ts index cb564924..c2360b96 100644 --- a/apps/app/src/components/ui/afterModalsClosed.ts +++ b/apps/app/src/components/ui/afterModalsClosed.ts @@ -29,11 +29,35 @@ export function flushAfterModals(): void { ready.forEach((fn) => fn()) } +/** + * The focus landing still waiting, as its cancel. The page has one focus, so one landing: + * a newer one supersedes it (a stale move never takes the focus once the dialogs close). + */ +let pendingLanding: () => void = () => undefined + /** * `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. + * microtask and is never undone by it. It cancels the landing still waiting, and answers + * its own cancel. */ export function landAfterModalsClosed(fn: () => void): () => void { - return afterModalsClosed(() => queueMicrotask(fn)) + pendingLanding() + let live = true + const unwait = afterModalsClosed(() => + queueMicrotask(() => { + if (live) fn() + }), + ) + const cancel = () => { + live = false + unwait() + } + pendingLanding = cancel + return cancel +} + +/** Drops the landing still waiting: a Back onto a dialog, an editor that goes. */ +export function cancelLanding(): void { + pendingLanding() } diff --git a/apps/app/src/editor/focusRequest.ts b/apps/app/src/editor/focusRequest.ts index 4392df0a..9c2612c8 100644 --- a/apps/app/src/editor/focusRequest.ts +++ b/apps/app/src/editor/focusRequest.ts @@ -92,7 +92,10 @@ function rowOf(key: ElementKey): HTMLElement | null { ) } -/** Scrolls to and focuses the visible row tagged with `key`; false unless the row now holds the focus. */ +/** + * Scrolls to and focuses the visible row tagged with `key`; false unless the row now + * holds the focus. + */ export function focusRow(key: ElementKey): boolean { const row = rowOf(key) if (!row) return false diff --git a/apps/app/src/editor/history/entry.ts b/apps/app/src/editor/history/entry.ts index 78b1f92b..d4a41f09 100644 --- a/apps/app/src/editor/history/entry.ts +++ b/apps/app/src/editor/history/entry.ts @@ -1,4 +1,5 @@ import type { ElementKey } from '@faunosteo/core-wasm/types' +import { MAX_FINDING_PATH } from '../findings/tree' import { ANNOTATION_SECTIONS, isFindingNode, @@ -34,16 +35,23 @@ export const ENTRY_KEY = 'editorEntry' const isRecord = (value: unknown): value is Record => typeof value === 'object' && value !== null +/** Longest id or key read back: a longer one is no id this editor wrote. */ +const MAX_ID_LENGTH = 128 + +const isId = (value: unknown): value is string => + typeof value === 'string' && value.length <= MAX_ID_LENGTH + +/** A finding path no deeper than the tree allows, each id within the cap. */ +const isPath = (path: unknown): path is string[] => + Array.isArray(path) && path.length <= MAX_FINDING_PATH && path.every(isId) + /** A finding or zone key as the tree builds it, or null when `raw` is no such key. */ function sanitizeKey(raw: unknown): ElementKey | null { if (!isRecord(raw)) return null - if (raw.kind === 'zone' && typeof raw.id === 'string') { - return { kind: 'zone', id: raw.id } - } + if (raw.kind === 'zone' && isId(raw.id)) return { kind: 'zone', id: raw.id } const { zone_id: zoneId, path } = raw - const ids = Array.isArray(path) && path.every((id) => typeof id === 'string') - if (raw.kind !== 'finding' || typeof zoneId !== 'string' || !ids) return null - return { kind: 'finding', zone_id: zoneId, path: path as string[] } + if (raw.kind !== 'finding' || !isId(zoneId) || !isPath(path)) return null + return { kind: 'finding', zone_id: zoneId, path } } const CREATION_KINDS = ['zone', 'category', 'node'] @@ -82,7 +90,7 @@ function sanitizeReference( const sheet = !!finding && 'key' in finding && finding.citations if (raw.create === true) return tab === 'references' ? { create: true } : null const id = raw.edit - if (typeof id !== 'string' || id === '') return null + if (!isId(id) || id === '') return null return tab === 'references' || sheet ? { edit: id } : null } @@ -121,16 +129,22 @@ export function withoutForms(view: EditorView): EditorView { return sanitizeView(view, false) ?? view } +/** The entry's id and owner, each a string within the cap, or null. */ +function idsOf(raw: Record) { + const { id, sheetId, userId } = raw + const valid = isId(id) && isId(sheetId) && isId(userId) + return valid ? { id, sheetId, userId } : null +} + /** The entry `state` (a `location.state`) carries, or null when it carries none. */ export function readEntry(state: unknown): HistoryEntry | null { const raw = isRecord(state) ? state[ENTRY_KEY] : null if (!isRecord(raw)) return null const view = sanitizeView(raw.view) - const { id, sheetId, userId } = raw - if (!view || typeof id !== 'string') return null - if (typeof sheetId !== 'string' || typeof userId !== 'string') return null + const ids = idsOf(raw) + if (!view || !ids) return null const below = raw.below === null ? null : sanitizeView(raw.below) - return { id, view, below, sheetId, userId } + return { ...ids, view, below } } /** An entry restores only for the sheet and the account that wrote it. */ @@ -164,7 +178,7 @@ function isStepOver(view: EditorView): boolean { /** True when the move took a layer away, or left a section for its drawing. */ function isRemoval(top: EditorView, view: EditorView): boolean { - // Another tab is a move of its own (« Tout afficher », « Aller à »): it pushes. + // Another tab is a move of its own (« Tout afficher »): it pushes. if (view.tab !== top.tab) return false if (layerCount(view) < layerCount(top)) return true const backToDrawing = view.tab === top.tab && isStepOver(top) @@ -186,18 +200,21 @@ export function showsFinding(view: EditorView, key: ElementKey): boolean { * au dessin"), goes back when the entry holds the view the move lands on (the entry that * opened it), else it replaces; a layer, tab or section added pushes, unless the move * asked for a replace. `backTo` (« Revenir au constat ») goes back when the entry below - * shows that finding. + * shows that finding. `own` (« Aller à ») is a move of its own: it pushes, even when it + * leaves fewer layers on the same tab, so the place it left stays one Back away. */ export function planWrite( top: HistoryEntry, view: EditorView, replace: boolean, backTo: ElementKey | null = null, + own = false, ): HistoryWrite { if (sameView(top.view, view)) return 'none' if (replace) return 'replace' // « Revenir au constat »: the entry below already shows that finding, a Back is the move. if (backTo && top.below && showsFinding(top.below, backTo)) return 'back' + if (own) return 'push' if (isRemoval(top.view, view)) { return top.below && sameView(top.below, view) ? 'back' : 'replace' } diff --git a/apps/app/src/editor/history/useEditorHistory.ts b/apps/app/src/editor/history/useEditorHistory.ts index 916ed57e..ae50e54c 100644 --- a/apps/app/src/editor/history/useEditorHistory.ts +++ b/apps/app/src/editor/history/useEditorHistory.ts @@ -1,6 +1,14 @@ import { useEffect, useMemo, useRef, useState } from 'react' -import { useLocation, useNavigate, useNavigationType } from 'react-router-dom' -import { landAfterModalsClosed } from '@/components/ui/afterModalsClosed' +import { + useLocation, + useNavigate, + useNavigationType, + type Location, +} from 'react-router-dom' +import { + cancelLanding, + landAfterModalsClosed, +} from '@/components/ui/afterModalsClosed' import { focusActiveTab } from '../focusRequest' import { sameView, type EditorView } from '../navigation' import { @@ -8,15 +16,18 @@ import { shownPlace, useMoveText, type EditorNavigation, + type MoveTrace, } from '../useEditorNavigation' import { createWriteBudget, entryState, + layerCount, ownedEntry, planWrite, withoutForms, type HistoryEntry, type HistoryOwner, + type HistoryWrite, } from './entry' /** Well under WebKit's 100 history writes per 10 s: past it a view stays in memory. */ @@ -29,28 +40,55 @@ const BACK_TIMEOUT_MS = 1_000 interface Book { /** The entry on top of the history as the adapter knows it (null before the mount). */ entry: HistoryEntry | null + /** The entry the browser holds on top: not `entry` once a push stayed in memory. */ + sent: HistoryEntry | null + /** The pathname the editor mounted on: a location elsewhere is not this editor's. */ + path: string | null /** The router location last read: each location object is read once (see `usePop`). */ seen: object | null pendingBack: boolean backTimer: ReturnType | undefined /** Scroll position of the entries left, by entry id. */ scrolls: Map + /** Entry ids: a prefix drawn once per mount, so a reload never reuses one, a counter. */ + prefix: string counter: number takeWrite: (now: number) => boolean } +/** A random prefix: entries left by an earlier mount of this tab keep their own ids. */ +function mountPrefix(): string { + const words = crypto.getRandomValues(new Uint32Array(2)) + return Array.from(words, (word) => word.toString(36)).join('') +} + function newBook(): Book { return { entry: null, + sent: null, + path: null, seen: null, pendingBack: false, backTimer: undefined, scrolls: new Map(), + prefix: mountPrefix(), counter: 0, takeWrite: createWriteBudget(WRITE_LIMIT, WRITE_WINDOW_MS), } } +/** An entry read from the browser's history: it is the top, as the browser holds it. */ +function adopt(book: Book, entry: HistoryEntry): void { + book.entry = entry + book.sent = entry +} + +const placeOf = ({ pathname, search, hash }: Location) => ({ + pathname, + search, + hash, +}) + /** A Back or Forward that changed the view: what the landing scrolls to, focuses and says. */ interface Landing { entry: HistoryEntry @@ -61,7 +99,8 @@ interface Landing { /** * The writes, through the router so its own location follows. `push` over the write - * budget keeps the entry in memory only; `replace` swallows a refused write. + * budget keeps the entry in memory only; `replace` swallows a refused write. Nothing is + * written over a location that is not the editor's (it is leaving). */ function useWriter(book: Book, owner: HistoryOwner) { const navigate = useNavigate() @@ -71,31 +110,38 @@ function useWriter(book: Book, owner: HistoryOwner) { return useMemo(() => { const send = (entry: HistoryEntry, replace: boolean) => { const { navigate, location } = latest.current - const { pathname, search, hash } = location - const to = { pathname, search, hash } + if (location.pathname !== book.path) return try { - navigate(to, { replace, state: entryState(entry) }) + navigate(placeOf(location), { replace, state: entryState(entry) }) + book.sent = entry } catch { // The view stays in memory; the next move writes again. } } const fresh = (view: EditorView, below: EditorView | null) => { book.counter += 1 - return { id: `e${book.counter}`, view, below, ...owner } + return { id: `${book.prefix}-${book.counter}`, view, below, ...owner } } const write = (entry: HistoryEntry, replace: boolean) => { book.entry = entry - // shortcut: past the write budget a push is kept in memory only, so a later Back - // lands on the real previous entry. Fine at one push per user move; upgrade path: - // coalesce the skipped views into one replace once the window slides. + // shortcut: past the write budget a push is kept in memory only (`settle` closes it + // without a Back), so a browser Back lands on the real previous entry. Fine at one + // push per user move; upgrade path: coalesce the skipped views into one replace once + // the window slides. if (replace || book.takeWrite(Date.now())) send(entry, replace) } + const replace = (view: EditorView) => { + const kept = book.entry ?? fresh(view, null) + write({ ...kept, view }, true) + } return { push: (view: EditorView) => write(fresh(view, book.entry?.view ?? null), false), - replace: (view: EditorView) => { - const kept = book.entry ?? fresh(view, null) - write({ ...kept, view }, true) + replace, + /** A close over a push kept in memory: the browser's top is the place, no Back. */ + settle: (view: EditorView) => { + book.entry = book.sent + if (!book.sent || !sameView(book.sent.view, view)) replace(view) }, first: (view: EditorView) => write(fresh(view, null), true), back: () => { @@ -112,6 +158,31 @@ function useWriter(book: Book, owner: HistoryOwner) { type Writer = ReturnType +/** What the last move left for the adapter, read once: the trace is reset. */ +function takeTrace(trace: MoveTrace): MoveTrace { + const taken = { ...trace } + Object.assign(trace, { + scrollY: null, + replace: false, + backTo: null, + own: false, + }) + return taken +} + +/** Carries a planned write out; a Back over a push kept in memory settles instead. */ +function follow( + plan: HistoryWrite, + view: EditorView, + book: Book, + writer: Writer, +) { + if (plan === 'push') writer.push(view) + else if (plan === 'replace') writer.replace(view) + else if (book.entry !== book.sent) writer.settle(view) + else writer.back() +} + /** User moves: the view changed, the history follows (R2F-1). */ function useReconcile( nav: EditorNavigation, @@ -120,18 +191,13 @@ function useReconcile( writer: Writer, ) { useEffect(() => { - const { scrollY, replace, backTo } = nav.trace - nav.trace.scrollY = null - nav.trace.replace = false - nav.trace.backTo = null + const move = takeTrace(nav.trace) const top = book.entry if (!top || book.pendingBack) return - const plan = planWrite(top, view, replace, backTo) + const plan = planWrite(top, view, move.replace, move.backTo, move.own) if (plan === 'none') return - book.scrolls.set(top.id, scrollY ?? window.scrollY) - if (plan === 'back') writer.back() - else if (plan === 'push') writer.push(view) - else writer.replace(view) + book.scrolls.set(top.id, move.scrollY ?? window.scrollY) + follow(plan, view, book, writer) }, [view, nav.trace, book, writer]) } @@ -183,7 +249,7 @@ function landOnForeign(ctx: PopContext): Landing | null { */ function refusePop(ctx: PopContext, landed: HistoryEntry | null): null { const { book, writer, view } = ctx - if (landed) book.entry = landed + if (landed) adopt(book, landed) writer.push(view) return null } @@ -205,7 +271,7 @@ function landOn(ctx: PopContext, state: unknown): Landing | null { const entry = ownedEntry(state, ctx.owner) if (!expected && popRefused(ctx, entry)) return refusePop(ctx, entry) if (!entry) return landOnForeign(ctx) - book.entry = entry + adopt(book, entry) if (sameView(entry.view, view)) return null nav.restoreView(entry.view) return { @@ -216,14 +282,15 @@ function landOn(ctx: PopContext, state: unknown): Landing | null { } /** - * The first location of the editor: an entry of this sheet and account is kept (a - * reload never reopens a form, so a form layer is replaced by the view without it), - * any other is replaced by the current view. + * The first location of the editor: its pathname is the editor's from now on. An entry of + * this sheet and account is kept (a reload never reopens a form, so a form layer is + * replaced by the view without it), any other is replaced by the current view. */ -function mount(ctx: PopContext, state: unknown): void { - const entry = ownedEntry(state, ctx.owner) +function mount(ctx: PopContext, location: Location): void { + ctx.book.path = location.pathname + const entry = ownedEntry(location.state, ctx.owner) if (!entry) return ctx.writer.first(ctx.view) - ctx.book.entry = entry + adopt(ctx.book, entry) const kept = withoutForms(entry.view) if (!sameView(kept, entry.view)) ctx.writer.replace(kept) } @@ -236,29 +303,42 @@ function landFocus({ entry, tabChanged, layerChanged }: Landing): void { else focusActiveTab({ preventScroll: true }) } -/** Scroll, focus and announcement once a Back or Forward has restored a view. */ +interface Speech { + nav: EditorNavigation + moveText: ReturnType +} + +/** Focus and announcement of a landing, once the dialogs it closed are gone. */ +function land(landing: Landing, { nav, moveText }: Speech): void { + landFocus(landing) + if (landing.layerChanged && !landing.tabChanged) return + const { view } = landing.entry + const section = view.tab === 'annotations' ? view.section : null + nav.announce(moveText({ place: 'tab', tab: view.tab, section, key: null })) +} + +/** + * Scroll, focus and announcement once a Back or Forward has restored a view. The effect + * follows the landing only (the rest is read from a ref): a later render, a dialog closed + * by ✕ or a locale switch, never cancels what it waits for. + */ function useLanding( nav: EditorNavigation, book: Book, landing: Landing | null, ) { const moveText = useMoveText() - const landed = useRef(null) + const latest = useRef({ nav, moveText }) + latest.current = { nav, moveText } useEffect(() => { - // A new wording (locale switch) re-creates `moveText`: the landing stays one. - if (!landing || landed.current === landing) return - landed.current = landing - const { id, view } = landing.entry - return landAfterModalsClosed(() => { - window.scrollTo(0, book.scrolls.get(id) ?? 0) - landFocus(landing) - if (landing.layerChanged && !landing.tabChanged) return - const section = view.tab === 'annotations' ? view.section : null - nav.announce( - moveText({ place: 'tab', tab: view.tab, section, key: null }), - ) - }) - }, [landing, book, nav, moveText]) + if (!landing) return + // The page behind a dialog scrolls too: the offset is applied at once. + window.scrollTo(0, book.scrolls.get(landing.entry.id) ?? 0) + // A dialog landed on keeps its own focus (then its return target): no older landing + // takes the focus once it is closed. + if (layerCount(landing.entry.view) > 0) return cancelLanding() + return landAfterModalsClosed(() => land(landing, latest.current)) + }, [landing, book]) } /** The view the reducer holds, as one object that changes only when the view does. */ @@ -284,6 +364,11 @@ function useManualScroll(): void { }, []) } +/** A Back still awaited when the editor goes: its timer goes with it. */ +function useBackTimerCleanup(book: Book): void { + useEffect(() => () => clearTimeout(book.backTimer), [book]) +} + /** * Each new location is read once: the first is the mount, a POP after it is a landing. * The router makes a new location object per navigation, so a Back onto a key this @@ -294,15 +379,19 @@ function usePop(ctx: PopContext): Landing | null { const location = useLocation() const navType = useNavigationType() const [landing, setLanding] = useState(null) - const { book } = ctx + // Read once per location: the context is the one the render of that location holds. + const latest = useRef(ctx) + latest.current = ctx useEffect(() => { - if (book.seen === location) return - book.seen = location - if (book.entry === null) mount(ctx, location.state) - else if (navType === 'POP') setLanding(landOn(ctx, location.state)) - // Read once per location: the context is the one this render holds. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [location]) + const now = latest.current + if (now.book.seen === location) return + now.book.seen = location + if (now.book.entry === null) mount(now, location) + // Another page (another sheet's editor, the list): the editor is leaving, it is the + // new page's location, and a dirty dialog goes like on any leave. + else if (location.pathname !== now.book.path) return + else if (navType === 'POP') setLanding(landOn(now, location.state)) + }, [location, navType]) return landing } @@ -329,4 +418,5 @@ export default function useEditorHistory( useReconcile(nav, view, book, writer) useLanding(nav, book, landing) useManualScroll() + useBackTimerCleanup(book) } diff --git a/apps/app/src/editor/leftDraft.ts b/apps/app/src/editor/leftDraft.ts new file mode 100644 index 00000000..9a8782af --- /dev/null +++ b/apps/app/src/editor/leftDraft.ts @@ -0,0 +1,88 @@ +import { useEffect, useRef, useState } from 'react' +import type { HistoryOwner } from './history/entry' +import type { NavigationState } from './navigation' +import type { EditorNavigation, LayerName } from './useEditorNavigation' + +/** + * A dirty dialog lost when the editor goes (a Back of several entries, BDR-078: a Back + * cannot be refused, and a draft is never stored). One flag in this tab's sessionStorage + * says so to the next mount of the same sheet for the same account (criterion 17). + */ +const PREFIX = 'faunosteo:editor:left-draft:' + +export const leftDraftKey = ({ sheetId, userId }: HistoryOwner) => + `${PREFIX}${sheetId}:${userId}` + +/** The top layer first: the dialog the user was typing in when they left. */ +const LAYERS_TOP_DOWN: readonly LayerName[] = ['reference', 'finding'] + +function storage(): Storage | null { + try { + return typeof sessionStorage === 'undefined' ? null : sessionStorage + } catch { + return null + } +} + +/** The element the layer showed: a key, a reference, a creation's parent. Never text. */ +function elementOf(state: NavigationState, layer: LayerName): unknown { + if (layer === 'reference') { + const { reference } = state + return reference && 'edit' in reference + ? { kind: 'reference', id: reference.edit } + : null + } + const { finding } = state + if (!finding) return null + return 'key' in finding ? finding.key : finding.create.parent +} + +/** Called as the editor goes: a layer whose form holds changes leaves the flag. */ +function flagIfDirty(owner: HistoryOwner, nav: EditorNavigation): void { + if (!owner.sheetId || !owner.userId) return + // A forced ask has no side effect: a dirty form answers with its note. + const layer = LAYERS_TOP_DOWN.find((l) => nav.guards.ask(l, true).note) + if (!layer) return + const flag = { kind: layer, key: elementOf(nav.state, layer) } + try { + storage()?.setItem(leftDraftKey(owner), JSON.stringify(flag)) + } catch { + // A full or blocked storage: the leave goes unsaid, as before. + } +} + +/** True when the flag is there; read once per mount. */ +function readFlag(owner: HistoryOwner): boolean { + try { + return storage()?.getItem(leftDraftKey(owner)) != null + } catch { + return false + } +} + +function clearFlag(owner: HistoryOwner): void { + try { + storage()?.removeItem(leftDraftKey(owner)) + } catch { + // Nothing to clear. + } +} + +/** + * Whether the last editor of this sheet and account left with a dirty dialog: shown once, + * then cleared. The editor's own cleanup runs before its dialogs' (a deleted tree is + * cleaned up from its root), so their guards still answer when it flags. + */ +export function useLeftDraft( + nav: EditorNavigation, + owner: HistoryOwner, +): boolean { + const latest = useRef(nav) + latest.current = nav + const [left] = useState(() => readFlag(owner)) + useEffect(() => { + clearFlag(owner) + return () => flagIfDirty(owner, latest.current) + }, [owner]) + return left +} diff --git a/apps/app/src/editor/navigation.ts b/apps/app/src/editor/navigation.ts index cb6dca89..714240bd 100644 --- a/apps/app/src/editor/navigation.ts +++ b/apps/app/src/editor/navigation.ts @@ -217,6 +217,12 @@ function openFinding(state: NavigationState, key: ElementKey): NavigationState { return shown({ ...state, ...LEFT_REFERENCES, tab: 'findings', finding }) } +/** The finding dialog closes with the reference dialog opened over its sheet. */ +function closeFinding(state: NavigationState): NavigationState { + const reference = state.finding ? null : state.reference + return { ...state, finding: null, reference } +} + /** The creation form of a zone, a category or a node, on the Constats tab. */ function createFinding( state: NavigationState, @@ -226,6 +232,17 @@ function createFinding( return shown({ ...state, ...LEFT_REFERENCES, tab: 'findings', finding }) } +/** The dialog a move to `target` opens with it: a zone's or a finding's, in view mode. */ +function dialogOf(target: EditorTarget): EditorView['finding'] { + const { key } = target + const element = key?.kind === 'zone' || key?.kind === 'finding' + return key && element ? { key, citations: false } : null +} + +/** + * « Aller à »: every layer closes and the target is shown. A zone or a finding opens its + * dialog in the same move, so the history writes one entry and keeps the place it left. + */ function goTo(state: NavigationState, target: EditorTarget): NavigationState { const serial = state.serial + 1 // The filter survives only a move to the tab itself that names no reference. @@ -234,7 +251,7 @@ function goTo(state: NavigationState, target: EditorTarget): NavigationState { ...state, tab: target.tab, section: target.section ?? state.section, - finding: null, + finding: dialogOf(target), reference: null, referenceFilter: keep ? state.referenceFilter : null, focus: { target, serial }, @@ -295,7 +312,7 @@ export function navigationReducer( case 'create_finding': return createFinding(state, { kind: action.kind, parent: action.parent }) case 'close_finding': - return { ...state, finding: null } + return closeFinding(state) case 'open_citations': return openCitations(state, action.citedBy) case 'close_citations': diff --git a/apps/app/src/editor/useEditorNavigation.ts b/apps/app/src/editor/useEditorNavigation.ts index 2059a691..14d64917 100644 --- a/apps/app/src/editor/useEditorNavigation.ts +++ b/apps/app/src/editor/useEditorNavigation.ts @@ -11,6 +11,7 @@ import { import type { ElementKey } from '@faunosteo/core-wasm/types' import { afterModalsClosed, + cancelLanding, landAfterModalsClosed, } from '@/components/ui/afterModalsClosed' import { useT } from '@/i18n/useT' @@ -75,6 +76,11 @@ export interface MoveTrace { replace: boolean /** « Revenir au constat »: a Back when the entry below shows this finding. */ backTo: ElementKey | null + /** + * « Aller à »: a move of its own, it pushes. Set by the move, read and reset by the + * adapter only: a place answering the move in the same commit (`mark`) keeps it. + */ + own: boolean } /** Options of a tab choice. */ @@ -100,8 +106,9 @@ export interface EditorNavigation { closeFinding: (forced?: boolean) => boolean /** * The finding layer becomes another view of itself, by replace (no Back entry): the new - * element's dialog, or `null` for none. With `text`, a close the user did not ask for - * (the element vanished): forced, said once the dialogs are closed. + * element's dialog, or `null` for none (the reference dialog over its sheet goes too). + * With `text`, a close the user did not ask for (the element vanished): forced, said + * once the dialogs are closed. */ replaceFinding: (key: ElementKey | null, text?: string) => void /** Opens the citations sheet of a finding node; any other key is ignored. */ @@ -209,6 +216,7 @@ function useMoveTrace() { scrollY: null, replace: false, backTo: null, + own: false, }).current const mark = useCallback( (replace = false) => { @@ -241,6 +249,7 @@ function useGo(dispatch: Dispatch, trace: MoveTrace) { trace.scrollY = window.scrollY trace.replace = false trace.backTo = null + trace.own = kind === 'go_to' dispatch(action) setMove({ kind }) }, @@ -428,6 +437,11 @@ function useMoveFocus( }, [move, state, outcomes, dispatch, openers]) } +/** A focus landing still waiting when the editor goes is dropped with it. */ +function useLandingCleanup() { + useEffect(() => cancelLanding, []) +} + /** The outcomes the places report for each focus request. */ function useReceipts(dispatch: Dispatch) { const outcomes = useRef(new Map()) @@ -496,6 +510,7 @@ export function useEditorNavigation( const guards = useGuards() const receipts = useReceipts(base.dispatch) useMoveFocus(base.move, base.state, receipts.outcomes, base.dispatch, openers) + useLandingCleanup() useCitedBy(base.state, openers) const ctx = { dispatch: base.dispatch, diff --git a/apps/app/src/editor/useReferenceMoves.ts b/apps/app/src/editor/useReferenceMoves.ts index f6c336a6..6fed7874 100644 --- a/apps/app/src/editor/useReferenceMoves.ts +++ b/apps/app/src/editor/useReferenceMoves.ts @@ -56,10 +56,9 @@ function useOpening({ dispatch, mark }: LayerContext, held: RefObject) { return { open, start } } -/** The moves that take it away: a user close, and the replace that is no Back step. */ -function useClosing(ctx: LayerContext) { - const { dispatch, announce, guards, mark } = ctx - const close = useCallback( +/** A user close: the form may refuse it (a dirty draft asks first). */ +function useClose({ dispatch, guards, mark }: LayerContext) { + return useCallback( (forced = false) => { if (!guards.ask('reference', forced).allowed) return false mark() @@ -68,7 +67,11 @@ function useClosing(ctx: LayerContext) { }, [guards, dispatch, mark], ) - const replace = useCallback( +} + +/** The replace that is no Back step; with `text`, forced and said with a dropped draft. */ +function useReplace({ dispatch, announce, guards, mark }: LayerContext) { + return useCallback( (id: string | null, text?: string) => { const note = text ? guards.ask('reference', true).note : undefined if (text) announce(note ? `${note}. ${text}` : text) @@ -79,7 +82,11 @@ function useClosing(ctx: LayerContext) { }, [guards, announce, dispatch, mark], ) - return { close, replace } +} + +/** The moves that take it away: a user close, and the replace that is no Back step. */ +function useClosing(ctx: LayerContext) { + return { close: useClose(ctx), replace: useReplace(ctx) } } /** A creation that succeeded: its entry becomes the reference's own, then it closes. */ diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index ac9f93d8..0bebe485 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -1645,6 +1645,9 @@ export const en: Dict = { 'editor.findings.discard': 'Discard', 'editor.findings.draft_dropped': 'Entry discarded', 'editor.findings.gone': 'This finding no longer exists', + // Provisional EN, pending the owner's wording. + 'editor.leave.draft_dropped': + 'An unsaved entry was discarded when you left the editor', 'editor.findings.flip_narrow': 'Widen the window to continue: your entry is kept.', 'editor.findings.flip_blocked': 'Editing is no longer possible: your entry is kept, you can only discard it.', 'editor.verification.title': 'Draft check', diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index 17a5a776..51563604 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -1676,6 +1676,8 @@ export const fr: Dict = { 'editor.findings.discard': 'Abandonner', 'editor.findings.draft_dropped': 'Saisie abandonnée', 'editor.findings.gone': "Ce constat n'existe plus", + 'editor.leave.draft_dropped': + "Une saisie non enregistrée a été abandonnée en quittant l'éditeur", 'editor.findings.flip_narrow': 'Élargissez la fenêtre pour poursuivre : votre saisie est conservée.', 'editor.findings.flip_blocked': "La modification n'est plus possible : votre saisie est conservée, vous pouvez seulement l'abandonner.", 'editor.verification.title': 'Contrôle du brouillon', diff --git a/apps/app/tests/unit/editor-finding-dialog.test.tsx b/apps/app/tests/unit/editor-finding-dialog.test.tsx index 1a1db7ba..503f6748 100644 --- a/apps/app/tests/unit/editor-finding-dialog.test.tsx +++ b/apps/app/tests/unit/editor-finding-dialog.test.tsx @@ -452,3 +452,94 @@ describe('read-only flip and the gone rule', () => { expect(findingDialog()).toBeNull() }) }) + +const liveText = () => + document.querySelector('p.sr-only[aria-live="polite"]')!.textContent + +describe('final review: a creation whose parent vanishes (M-1)', () => { + it('says the dropped names with the gone text, never silently', async () => { + const user = await mount() + act(() => treeRow(/Cat A/).focus()) + await user.keyboard('{ArrowUp}{ArrowDown}') + await user.click(screen.getByRole('button', { name: 'Ajouter un constat' })) + await waitFor(() => expect(findingDialog()).not.toBeNull()) + await user.type(document.getElementById('finding-new-name-fr')!, 'Tête') + act(() => { + store.getState().commit({ + op: 'remove', + key: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a'] }, + }) + }) + await closed() + await waitFor(() => + expect(liveText()).toBe("Saisie abandonnée. Ce constat n'existe plus"), + ) + }) +}) + +describe('final review: the zone of a new category is part of the draft (criterion 8)', () => { + it('a zone changed alone asks before « Annuler » closes', async () => { + serverHas( + insert(sheetText(), { + kind: 'zone', + value: { id: 'zone-b', name: name('Zone B'), categories: [] }, + }), + 3, + ) + const user = userEvent.setup() + mountDraft({ width: 1280, probe }) + await screen.findByRole('heading', { + level: 1, + name: 'Brouillon, version 4', + }) + await user.click(screen.getByRole('tab', { name: 'Constats' })) + await user.click( + screen.getByRole('button', { name: 'Ajouter une catégorie' }), + ) + await waitFor(() => expect(findingDialog()).not.toBeNull()) + await user.selectOptions(inDialog().getByLabelText('Zone'), 'zone-b') + await user.click(inDialog().getByRole('button', { name: 'Annuler' })) + expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible() + await user.click( + inDialog().getByRole('button', { name: 'Continuer la saisie' }), + ) + act(() => inDialog().getByLabelText('Zone').focus()) + await user.keyboard('{Escape}') + expect(findingDialog()).not.toBeNull() + expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible() + }) +}) + +describe('final review: leaving the editor with a dirty dialog (criterion 17)', () => { + const flagKey = `faunosteo:editor:left-draft:${SHEET}:${USER}` + const notice = + "Une saisie non enregistrée a été abandonnée en quittant l'éditeur" + + it('leaves one flag without the text, then a notice once on the next mount', async () => { + const user = await mount() + await openFinding(user, /Node A/) + await modify(user) + await user.type(nameField(), ' bis') + cleanup() + const flag = sessionStorage.getItem(flagKey) + expect(flag).not.toBeNull() + expect(flag).not.toContain('bis') + expect(JSON.parse(flag!)).toEqual({ + kind: 'finding', + key: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a', 'fnode-a'] }, + }) + await mount() + expect(screen.getByText(notice)).toBeVisible() + expect(sessionStorage.getItem(flagKey)).toBeNull() + cleanup() + await mount() + expect(screen.queryByText(notice)).toBeNull() + }) + + it('a clean dialog leaves no flag', async () => { + const user = await mount() + await openFinding(user, /Node A/) + cleanup() + expect(sessionStorage.getItem(flagKey)).toBeNull() + }) +}) diff --git a/apps/app/tests/unit/editor-history-entry.test.ts b/apps/app/tests/unit/editor-history-entry.test.ts index e971f05f..11e90a2f 100644 --- a/apps/app/tests/unit/editor-history-entry.test.ts +++ b/apps/app/tests/unit/editor-history-entry.test.ts @@ -331,3 +331,57 @@ describe('the view the reducer holds', () => { expect(state.visitedTabs).toEqual(['findings']) }) }) + +describe('final review: « Aller à » is a move of its own (I-2)', () => { + it('pushes over the sheet it leaves, even with fewer layers on the same tab', () => { + const sheet = view('findings', { finding: { key: node, citations: true } }) + const other: ElementKey = { + kind: 'finding', + zone_id: 'z', + path: ['f', 'm'], + } + const target = view('findings', { + finding: { key: other, citations: false }, + }) + const top = entry({ view: sheet, below: view('findings') }) + expect(planWrite(top, target, false)).toBe('replace') + expect(planWrite(top, target, false, null, true)).toBe('push') + // An arrow-key replace still wins. + expect(planWrite(top, target, true, null, true)).toBe('replace') + }) +}) + +describe('final review: read-back values are capped', () => { + const long = 'x'.repeat(129) + const atCap = 'x'.repeat(128) + const deep = (length: number): ElementKey => ({ + kind: 'finding', + zone_id: 'z', + path: Array.from({ length }, (_, i) => `p${i}`), + }) + const onFindings = (key: ElementKey) => + view('findings', { finding: { key, citations: false } }) + + it('drops an entry whose id, sheet or account is over 128 characters', () => { + expect(readEntry(stateOf(entry({ id: atCap })))).not.toBeNull() + expect(readEntry(stateOf(entry({ id: long })))).toBeNull() + expect(readEntry(stateOf(entry({ sheetId: long })))).toBeNull() + expect(readEntry(stateOf(entry({ userId: long })))).toBeNull() + }) + + it('drops a key with an over-long id or a path deeper than the tree allows', () => { + const zone: ElementKey = { kind: 'zone', id: long } + expect( + readEntry(stateOf(entry({ view: onFindings(zone) })))?.view.finding, + ).toBeNull() + const wideZone: ElementKey = { kind: 'finding', zone_id: long, path: ['a'] } + expect(sanitizeView(onFindings(wideZone))?.finding).toBeNull() + const wideId: ElementKey = { kind: 'finding', zone_id: 'z', path: [long] } + expect(sanitizeView(onFindings(wideId))?.finding).toBeNull() + expect(sanitizeView(onFindings(deep(8)))?.finding).not.toBeNull() + expect(sanitizeView(onFindings(deep(9)))?.finding).toBeNull() + const edit = { ...onFindings(node), reference: { edit: long } } + const sheet = { ...edit, finding: { key: node, citations: true } } + expect(sanitizeView(sheet)?.reference).toBeNull() + }) +}) diff --git a/apps/app/tests/unit/editor-history-guards.test.tsx b/apps/app/tests/unit/editor-history-guards.test.tsx index 2827aa41..966db72a 100644 --- a/apps/app/tests/unit/editor-history-guards.test.tsx +++ b/apps/app/tests/unit/editor-history-guards.test.tsx @@ -3,9 +3,11 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, + fireEvent, render, renderHook, screen, + waitFor, } from '@testing-library/react' import userEvent from '@testing-library/user-event' import type { ElementKey } from '@faunosteo/core-wasm/types' @@ -21,7 +23,7 @@ import { useBeforeUnload } from '@/app/useLeaveGuard' import EditorTabs from '@/components/editor/EditorTabs' import { ENTRY_KEY, type HistoryEntry } from '@/editor/history/entry' import useEditorHistory from '@/editor/history/useEditorHistory' -import { defaultView } from '@/editor/navigation' +import { defaultView, targetOfKey } from '@/editor/navigation' import { useEditorNavigation } from '@/editor/useEditorNavigation' import { useLocaleStore } from '@/state/localeStore' @@ -33,6 +35,11 @@ const finding: ElementKey = { zone_id: 'zone', path: ['family', 'node'], } +const other: ElementKey = { + kind: 'finding', + zone_id: 'zone', + path: ['family', 'other'], +} let navigate: NavigateFunction let location: Location @@ -48,6 +55,10 @@ function Page({ guard }: { guard?: () => { allowed: boolean } }) { + + + + @@ -59,9 +70,12 @@ function Page({ guard }: { guard?: () => { allowed: boolean } }) { ) } -const mount = (guard?: () => { allowed: boolean }) => +const mount = ( + guard?: () => { allowed: boolean }, + entries: string[] = ['/x'], +) => render( - + , ) @@ -204,3 +218,144 @@ describe('useBeforeUnload', () => { expect(second.defaultPrevented).toBe(false) }) }) + +const click = (name: string) => + userEvent.click(screen.getByRole('button', { name })) +const findingLayer = () => JSON.parse(screen.getByTestId('layer').textContent!) +/** A layer dialog on screen: what a Back that reopens the layers shows. */ +function openLayerDialog() { + const dialog = document.createElement('dialog') + dialog.setAttribute('open', '') + dialog.setAttribute('data-layer', '') + document.body.append(dialog) + return dialog +} +async function settleDialogs(dialog: HTMLElement) { + dialog.remove() + await act(async () => { + flushAfterModals() + await Promise.resolve() + await Promise.resolve() + }) +} +const setScrollY = (y: number) => + Object.defineProperty(window, 'scrollY', { + configurable: true, + writable: true, + value: y, + }) + +describe('final review: a Back into the layers (I-1)', () => { + afterEach(() => { + setScrollY(0) + vi.restoreAllMocks() + }) + + it('restores the page scroll, however the dialogs are closed afterwards', async () => { + useLocaleStore.setState({ locale: 'fr' }) + const scrollTo = vi.spyOn(window, 'scrollTo').mockImplementation(() => {}) + mount() + await userEvent.click(screen.getByRole('tab', { name: 'Constats' })) + setScrollY(500) + await click('open') + await click('cite') + await click('show all') + setScrollY(0) + scrollTo.mockClear() + const dialog = openLayerDialog() + act(() => navigate(-1)) + expect(findingLayer()).toMatchObject({ citations: true }) + // Closed by ✕ / Escape: each close dispatches and renders again. + await click('uncite') + await click('close') + await settleDialogs(dialog) + expect(scrollTo).toHaveBeenCalledWith(0, 500) + }) +}) + +describe('final review: « Aller à » from the sheet (I-2)', () => { + it('keeps the entry of the finding with its sheet: Back from the target returns to it', async () => { + useLocaleStore.setState({ locale: 'fr' }) + mount() + await userEvent.click(screen.getByRole('tab', { name: 'Constats' })) + await click('open') + await click('cite') + await click('go to') + expect(findingLayer()).toEqual({ key: other, citations: false }) + expect(entry().below?.finding).toEqual({ key: finding, citations: true }) + act(() => navigate(-1)) + expect(findingLayer()).toEqual({ key: finding, citations: true }) + }) +}) + +describe('final review: a location that is not the editor’s (M-3)', () => { + it('writes nothing and asks no layer on a Back to another page', async () => { + useLocaleStore.setState({ locale: 'fr' }) + const guard = vi.fn(() => ({ allowed: false })) + mount(guard, ['/y', '/x']) + await click('guard') + await userEvent.click(screen.getByRole('tab', { name: 'Constats' })) + await click('open') + act(() => navigate(-3)) + expect(location.pathname).toBe('/y') + expect(location.state).toBeNull() + expect(guard).not.toHaveBeenCalled() + }) +}) + +describe('final review: entry ids (M-4)', () => { + it('two mounts never share an entry id', async () => { + mount() + await waitFor(() => expect(entry()).toBeTruthy()) + const first = entry().id + cleanup() + mount() + await waitFor(() => expect(entry()).toBeTruthy()) + expect(entry().id).not.toBe(first) + }) +}) + +describe('final review: past the write budget (M-5)', () => { + it('a close over a push kept in memory never goes back a real entry', async () => { + useLocaleStore.setState({ locale: 'fr' }) + mount() + const tabOf = (name: string) => screen.getByRole('tab', { name }) + fireEvent.click(tabOf('Constats')) + for (let i = 0; i < 19; i += 1) { + fireEvent.click(tabOf('Général')) + fireEvent.click(tabOf('Constats')) + } + // The 40th write of the window: sent. The 41st (the sheet) stays in memory. + fireEvent.click(screen.getByRole('button', { name: 'open' })) + fireEvent.click(screen.getByRole('button', { name: 'cite' })) + const top = location.key + fireEvent.click(screen.getByRole('button', { name: 'uncite' })) + expect(findingLayer()).toEqual({ key: finding, citations: false }) + expect(screen.getByRole('tab', { selected: true })).toHaveTextContent( + 'Constats', + ) + expect(location.key).toBe(top) + expect(entry().view.finding).toEqual({ key: finding, citations: false }) + }) +}) + +describe('final review: queued landings (M-6)', () => { + it('a Back during the exit cancels the stale « Tout afficher » landing', async () => { + useLocaleStore.setState({ locale: 'fr' }) + mount() + await userEvent.click(screen.getByRole('tab', { name: 'Constats' })) + await click('open') + await click('cite') + const exiting = openLayerDialog() + await click('show all') + act(() => navigate(-1)) + expect(findingLayer()).toMatchObject({ citations: true }) + const focused: Element[] = [] + const record = (event: FocusEvent) => focused.push(event.target as Element) + document.addEventListener('focusin', record) + await settleDialogs(exiting) + document.removeEventListener('focusin', record) + const references = screen.getByRole('tab', { name: 'Références' }) + expect(focused).not.toContain(references) + }) +}) diff --git a/apps/app/tests/unit/editor-more-menu.test.tsx b/apps/app/tests/unit/editor-more-menu.test.tsx index b3c8d076..c4dfa0f3 100644 --- a/apps/app/tests/unit/editor-more-menu.test.tsx +++ b/apps/app/tests/unit/editor-more-menu.test.tsx @@ -231,3 +231,18 @@ describe('the platform back request', () => { expect(more()).toHaveAttribute('aria-expanded', 'false') }) }) + +describe('final review: keyboard focus leaving « Plus » (M-8)', () => { + it('closes when the focus moves out of the trigger and the list', async () => { + const { user } = mount() + await user.click(more()) + const item = screen.getByRole('button', { name: 'Constats' }) + act(() => item.focus()) + expect(more()).toHaveAttribute('aria-expanded', 'true') + act(() => more().focus()) + expect(more()).toHaveAttribute('aria-expanded', 'true') + act(() => screen.getByRole('button', { name: 'outside' }).focus()) + expect(more()).toHaveAttribute('aria-expanded', 'false') + await gone() + }) +}) diff --git a/apps/app/tests/unit/editor-navigation.test.ts b/apps/app/tests/unit/editor-navigation.test.ts index 8e90371f..3e278cdb 100644 --- a/apps/app/tests/unit/editor-navigation.test.ts +++ b/apps/app/tests/unit/editor-navigation.test.ts @@ -104,11 +104,11 @@ describe('navigationReducer', () => { expect(state.focus?.target).toEqual(targetOfKey(key)) }) - it('go_to a tab closes the finding layers', () => { + it('go_to a place that is no finding closes the finding layers', () => { const state = run( initialNavigation('general'), { type: 'open_citations', citedBy: node }, - { type: 'go_to', target: targetOfKey(finding) }, + { type: 'go_to', target: targetOfKey(view) }, ) expect(state.finding).toBeNull() }) @@ -306,3 +306,28 @@ describe('navigationReducer', () => { expect(state.visitedSections).toEqual(['drawing', 'categories']) }) }) + +describe('final review', () => { + it('a go_to a finding or a zone opens its dialog in the same move (I-2)', () => { + const state = run( + initialNavigation('general'), + { type: 'open_citations', citedBy: node }, + { type: 'go_to', target: targetOfKey(finding) }, + ) + expect(state.finding).toEqual({ key: finding, citations: false }) + const zone: ElementKey = { kind: 'zone', id: 'z1' } + const onZone = run(state, { type: 'go_to', target: targetOfKey(zone) }) + expect(onZone.finding).toEqual({ key: zone, citations: false }) + }) + + it('close_finding takes the reference dialog over the sheet with it (M-2)', () => { + const state = run( + initialNavigation('findings'), + { type: 'open_citations', citedBy: node }, + { type: 'open_reference', id: 'r1' }, + { type: 'close_finding' }, + ) + expect(state.finding).toBeNull() + expect(state.reference).toBeNull() + }) +}) diff --git a/apps/app/tests/unit/editor-reference-dialog.test.tsx b/apps/app/tests/unit/editor-reference-dialog.test.tsx index d5fd3cea..95430749 100644 --- a/apps/app/tests/unit/editor-reference-dialog.test.tsx +++ b/apps/app/tests/unit/editor-reference-dialog.test.tsx @@ -532,3 +532,30 @@ describe('the finding filter', () => { expect(chip()).toBeVisible() }) }) + +describe('final review: the creation dialog fades out as a creation (M-9)', () => { + it('never shows the edit title while it closes', async () => { + const user = await mount() + await user.click( + screen.getByRole('button', { name: 'Ajouter une référence' }), + ) + await waitFor(() => expect(refDialog()).toBeDefined()) + await user.selectOptions(field('Type'), 'book') + await user.type(field('Citation'), 'Nouvelle source') + const titles = new Set() + const seen = new MutationObserver(() => { + document + .querySelectorAll('dialog h2') + .forEach((h) => titles.add(h.textContent ?? '')) + }) + seen.observe(document.body, { + subtree: true, + childList: true, + characterData: true, + }) + await save(user) + await closed() + seen.disconnect() + expect(titles).not.toContain('Modifier la référence') + }) +})