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

@@ -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