@@ -53,6 +56,7 @@ export default function CitersList({
onGoTo(citer.key)}
className="inline-flex min-h-11 items-center whitespace-nowrap text-[var(--color-accent-strong)] underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
>
diff --git a/apps/app/src/components/editor/references/NoResult.tsx b/apps/app/src/components/editor/references/NoResult.tsx
index 99b31d17..6209e95c 100644
--- a/apps/app/src/components/editor/references/NoResult.tsx
+++ b/apps/app/src/components/editor/references/NoResult.tsx
@@ -2,7 +2,10 @@ import Button from '@/components/ui/Button'
import Icon from '@/components/ui/Icon'
import { useT } from '@/i18n/useT'
-/** Board 24 B: nothing contains the search; the notice offers to clear it. */
+/**
+ * Board 24 B: nothing contains the search; the notice offers to clear it. Not a live
+ * region: the count line already announces the empty result (M11).
+ */
export default function NoResult({
query,
onClear,
@@ -13,12 +16,12 @@ export default function NoResult({
const t = useT()
return (
- {t('editor.references.no_result').replace('{q}', query.trim())}
+ {t('editor.references.no_result').replace('{q}', () => query.trim())}
{' '}
{t('editor.references.no_result_scope')}
diff --git a/apps/app/src/components/editor/references/ReferenceEditor.tsx b/apps/app/src/components/editor/references/ReferenceEditor.tsx
index 58fba400..8716b6c1 100644
--- a/apps/app/src/components/editor/references/ReferenceEditor.tsx
+++ b/apps/app/src/components/editor/references/ReferenceEditor.tsx
@@ -5,16 +5,16 @@ import { useT } from '@/i18n/useT'
import { REFERENCE_TYPES } from './referenceTypes'
import {
useReferenceEdit,
+ type EditHooks,
type Field,
- type LeaveGuard,
} from './useReferenceEdit'
interface Props {
reference: Reference
/** DOM id prefix of the tile (host, position and id): the fields' ids derive from it. */
base: string
- /** The tile's leave guard, registered while the view is mounted and null after. */
- registerLeave: (guard: LeaveGuard | null) => void
+ /** The tile's leave guard (registered while mounted), focus ticket and dropped-draft slot. */
+ hooks: EditHooks
}
/** The edit view of one reference (board 24 D): type, DOI, citation and URL. */
@@ -24,7 +24,7 @@ export default function ReferenceEditor(props: Props) {
const { edit, drafts, setDraft, commitField, setType } = useReferenceEdit(
reference,
base,
- props.registerLeave,
+ props.hooks,
)
const text = (field: Field, label: string, multiline = false) => (
- setType({ ...reference, type: type as ReferenceType })
- }
+ onCommit={(type) => setType(type as ReferenceType)}
error={edit.fieldError('type')}
/>
{text('doi', t('editor.reference.doi'))}
diff --git a/apps/app/src/components/editor/references/ReferenceTile.tsx b/apps/app/src/components/editor/references/ReferenceTile.tsx
index 660322fb..e090ea24 100644
--- a/apps/app/src/components/editor/references/ReferenceTile.tsx
+++ b/apps/app/src/components/editor/references/ReferenceTile.tsx
@@ -9,7 +9,7 @@ import CitersList from './CitersList'
import ReferenceEditor from './ReferenceEditor'
import ReferenceFacts from './ReferenceFacts'
import type { ReferenceHost } from './referenceTypes'
-import type { LeaveGuard } from './useReferenceEdit'
+import { useDropNote, type Field, type LeaveGuard } from './useReferenceEdit'
/** What a tile asks of the library that owns its state. */
export interface TileHandlers {
@@ -23,6 +23,8 @@ export interface TileHandlers {
move?: (position: number) => void
goTo: (key: ElementKey) => void
registerLeave: (guard: LeaveGuard | null) => void
+ /** True once after « Modifier »: the edit view then focuses its Citation field. */
+ takeFocus: () => boolean
}
/** What a tile of the citations panel adds: the finding it belongs to and « Retirer ». */
@@ -97,7 +99,15 @@ function TileHeader({
- {editing ? t('editor.references.edit_title') : reference.citation}
+ {editing ? (
+ // In edit this button ends the edit: its name says so, the title stays visible (M7).
+ <>
+ {t('editor.references.done')}.
+ {t('editor.references.edit_title')}
+ >
+ ) : (
+ reference.citation
+ )}
{!editing && (
@@ -216,6 +226,8 @@ export default function ReferenceTile(props: TileProps) {
const t = useT()
const base = tileBase(host, position, reference)
const headerRef = useRef(null)
+ const dropped = useRef(null)
+ useDropNote(props.readOnly, dropped)
const done = () => {
if (on.done()) headerRef.current?.focus()
}
@@ -231,7 +243,11 @@ export default function ReferenceTile(props: TileProps) {
) : (
diff --git a/apps/app/src/components/editor/references/ReferenceTiles.tsx b/apps/app/src/components/editor/references/ReferenceTiles.tsx
index 485de7ec..8824c542 100644
--- a/apps/app/src/components/editor/references/ReferenceTiles.tsx
+++ b/apps/app/src/components/editor/references/ReferenceTiles.tsx
@@ -57,6 +57,7 @@ export default function ReferenceTiles(props: Props) {
move: (to) => move(reference, to),
goTo: (target) => navigate(targetOfKey(target)),
registerLeave: tiles.registerLeave,
+ takeFocus: () => tiles.takeFocus(key),
}}
/>
)
diff --git a/apps/app/src/components/editor/references/ReferenceToolbar.tsx b/apps/app/src/components/editor/references/ReferenceToolbar.tsx
index ec92cc3b..114fc3ef 100644
--- a/apps/app/src/components/editor/references/ReferenceToolbar.tsx
+++ b/apps/app/src/components/editor/references/ReferenceToolbar.tsx
@@ -29,7 +29,7 @@ function CountLine({ shown, total }: { shown: number; total: number }) {
const text = plural(`editor.references.${key}`, shown)
return (
- {text.replace('{total}', String(total))}
+ {text.replace('{total}', () => String(total))}
)
}
diff --git a/apps/app/src/components/editor/references/useCitationsPanel.ts b/apps/app/src/components/editor/references/useCitationsPanel.ts
index fb576ade..deb5e511 100644
--- a/apps/app/src/components/editor/references/useCitationsPanel.ts
+++ b/apps/app/src/components/editor/references/useCitationsPanel.ts
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useRef, useState } from 'react'
+import { useEffect, useMemo, useRef, useState, type FocusEvent } from 'react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import { patchElement, type FindingItem } from '@/editor/findings/tree'
import { citersOf } from '@/editor/references/citations'
@@ -54,7 +54,7 @@ function useLeaveCheck(
const field = t(`editor.reference.${refused}`)
const note = t('editor.references.draft_dropped').replace(
'{field}',
- field,
+ () => field,
)
return { allowed: true, note }
})
@@ -62,22 +62,53 @@ function useLeaveCheck(
})
}
-/** After a removal the focus goes to the next row's button, else the previous, else the heading. */
-function useFocusAfterRemoval(count: number) {
+/** The row the focus is in: its element, its index in the list and the list's length. */
+interface Held {
+ element: Element
+ at: number
+ rows: number
+}
+
+/**
+ * P20: when the row that holds the focus leaves the list (« Retirer de ce constat », an
+ * undo that removes the reference), the focus goes to the next row's button, else the
+ * previous row's, else the heading. A row swapped for another at the same index (a
+ * tile turned into « Référence introuvable ») counts as gone, so « next » is the one
+ * after it. `lost` registers a row that is about to go without having held the focus.
+ */
+function useFocusRescue() {
const list = useRef(null)
const heading = useRef(null)
- const [removed, setRemoved] = useState<{ at: number; before: number } | null>(
- null,
- )
+ const held = useRef(null)
+ const rowsOf = () => [...(list.current?.children ?? [])]
+ const hold = (element: Element, at: number) => {
+ held.current = { element, at, rows: rowsOf().length }
+ }
+ const track = (event: FocusEvent) => {
+ const at = rowsOf().indexOf(event.target.closest('li') as Element)
+ if (at >= 0) hold(event.target, at)
+ }
useEffect(() => {
- if (removed === null || count >= removed.before) return
- setRemoved(null)
- const rows = [...(list.current?.children ?? [])]
- const row = rows[removed.at] ?? rows[removed.at - 1]
+ const was = held.current
+ if (!was || was.element.isConnected) return
+ held.current = null
+ const active = document.activeElement
+ if (active !== null && active !== document.body) return
+ const rows = rowsOf()
+ const next = rows.length < was.rows ? was.at : was.at + 1
+ const row = rows[next] ?? rows[was.at - 1]
const target = row?.querySelector('button') ?? heading.current
target?.focus()
- }, [removed, count])
- return { list, heading, afterRemoval: setRemoved }
+ })
+ return {
+ list,
+ heading,
+ track,
+ lost: (at: number) => {
+ const row = rowsOf()[at]
+ if (row) hold(row, at)
+ },
+ }
}
/**
@@ -102,15 +133,20 @@ function useShownFinding(
return found ?? last ?? { ids: [], path: [] }
}
-/** What the citations panel reads and does: the cited entries, tiles, « Retirer ». */
-export function useCitationsPanel(hooks: PanelHooks) {
+/** The cited entries of the finding, in its order, with one tile key each. */
+function useCitedEntries(hooks: PanelHooks) {
const { doc, item } = useCitedFinding(hooks.citedBy)
- const edit = useEditCommand()
const { ids, path } = useShownFinding(doc, item, hooks.citedBy)
const entries = citationEntries(doc?.references ?? [], ids)
- const keys = tileKeys(entries)
+ return { doc, item, ids, path, entries, keys: tileKeys(entries) }
+}
+
+/** What the citations panel reads and does: the cited entries, tiles, « Retirer ». */
+export function useCitationsPanel(hooks: PanelHooks) {
+ const { doc, item, ids, path, entries, keys } = useCitedEntries(hooks)
+ const edit = useEditCommand()
const tiles = useTileState(doc ? keys : null)
- const focus = useFocusAfterRemoval(ids.length)
+ const focus = useFocusRescue()
useLeaveCheck(tiles, hooks.registerCanLeave)
useCloseWhenGone(doc !== null && item === null, hooks.onGone)
// « Retirer de ce constat » is the detail's « Retirer »: the same update of the finding's
@@ -121,9 +157,7 @@ export function useCitationsPanel(hooks: PanelHooks) {
const rest = ids.filter((_, index) => index !== at)
const element = patchElement(item, { reference_ids: rest })
const command = { op: 'update', key: item.key, element } as const
- if (edit.run('references', command)) {
- focus.afterRemoval({ at, before: ids.length })
- }
+ if (edit.run('references', command)) focus.lost(at)
}
return {
doc,
@@ -136,5 +170,6 @@ export function useCitationsPanel(hooks: PanelHooks) {
remove,
list: focus.list,
heading: focus.heading,
+ trackFocus: focus.track,
}
}
diff --git a/apps/app/src/components/editor/references/useReferenceEdit.ts b/apps/app/src/components/editor/references/useReferenceEdit.ts
index 16b11fd0..bb6d6664 100644
--- a/apps/app/src/components/editor/references/useReferenceEdit.ts
+++ b/apps/app/src/components/editor/references/useReferenceEdit.ts
@@ -1,7 +1,16 @@
-import { useEffect, useState } from 'react'
-import type { Reference } from '@faunosteo/core-wasm/types'
+import {
+ useContext,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+ type RefObject,
+} from 'react'
+import type { Reference, ReferenceType } from '@faunosteo/core-wasm/types'
+import { AnnounceContext } from '@/editor/focusRequest'
import { isBlank, nullable } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
+import { useT } from '@/i18n/useT'
/** The text fields of the edit view, in the order the leave guard tries them. */
export const FIELDS = ['citation', 'doi', 'url'] as const
@@ -14,6 +23,14 @@ type Drafts = Record
*/
export type LeaveGuard = () => Field | null
+/** What the tile hands its edit view (the library owns the state). */
+export interface EditHooks {
+ registerLeave: (guard: LeaveGuard | null) => void
+ /** True once per « Modifier »: the mount focuses Citation, a remount never does. */
+ takeFocus: () => boolean
+ dropped: RefObject
+}
+
const committedOf = (reference: Reference): Drafts => ({
citation: reference.citation,
doi: reference.doi ?? '',
@@ -45,62 +62,128 @@ function useDrafts(reference: Reference) {
return [drafts, setDraft] as const
}
+/** The first field whose draft differs from `reference`, null when none does. */
+const pendingField = (reference: Reference, drafts: Drafts) =>
+ FIELDS.find(
+ (field) =>
+ normalized(field, drafts[field]) !== committedOf(reference)[field],
+ ) ?? null
+
/**
- * The write path of one reference's edit view. A field applies to the draft when it
- * loses the focus (`commitField`); `leave` re-applies every field whose text differs from
- * the document, stops at the first refusal, shows it and focuses that field (P22, P22').
- * `base` is the DOM id prefix of the tile; `registerLeave` hands `leave` to the library.
+ * The reference as the document holds it now, and the drafts as typed. A blur right after
+ * an apply (« Terminer » focusing the header, a close) runs before the next render, so
+ * the rendered `reference` is stale there: `applied` advances with every apply and is
+ * replaced when the document hands a new reference (undo, reload) (C1).
*/
-export function useReferenceEdit(
- reference: Reference,
- base: string,
- registerLeave: (guard: LeaveGuard | null) => void,
-) {
+function useAppliedReference(reference: Reference, drafts: Drafts) {
+ const applied = useRef(reference)
+ const typed = useRef(drafts)
+ useLayoutEffect(() => {
+ applied.current = reference
+ }, [reference])
+ useLayoutEffect(() => {
+ typed.current = drafts
+ })
+ return { applied, typed }
+}
+
+/** What the view does to the document: `update`, `apply` a draft, which drafts are `pending`. */
+function useWriter(reference: Reference, drafts: Drafts) {
const edit = useEditCommand()
- const [drafts, setDraft] = useDrafts(reference)
- const key = { kind: 'reference', id: reference.id } as const
- const update = (field: string, value: Reference) =>
- edit.run(field, {
- op: 'update',
- key,
- element: { kind: 'reference', value },
- })
- const apply = (current: Reference, field: Field): Reference | null => {
- const draft = drafts[field]
- if (field === 'citation' && isBlank(draft)) {
- edit.reject(field, 'editor.field.required')
- return null
- }
- const next = patched(current, field, draft)
- return update(field, next) ? next : null
+ const { applied, typed } = useAppliedReference(reference, drafts)
+ const update = (field: string, value: Reference) => {
+ const key = { kind: 'reference', id: reference.id } as const
+ const element = { kind: 'reference', value } as const
+ const done = edit.run(field, { op: 'update', key, element })
+ if (done) applied.current = value
+ return done
}
- const pending = (current: Reference, field: Field) =>
- normalized(field, drafts[field]) !== committedOf(current)[field]
- const leave: LeaveGuard = () => {
- let current = reference
- for (const field of FIELDS.filter((name) => pending(current, name))) {
- const next = apply(current, field)
- if (!next) {
- document.getElementById(`${base}-${field}`)?.focus()
- return field
- }
- current = next
+ const apply = (field: Field): boolean => {
+ if (field === 'citation' && isBlank(drafts[field])) {
+ return edit.reject(field, 'editor.field.required')
}
- return null
+ return update(field, patched(applied.current, field, drafts[field]))
}
+ const pending = (field: Field) =>
+ normalized(field, drafts[field]) !== committedOf(applied.current)[field]
+ return { edit, applied, typed, update, apply, pending }
+}
+
+/** The view's three effects: its guard, the focus ticket and the dropped-draft slot. */
+function useEditLifecycle(
+ base: string,
+ hooks: EditHooks,
+ leave: LeaveGuard,
+ writer: Pick, 'applied' | 'typed'>,
+) {
+ const { registerLeave, takeFocus, dropped } = hooks
+ const { applied, typed } = writer
useEffect(() => {
registerLeave(leave)
return () => registerLeave(null)
})
useEffect(() => {
- document.getElementById(`${base}-citation`)?.focus()
- }, [base])
+ if (takeFocus()) document.getElementById(`${base}-citation`)?.focus()
+ }, [base, takeFocus])
+ useLayoutEffect(
+ () => () => {
+ dropped.current = pendingField(applied.current, typed.current)
+ },
+ [applied, typed, dropped],
+ )
+}
+
+/**
+ * The write path of one reference's edit view. A field applies to the draft when it
+ * loses the focus (`commitField`); `leave` re-applies every field whose text differs from
+ * the document, stops at the first refusal, shows it and focuses that field (P22, P22').
+ * `base` is the DOM id prefix of the tile; `registerLeave` hands `leave` to the library.
+ * `takeFocus` says whether this mount is a user's « Modifier » (it focuses Citation) and
+ * `dropped` receives the field of a refused draft the view is unmounted with (M1).
+ */
+export function useReferenceEdit(
+ reference: Reference,
+ base: string,
+ hooks: EditHooks,
+) {
+ const [drafts, setDraft] = useDrafts(reference)
+ const writer = useWriter(reference, drafts)
+ const { edit, applied, apply, pending } = writer
+ const leave: LeaveGuard = () => {
+ for (const field of FIELDS.filter(pending)) {
+ if (apply(field)) continue
+ document.getElementById(`${base}-${field}`)?.focus()
+ return field
+ }
+ return null
+ }
+ useEditLifecycle(base, hooks, leave, writer)
return {
edit,
drafts,
setDraft,
- commitField: (field: Field) =>
- pending(reference, field) && apply(reference, field),
- setType: (value: Reference) => update('type', value),
+ commitField: (field: Field) => pending(field) && apply(field),
+ setType: (type: ReferenceType) =>
+ writer.update('type', { ...applied.current, type }),
}
}
+
+/**
+ * A read-only flip unmounts the edit view of the tile in edit: a refused draft it held
+ * (left in `dropped` by the view) is lost, so the live region says which field (M1).
+ */
+export function useDropNote(
+ readOnly: boolean,
+ dropped: RefObject,
+) {
+ const t = useT()
+ const announce = useContext(AnnounceContext)
+ useEffect(() => {
+ if (!readOnly || dropped.current === null) return
+ const field = t(`editor.reference.${dropped.current}`)
+ dropped.current = null
+ announce(
+ t('editor.references.draft_dropped').replace('{field}', () => field),
+ )
+ }, [readOnly, dropped, t, announce])
+}
diff --git a/apps/app/src/components/editor/references/useReferenceLibrary.ts b/apps/app/src/components/editor/references/useReferenceLibrary.ts
index 176b75a2..5be5134f 100644
--- a/apps/app/src/components/editor/references/useReferenceLibrary.ts
+++ b/apps/app/src/components/editor/references/useReferenceLibrary.ts
@@ -20,8 +20,12 @@ export function useReferenceLibrary(readOnly: boolean, resetSignal: number) {
const keys = tileKeys(all)
const tiles = useTileState(doc ? keys : null)
const citers = doc ? citersOf(doc) : NO_CITERS
- const editedAt = readOnly ? -1 : keys.indexOf(tiles.editingKey ?? '')
- const shown = useReferenceView(all, citers, editedAt, resetSignal)
+ const shown = useReferenceView(
+ { all, keys, citers },
+ tiles.editingKey,
+ readOnly,
+ resetSignal,
+ )
return { loaded: doc !== null, all, keys, tiles, citers, shown }
}
export type ReferenceLibraryState = ReturnType
@@ -85,13 +89,15 @@ export function useReferenceActions(
shown.reset()
setDraft((serial) => (serial ?? 0) + 1)
},
+ // P24: the new tile is shown whatever was typed meanwhile, so the view is reset.
added: (id: string) => {
setDraft(null)
+ shown.reset()
tiles.reveal(`${id}#0`)
later({ kind: 'reference', id })
},
edit: (position: number) => {
- if (tiles.startEdit(keys[position])) shown.markEdited(position)
+ if (tiles.startEdit(keys[position])) shown.markEdited(keys[position])
},
}
}
diff --git a/apps/app/src/components/editor/references/useReferenceView.ts b/apps/app/src/components/editor/references/useReferenceView.ts
index 8ee733c9..ca52ffd5 100644
--- a/apps/app/src/components/editor/references/useReferenceView.ts
+++ b/apps/app/src/components/editor/references/useReferenceView.ts
@@ -11,30 +11,48 @@ import { useLocaleStore } from '@/state/localeStore'
const INITIAL: ReferenceView = { query: '', sort: 'sheet' }
+/** The tile kept in the shown set, by key, and the index it is shown at (P23). */
+interface Pinned {
+ key: string
+ index: number
+}
+
+/** The bibliography the view reads: references, one tile key per position, citers. */
+interface Shown {
+ all: readonly Reference[]
+ keys: readonly string[]
+ citers: ReadonlyMap
+}
+
/**
* The search, the sort and the resulting tile order of the Références tab. All three are
* display state: nothing here reaches the document (BDR-114). `resetSignal` (« Tout
* afficher ») empties the search and the sort once per bump; the tab stays mounted (A2).
- * `editedAt` is the position of the tile in edit: while the view is not the sheet view it
- * keeps the index it had when the view last changed (P23).
+ * The tile that entered edit is pinned at the index it was shown at, whatever the search
+ * or the sort, and stays pinned after « Terminer » until the next search or sort change,
+ * so the tile the user just edited never vanishes under their focus (P23, I1). While
+ * read-only the pin is suspended and its index kept (M3). `editingKey` is the tile in
+ * edit, if any.
*/
export function useReferenceView(
- all: readonly Reference[],
- citers: ReadonlyMap,
- editedAt: number,
+ { all, keys, citers }: Shown,
+ editingKey: string | null,
+ readOnly: boolean,
resetSignal: number,
) {
const locale = useLocaleStore((state) => state.locale)
const [view, setView] = useState(INITIAL)
const [seen, setSeen] = useState(resetSignal)
- const [pinIndex, setPinIndex] = useState(0)
+ const [pinned, setPinned] = useState(null)
if (seen !== resetSignal) {
setSeen(resetSignal)
setView(INITIAL)
+ setPinned(null)
}
+ const pinAt = pinned === null ? -1 : keys.indexOf(pinned.key)
const pin =
- editedAt >= 0 && !isSheetView(view)
- ? { position: editedAt, index: pinIndex }
+ !readOnly && pinned !== null && pinAt >= 0 && !isSheetView(view)
+ ? { position: pinAt, index: pinned.index }
: null
const context = {
locale,
@@ -43,17 +61,28 @@ export function useReferenceView(
const positions = shownPositions(all, view, context, pin)
// The count is the matches: a pinned tile the search misses is shown, not counted.
const matchCount = all.filter((r) => referenceMatches(r, view.query)).length
+ const pinAtShown = (key: string) =>
+ Math.max(0, positions.indexOf(keys.indexOf(key)))
+ // A new search or sort: the tile in edit stays where it is shown, any other pin ends.
+ const pinAfterChange = (): Pinned | null => {
+ if (pinned === null || pinned.key !== editingKey) return null
+ return readOnly
+ ? pinned
+ : { key: pinned.key, index: pinAtShown(pinned.key) }
+ }
return {
view,
positions,
matchCount,
- /** A new search or sort: the tile in edit stays where it is shown now. */
update: (patch: Partial) => {
- setPinIndex(positions.indexOf(editedAt))
+ setPinned(pinAfterChange())
setView((current) => ({ ...current, ...patch }))
},
- reset: () => setView(INITIAL),
- /** The tile at `position` enters edit: remember where it is shown. */
- markEdited: (position: number) => setPinIndex(positions.indexOf(position)),
+ reset: () => {
+ setView(INITIAL)
+ setPinned(null)
+ },
+ /** The tile `key` enters edit: remember where it is shown. */
+ markEdited: (key: string) => setPinned({ key, index: pinAtShown(key) }),
}
}
diff --git a/apps/app/src/components/editor/references/useTileState.ts b/apps/app/src/components/editor/references/useTileState.ts
index 12acf1ec..5ddb0c63 100644
--- a/apps/app/src/components/editor/references/useTileState.ts
+++ b/apps/app/src/components/editor/references/useTileState.ts
@@ -32,6 +32,9 @@ export function useTileState(keys: readonly string[] | null) {
if (editingKey !== null && !live.has(editingKey)) setEditingKey(null)
}
const guard = useRef(null)
+ // The tile a « Modifier » just opened: its edit view focuses Citation once, a remount
+ // after a read-only interval does not (M1).
+ const focusTicket = useRef(null)
/** Applies the tile in edit; the field that refused, null when nothing is left to apply. */
const leave = (): Field | null => guard.current?.() ?? null
const open = (key: string) => setOpenKeys((prev) => new Set(prev).add(key))
@@ -51,10 +54,16 @@ export function useTileState(keys: readonly string[] | null) {
const startEdit = (key: string) => {
if (editingKey !== null && editingKey !== key && leave() !== null)
return false
+ focusTicket.current = key
setEditingKey(key)
open(key)
return true
}
+ const takeFocus = (key: string) => {
+ const mine = focusTicket.current === key
+ if (mine) focusTicket.current = null
+ return mine
+ }
return {
openKeys,
editingKey,
@@ -62,6 +71,7 @@ export function useTileState(keys: readonly string[] | null) {
startEdit,
finish,
leave,
+ takeFocus,
reveal: open,
registerLeave: (next: LeaveGuard | null) => {
guard.current = next
diff --git a/apps/app/src/editor/focusRequest.ts b/apps/app/src/editor/focusRequest.ts
index 368779d9..41ef7d36 100644
--- a/apps/app/src/editor/focusRequest.ts
+++ b/apps/app/src/editor/focusRequest.ts
@@ -97,7 +97,7 @@ export function focusRow(key: ElementKey): boolean {
return true
}
-/** Row-based places (Général, Vues, Catégories, Régions, Références): focus the named row. */
+/** Row-based places (Général, Vues, Catégories, Régions): focus the named row. */
export function useRowFocus(focus: FocusRequest | undefined): void {
useFocusRequest(focus, (target) =>
target.key && focusRow(target.key) ? 'found' : 'none',
diff --git a/apps/app/src/editor/useEditorNavigation.ts b/apps/app/src/editor/useEditorNavigation.ts
index f06ba529..9c0e4486 100644
--- a/apps/app/src/editor/useEditorNavigation.ts
+++ b/apps/app/src/editor/useEditorNavigation.ts
@@ -62,14 +62,15 @@ export interface EditorNavigation {
/** The polite live region's text; a repeat alternates a trailing no-break space. */
live: string
navigate: (target: EditorTarget) => void
- selectTab: (tab: EditorTabId) => void
+ /** False when the open panel refused the tab change (a refused field keeps the page). */
+ selectTab: (tab: EditorTabId) => boolean
openSection: (section: AnnotationSection, opener?: Opener) => void
backToDrawing: () => void
/** Opens the citations panel of a finding node; any other key is ignored. */
openCitations: (citedBy: ElementKey, opener?: Opener) => void
/** A user close (✕, Escape, scrim): the panel exits, then the focus goes to P6's fallbacks. */
closeCitations: () => void
- /** The finding vanished: the same close, never refused (a refused draft is dropped, said aloud). */
+ /** The finding vanished: the same close, never refused (a refused draft is dropped, said). */
dropCitations: () => void
/** « Tout afficher dans l'onglet Références »: panel closed, tab shown, library reset. */
showAllReferences: () => void
@@ -199,20 +200,24 @@ interface PanelContext {
/**
* Records a close of the panel. A user close asks the panel first (P22''): a refused
- * draft cancels it. While an exit is playing, a close is a no-op (a tab choice replaces
- * the pending move) and asks nothing: the draft was settled by the first close.
+ * draft cancels it (false). While an exit is playing, a close is a no-op (a tab choice
+ * replaces the pending move) and asks nothing: the draft was settled by the first close.
*/
function useRequestClose(ctx: PanelContext) {
const { open, exit, canLeave } = ctx
const { busy, record } = exit
return useCallback(
- (move: PendingClose, forced: boolean) => {
- if (!open) return
- if (busy()) return record(move)
+ (move: PendingClose, forced: boolean): boolean => {
+ if (!open) return true
+ if (busy()) {
+ record(move)
+ return true
+ }
commitFocusedField()
const { allowed, note } = canLeave.current?.(forced) ?? { allowed: true }
- if (!allowed) return
+ if (!allowed) return false
record(note ? { ...move, note } : move)
+ return true
},
[open, busy, record, canLeave],
)
@@ -228,14 +233,14 @@ function useOpenCitations(ctx: PanelContext) {
commitFocusedField()
openers.citations.current = opener ?? null
openers.citedBy.current = citedBy
- announce(t('editor.place.references'))
+ announce(t('editor.references.panel_title'))
dispatch({ type: 'open_citations', citedBy })
},
[openers, dispatch, announce, t],
)
}
-/** The closes of the panel: ✕ / Escape / scrim, the vanished finding, « Tout afficher », « Aller à ». */
+/** The panel's closes: ✕ / Escape / scrim, the vanished finding, « Tout afficher », « Aller à ». */
function useCloseMoves(ctx: PanelContext) {
const t = useT()
const moveText = useMoveText()
@@ -373,7 +378,7 @@ function useTabSelect(
) {
const t = useT()
return useCallback(
- (tab: EditorTabId) => {
+ (tab: EditorTabId): boolean => {
const action = { type: 'select_tab', tab } as const
if (open) {
const text = t(`editor.tab.${tab}`)
@@ -381,6 +386,7 @@ function useTabSelect(
}
commitFocusedField()
dispatch(action)
+ return true
},
[request, dispatch, open, t],
)
diff --git a/apps/app/tests/unit/editor-references-panel.test.tsx b/apps/app/tests/unit/editor-references-panel.test.tsx
index b2b8077c..996ce77a 100644
--- a/apps/app/tests/unit/editor-references-panel.test.tsx
+++ b/apps/app/tests/unit/editor-references-panel.test.tsx
@@ -9,6 +9,7 @@ import {
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import type { ElementKey } from '@faunosteo/core-wasm/types'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
import {
@@ -205,7 +206,7 @@ describe('opening', () => {
const tile = tiles()[0] as HTMLElement
expect(within(tile).getByText('ce constat')).toBeInTheDocument()
expect(
- within(tile).getAllByRole('button', { name: 'Aller à' }),
+ within(tile).getAllByRole('button', { name: /^Aller à / }),
).toHaveLength(2)
expect(within(tile).getByRole('button', { name: 'Modifier' })).toBeVisible()
expect(
@@ -358,7 +359,7 @@ describe.each(MODES)('closing, %s', (_label, reduced) => {
const user = await mount()
await openFromFinding(user)
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
- const go = within(panel()).getAllByRole('button', { name: 'Aller à' })
+ const go = within(panel()).getAllByRole('button', { name: /^Aller à / })
await user.click(go[0])
await closed()
await focusIs(() => screen.getByRole('treeitem', { name: /Cat A/ }))
@@ -705,3 +706,149 @@ describe("a tile in edit when the panel closes (P22'')", () => {
expect(doc().references[0].citation).toBe('Barone, Ostéologie')
})
})
+
+const live = () => document.querySelector('p.sr-only[aria-live="polite"]')
+const entries = () => store.getState().undo.length
+const undo = () => act(() => store.getState().undoStep())
+const nodeKey: ElementKey = {
+ kind: 'finding',
+ zone_id: 'zone-a',
+ path: ['fcat-a', 'fnode-a'],
+}
+
+/** The finding node cites `ids` from now on (one history entry). */
+function cite(ids: string[]) {
+ act(() => {
+ store.getState().commit({
+ op: 'update',
+ key: nodeKey,
+ element: {
+ kind: 'finding_node',
+ value: {
+ ...doc().finding_zones[0].categories[0].children[0],
+ reference_ids: ids,
+ },
+ },
+ })
+ })
+}
+
+describe('one user edit, one history entry in the panel (C1)', () => {
+ /** Opens Barone, enters edit and types a URL; the field keeps the focus. */
+ async function typeUrl(user: User) {
+ await openFromFinding(user)
+ await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
+ await user.click(within(panel()).getByRole('button', { name: 'Modifier' }))
+ const url = panel().querySelector(
+ '#panel-reference-0-ref-a-url',
+ )!
+ await user.type(url, 'https://a.org/')
+ expect(document.activeElement).toBe(url)
+ return entries()
+ }
+
+ it('✕ pressed with the field still focused (iPadOS) adds one entry', async () => {
+ const user = await mount()
+ const before = await typeUrl(user)
+ fireEvent.click(closeButton())
+ await closed()
+ expect(entries() - before).toBe(1)
+ expect(doc().references[0].url).toBe('https://a.org/')
+ undo()
+ expect(doc().references[0].url).toBeNull()
+ })
+
+ it('a tab switch with the field still focused adds one entry', async () => {
+ const user = await mount()
+ const before = await typeUrl(user)
+ fireEvent.click(screen.getByRole('tab', { name: 'Vérification' }))
+ await closed()
+ expect(entries() - before).toBe(1)
+ undo()
+ expect(doc().references[0].url).toBeNull()
+ })
+
+ it('a forced close (finding vanished) adds the edit once, besides the removal', async () => {
+ const user = await mount()
+ const before = await typeUrl(user)
+ act(() => {
+ store.getState().commit({ op: 'remove', key: nodeKey })
+ })
+ await closed()
+ expect(entries() - before).toBe(2)
+ expect(doc().references[0].url).toBe('https://a.org/')
+ })
+})
+
+describe('the panel review fixes', () => {
+ it('opening announces the panel title, not the tab name (M4)', async () => {
+ const user = await mount()
+ await openFromFinding(user)
+ expect(live()?.textContent?.trim()).toBe('Références citées')
+ })
+
+ it('every « Aller à » names its citer (M6)', async () => {
+ const user = await mount()
+ await openFromFinding(user)
+ await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
+ const names = within(panel())
+ .getAllByRole('button', { name: /^Aller à / })
+ .map((button) => button.getAttribute('aria-label'))
+ expect(new Set(names).size).toBe(names.length)
+ expect(names).toEqual([
+ 'Aller à Zone A › Cat A',
+ 'Aller à Zone A › Cat A › Node A',
+ ])
+ })
+
+ it('an undo that removes the focused tile moves the focus to the next one (M8)', async () => {
+ const user = await mount(1280, nodeText(['ref-c']))
+ cite(['ref-a', 'ref-c'])
+ await openFromFinding(user)
+ await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
+ expect(document.activeElement).toBe(tiles()[0].querySelector('button'))
+ undo()
+ expect(tiles()).toHaveLength(1)
+ await focusIs(() => tiles()[0].querySelector('button')!)
+ expect(tiles()[0]).toHaveTextContent('Code rural')
+ })
+
+ it('an undo that removes the last focused tile moves the focus to the previous one (M8)', async () => {
+ const user = await mount(1280, nodeText(['ref-a']))
+ cite(['ref-a', 'ref-c'])
+ await openFromFinding(user)
+ await user.click(
+ within(panel()).getByRole('button', { name: /^Code rural/ }),
+ )
+ undo()
+ expect(tiles()).toHaveLength(1)
+ await focusIs(() => tiles()[0].querySelector('button')!)
+ expect(tiles()[0]).toHaveTextContent('Barone')
+ })
+
+ it('an undo that removes the only tile puts the focus on the heading (M8)', async () => {
+ const user = await mount(1280, nodeText([]))
+ cite(['ref-a'])
+ await openFromFinding(user, '1 référence')
+ await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
+ undo()
+ expect(tiles()).toHaveLength(0)
+ await focusIs(heading)
+ })
+
+ it('an arrow key in the tab row leaves the focus on the refused field (M2)', async () => {
+ const user = await mount()
+ await openFromFinding(user)
+ await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
+ await user.click(within(panel()).getByRole('button', { name: 'Modifier' }))
+ const field = panel().querySelector(
+ '#panel-reference-0-ref-a-citation',
+ )!
+ await user.clear(field)
+ const tab = screen.getByRole('tab', { name: 'Constats' })
+ fireEvent.keyDown(tab, { key: 'ArrowRight' })
+ expect(hasPanel()).toBe(true)
+ expect(document.activeElement).toBe(field)
+ expect(tab).toHaveAttribute('aria-selected', 'true')
+ })
+})
diff --git a/apps/app/tests/unit/editor-references-tab.test.tsx b/apps/app/tests/unit/editor-references-tab.test.tsx
index 21d54ef2..b5eb5dc4 100644
--- a/apps/app/tests/unit/editor-references-tab.test.tsx
+++ b/apps/app/tests/unit/editor-references-tab.test.tsx
@@ -1,6 +1,7 @@
/** R2.1 and R2.2: the Références tab, the library (search, order, counts, add, « Aller à »). */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
+ act,
cleanup,
fireEvent,
render,
@@ -412,7 +413,7 @@ describe('an open tile', () => {
await user.click(header('Barone'))
const open = within(tile('Barone'))
expect(open.getByText('Citée 2 fois, par :')).toBeInTheDocument()
- expect(open.getAllByRole('button', { name: 'Aller à' })).toHaveLength(2)
+ expect(open.getAllByRole('button', { name: /^Aller à / })).toHaveLength(2)
expect(open.getAllByText('famille')).toHaveLength(1)
expect(open.getByText(/Zone A › Cat A ›/)).toBeInTheDocument()
})
@@ -442,7 +443,7 @@ describe('an open tile', () => {
const user = await mount()
await user.click(header('Barone'))
const [family] = within(tile('Barone')).getAllByRole('button', {
- name: 'Aller à',
+ name: /^Aller à /,
})
await user.click(family)
expect(screen.getByRole('tab', { name: 'Constats' })).toHaveAttribute(
@@ -473,7 +474,7 @@ describe('a tile in edit', () => {
expect(view.getByText('Modifier la référence')).toBeInTheDocument()
expect(document.activeElement).toBe(view.getByLabelText('Citation'))
expect(view.getByText('Citée 2 fois, par :')).toBeInTheDocument()
- expect(view.getAllByRole('button', { name: 'Aller à' })).toHaveLength(2)
+ expect(view.getAllByRole('button', { name: /^Aller à / })).toHaveLength(2)
for (const name of ['Modifier', 'Supprimer', 'Monter', 'Descendre']) {
expect(view.queryByRole('button', { name })).toBeNull()
}
@@ -546,9 +547,11 @@ describe('a tile in edit', () => {
const user = await mount()
const item = await startEdit(user, 'Barone')
const view = within(item)
+ const before = store.getState().undo.length
await user.type(view.getByLabelText('DOI'), '10.1000/xyz')
await user.type(view.getByLabelText('Adresse web (URL)'), 'https://a.org/')
await user.click(view.getByRole('button', { name: 'Terminer' }))
+ expect(store.getState().undo.length - before).toBe(2)
expect(doc().references[0]).toMatchObject({
doi: '10.1000/xyz',
url: 'https://a.org/',
@@ -586,13 +589,82 @@ describe('a tile in edit', () => {
})
})
+describe('the disclosure button in edit (M7)', () => {
+ it('is named for what it does, and pressing it ends the edit', async () => {
+ const user = await mount()
+ const item = await startEdit(user, 'Barone')
+ const button = within(item).getByRole('button', {
+ name: /^Terminer\. Modifier la référence/,
+ })
+ expect(button).toHaveAttribute('aria-expanded', 'true')
+ await user.click(button)
+ expect(within(item).queryByLabelText('Citation')).toBeNull()
+ })
+})
+
+describe('one user edit, one history entry (C1)', () => {
+ const entries = () => store.getState().undo.length
+ const undo = () => act(() => store.getState().undoStep())
+
+ it('« Terminer » after one typed field adds one entry, the first « Défaire » undoes it', async () => {
+ const user = await mount()
+ const view = within(await startEdit(user, 'Barone'))
+ const before = entries()
+ await user.type(view.getByLabelText('Adresse web (URL)'), 'https://a.org/')
+ await user.click(view.getByRole('button', { name: 'Terminer' }))
+ expect(entries() - before).toBe(1)
+ expect(doc().references[0].url).toBe('https://a.org/')
+ undo()
+ expect(doc().references[0].url).toBeNull()
+ })
+
+ it('« Terminer » pressed with the field still focused (no pointer) adds one entry', async () => {
+ const user = await mount()
+ const view = within(await startEdit(user, 'Barone'))
+ const before = entries()
+ const url = view.getByLabelText('Adresse web (URL)')
+ await user.type(url, 'https://a.org/')
+ expect(document.activeElement).toBe(url)
+ fireEvent.click(view.getByRole('button', { name: 'Terminer' }))
+ expect(entries() - before).toBe(1)
+ undo()
+ expect(doc().references[0].url).toBeNull()
+ })
+
+ it('a tab switch with the field still focused adds one entry', async () => {
+ const user = await mount()
+ const view = within(await startEdit(user, 'Barone'))
+ const before = entries()
+ await user.type(view.getByLabelText('Adresse web (URL)'), 'https://a.org/')
+ fireEvent.click(screen.getByRole('tab', { name: 'Constats' }))
+ expect(entries() - before).toBe(1)
+ undo()
+ expect(doc().references[0].url).toBeNull()
+ })
+
+ it('a blur after the field was applied adds nothing; a changed text adds one more', async () => {
+ const user = await mount()
+ const view = within(await startEdit(user, 'Barone'))
+ const before = entries()
+ const url = view.getByLabelText('Adresse web (URL)')
+ await user.type(url, 'https://a.org/')
+ await user.tab()
+ await user.click(url)
+ await user.tab()
+ expect(entries() - before).toBe(1)
+ await user.type(url, 'x')
+ await user.tab()
+ expect(entries() - before).toBe(2)
+ })
+})
+
describe('read-only tiles', () => {
it('keep DOI, URL and « Aller à », and offer no edit control', async () => {
const user = await mount(800)
await user.click(header('Barone'))
await user.click(header('Denoix'))
const cited = within(tile('Barone'))
- expect(cited.getAllByRole('button', { name: 'Aller à' })).toHaveLength(2)
+ expect(cited.getAllByRole('button', { name: /^Aller à / })).toHaveLength(2)
expect(
within(tile('Denoix')).getByRole('link', { name: /exemple\.org/ }),
).toBeInTheDocument()
diff --git a/apps/app/tests/unit/editor-references-view.test.tsx b/apps/app/tests/unit/editor-references-view.test.tsx
index 6833fb36..e09817bd 100644
--- a/apps/app/tests/unit/editor-references-view.test.tsx
+++ b/apps/app/tests/unit/editor-references-view.test.tsx
@@ -4,6 +4,7 @@ import { act, cleanup, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { ReferenceType } from '@faunosteo/core-wasm/types'
import ReferencesTab from '@/components/editor/tabs/ReferencesTab'
+import { AnnounceContext } from '@/editor/focusRequest'
import { targetOfKey } from '@/editor/navigation'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
@@ -208,6 +209,22 @@ describe('clearing the search', () => {
expect(order()).toHaveLength(5)
})
+ it('is announced once: the count line is the live region, the notice is not (M11)', async () => {
+ const { user } = await mount()
+ await user.type(search(), 'radiographie')
+ const live = document.querySelectorAll('[aria-live], [role="status"]')
+ expect(live).toHaveLength(1)
+ expect(live[0]).toHaveTextContent('0 référence sur 5')
+ })
+
+ it('writes the typed text as it is, `$&` and friends included (M5)', async () => {
+ const { user } = await mount()
+ await user.type(search(), "$& $` $'")
+ expect(screen.getByTestId('editor-references-no-result')).toHaveTextContent(
+ "Aucune référence ne contient « $& $` $' ».",
+ )
+ })
+
it('Escape empties a non-empty search and stops there (P12)', async () => {
const { user } = await mount()
const bubbled = vi.fn()
@@ -229,9 +246,7 @@ describe('no result (board 24 B)', () => {
const { user } = await mount()
await user.type(search(), 'radiographie')
expect(order()).toEqual([])
- const notice = screen.getByRole('status', {
- name: '',
- })
+ const notice = screen.getByTestId('editor-references-no-result')
expect(notice).toHaveTextContent(
"Aucune référence ne contient « radiographie ». La recherche porte sur la citation, le DOI et l'URL.",
)
@@ -315,16 +330,43 @@ describe('the tile in edit is pinned (P23)', () => {
expect(order()).toEqual(['r5', 'r4', 'r3', 'r2', 'r1'])
})
- it('stays shown under a search that does not match it, until it leaves edit', async () => {
+ it('stays shown under a search that does not match it, also after « Terminer », until the next search change (I1)', async () => {
const { user } = await mount()
const item = await startEdit(user, 'r1')
await user.type(search(), 'alpha')
expect(order()).toEqual(['r1', 'r5'])
expect(within(item).getByLabelText('Citation')).toBeInTheDocument()
await user.click(within(item).getByRole('button', { name: 'Terminer' }))
+ expect(order()).toEqual(['r1', 'r5'])
+ expect(document.activeElement).toBe(header('r1'))
+ await user.clear(search())
+ await user.type(search(), 'alpha')
expect(order()).toEqual(['r5'])
})
+ it('keeps the tile shown and focused when its edit stops matching the search (I1)', async () => {
+ const { user } = await mount()
+ await user.type(search(), 'zèbre')
+ const item = await startEdit(user, 'r1')
+ const citation = within(item).getByLabelText('Citation')
+ await user.clear(citation)
+ await user.type(citation, 'Autre titre')
+ await user.click(within(item).getByRole('button', { name: 'Terminer' }))
+ expect(order()).toEqual(['r1', 'r2'])
+ expect(document.activeElement).toBe(header('r1'))
+ })
+
+ it('keeps its index across a search or sort change made while read-only (M3)', async () => {
+ const { user, view } = await mount()
+ await user.selectOptions(sortBox(), 'citation')
+ await startEdit(user, 'r3')
+ expect(order()).toEqual(['r5', 'r3', 'r4', 'r2', 'r1'])
+ view.rerender(lib(true))
+ await user.selectOptions(sortBox(), 'count')
+ view.rerender(lib(false))
+ expect(order()).toEqual(['r2', 'r3', 'r1', 'r5', 'r4'])
+ })
+
it('is suspended in read-only: the tile renders its read view', async () => {
const { user, view } = await mount()
await startEdit(user, 'r1')
@@ -384,6 +426,22 @@ describe('adding (P24)', () => {
).toBeInTheDocument()
})
+ it('a search typed after « Ajouter une référence » is cleared by the add, the new tile takes the focus (I1)', async () => {
+ const { user } = await mount()
+ await user.click(add())
+ await user.selectOptions(screen.getByLabelText('Type'), 'book')
+ await user.type(draftCitation()!, 'Nouvelle source')
+ await user.type(search(), 'alpha')
+ expect(order()).toEqual(['r5'])
+ await user.click(
+ screen.getByRole('button', { name: 'Ajouter la référence' }),
+ )
+ const id = doc().references[5].id
+ expect(search()).toHaveValue('')
+ expect(order()).toHaveLength(6)
+ expect(document.activeElement).toBe(header(id))
+ })
+
it('a second click on the button takes the focus back to the citation', async () => {
const { user } = await mount()
await user.click(add())
@@ -492,3 +550,53 @@ describe('state of a reference that left the document (P23-prime)', () => {
).toBeNull()
})
})
+
+describe('a read-only flip with a tile in edit (M1)', () => {
+ const ui = (announce: (text: string) => void, readOnly: boolean) => (
+ {lib(readOnly)}
+ )
+
+ async function refusedUrl() {
+ await openReady({ text: sortText() })
+ const user = userEvent.setup()
+ const announce = vi.fn()
+ const view = render(ui(announce, false))
+ const item = await startEdit(user, 'r1')
+ await user.type(
+ within(item).getByLabelText('Adresse web (URL)'),
+ 'exemple.org',
+ )
+ await user.tab()
+ return { view, announce, item, user }
+ }
+
+ it('says which refused draft is dropped, once', async () => {
+ const { view, announce } = await refusedUrl()
+ view.rerender(ui(announce, true))
+ expect(announce).toHaveBeenCalledTimes(1)
+ expect(announce).toHaveBeenCalledWith(
+ 'Saisie non appliquée : Adresse web (URL)',
+ )
+ view.rerender(ui(announce, false))
+ expect(announce).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not move the focus to Citation when editing is possible again', async () => {
+ const { view, announce } = await refusedUrl()
+ view.rerender(ui(announce, true))
+ view.rerender(ui(announce, false))
+ const citation = screen.getByLabelText('Citation')
+ expect(document.activeElement).not.toBe(citation)
+ expect(screen.getByLabelText('Adresse web (URL)')).toHaveValue('')
+ })
+
+ it('says nothing when no draft is lost', async () => {
+ await openReady({ text: sortText() })
+ const user = userEvent.setup()
+ const announce = vi.fn()
+ const view = render(ui(announce, false))
+ await startEdit(user, 'r1')
+ view.rerender(ui(announce, true))
+ expect(announce).not.toHaveBeenCalled()
+ })
+})
diff --git a/docs/development/V1-2-6_R2_LABELS.md b/docs/development/V1-2-6_R2_LABELS.md
index 08397837..b43cbf87 100644
--- a/docs/development/V1-2-6_R2_LABELS.md
+++ b/docs/development/V1-2-6_R2_LABELS.md
@@ -18,15 +18,15 @@ Règles de lecture :
| Clé | FR | EN (provisoire) | Où | Statut | Notes |
|---|---|---|---|---|---|
| `editor.tab.references` | Références | References | Rangée d'onglets de l'éditeur (sous « Plus » sous 640 px), titre de l'onglet, annonce de navigation | nouveau | |
-| `editor.references.panel_title` | Références citées | Cited references | Panneau des citations, en-tête | nouveau | |
+| `editor.references.panel_title` | Références citées | Cited references | Panneau des citations, en-tête et annonce à l'ouverture (la région live dit « Références citées », non le nom de l'onglet) | nouveau | |
| `editor.references.panel_count_one` | {count} référence citée par ce constat | {count} reference cited by this finding | Panneau des citations, ligne de décompte | nouveau | |
| `editor.references.panel_count_other` | {count} références citées par ce constat | {count} references cited by this finding | Panneau des citations, ligne de décompte | nouveau | |
| `editor.references.panel_show_all` | Tout afficher dans l'onglet Références | Show all in the References tab | Panneau des citations, bouton de bas de liste | nouveau | Ferme le panneau, ouvre l'onglet, remet recherche et tri à zéro. |
| `editor.references.panel_empty` | Ce constat ne cite plus aucune référence. | This finding no longer cites any reference. | Panneau des citations, état à zéro | nouveau ; provisoire, accepté 2026-11-12 | Libellé provisoire, accepté 2026-11-12. |
| `editor.references.remove_citation` | Retirer de ce constat | Remove from this finding | Panneau des citations, tuile (action) | nouveau | Voir ambiguïté 2 : « Retirer » ailleurs. |
-| `editor.references.this_finding` | ce constat | this finding | Onglet Références, tuile ouverte, liste des citants | nouveau | Désigne le constat qui est lui-même le citant. |
+| `editor.references.this_finding` | ce constat | this finding | Panneau des citations, tuile ouverte, liste des citants (seul le panneau connaît le constat courant) | nouveau | Désigne le constat qui est lui-même le citant ; l'onglet Références ne l'affiche jamais. |
| `editor.references.missing` | Référence introuvable | Reference not found | Panneau des citations, ligne d'un identifiant sans référence | nouveau ; provisoire, accepté 2026-11-12 | Libellé provisoire, accepté 2026-11-12. |
-| `editor.references.draft_dropped` | Saisie non appliquée : {field} | Entry not applied: {field} | Annonce (région live) quand le panneau est fermé de force et qu'une saisie refusée est abandonnée | nouveau ; provisoire, accepté 2026-11-12 | Libellé provisoire, accepté 2026-11-12. {field} est le libellé du champ refusé (Type, Citation, DOI ou Adresse web (URL)). Voir ambiguïté 5. |
+| `editor.references.draft_dropped` | Saisie non appliquée : {field} | Entry not applied: {field} | Annonce (région live) quand une saisie refusée est abandonnée : panneau fermé de force, ou passage en lecture seule (largeur sous 1 024 px) avec une tuile en modification | nouveau ; provisoire, accepté 2026-11-12 | Libellé provisoire, accepté 2026-11-12. {field} est le libellé du champ refusé (Citation, DOI ou Adresse web (URL) ; Type n'en fait pas partie : un choix de liste s'applique aussitôt). Voir ambiguïté 5. |
| `editor.references.cited_one` | Citée {count} fois | Cited {count} time | Onglet Références et panneau, en-tête de tuile | modifié : « citée {count} fois » → « Citée {count} fois » (EN : « cited {count} time » → « Cited {count} time ») | Modifié : majuscule initiale. FR : « Citée 1 fois » (même forme pour 1 et plus). |
| `editor.references.cited_other` | Citée {count} fois | Cited {count} times | Onglet Références et panneau, en-tête de tuile | modifié : « citée {count} fois » → « Citée {count} fois » (EN : « cited {count} times » → « Cited {count} times ») | Modifié : majuscule initiale. |
| `editor.references.uncited` | Non citée | Not cited | Tuile, en-tête | nouveau | |
@@ -34,9 +34,9 @@ Règles de lecture :
| `editor.references.citers_other` | Citée {count} fois, par : | Cited {count} times, by: | Tuile ouverte, intitulé de la liste des citants | nouveau | |
| `editor.references.no_citers` | Aucun constat ni aucune famille ne cite cette référence. | No finding or family cites this reference. | Tuile ouverte, aucun citant | nouveau | |
| `editor.references.family` | famille | family | Tuile ouverte, pastille d'un citant famille | nouveau | Voir ambiguïté 1. |
-| `editor.references.go_to` | Aller à | Go to | Tuile ouverte, bouton sur un citant | nouveau | Vérification dit « Aller à {tab} » (autre clé). |
+| `editor.references.go_to` | Aller à | Go to | Tuile ouverte, bouton sur un citant | nouveau | Vérification dit « Aller à {tab} » (autre clé). Le nom accessible de chaque bouton est « Aller à » suivi du chemin du citant (« Aller à Zone › Famille › Constat »), pour que les boutons d'une liste se distinguent ; aucune clé ajoutée. |
| `editor.references.edit` | Modifier | Edit | Tuile ouverte et panneau, bouton | nouveau | |
-| `editor.references.done` | Terminer | Done | Tuile en modification, bouton | nouveau | Ferme la modification, sans bouton « Annuler » associé. Voir ambiguïté 3. |
+| `editor.references.done` | Terminer | Done | Tuile en modification, bouton | nouveau | Ferme la modification, sans bouton « Annuler » associé. Voir ambiguïté 3. Le bouton de dépliage de la tuile en modification ferme aussi la modification : son nom accessible est un « Terminer. » masqué (`sr-only`) suivi du titre visible et du décompte, par exemple « Terminer. Modifier la référence Citée 2 fois » ; aucune clé ajoutée. Voir ambiguïté 9. |
| `editor.references.edit_title` | Modifier la référence | Edit the reference | Tuile en modification, titre | nouveau | |
| `editor.references.url_label` | URL | URL | Tuile ouverte, ligne de faits | nouveau | |
| `editor.references.none_doi` | Aucun | None | Tuile ouverte, DOI absent | nouveau | Genre : « Aucun » (DOI masculin). |
@@ -56,7 +56,7 @@ Règles de lecture :
| `editor.references.count_of_one` | {count} référence sur {total} | {count} reference of {total} | Barre d'outils, décompte avec recherche | nouveau | |
| `editor.references.count_of_other` | {count} références sur {total} | {count} references of {total} | Barre d'outils, décompte avec recherche | nouveau | |
| `editor.references.reorder_hint` | Pour réorganiser, affichez l'ordre de la fiche sans recherche. | To reorder, show the sheet order without a search. | Onglet Références, sous la barre d'outils quand « Monter » et « Descendre » sont absents | nouveau | |
-| `editor.references.no_result` | Aucune référence ne contient « {q} ». | No reference contains “{q}”. | Onglet Références, état sans résultat | nouveau | {q} est le texte tapé, rogné. |
+| `editor.references.no_result` | Aucune référence ne contient « {q} ». | No reference contains “{q}”. | Onglet Références, état sans résultat | nouveau | {q} est le texte tapé, rogné, repris tel quel (`$&` reste littéral). L'état n'est pas une région live : la ligne de décompte annonce déjà « 0 référence sur N ». |
| `editor.references.no_result_scope` | La recherche porte sur la citation, le DOI et l'URL. | The search covers the citation, the DOI and the URL. | Onglet Références, état sans résultat | nouveau | |
## 2. Clés retirées
@@ -89,7 +89,7 @@ Aucune n'est lue par le code (recherche faite sur `src`, `tests` et `e2e`, `edit
4. Singulier contre pluriel du verbe « Citée ». FR : « Citée 1 fois » (pas de « Cité » au masculin, la
référence est féminine). EN : « Cited 1 time » contre « Cited 2 times ».
5. « Saisie non appliquée : {field} ». {field} est le libellé du champ dont la valeur refusée a été
- abandonnée : « Type », « Citation », « DOI » ou « Adresse web (URL) » (clés `editor.reference.*`,
+ abandonnée : « Citation », « DOI » ou « Adresse web (URL) » (clés `editor.reference.*`,
existantes). Les parenthèses de « Adresse web (URL) » se lisent mal dans la phrase.
6. « URL » seul. La ligne de faits d'une tuile ouverte dit « URL » (`editor.references.url_label`), le
formulaire dit « Adresse web (URL) » : deux formes pour un champ.
@@ -100,6 +100,11 @@ Aucune n'est lue par le code (recherche faite sur `src`, `tests` et `e2e`, `edit
(EN) contre « Terminer » (FR) : le verbe anglais est moins précis.
8. « Aucun » et « Aucune ». DOI absent : « Aucun » ; URL absente : « Aucune ». L'accord suit le genre, la
cohérence visuelle est faible.
+9. Nom accessible du bouton de dépliage en modification (WCAG 2.5.3, étiquette dans le nom). Le texte visible
+ (« Modifier la référence », puis le décompte) n'est pas au début du nom : « Terminer. » le précède, masqué. Il
+ y figure en entier, ce qu'axe accepte, mais un utilisateur de commande vocale qui dit le texte visible ne tombe pas
+ sur un nom qui commence par lui. Alternative écartée : un `aria-label` sans le décompte, refusé par axe
+ (`label-content-name-mismatch`).
## 4. Comportement visible en attente du propriétaire
diff --git a/docs/development/V1-2-6_U1_CORRECTIONS.md b/docs/development/V1-2-6_U1_CORRECTIONS.md
index 5b578427..54b495c2 100644
--- a/docs/development/V1-2-6_U1_CORRECTIONS.md
+++ b/docs/development/V1-2-6_U1_CORRECTIONS.md
@@ -186,7 +186,9 @@ Labels: `V1-2-6_R2_LABELS.md`. Decision record: BDR-114. What the build settled
- Selecting a tab closes the panel. Every close (✕, Escape outside a field, scrim, tab, « Aller à », « Tout
afficher », element gone) records one pending move applied after the exit: the focus goes back to the trigger,
else to the active tab button.
-- A read-only flip (window under 1 024 px) keeps the panel open, in its read view.
+- A read-only flip (window under 1 024 px) keeps the panel open, in its read view: implemented, pending owner
+ ratification (the contract's criterion 15 and P22'' still say the panel closes). A refused draft the flip drops is
+ announced (« Saisie non appliquée : … »).
- Motion goes through `motion/react` (slide in 180 ms, out 140 ms, none under reduced motion, callbacks still
fire), not through the Tailwind `motion-reduce:` text below: deviation approved by the owner, 2026-11-12.
- The Places area keeps a permanent `dvh` minimum height so that opening the panel never changes the document's