From b703333b208f1f56bac6046b82f1ed2b92bf3d6c Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 13 Nov 2026 19:39:29 +0100 Subject: [PATCH] fix(editor): Task 2 review round 1, trace calls, form hooks, keyboard proof --- apps/app/e2e/shell/editor-citations.spec.ts | 39 ++-- .../editor/findings/DiscardConfirm.tsx | 35 ++++ .../editor/findings/FindingCreateForm.tsx | 167 ++++++++-------- .../editor/findings/FindingEditForm.tsx | 180 ++++++++++-------- .../editor/findings/useDirtyGuard.ts | 32 +++- .../components/editor/tabs/FindingsTab.tsx | 180 +++++++++++------- apps/app/src/editor/focusRequest.ts | 14 +- apps/app/src/editor/navigation.ts | 2 - apps/app/src/editor/useEditorNavigation.ts | 17 +- apps/app/src/i18n/en.ts | 1 + apps/app/src/i18n/fr.ts | 1 + apps/app/tests/helpers/findingsHost.tsx | 17 ++ .../tests/unit/editor-finding-dialog.test.tsx | 39 ++++ .../tests/unit/editor-focus-request.test.tsx | 11 +- .../app/tests/unit/editor-keep-alive.test.tsx | 2 + 15 files changed, 476 insertions(+), 261 deletions(-) diff --git a/apps/app/e2e/shell/editor-citations.spec.ts b/apps/app/e2e/shell/editor-citations.spec.ts index f8d6db9b..5851fbcc 100644 --- a/apps/app/e2e/shell/editor-citations.spec.ts +++ b/apps/app/e2e/shell/editor-citations.spec.ts @@ -362,27 +362,36 @@ test.describe('citations sheet, editing', () => { 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 ({ + test('keyboard: Enter opens the sheet, Tab reaches each control in order, Escape from one closes only the sheet', 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 openFinding(page, dict, 'Constat A') + await trigger(page).focus() + await page.keyboard.press('Enter') + await expect(place(page, 'citations')).toBeVisible() + await expect(page.locator('dialog[open]')).toHaveCount(2) + // The tab order of the sheet, in the document's order, each control tagged. + const count = await panel(page).evaluate((root) => { + const sheet = root.closest('dialog')! + const tabbable = [ + ...sheet.querySelectorAll( + 'button:not([disabled]), [href], input:not([disabled]), select, textarea', + ), + ] + tabbable.forEach((el, index) => el.setAttribute('data-kb', String(index))) + return tabbable.length + }) + expect(count).toBeGreaterThanOrEqual(5) + const at = () => + page.evaluate(() => document.activeElement?.getAttribute('data-kb')) + // On open the first control (✕) holds the focus; Tab then walks the rest. + expect(await at()).toBe('0') + for (let index = 1; index < count; index++) { 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') + expect(await at(), `Tab to control ${index}`).toBe(String(index)) } - 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() diff --git a/apps/app/src/components/editor/findings/DiscardConfirm.tsx b/apps/app/src/components/editor/findings/DiscardConfirm.tsx index 8532638a..980f6af3 100644 --- a/apps/app/src/components/editor/findings/DiscardConfirm.tsx +++ b/apps/app/src/components/editor/findings/DiscardConfirm.tsx @@ -1,5 +1,6 @@ import { useEffect, useRef } from 'react' import Button from '@/components/ui/Button' +import type { DiscardTarget } from '@/components/editor/findings/useDirtyGuard' import { useT } from '@/i18n/useT' /** @@ -39,3 +40,37 @@ export default function DiscardConfirm({ ) } + +interface ActionsProps { + confirming: DiscardTarget | null + readOnly: boolean + /** « Créer » or « Enregistrer ». */ + submitLabel: string + onCancel: () => void + onKeepTyping: () => void + onDiscard: () => void +} + +/** A form's footer: cancel and submit, or the discard confirmation once a close asked. */ +export function FormActions(props: ActionsProps) { + const t = useT() + if (props.confirming) { + return ( + + ) + } + const cancel = props.readOnly ? 'discard' : 'cancel' + return ( +
+ + +
+ ) +} diff --git a/apps/app/src/components/editor/findings/FindingCreateForm.tsx b/apps/app/src/components/editor/findings/FindingCreateForm.tsx index 7b6eca17..b827b3e0 100644 --- a/apps/app/src/components/editor/findings/FindingCreateForm.tsx +++ b/apps/app/src/components/editor/findings/FindingCreateForm.tsx @@ -6,10 +6,9 @@ import type { } from '@faunosteo/core-wasm/types' import DraftField from '@/components/editor/fields/DraftField' import SelectField from '@/components/editor/fields/SelectField' -import DiscardConfirm from '@/components/editor/findings/DiscardConfirm' +import { FormActions } from '@/components/editor/findings/DiscardConfirm' import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice' -import { useDirtyGuard } from '@/components/editor/findings/useDirtyGuard' -import Button from '@/components/ui/Button' +import { useFormDraft } from '@/components/editor/findings/useDirtyGuard' import { buildItems, type FindingItem, @@ -45,32 +44,35 @@ export interface FindingCreateFormProps { onClose: (forced: boolean) => void } -/** - * Collects what the core requires (names FR/EN, the kind of a category), then one - * `insert`: no element exists with default labels. The fields are a local draft: nothing - * is written before « Créer », a close or a move never creates (R2F-3). - */ -export default function FindingCreateForm(props: FindingCreateFormProps) { - const { pending, readOnly, guards, onCreated, onClose } = props - const t = useT() +interface Draft { + fr: string + en: string + kind: string +} + +const EMPTY: Draft = { fr: '', en: '', kind: '' } +const sameDraft = (a: Draft, b: Draft) => + a.fr === b.fr && a.en === b.en && a.kind === b.kind + +/** 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) { + if (isBlank(draft.fr) || isBlank(draft.en)) return false + return pending.kind !== 'category' || (parent !== null && draft.kind !== '') +} + +/** The form's state and its one `insert` (« Créer »), refused on a missing field. */ +function useCreateForm(props: FindingCreateFormProps) { + const { pending, guards, onCreated } = props const edit = useEditCommand() const zones = useZoneChoice() - const [fr, setFr] = useState('') - const [en, setEn] = useState('') - const [kind, setKind] = useState('') - const guard = useDirtyGuard(guards, fr !== '' || en !== '' || kind !== '') + const form = useFormDraft(EMPTY, guards, sameDraft) const create = () => { const parent = pending.kind === 'category' ? zones.chosen : pending.parent - const missingParent = pending.kind === 'category' && !parent - const incomplete = - isBlank(fr) || - isBlank(en) || - missingParent || - (pending.kind === 'category' && !kind) - if (incomplete) { + if (!isComplete(form.draft, pending, parent)) { edit.reject('form', 'editor.findings.required') return } + const { fr, en, kind } = form.draft let createdId = '' const added = edit.runNew('form', PREFIX[pending.kind], (id) => { createdId = id @@ -79,6 +81,58 @@ export default function FindingCreateForm(props: FindingCreateFormProps) { }) if (added) onCreated(createdId, parent) } + return { ...form, zones, create, error: edit.fieldError('form') } +} + +/** The kind choice of a category and its two names, as draft fields. */ +function CreateFields(props: { + form: ReturnType + category: boolean + readOnly: boolean +}) { + const { form, category, readOnly } = props + const t = useT() + const kinds = CATEGORY_KINDS.map((k) => ({ + value: k, + label: t(`editor.findings.kind.${k}`), + })) + return ( +
+ {category && } + {category && ( + form.set({ kind })} + /> + )} + {(['fr', 'en'] as const).map((l) => ( + form.set({ [l]: value })} + readOnly={readOnly} + /> + ))} +
+ ) +} + +/** + * Collects what the core requires (names FR/EN, the kind of a category), then one + * `insert`: no element exists with default labels. The fields are a local draft: nothing + * is written before « Créer », a close or a move never creates (R2F-3). + */ +export default function FindingCreateForm(props: FindingCreateFormProps) { + const { pending, readOnly, onClose } = props + const t = useT() + const form = useCreateForm(props) + const { guard } = form const category = pending.kind === 'category' return (
{ event.preventDefault() - create() + form.create() }} > {readOnly && } - {category && zones.chosen && } -
- {category && } - {category && ( - ({ - value: k, - label: t(`editor.findings.kind.${k}`), - })), - ]} - onCommit={setKind} - /> - )} - - -
- {edit.fieldError('form') && ( + {category && form.zones.chosen && } + + {form.error && (

- {edit.fieldError('form')} + {form.error}

)} - {guard.confirming ? ( - onClose(true)} - /> - ) : ( -
- - -
- )} + onClose(readOnly)} + onKeepTyping={guard.keepTyping} + onDiscard={() => onClose(true)} + /> ) } diff --git a/apps/app/src/components/editor/findings/FindingEditForm.tsx b/apps/app/src/components/editor/findings/FindingEditForm.tsx index 9dc27a74..f4b971ba 100644 --- a/apps/app/src/components/editor/findings/FindingEditForm.tsx +++ b/apps/app/src/components/editor/findings/FindingEditForm.tsx @@ -1,9 +1,8 @@ -import { useRef, useState } from 'react' +import { useState } from 'react' import DraftField from '@/components/editor/fields/DraftField' -import DiscardConfirm from '@/components/editor/findings/DiscardConfirm' -import { useDirtyGuard } from '@/components/editor/findings/useDirtyGuard' +import { FormActions } from '@/components/editor/findings/DiscardConfirm' +import { useFormDraft } from '@/components/editor/findings/useDirtyGuard' import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice' -import Button from '@/components/ui/Button' import { patchElement, type FindingItem } from '@/editor/findings/tree' import { isBlank, optionalText } from '@/editor/sheetDocument' import { useEditCommand } from '@/editor/useEditCommand' @@ -98,6 +97,74 @@ function VetCheckbox({ ) } +type Locale2 = 'fr' | 'en' +const LOCALES: readonly Locale2[] = ['fr', 'en'] + +interface FieldsProps { + draft: Draft + set: (change: Partial) => void + readOnly: boolean + described: boolean + blank: readonly string[] +} + +/** The names, then the descriptions of a family or a node, as draft fields. */ +function EditFields({ draft, set, readOnly, described, blank }: FieldsProps) { + const t = useT() + const text = (l: Locale2) => (l === 'fr' ? 'descriptionFr' : 'descriptionEn') + return ( +
+ {LOCALES.map((l) => ( + set({ [l]: value })} + readOnly={readOnly} + error={blank.includes(l) ? t('editor.field.required') : undefined} + /> + ))} + {described && + LOCALES.map((l) => ( + set({ [text(l)]: value })} + readOnly={readOnly} + multiline + /> + ))} +
+ ) +} + +/** The form's state: draft, blank names, and the one save (none when nothing changed). */ +function useEditForm(props: FindingEditFormProps) { + const { item, readOnly, guards, onDone } = props + const edit = useEditCommand() + const form = useFormDraft(draftOf(item), guards, sameDraft) + const [blank, setBlank] = useState([]) + const save = () => { + const missing = LOCALES.filter((l) => isBlank(form.draft[l])) + setBlank(missing) + if (missing.length > 0) { + document.getElementById(`finding-edit-name-${missing[0]}`)?.focus() + } else if (!form.dirty) { + onDone(false) + } else { + const element = patchOf(item, form.draft) + const command = { op: 'update', key: item.key, element } as const + if (edit.run('save', command)) onDone(true) + } + } + const cancel = () => + form.dirty && !readOnly ? form.guard.askToLeave() : onDone(false) + return { ...form, blank, save, cancel, error: edit.fieldError('save') } +} + /** * The element edited in the finding dialog (R2F-3): a local draft, one `update` on * « Enregistrer » (none when nothing changed), nothing on « Annuler » or a close. When the @@ -105,34 +172,12 @@ function VetCheckbox({ * is left. */ export default function FindingEditForm(props: FindingEditFormProps) { - const { item, readOnly, guards, onDone, onDiscardClose } = props + const { item, readOnly, onDone, onDiscardClose } = props const t = useT() - const edit = useEditCommand() - const initial = useRef(draftOf(item)).current - const [draft, setDraft] = useState(initial) - const [blank, setBlank] = useState([]) - const dirty = !sameDraft(draft, initial) - const guard = useDirtyGuard(guards, dirty) - const set = (change: Partial) => setDraft({ ...draft, ...change }) - const save = () => { - const missing = (['fr', 'en'] as const).filter((l) => isBlank(draft[l])) - setBlank(missing) - if (missing.length > 0) { - document.getElementById(`finding-edit-name-${missing[0]}`)?.focus() - return - } - if (!dirty) return onDone(false) - const command = { - op: 'update', - key: item.key, - element: patchOf(item, draft), - } as const - if (edit.run('save', command)) onDone(true) - } - const cancel = () => (dirty && !readOnly ? guard.askToLeave() : onDone(false)) - const described = item.kind !== 'zone' - const fieldError = (l: 'fr' | 'en') => - blank.includes(l) ? t('editor.field.required') : undefined + const form = useEditForm(props) + const { guard } = form + const discard = + guard.confirming === 'dialog' ? onDiscardClose : () => onDone(false) return (
{ event.preventDefault() - save() + form.save() }} > {readOnly && } -
- {(['fr', 'en'] as const).map((l) => ( - set({ [l]: value })} - readOnly={readOnly} - error={fieldError(l)} - /> - ))} - {described && - (['fr', 'en'] as const).map((l) => ( - - set( - l === 'fr' - ? { descriptionFr: value } - : { descriptionEn: value }, - ) - } - readOnly={readOnly} - multiline - /> - ))} -
+ {item.element.kind === 'finding_node' && ( set({ vet })} + onChange={(vet) => form.set({ vet })} /> )} - {edit.fieldError('save') && ( + {form.error && (

- {edit.fieldError('save')} + {form.error}

)} - {guard.confirming ? ( - - guard.confirming === 'dialog' ? onDiscardClose() : onDone(false) - } - /> - ) : ( -
- - -
- )} + ) } diff --git a/apps/app/src/components/editor/findings/useDirtyGuard.ts b/apps/app/src/components/editor/findings/useDirtyGuard.ts index 458a8606..5d1094fc 100644 --- a/apps/app/src/components/editor/findings/useDirtyGuard.ts +++ b/apps/app/src/components/editor/findings/useDirtyGuard.ts @@ -1,6 +1,7 @@ import { useEffect, useRef, useState } from 'react' import { useBeforeUnload } from '@/app/useLeaveGuard' import type { Guards } from '@/editor/useEditorNavigation' +import { useT } from '@/i18n/useT' /** What the footer's « Abandonner » does: leave the form, or the whole dialog. */ export type DiscardTarget = 'form' | 'dialog' @@ -8,17 +9,21 @@ export type DiscardTarget = 'form' | 'dialog' /** * The finding layer's guard while a form holds changes (R2F-3): a user close that reaches * the layer (✕, Escape, scrim, Back) is refused and the form asks « Abandonner les - * modifications ? » (`confirming`). A forced close, or a form with nothing typed, goes - * ahead. `askToLeave` is the form's own « Annuler ». The browser's unload is guarded too. + * modifications ? » (`confirming`). A forced close (the element vanished) goes ahead and + * says the draft was dropped (BDR-115); a form with nothing typed says nothing. + * `askToLeave` is the form's own « Annuler ». The browser's unload is guarded too. */ export function useDirtyGuard(guards: Guards, dirty: boolean) { + const t = useT() const [confirming, setConfirming] = useState(null) - const latest = useRef(dirty) - latest.current = dirty + const latest = useRef({ dirty, dropped: t('editor.findings.draft_dropped') }) + latest.current = { dirty, dropped: t('editor.findings.draft_dropped') } useBeforeUnload(dirty) useEffect(() => { guards.register('finding', (forced) => { - if (forced || !latest.current) return { allowed: true } + const { dirty: held, dropped } = latest.current + if (!held) return { allowed: true } + if (forced) return { allowed: true, note: dropped } setConfirming('dialog') return { allowed: false } }) @@ -30,3 +35,20 @@ export function useDirtyGuard(guards: Guards, dirty: boolean) { keepTyping: () => setConfirming(null), } } + +/** + * A form's local draft: `set` merges a change, `dirty` is true once it differs from the + * first value (`same` compares two drafts), and the layer's guard follows `dirty`. + */ +export function useFormDraft( + initial: T, + guards: Guards, + same: (a: T, b: T) => boolean, +) { + const first = useRef(initial).current + const [draft, setDraft] = useState(first) + const dirty = !same(draft, first) + const guard = useDirtyGuard(guards, dirty) + const set = (change: Partial) => setDraft({ ...draft, ...change }) + return { draft, set, dirty, guard } +} diff --git a/apps/app/src/components/editor/tabs/FindingsTab.tsx b/apps/app/src/components/editor/tabs/FindingsTab.tsx index bf6c67fc..adadc4ef 100644 --- a/apps/app/src/components/editor/tabs/FindingsTab.tsx +++ b/apps/app/src/components/editor/tabs/FindingsTab.tsx @@ -36,22 +36,6 @@ function currentItems(): FindingItem[] { } } -/** A place mounted without the navigation (a test harness): no layer ever opens. */ -const NO_LAYER: FindingLayer = { - view: null, - guards: { - register: () => undefined, - ask: () => ({ allowed: true }), - askAll: () => ({ allowed: true }), - }, - open: () => undefined, - start: () => undefined, - close: () => true, - replace: () => undefined, - openCitations: () => undefined, - announce: () => undefined, -} - const ADD_BUTTON: Record = { zone: 'finding-add-zone', category: 'finding-add-category', @@ -158,35 +142,35 @@ function pendingOf( return { kind: kind as FindingKind, parent: found?.item ?? null } } -/** Constats: the tree zones → categories → nodes; each element opens in a dialog. */ -export default function FindingsTab({ - readOnly, - focus, - layer = NO_LAYER, -}: EditorPlaceProps) { - const t = useT() - const doc = useSheetDocument() - const [selectedId, setSelectedId] = useState(null) +interface TreeSelection { + selectedId: string | null + selected: FindingItem | undefined + expanded: ReadonlySet + select: (id: string | null) => void + toggle: (id: string, open: boolean) => void + reveal: (found: { item: FindingItem; ancestors: string[] }) => void +} + +/** Selection and expansion of the tree: the zones start open, a closed branch takes the selection. */ +function useTreeSelection( + items: readonly FindingItem[], + loaded: boolean, +): TreeSelection { + const [selectedId, select] = useState(null) const [expanded, setExpanded] = useState>(new Set()) const [seeded, setSeeded] = useState(false) - const [focusId, setFocusId] = useState<{ id: string } | null>(null) - const clearFocusId = useCallback(() => setFocusId(null), []) - const items = useMemo(() => (doc ? buildItems(doc) : []), [doc]) - if (doc && !seeded) { + if (loaded && !seeded) { setSeeded(true) setExpanded( new Set(items.filter((i) => i.kind === 'zone').map((i) => i.id)), ) } - const selected = items.find((item) => item.id === selectedId) - const reveal = (found: { item: FindingItem; ancestors: string[] }) => { + const reveal: TreeSelection['reveal'] = (found) => { setExpanded((prev) => new Set([...prev, ...found.ancestors])) - setSelectedId(found.item.id) + select(found.item.id) } const toggle = (id: string, open: boolean) => { - if (!open && selectedId && isUnder(items, selectedId, id)) { - setSelectedId(id) - } + if (!open && selectedId && isUnder(items, selectedId, id)) select(id) setExpanded((prev) => { const next = new Set(prev) if (open) next.add(id) @@ -194,36 +178,97 @@ export default function FindingsTab({ return next }) } + const selected = items.find((item) => item.id === selectedId) + return { selectedId, selected, expanded, select, toggle, reveal } +} + +/** The row the focus lands on after a move: set, applied once the dialogs are gone, cleared. */ +function useFocusLanding() { + const [focusId, setFocusId] = useState<{ id: string } | null>(null) + const clear = useCallback(() => setFocusId(null), []) + const land = useCallback( + (id: string | null) => setFocusId(id ? { id } : null), + [], + ) + return { focusId, clear, land } +} + +interface TabContext { + layer: FindingLayer + items: readonly FindingItem[] + sel: TreeSelection + land: (id: string | null) => void +} + +/** « Aller à » and the layer's own element: both select the row, the first opens the dialog. */ +function useLayerFollow(focus: EditorPlaceProps['focus'], ctx: TabContext) { + const { layer, items, sel, land } = ctx useFocusRequest(focus, (target) => { const found = target.key && itemForKey(items, target.key) if (!found) return 'none' - reveal(found) - // « Aller à » shows the element as its row selected and its dialog open in view - // mode; the row takes the focus again when the dialog is closed. + sel.reveal(found) + // The row takes the focus again when the dialog is closed. layer.open(found.item.key) - setFocusId({ id: found.item.id }) + land(found.item.id) return 'found' }) - useSelectionOfLayer(layer, items, reveal) - useGoneRule(layer, doc !== null) + useSelectionOfLayer(layer, items, sel.reveal) +} + +/** What the tab does with the layer: a creation turns into its element, a row opens its dialog, a deletion. */ +function useFindingActions(ctx: TabContext) { + const { layer, items, sel, land } = ctx + const deletion = useFindingDeletion(items, sel.selectedId, { + select: sel.select, + focusItem: land, + closeLayer: () => layer.replace(null), + }) const created = ( id: string, parent: FindingItem | null, kind: FindingKind, ) => { - if (parent) toggle(parent.id, true) - setSelectedId(createdItemId(kind, parent, id)) + if (parent) sel.toggle(parent.id, true) + sel.select(createdItemId(kind, parent, id)) layer.replace(createdKey(kind, parent, id)) } - const { deleting, askDelete, closeDelete } = useFindingDeletion( - items, - selectedId, - { - select: setSelectedId, - focusItem: (id) => setFocusId(id ? { id } : null), - closeLayer: () => layer.replace(null), - }, - ) + const activate = (item: FindingItem) => { + sel.select(item.id) + layer.open(item.key) + } + return { ...deletion, created, activate } +} + +/** Everything the tab shows and does, so the component only lays it out. */ +function useFindingsTab(focus: EditorPlaceProps['focus'], layer: FindingLayer) { + const doc = useSheetDocument() + const items = useMemo(() => (doc ? buildItems(doc) : []), [doc]) + const sel = useTreeSelection(items, doc !== null) + const landing = useFocusLanding() + const ctx = { layer, items, sel, land: landing.land } + useLayerFollow(focus, ctx) + useGoneRule(layer, doc !== null) + const actions = useFindingActions(ctx) + const returnFocus = useReturnTarget(layer.view) + return { doc, items, sel, landing, actions, returnFocus } +} + +/** Constats: the tree zones → categories → nodes; each element opens in a dialog. */ +export default function FindingsTab(props: EditorPlaceProps) { + const { layer } = props + if (!layer) + throw new Error('Constats needs the finding layer of the workspace') + return +} + +function FindingsBody({ + readOnly, + focus, + layer, +}: EditorPlaceProps & { layer: FindingLayer }) { + const t = useT() + const tab = useFindingsTab(focus, layer) + const { items, sel, landing, actions } = tab const { view } = layer const shown = view && 'key' in view ? itemForKey(items, view.key) : null return ( @@ -233,39 +278,36 @@ export default function FindingsTab({ className="min-h-24 space-y-3" > item.kind === 'zone')} readOnly={readOnly} onStart={(p) => layer.start(p.kind, p.parent?.key ?? null)} /> - {doc && items.length === 0 && ( + {tab.doc && items.length === 0 && (

{t('editor.findings.empty')}

)} { - setSelectedId(item.id) - layer.open(item.key) - }} - onToggle={toggle} - focusId={focusId} - onFocused={clearFocusId} + visible={visibleItems(items, sel.expanded)} + selectedId={sel.selected?.id ?? null} + expanded={sel.expanded} + onSelect={sel.select} + onActivate={actions.activate} + onToggle={sel.toggle} + focusId={landing.focusId} + onFocused={landing.clear} /> - + ) } diff --git a/apps/app/src/editor/focusRequest.ts b/apps/app/src/editor/focusRequest.ts index e6562e1f..9df13545 100644 --- a/apps/app/src/editor/focusRequest.ts +++ b/apps/app/src/editor/focusRequest.ts @@ -211,7 +211,19 @@ export function refocusIfHidden( if (!gone && document.activeElement === held) return const homeShown = home?.isConnected && !home.closest('[hidden]') if (homeShown) home.focus() - if (!homeShown || document.activeElement !== home) focusActiveTab() + if (homeShown && document.activeElement === home) return + // Under a modal dialog the tab row is inert: the focus stays in the top dialog. + if (!focusTopDialog()) focusActiveTab() +} + +/** The first control of the top open dialog takes the focus; false when none is open. */ +function focusTopDialog(): boolean { + const top = [...document.querySelectorAll('dialog[open]')].at(-1) + const control = top?.querySelector( + 'button:not([disabled]), input:not([disabled]), select, textarea, a[href]', + ) + control?.focus() + return control !== undefined && document.activeElement === control } /** diff --git a/apps/app/src/editor/navigation.ts b/apps/app/src/editor/navigation.ts index 75e97b8c..011f80a9 100644 --- a/apps/app/src/editor/navigation.ts +++ b/apps/app/src/editor/navigation.ts @@ -258,7 +258,6 @@ export function navigationReducer( case 'create_finding': return createFinding(state, { kind: action.kind, parent: action.parent }) case 'close_finding': - console.trace('CLOSE_FINDING') return { ...state, finding: null } case 'open_citations': return openCitations(state, action.citedBy) @@ -269,7 +268,6 @@ export function navigationReducer( case 'go_to': return goTo(state, action.target) case 'restore_view': - console.trace('RESTORE', JSON.stringify(action.view.finding)) return restoreView(state, action.view) case 'focus_consumed': return state.focus?.serial === action.serial diff --git a/apps/app/src/editor/useEditorNavigation.ts b/apps/app/src/editor/useEditorNavigation.ts index f0146358..661b75df 100644 --- a/apps/app/src/editor/useEditorNavigation.ts +++ b/apps/app/src/editor/useEditorNavigation.ts @@ -168,7 +168,7 @@ function useLiveRegion() { waiting.current() waiting.current = afterModalsClosed(() => { const joined = queued.current.splice(0).join('. ') - setLive((previous) => (previous === joined ? `${joined} ` : joined)) + setLive((previous) => (previous === joined ? `${joined} ` : joined)) }) }, []) return { live, announce } @@ -267,7 +267,12 @@ interface LayerContext { * own confirmation and the close is cancelled. `replaceFinding` is the move that is no * Back step: the creation turned into its element, a deletion, an element that vanished. */ -function useFindingLayer({ dispatch, announce, guards, mark }: LayerContext) { +function useFindingLayer(ctx: LayerContext) { + return { ...useFindingOpening(ctx), ...useFindingClosing(ctx) } +} + +/** The moves that add the layer: a dialog for an element, a creation form. */ +function useFindingOpening({ dispatch, mark }: LayerContext) { const openFinding = useCallback( (key: ElementKey) => { mark() @@ -282,9 +287,13 @@ function useFindingLayer({ dispatch, announce, guards, mark }: LayerContext) { }, [dispatch, mark], ) + return { openFinding, startFinding } +} + +/** The moves that take it away: a user close, and the replace that is no Back step. */ +function useFindingClosing({ dispatch, announce, guards, mark }: LayerContext) { const closeFinding = useCallback( (forced = false) => { - console.trace('closeFinding', forced) if (!guards.askAll(forced).allowed) return false mark() dispatch({ type: 'close_finding' }) @@ -301,7 +310,7 @@ function useFindingLayer({ dispatch, announce, guards, mark }: LayerContext) { }, [guards, announce, dispatch, mark], ) - return { openFinding, startFinding, closeFinding, replaceFinding } + return { closeFinding, replaceFinding } } /** The citations sheet over the finding dialog: opened from a finding node only. */ diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index ea459064..f56b1e7c 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -1640,6 +1640,7 @@ export const en: Dict = { 'editor.findings.discard_ask': 'Discard your changes?', 'editor.findings.keep_typing': 'Keep editing', 'editor.findings.discard': 'Discard', + 'editor.findings.draft_dropped': 'Entry discarded', 'editor.findings.gone': 'This finding no longer exists', '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.', diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index ded0094e..b289741f 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -1671,6 +1671,7 @@ export const fr: Dict = { 'editor.findings.discard_ask': 'Abandonner les modifications ?', 'editor.findings.keep_typing': 'Continuer la saisie', 'editor.findings.discard': 'Abandonner', + 'editor.findings.draft_dropped': 'Saisie abandonnée', 'editor.findings.gone': "Ce constat n'existe plus", '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.", diff --git a/apps/app/tests/helpers/findingsHost.tsx b/apps/app/tests/helpers/findingsHost.tsx index c6642afe..7eb6d60b 100644 --- a/apps/app/tests/helpers/findingsHost.tsx +++ b/apps/app/tests/helpers/findingsHost.tsx @@ -1,4 +1,5 @@ import { vi } from 'vitest' +import type { FindingLayer } from '@/editor/tabs' import CitationsSheet from '@/components/editor/references/CitationsSheet' import FindingsTab from '@/components/editor/tabs/FindingsTab' import { findingLayerOf } from '@/editor/findingLayer' @@ -36,3 +37,19 @@ export default function FindingsHost({ ) } + +/** A layer that never opens: for a test that mounts Constats only to read its focus. */ +export const testLayer: FindingLayer = { + view: null, + guards: { + register: () => undefined, + ask: () => ({ allowed: true }), + askAll: () => ({ allowed: true }), + }, + open: () => undefined, + start: () => undefined, + close: () => true, + replace: () => undefined, + openCitations: () => undefined, + announce: () => undefined, +} diff --git a/apps/app/tests/unit/editor-finding-dialog.test.tsx b/apps/app/tests/unit/editor-finding-dialog.test.tsx index cf8a6d23..1a1db7ba 100644 --- a/apps/app/tests/unit/editor-finding-dialog.test.tsx +++ b/apps/app/tests/unit/editor-finding-dialog.test.tsx @@ -330,6 +330,45 @@ describe('read-only flip and the gone rule', () => { expect(field).toHaveFocus() }) + it('a flip to read-only while « Modifier » holds the focus keeps it in the dialog (the tab row is inert)', async () => { + const user = await mount() + await openFinding(user, /Cat A/) + const button = inDialog().getByRole('button', { name: 'Modifier' }) + button.focus() + expect(button).toHaveFocus() + act(() => { + setWidth(900) + window.dispatchEvent(new Event('resize')) + }) + // The edit-only actions left the page: the focus moved to the dialog's first control. + expect(button.isConnected).toBe(false) + expect(findingDialog()!.contains(document.activeElement)).toBe(true) + }) + + it('a forced close of a dirty form says the dropped draft once, with the gone text', async () => { + const user = await mount() + await openFinding(user, /Node A/) + await modify(user) + await user.type(nameField(), ' bis') + act(() => { + store.getState().commit({ + op: 'remove', + key: { + kind: 'finding', + zone_id: 'zone-a', + path: ['fcat-a', 'fnode-a'], + }, + }) + }) + await closed() + const live = () => document.querySelector('p.sr-only[aria-live="polite"]')! + await waitFor(() => + expect(live().textContent).toBe( + "Saisie abandonnée. Ce constat n'existe plus", + ), + ) + }) + it('an element that vanishes closes its dialog by replace and says so', async () => { const user = await mount() await openFinding(user, /Node A/) diff --git a/apps/app/tests/unit/editor-focus-request.test.tsx b/apps/app/tests/unit/editor-focus-request.test.tsx index 73f71a45..d5e63a4d 100644 --- a/apps/app/tests/unit/editor-focus-request.test.tsx +++ b/apps/app/tests/unit/editor-focus-request.test.tsx @@ -13,6 +13,8 @@ import type { AnatomicalSheetDocument, ElementKey, } from '@faunosteo/core-wasm/types' +import { findingLayerOf } from '@/editor/findingLayer' +import { testLayer } from '../helpers/findingsHost' import FindingsTab from '@/components/editor/tabs/FindingsTab' import RegionsSection from '@/components/editor/annotations/sections/RegionsSection' import EditorTabBody from '@/components/editor/EditorTabBody' @@ -115,7 +117,7 @@ describe('focus requests', () => { zone_id: 'zone-a', path: ['fcat-a', 'node-a'], } - render() + render() const item = await screen.findByRole('treeitem', { name: /Nœud A/ }) expect(item.getAttribute('aria-selected')).toBe('true') await waitFor(() => expect(document.activeElement).toBe(item)) @@ -210,7 +212,7 @@ describe('focus requests', () => { const gone: ElementKey = { kind: 'zone', id: 'zone-gone' } render( - + , ) await waitFor(() => expect(consumed).toHaveBeenCalledWith(4, 'none')) @@ -268,7 +270,7 @@ function Probe({ go, tier }: { go: EditorTarget; tier: 'wide' | 'small' }) { visited={state.visitedTabs} {...base} navigate={nav.navigate} - openCitations={nav.openCitations} + layer={findingLayerOf(nav)} focus={state.focus} annotations={{ section: state.section, @@ -388,6 +390,9 @@ describe('a request that finds nothing', () => { const key: ElementKey = { kind: 'zone', id: 'zone-a' } render() await user.click(screen.getByText('go')) + // « Aller à » opens the element's dialog; closed, its row holds the focus. + const dialog = await screen.findByRole('dialog') + await user.click(within(dialog).getByRole('button', { name: 'Fermer' })) await waitFor(() => expect(document.activeElement).toBe( screen.getByRole('treeitem', { name: /Zone A/ }), diff --git a/apps/app/tests/unit/editor-keep-alive.test.tsx b/apps/app/tests/unit/editor-keep-alive.test.tsx index 6bc19cf2..20dddf87 100644 --- a/apps/app/tests/unit/editor-keep-alive.test.tsx +++ b/apps/app/tests/unit/editor-keep-alive.test.tsx @@ -35,6 +35,7 @@ import { store, versionAnswer, } from '../helpers/editorHarness' +import { testLayer } from '../helpers/findingsHost' import { openFinding } from '../helpers/findingDialog' import { mountDraft, setWidth } from '../helpers/editorRoute' @@ -513,6 +514,7 @@ describe('a request reaches only its owner', () => { readOnly={false} navigate={vi.fn()} reloadSheet={vi.fn()} + layer={testLayer} focus={{ target: targetOfKey({ kind: 'finding',