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 export type Field = (typeof FIELDS)[number] type Drafts = Record /** * What the guard calls on a leave: null when every pending field was applied, else the * field that refused (its draft stays, the field is focused). */ 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 ?? '', url: reference.url ?? '', }) /** The document value a draft gives (a blank optional field is null, so ''). */ const normalized = (field: Field, draft: string) => field === 'citation' ? draft : (nullable(draft) ?? '') const patched = (reference: Reference, field: Field, draft: string) => field === 'citation' ? { ...reference, citation: draft } : { ...reference, [field]: nullable(draft) } /** One draft per text field; a new committed value (undo, reload) replaces its draft. */ function useDrafts(reference: Reference) { const committed = committedOf(reference) const [drafts, setDrafts] = useState(committed) const [seen, setSeen] = useState(committed) const changed = FIELDS.filter((field) => seen[field] !== committed[field]) if (changed.length > 0) { setSeen(committed) const fresh = changed.map((field) => [field, committed[field]]) setDrafts({ ...drafts, ...Object.fromEntries(fresh) }) } const setDraft = (field: Field, value: string) => setDrafts({ ...drafts, [field]: value }) 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 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). */ 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 { 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 apply = (field: Field): boolean => { if (field === 'citation' && isBlank(drafts[field])) { return edit.reject(field, 'editor.field.required') } 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(() => { 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(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]) }