fix(editor): Task 2 review round 1, trace calls, form hooks, keyboard proof

This commit is contained in:
bchanot committed 2026-11-13 19:39:29 +01:00
1 parent c893dec60b
commit b703333b20
15 files changed
+476 -261

No files matched your search

+24 -15
View File
@@ -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<HTMLElement>(
'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()
@@ -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({
</div>
)
}
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 (
<DiscardConfirm
onKeepTyping={props.onKeepTyping}
onDiscard={props.onDiscard}
/>
)
}
const cancel = props.readOnly ? 'discard' : 'cancel'
return (
<div className="flex flex-wrap justify-end gap-2">
<Button type="button" variant="ghost" onClick={props.onCancel}>
{t(`editor.findings.${cancel}`)}
</Button>
<Button type="submit" disabled={props.readOnly}>
{props.submitLabel}
</Button>
</div>
)
}
@@ -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<typeof useCreateForm>
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 (
<div className="grid gap-3 md:grid-cols-2">
{category && <ZoneSelect zones={form.zones} readOnly={readOnly} />}
{category && (
<SelectField
id="finding-new-kind"
label={t('editor.findings.kind')}
value={form.draft.kind}
readOnly={readOnly}
options={[{ value: '', label: t('editor.field.choose') }, ...kinds]}
onCommit={(kind) => form.set({ kind })}
/>
)}
{(['fr', 'en'] as const).map((l) => (
<DraftField
key={l}
id={`finding-new-name-${l}`}
label={t(`editor.general.name_${l}`)}
value={form.draft[l]}
onChange={(value) => form.set({ [l]: value })}
readOnly={readOnly}
/>
))}
</div>
)
}
/**
* 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 (
<form
@@ -87,68 +141,25 @@ export default function FindingCreateForm(props: FindingCreateFormProps) {
noValidate
onSubmit={(event) => {
event.preventDefault()
create()
form.create()
}}
>
{readOnly && <ReadOnlyNotice />}
{category && zones.chosen && <ZoneTitle zone={zones.chosen} />}
<div className="grid gap-3 md:grid-cols-2">
{category && <ZoneSelect zones={zones} readOnly={readOnly} />}
{category && (
<SelectField
id="finding-new-kind"
label={t('editor.findings.kind')}
value={kind}
readOnly={readOnly}
options={[
{ value: '', label: t('editor.field.choose') },
...CATEGORY_KINDS.map((k) => ({
value: k,
label: t(`editor.findings.kind.${k}`),
})),
]}
onCommit={setKind}
/>
)}
<DraftField
id="finding-new-name-fr"
label={t('editor.general.name_fr')}
value={fr}
onChange={setFr}
readOnly={readOnly}
/>
<DraftField
id="finding-new-name-en"
label={t('editor.general.name_en')}
value={en}
onChange={setEn}
readOnly={readOnly}
/>
</div>
{edit.fieldError('form') && (
{category && form.zones.chosen && <ZoneTitle zone={form.zones.chosen} />}
<CreateFields form={form} category={category} readOnly={readOnly} />
{form.error && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('form')}
{form.error}
</p>
)}
{guard.confirming ? (
<DiscardConfirm
onKeepTyping={guard.keepTyping}
onDiscard={() => onClose(true)}
/>
) : (
<div className="flex flex-wrap justify-end gap-2">
<Button
type="button"
variant="ghost"
onClick={() => onClose(readOnly)}
>
{t(readOnly ? 'editor.findings.discard' : 'editor.findings.cancel')}
</Button>
<Button type="submit" disabled={readOnly}>
{t('editor.findings.create')}
</Button>
</div>
)}
<FormActions
confirming={guard.confirming}
readOnly={readOnly}
submitLabel={t('editor.findings.create')}
onCancel={() => onClose(readOnly)}
onKeepTyping={guard.keepTyping}
onDiscard={() => onClose(true)}
/>
</form>
)
}
@@ -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<Draft>) => 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 (
<div className="grid gap-3 md:grid-cols-2">
{LOCALES.map((l) => (
<DraftField
key={l}
id={`finding-edit-name-${l}`}
label={t(`editor.general.name_${l}`)}
value={draft[l]}
onChange={(value) => set({ [l]: value })}
readOnly={readOnly}
error={blank.includes(l) ? t('editor.field.required') : undefined}
/>
))}
{described &&
LOCALES.map((l) => (
<DraftField
key={`d-${l}`}
id={`finding-edit-description-${l}`}
label={t(`editor.findings.description_${l}`)}
value={draft[text(l)]}
onChange={(value) => set({ [text(l)]: value })}
readOnly={readOnly}
multiline
/>
))}
</div>
)
}
/** 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<readonly string[]>([])
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<readonly string[]>([])
const dirty = !sameDraft(draft, initial)
const guard = useDirtyGuard(guards, dirty)
const set = (change: Partial<Draft>) => 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 (
<form
data-draft-form
@@ -140,70 +185,37 @@ export default function FindingEditForm(props: FindingEditFormProps) {
noValidate
onSubmit={(event) => {
event.preventDefault()
save()
form.save()
}}
>
{readOnly && <ReadOnlyNotice />}
<div className="grid gap-3 md:grid-cols-2">
{(['fr', 'en'] as const).map((l) => (
<DraftField
key={l}
id={`finding-edit-name-${l}`}
label={t(`editor.general.name_${l}`)}
value={draft[l]}
onChange={(value) => set({ [l]: value })}
readOnly={readOnly}
error={fieldError(l)}
/>
))}
{described &&
(['fr', 'en'] as const).map((l) => (
<DraftField
key={`d-${l}`}
id={`finding-edit-description-${l}`}
label={t(`editor.findings.description_${l}`)}
value={l === 'fr' ? draft.descriptionFr : draft.descriptionEn}
onChange={(value) =>
set(
l === 'fr'
? { descriptionFr: value }
: { descriptionEn: value },
)
}
readOnly={readOnly}
multiline
/>
))}
</div>
<EditFields
draft={form.draft}
set={form.set}
readOnly={readOnly}
described={item.kind !== 'zone'}
blank={form.blank}
/>
{item.element.kind === 'finding_node' && (
<VetCheckbox
checked={draft.vet}
checked={form.draft.vet}
readOnly={readOnly}
onChange={(vet) => set({ vet })}
onChange={(vet) => form.set({ vet })}
/>
)}
{edit.fieldError('save') && (
{form.error && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('save')}
{form.error}
</p>
)}
{guard.confirming ? (
<DiscardConfirm
onKeepTyping={guard.keepTyping}
onDiscard={() =>
guard.confirming === 'dialog' ? onDiscardClose() : onDone(false)
}
/>
) : (
<div className="flex flex-wrap justify-end gap-2">
<Button type="button" variant="ghost" onClick={cancel}>
{t(readOnly ? 'editor.findings.discard' : 'editor.findings.cancel')}
</Button>
<Button type="submit" disabled={readOnly}>
{t('editor.findings.save')}
</Button>
</div>
)}
<FormActions
confirming={guard.confirming}
readOnly={readOnly}
submitLabel={t('editor.findings.save')}
onCancel={form.cancel}
onKeepTyping={guard.keepTyping}
onDiscard={discard}
/>
</form>
)
}
@@ -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<DiscardTarget | null>(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<T extends object>(
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<T>) => setDraft({ ...draft, ...change })
return { draft, set, dirty, guard }
}
@@ -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<string, string> = {
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<string | null>(null)
interface TreeSelection {
selectedId: string | null
selected: FindingItem | undefined
expanded: ReadonlySet<string>
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<string | null>(null)
const [expanded, setExpanded] = useState<ReadonlySet<string>>(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 <FindingsBody {...props} layer={layer} />
}
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"
>
<AddBar
selected={selected}
selected={sel.selected}
hasZone={items.some((item) => item.kind === 'zone')}
readOnly={readOnly}
onStart={(p) => layer.start(p.kind, p.parent?.key ?? null)}
/>
{doc && items.length === 0 && (
{tab.doc && items.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.findings.empty')}
</p>
)}
<FindingTree
visible={visibleItems(items, expanded)}
selectedId={selected?.id ?? null}
expanded={expanded}
onSelect={setSelectedId}
onActivate={(item) => {
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}
/>
<FindingDialog
layer={layer}
item={shown?.item ?? null}
pending={pendingOf(view, items)}
readOnly={readOnly}
returnFocus={useReturnTarget(view)}
onDelete={askDelete}
onCreated={created}
returnFocus={tab.returnFocus}
onDelete={actions.askDelete}
onCreated={actions.created}
/>
<DeleteDialog target={deleting} onClose={closeDelete} />
<DeleteDialog target={actions.deleting} onClose={actions.closeDelete} />
</section>
)
}
+13 -1
View File
@@ -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<HTMLElement>('dialog[open]')].at(-1)
const control = top?.querySelector<HTMLElement>(
'button:not([disabled]), input:not([disabled]), select, textarea, a[href]',
)
control?.focus()
return control !== undefined && document.activeElement === control
}
/**
-2
View File
@@ -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
+13 -4
View File
@@ -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. */
+1
View File
@@ -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.',
+1
View File
@@ -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.",
+17
View File
@@ -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({
</ReadOnlyContext>
)
}
/** 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,
}
@@ -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/)
@@ -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(<FindingsTab {...base} focus={request(key)} />)
render(<FindingsTab {...base} layer={testLayer} focus={request(key)} />)
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(
<FocusConsumedContext value={consumed}>
<FindingsTab {...base} focus={request(gone, 4)} />
<FindingsTab {...base} layer={testLayer} focus={request(gone, 4)} />
</FocusConsumedContext>,
)
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(<Probe go={targetOfKey(key)} tier="wide" />)
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/ }),
@@ -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',