fix(editor): one history entry per reference edit, focus kept

Final review fixes. « Terminer » and every panel close re-committed the
edited field against a stale value, adding a second identical history
entry so the first « Défaire » seemed to do nothing: the tile now reads
the latest applied value (tests assert the undo-length delta). A tile
leaving the search on « Terminer » stays pinned until the next view
change and keeps focus; « Ajouter la référence » resets search and sort
and focuses the new tile. Also: refused draft dropped on a read-only
flip is announced; arrow keys respect a refused tab switch; pinned
index kept across read-only; the panel announces « Références citées »;
search text inserted literally; « Aller à » names its citer; the edit
header's name starts with « Terminer. »; undo removing the focused panel
tile moves focus per P20; no-result announced once; docs corrected.

Gates: typecheck, lint, test:run (app 1510), build, e2e:ui 251;
e2e:shell 16 specs (admin and editor-equine excluded): 117 passed / 108
skipped / 1 failed (crossing:211 stuck on the MFA step-up screen before
the editor), rerun alone 11 passed; full-row guard: no pre-existing row
changed in any table.
This commit is contained in:
bchanot committed 2026-11-13 01:08:00 +01:00
1 parent 2182307c62
commit 1bf27014b3
21 files changed
+677 -136

No files matched your search

+14 -6
View File
@@ -168,15 +168,24 @@ test.describe('reference tiles, edit mode', () => {
const url = tile.getByLabel(dict['editor.reference.url'])
await url.fill('exemple.org')
await tile
.getByRole('button', { name: dict['editor.references.done'] })
.getByRole('button', {
name: dict['editor.references.done'],
exact: true,
})
.click()
await expect(url).toBeFocused()
await expect(
tile.getByRole('button', { name: dict['editor.references.done'] }),
tile.getByRole('button', {
name: dict['editor.references.done'],
exact: true,
}),
).toBeVisible()
await url.fill('https://exemple.org/page')
await tile
.getByRole('button', { name: dict['editor.references.done'] })
.getByRole('button', {
name: dict['editor.references.done'],
exact: true,
})
.click()
await expect(tile.getByLabel(dict['editor.reference.url'])).toHaveCount(0)
await expect(
@@ -338,9 +347,8 @@ test.describe('reference tiles, search, sort and add', () => {
// No result, then the notice's own clear button.
await bar.search.fill('radiographie')
const notice = libraryRoot(page).getByRole('status').filter({
hasText: 'radiographie',
})
const notice = libraryRoot(page).getByTestId('editor-references-no-result')
await expect(notice).toContainText('radiographie')
await expect(notice).toContainText('Aucune référence ne contient')
await expectAccessible(page, 'the no result notice')
await notice
@@ -40,10 +40,13 @@ function ErrorCount({ tab }: { tab: EditorTabId }) {
)
}
/** Answers false when the change was refused (a field of the open panel refused to apply). */
type SelectTab = (tab: EditorTabId) => boolean | void
interface TabListProps {
shown: readonly EditorTabId[]
active: EditorTabId
onSelect: (tab: EditorTabId) => void
onSelect: SelectTab
}
/** The tablist proper: the shown tabs only, arrows move between them. */
@@ -56,7 +59,7 @@ function TabList({ shown, active, onSelect }: TabListProps) {
if (step === 0 || at < 0) return
event.preventDefault()
const next = shown[(at + step + shown.length) % shown.length]
onSelect(next)
if (onSelect(next) === false) return
document.getElementById(tabDomId(next))?.focus()
}
return (
@@ -89,7 +92,7 @@ function TabList({ shown, active, onSelect }: TabListProps) {
interface MoreTabsProps {
more: readonly EditorTabId[]
active: EditorTabId
onSelect: (tab: EditorTabId) => void
onSelect: SelectTab
}
/**
@@ -164,7 +167,7 @@ function MoreTabs({ more, active, onSelect }: MoreTabsProps) {
interface EditorTabsProps {
active: EditorTabId
tier: TabTier
onSelect: (tab: EditorTabId) => void
onSelect: SelectTab
}
/**
@@ -168,6 +168,7 @@ function EntryTile({
done: tiles.finish,
goTo: (target) => navigate(targetOfKey(target)),
registerLeave: tiles.registerLeave,
takeFocus: () => tiles.takeFocus(key),
}}
/>
)
@@ -176,7 +177,11 @@ function EntryTile({
/** The cited references as tiles, the dangling ids as rows. */
function Entries({ panel, props }: { panel: Panel; props: Props }) {
return (
<ul ref={panel.list} className="space-y-3">
<ul
ref={panel.list}
onFocusCapture={panel.trackFocus}
className="space-y-3"
>
{panel.entries.map((entry) =>
entry.reference ? (
<EntryTile
@@ -26,6 +26,9 @@ export default function CitersList({
</p>
)
}
// « Aller à » alone repeats per citer: the name says where each one goes (M6).
const where = (citer: CiterItem) =>
[...citer.trail, citer.name].map((name) => name[locale]).join(' › ')
return (
<div className="space-y-1">
<p className="text-sm font-semibold">
@@ -53,6 +56,7 @@ export default function CitersList({
</span>
<button
type="button"
aria-label={`${t('editor.references.go_to')} ${where(citer)}`}
onClick={() => 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)]"
>
@@ -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 (
<div
role="status"
data-testid="editor-references-no-result"
className="space-y-2 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-strong)] p-3 text-sm"
>
<p>
<strong>
{t('editor.references.no_result').replace('{q}', query.trim())}
{t('editor.references.no_result').replace('{q}', () => query.trim())}
</strong>{' '}
{t('editor.references.no_result_scope')}
</p>
@@ -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) => (
<DraftField
@@ -49,9 +49,7 @@ export default function ReferenceEditor(props: Props) {
label={t('editor.reference.type')}
value={reference.type}
options={options}
onCommit={(type) =>
setType({ ...reference, type: type as ReferenceType })
}
onCommit={(type) => setType(type as ReferenceType)}
error={edit.fieldError('type')}
/>
{text('doi', t('editor.reference.doi'))}
@@ -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({
<span
className={`min-w-0 break-words text-sm ${open || editing ? '' : 'line-clamp-2'} ${editing ? 'font-semibold' : ''}`}
>
{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).
<>
<span className="sr-only">{t('editor.references.done')}. </span>
{t('editor.references.edit_title')}
</>
) : (
reference.citation
)}
</span>
<span className="col-start-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-[var(--color-ink-muted)] sm:col-start-3 sm:row-start-1 sm:flex-col sm:items-end">
{!editing && (
@@ -216,6 +226,8 @@ export default function ReferenceTile(props: TileProps) {
const t = useT()
const base = tileBase(host, position, reference)
const headerRef = useRef<HTMLButtonElement>(null)
const dropped = useRef<Field | null>(null)
useDropNote(props.readOnly, dropped)
const done = () => {
if (on.done()) headerRef.current?.focus()
}
@@ -231,7 +243,11 @@ export default function ReferenceTile(props: TileProps) {
<ReferenceEditor
reference={reference}
base={base}
registerLeave={on.registerLeave}
hooks={{
registerLeave: on.registerLeave,
takeFocus: on.takeFocus,
dropped,
}}
/>
) : (
<ReferenceFacts reference={reference} />
@@ -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),
}}
/>
)
@@ -29,7 +29,7 @@ function CountLine({ shown, total }: { shown: number; total: number }) {
const text = plural(`editor.references.${key}`, shown)
return (
<p aria-live="polite" className="text-sm text-[var(--color-ink-muted)]">
{text.replace('{total}', String(total))}
{text.replace('{total}', () => String(total))}
</p>
)
}
@@ -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<HTMLUListElement>(null)
const heading = useRef<HTMLHeadingElement>(null)
const [removed, setRemoved] = useState<{ at: number; before: number } | null>(
null,
)
const held = useRef<Held | null>(null)
const rowsOf = () => [...(list.current?.children ?? [])]
const hold = (element: Element, at: number) => {
held.current = { element, at, rows: rowsOf().length }
}
const track = (event: FocusEvent<HTMLUListElement>) => {
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,
}
}
@@ -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<Field, string>
*/
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<Field | null>
}
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<ReturnType<typeof useWriter>, '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<Field | null>,
) {
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])
}
@@ -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<typeof useReferenceLibrary>
@@ -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])
},
}
}
@@ -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<string, readonly CiterItem[]>
}
/**
* 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<string, readonly CiterItem[]>,
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<Pinned | null>(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<ReferenceView>) => {
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) }),
}
}
@@ -32,6 +32,9 @@ export function useTileState(keys: readonly string[] | null) {
if (editingKey !== null && !live.has(editingKey)) setEditingKey(null)
}
const guard = useRef<LeaveGuard | null>(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<string | null>(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
+1 -1
View File
@@ -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',
+17 -11
View File
@@ -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],
)
@@ -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<HTMLInputElement>(
'#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<HTMLTextAreaElement>(
'#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')
})
})
@@ -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()
@@ -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) => (
<AnnounceContext value={announce}>{lib(readOnly)}</AnnounceContext>
)
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()
})
})