refactor(editor): Task 2 round 2, locals and line limits

This commit is contained in:
bchanot committed 2026-11-13 19:45:50 +01:00
1 parent b703333b20
commit 20905adf72
10 files changed
+258 -168

No files matched your search

@@ -7,6 +7,9 @@ import { useT } from '@/i18n/useT'
* The footer of a form with changes that a close request reached: keep typing (focused),
* or discard. It is part of the dialog, never inert.
*/
const BOX =
'space-y-2 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-strong)] p-3'
export default function DiscardConfirm({
onKeepTyping,
onDiscard,
@@ -21,7 +24,7 @@ export default function DiscardConfirm({
<div
role="group"
aria-label={t('editor.findings.discard_ask')}
className="space-y-2 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-strong)] p-3"
className={BOX}
>
<p className="text-sm font-medium">{t('editor.findings.discard_ask')}</p>
<div className="flex flex-wrap justify-end gap-2">
@@ -63,7 +63,7 @@ interface ActionsProps {
/** The view mode's actions (edit tier only): « Modifier », review, order, « Supprimer ». */
export default function FindingActions(props: ActionsProps) {
const { item, readOnly, edit, onEdit, onDelete } = props
const { item, readOnly, edit } = props
const t = useT()
return (
<>
@@ -73,7 +73,7 @@ export default function FindingActions(props: ActionsProps) {
readOnly={readOnly}
variant="secondary"
size="sm"
onClick={onEdit}
onClick={props.onEdit}
>
{t('editor.findings.edit')}
</ActionButton>
@@ -90,7 +90,7 @@ export default function FindingActions(props: ActionsProps) {
readOnly={readOnly}
variant="danger"
size="sm"
onClick={onDelete}
onClick={props.onDelete}
>
{t('editor.action.delete')}
</ActionButton>
@@ -17,6 +17,9 @@ interface CitationsProps {
onShowReferences: (opener: HTMLElement) => void
}
const PILL =
'inline-flex min-h-11 items-center gap-1 rounded-full border px-3 text-sm ' +
'border-[var(--color-border)]'
const RING =
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
@@ -37,7 +40,7 @@ function SheetTrigger({
aria-expanded={sheetOpen}
aria-controls="editor-citations-panel"
onClick={(event) => onShowReferences(event.currentTarget)}
className={`inline-flex min-h-11 items-center gap-1 rounded-full border border-[var(--color-border)] px-3 text-sm ${RING}`}
className={`${PILL} ${RING}`}
>
<Icon name="book" size={16} />
{plural('editor.findings.references_open', count)}
@@ -79,6 +82,28 @@ function CitationList({
)
}
/** The finding's cited ids, the update that changes them and the references still citable. */
function useCitationEdit(item: FindingItem, edit: EditCommandApi) {
const t = useT()
const doc = useSheetDocument()
const ids =
item.element.kind === 'zone' ? [] : item.element.value.reference_ids
const patch = (reference_ids: string[]) =>
edit.run('references', {
op: 'update',
key: item.key,
element: patchElement(item, { reference_ids }),
})
const options = (doc?.references ?? [])
.filter((r) => !ids.includes(r.id))
.map((r) => ({ value: r.id, label: r.citation }))
return {
ids,
patch,
options: [{ value: '', label: t('editor.field.choose') }, ...options],
}
}
/**
* « Références citées » of a category or a node. A finding node shows « X références »
* (the sheet), a family its list. « Citer une référence » acts at once, one entry in the
@@ -87,40 +112,28 @@ function CitationList({
export default function FindingCitations(props: CitationsProps) {
const { item, readOnly, edit } = props
const t = useT()
const doc = useSheetDocument()
const { element } = item
if (element.kind === 'zone') return null
const ids = element.value.reference_ids
const patch = (reference_ids: string[]) =>
edit.run('references', {
op: 'update',
key: item.key,
element: patchElement(item, { reference_ids }),
})
const options = [
{ value: '', label: t('editor.field.choose') },
...(doc?.references ?? [])
.filter((r) => !ids.includes(r.id))
.map((r) => ({ value: r.id, label: r.citation })),
]
const cited = useCitationEdit(item, edit)
if (item.element.kind === 'zone') return null
return (
<div className="space-y-2">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="text-sm font-medium">{t('editor.findings.references')}</p>
{ids.length > 0 && element.kind === 'finding_node' && (
<SheetTrigger {...props} count={ids.length} />
{cited.ids.length > 0 && item.element.kind === 'finding_node' && (
<SheetTrigger {...props} count={cited.ids.length} />
)}
</div>
{ids.length === 0 && (
{cited.ids.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.findings.references_none')}
</p>
)}
{element.kind === 'finding_category' && (
{item.element.kind === 'finding_category' && (
<CitationList
ids={ids}
ids={cited.ids}
readOnly={readOnly}
remove={(id) => patch(ids.filter((other) => other !== id))}
remove={(id) =>
cited.patch(cited.ids.filter((other) => other !== id))
}
/>
)}
{!readOnly && (
@@ -128,8 +141,8 @@ export default function FindingCitations(props: CitationsProps) {
id="finding-add-reference"
label={t('editor.findings.reference_add')}
value=""
options={options}
onCommit={(id) => id !== '' && patch([...ids, id])}
options={cited.options}
onCommit={(id) => id !== '' && cited.patch([...cited.ids, id])}
error={edit.fieldError('references')}
/>
)}
@@ -16,7 +16,7 @@ import {
} from '@/editor/findings/tree'
import type { IdPrefix } from '@/editor/ids'
import { isBlank, useSheetDocument } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import { useEditCommand, type EditCommandApi } from '@/editor/useEditCommand'
import type { Guards } from '@/editor/useEditorNavigation'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
@@ -60,26 +60,36 @@ function isComplete(draft: Draft, pending: PendingFinding, parent: unknown) {
return pending.kind !== 'category' || (parent !== null && draft.kind !== '')
}
/** The one `insert`, under a fresh id; the new id, or null when the core refused it. */
function insertNew(
edit: EditCommandApi,
pending: PendingFinding,
parent: FindingItem | null,
draft: Draft,
): string | null {
let createdId = ''
const name = { fr: draft.fr.trim(), en: draft.en.trim() }
const added = edit.runNew('form', PREFIX[pending.kind], (id) => {
createdId = id
return insertCommand({ ...pending, parent }, id, name, draft.kind)
})
return added ? createdId : null
}
/** The form's state and its one `insert` (« Créer »), refused on a missing field. */
function useCreateForm(props: FindingCreateFormProps) {
const { pending, guards, onCreated } = props
const edit = useEditCommand()
const zones = useZoneChoice()
const form = useFormDraft(EMPTY, guards, sameDraft)
const form = useFormDraft(EMPTY, props.guards, sameDraft)
const create = () => {
const { pending } = props
const parent = pending.kind === 'category' ? zones.chosen : pending.parent
if (!isComplete(form.draft, pending, parent)) {
edit.reject('form', 'editor.findings.required')
return
}
const { fr, en, kind } = form.draft
let createdId = ''
const added = edit.runNew('form', PREFIX[pending.kind], (id) => {
createdId = id
const name = { fr: fr.trim(), en: en.trim() }
return insertCommand({ ...pending, parent }, id, name, kind)
})
if (added) onCreated(createdId, parent)
const id = insertNew(edit, pending, parent, form.draft)
if (id !== null) props.onCreated(id, parent)
}
return { ...form, zones, create, error: edit.fieldError('form') }
}
@@ -129,11 +139,9 @@ function CreateFields(props: {
* is written before « Créer », a close or a move never creates (R2F-3).
*/
export default function FindingCreateForm(props: FindingCreateFormProps) {
const { pending, readOnly, onClose } = props
const t = useT()
const form = useCreateForm(props)
const { guard } = form
const category = pending.kind === 'category'
const category = props.pending.kind === 'category'
return (
<form
data-draft-form
@@ -144,21 +152,21 @@ export default function FindingCreateForm(props: FindingCreateFormProps) {
form.create()
}}
>
{readOnly && <ReadOnlyNotice />}
{props.readOnly && <ReadOnlyNotice />}
{category && form.zones.chosen && <ZoneTitle zone={form.zones.chosen} />}
<CreateFields form={form} category={category} readOnly={readOnly} />
<CreateFields form={form} category={category} readOnly={props.readOnly} />
{form.error && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{form.error}
</p>
)}
<FormActions
confirming={guard.confirming}
readOnly={readOnly}
confirming={form.guard.confirming}
readOnly={props.readOnly}
submitLabel={t('editor.findings.create')}
onCancel={() => onClose(readOnly)}
onKeepTyping={guard.keepTyping}
onDiscard={() => onClose(true)}
onCancel={() => props.onClose(props.readOnly)}
onKeepTyping={form.guard.keepTyping}
onDiscard={() => props.onClose(true)}
/>
</form>
)
@@ -46,43 +46,50 @@ function useFocusEditButton(editing: boolean) {
}
}
/** The local mode of the one dialog: view or edit, and whether a save was just made. */
function useItemMode() {
const [mode, setMode] = useState({ editing: false, saved: false })
const returnToEdit = useFocusEditButton(mode.editing)
return {
...mode,
startEdit: () => setMode({ editing: true, saved: false }),
done: (saved: boolean) => {
returnToEdit()
setMode({ editing: false, saved })
},
}
}
/** View mode, or the edit form: a local mode of the one dialog, no history entry. */
function ItemBody({ item, layer, readOnly, onDelete }: ItemBodyProps) {
function ItemBody(props: ItemBodyProps) {
const { layer } = props
const t = useT()
const [editing, setEditing] = useState(false)
const [saved, setSaved] = useState(false)
const returnToEdit = useFocusEditButton(editing)
const { view } = layer
const sheetOpen = view !== null && 'key' in view && view.citations
const mode = useItemMode()
const sheetOpen = !!layer.view && 'key' in layer.view && layer.view.citations
return (
<div className="space-y-2">
{editing ? (
{mode.editing ? (
<FindingEditForm
item={item}
readOnly={readOnly}
item={props.item}
readOnly={props.readOnly}
guards={layer.guards}
onDone={(wrote) => {
returnToEdit()
setSaved(wrote)
setEditing(false)
}}
onDone={mode.done}
onDiscardClose={() => layer.close(true)}
/>
) : (
<FindingView
item={item}
readOnly={readOnly}
item={props.item}
readOnly={props.readOnly}
sheetOpen={sheetOpen}
onEdit={() => {
setSaved(false)
setEditing(true)
}}
onDelete={() => onDelete(item)}
onShowReferences={(opener) => layer.openCitations(item.key, opener)}
onEdit={mode.startEdit}
onDelete={() => props.onDelete(props.item)}
onShowReferences={(opener) =>
layer.openCitations(props.item.key, opener)
}
/>
)}
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{saved ? t('editor.findings.saved') : ''}
{mode.saved ? t('editor.findings.saved') : ''}
</p>
</div>
)
@@ -94,37 +101,37 @@ function ItemBody({ item, layer, readOnly, onDelete }: ItemBodyProps) {
* place is shown (no native modal inside a hidden part).
*/
export default function FindingDialog(props: FindingDialogProps) {
const { layer, item, pending, readOnly } = props
const { pending } = props
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const visible = usePlaceVisible()
const title = pending
? t(`editor.findings.new.${pending.kind}`)
: (item?.name[locale] ?? '')
: (props.item?.name[locale] ?? '')
return (
<Dialog
open={visible && (item !== null || pending !== null)}
open={visible && (props.item !== null || pending !== null)}
layer
size="lg"
title={title}
returnFocus={props.returnFocus}
onClose={() => (layer.close() ? undefined : 'kept')}
onClose={() => (props.layer.close() ? undefined : 'kept')}
>
{pending && (
<FindingCreateForm
pending={pending}
readOnly={readOnly}
guards={layer.guards}
readOnly={props.readOnly}
guards={props.layer.guards}
onCreated={(id, parent) => props.onCreated(id, parent, pending.kind)}
onClose={(forced) => layer.close(forced)}
onClose={(forced) => props.layer.close(forced)}
/>
)}
{item && (
{props.item && (
<ItemBody
key={item.id}
item={item}
layer={layer}
readOnly={readOnly}
key={props.item.id}
item={props.item}
layer={props.layer}
readOnly={props.readOnly}
onDelete={props.onDelete}
/>
)}
@@ -141,11 +141,9 @@ function EditFields({ draft, set, readOnly, described, blank }: FieldsProps) {
)
}
/** The form's state: draft, blank names, and the one save (none when nothing changed). */
function useEditForm(props: FindingEditFormProps) {
const { item, readOnly, guards, onDone } = props
/** The one save: blank names refused on their field, nothing written when unchanged. */
function useEditSave(props: FindingEditFormProps, form: EditDraft) {
const edit = useEditCommand()
const form = useFormDraft(draftOf(item), guards, sameDraft)
const [blank, setBlank] = useState<readonly string[]>([])
const save = () => {
const missing = LOCALES.filter((l) => isBlank(form.draft[l]))
@@ -153,16 +151,27 @@ function useEditForm(props: FindingEditFormProps) {
if (missing.length > 0) {
document.getElementById(`finding-edit-name-${missing[0]}`)?.focus()
} else if (!form.dirty) {
onDone(false)
props.onDone(false)
} else {
const element = patchOf(item, form.draft)
const command = { op: 'update', key: item.key, element } as const
if (edit.run('save', command)) onDone(true)
const element = patchOf(props.item, form.draft)
const command = { op: 'update', key: props.item.key, element } as const
if (edit.run('save', command)) props.onDone(true)
}
}
return { blank, save, error: edit.fieldError('save') }
}
type EditDraft = ReturnType<typeof useFormDraft<Draft>>
/** The form's state: draft, blank names, save and cancel. */
function useEditForm(props: FindingEditFormProps) {
const form = useFormDraft(draftOf(props.item), props.guards, sameDraft)
const saving = useEditSave(props, form)
const cancel = () =>
form.dirty && !readOnly ? form.guard.askToLeave() : onDone(false)
return { ...form, blank, save, cancel, error: edit.fieldError('save') }
form.dirty && !props.readOnly
? form.guard.askToLeave()
: props.onDone(false)
return { ...form, ...saving, cancel }
}
/**
@@ -172,12 +181,13 @@ function useEditForm(props: FindingEditFormProps) {
* is left.
*/
export default function FindingEditForm(props: FindingEditFormProps) {
const { item, readOnly, onDone, onDiscardClose } = props
const t = useT()
const form = useEditForm(props)
const { guard } = form
const discard =
guard.confirming === 'dialog' ? onDiscardClose : () => onDone(false)
guard.confirming === 'dialog'
? props.onDiscardClose
: () => props.onDone(false)
return (
<form
data-draft-form
@@ -188,18 +198,18 @@ export default function FindingEditForm(props: FindingEditFormProps) {
form.save()
}}
>
{readOnly && <ReadOnlyNotice />}
{props.readOnly && <ReadOnlyNotice />}
<EditFields
draft={form.draft}
set={form.set}
readOnly={readOnly}
described={item.kind !== 'zone'}
readOnly={props.readOnly}
described={props.item.kind !== 'zone'}
blank={form.blank}
/>
{item.element.kind === 'finding_node' && (
{props.item.element.kind === 'finding_node' && (
<VetCheckbox
checked={form.draft.vet}
readOnly={readOnly}
readOnly={props.readOnly}
onChange={(vet) => form.set({ vet })}
/>
)}
@@ -210,7 +220,7 @@ export default function FindingEditForm(props: FindingEditFormProps) {
)}
<FormActions
confirming={guard.confirming}
readOnly={readOnly}
readOnly={props.readOnly}
submitLabel={t('editor.findings.save')}
onCancel={form.cancel}
onKeepTyping={guard.keepTyping}
@@ -49,6 +49,10 @@ export function useFormDraft<T extends object>(
const [draft, setDraft] = useState(first)
const dirty = !same(draft, first)
const guard = useDirtyGuard(guards, dirty)
const set = (change: Partial<T>) => setDraft({ ...draft, ...change })
return { draft, set, dirty, guard }
return {
draft,
dirty,
guard,
set: (c: Partial<T>) => setDraft({ ...draft, ...c }),
}
}
@@ -25,6 +25,16 @@ export interface CitationsSheetProps {
returnFocus: () => HTMLElement | null
}
/** The slide and its timings; under reduced motion nothing moves and nothing waits. */
function useSheetMotion() {
const reduced = useReducedMotion()
return {
slide: reduced ? { x: 0 } : { x: '100%' },
enter: { duration: reduced ? 0 : ENTER_S, ease: 'easeOut' } as const,
leave: { duration: reduced ? 0 : EXIT_S, ease: 'easeIn' } as const,
}
}
/**
* The citations of a finding as a modal side sheet at the right edge, over the finding
* dialog (R2F-4): the host sits after the tab body in the tree, so it is shown after the
@@ -33,10 +43,7 @@ export interface CitationsSheetProps {
*/
function SheetSurface(props: CitationsSheetProps & { citedBy: ElementKey }) {
const { citedBy, onClose } = props
const reduced = useReducedMotion()
const slide = reduced ? { x: 0 } : { x: '100%' }
const enter = { duration: reduced ? 0 : ENTER_S, ease: 'easeOut' } as const
const leave = { duration: reduced ? 0 : EXIT_S, ease: 'easeIn' } as const
const sheetMotion = useSheetMotion()
const close = () => (onClose() ? undefined : 'kept')
return (
<ModalDialog
@@ -53,15 +60,15 @@ function SheetSurface(props: CitationsSheetProps & { citedBy: ElementKey }) {
onClick={close}
className="absolute inset-0 bg-[rgba(31,27,22,0.25)]"
initial={{ opacity: 0 }}
animate={{ opacity: 1, transition: enter }}
exit={{ opacity: 0, transition: leave }}
animate={{ opacity: 1, transition: sheetMotion.enter }}
exit={{ opacity: 0, transition: sheetMotion.leave }}
/>
<motion.div
data-place="citations"
className="absolute inset-y-0 right-0 w-[min(34rem,100vw)]"
initial={slide}
animate={{ x: 0, transition: enter }}
exit={{ ...slide, transition: leave }}
initial={sheetMotion.slide}
animate={{ x: 0, transition: sheetMotion.enter }}
exit={{ ...sheetMotion.slide, transition: sheetMotion.leave }}
>
<CitationsPanel
readOnly={props.readOnly}
@@ -53,22 +53,24 @@ function useFindingDeletion(
},
) {
const locale = useLocaleStore((s) => s.locale)
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
const [fallback, setFallback] = useState<string | null>(null)
const [ask, setAsk] = useState<{
target: DeleteTarget
fallback: string | null
} | null>(null)
const askDelete = (item: FindingItem) => {
setFallback(fallbackAfterRemoval(items, item))
setDeleting({ key: item.key, label: item.name[locale] })
const target = { key: item.key, label: item.name[locale] }
setAsk({ target, fallback: fallbackAfterRemoval(items, item) })
}
// The element is gone: its dialog closes in the same move (replace, no Back step) and
// the focus lands on the nearest row once every dialog is closed.
const closeDelete = () => {
setDeleting(null)
if (currentItems().some((item) => item.id === selectedId)) return
actions.select(fallback)
setAsk(null)
if (!ask || currentItems().some((item) => item.id === selectedId)) return
actions.select(ask.fallback)
actions.closeLayer()
afterModalsClosed(() => actions.focusItem(fallback))
afterModalsClosed(() => actions.focusItem(ask.fallback))
}
return { deleting, askDelete, closeDelete }
return { deleting: ask?.target ?? null, askDelete, closeDelete }
}
/** The layer's element follows the view: a Back or a reload selects and shows its row. */
@@ -151,35 +153,49 @@ interface TreeSelection {
reveal: (found: { item: FindingItem; ancestors: string[] }) => void
}
/** Selection and expansion of the tree: the zones start open, a closed branch takes the selection. */
/** Which branches are open: the zones start open once the sheet has loaded. */
function useExpansion(items: readonly FindingItem[], loaded: boolean) {
const [state, setState] = useState({ ids: new Set<string>(), seeded: false })
if (loaded && !state.seeded) {
const zones = items.filter((i) => i.kind === 'zone')
setState({ ids: new Set(zones.map((i) => i.id)), seeded: true })
}
const open = (ids: readonly string[]) =>
setState((prev) => ({ ...prev, ids: new Set([...prev.ids, ...ids]) }))
const set = (id: string, on: boolean) =>
setState((prev) => {
const ids = new Set(prev.ids)
if (on) ids.add(id)
else ids.delete(id)
return { ...prev, ids }
})
return { expanded: state.ids as ReadonlySet<string>, open, set }
}
/** Selection of the tree; a closed branch takes the selection of what it hides. */
function useTreeSelection(
items: readonly FindingItem[],
loaded: boolean,
): TreeSelection {
const [selectedId, select] = useState<string | null>(null)
const [expanded, setExpanded] = useState<ReadonlySet<string>>(new Set())
const [seeded, setSeeded] = useState(false)
if (loaded && !seeded) {
setSeeded(true)
setExpanded(
new Set(items.filter((i) => i.kind === 'zone').map((i) => i.id)),
)
}
const exp = useExpansion(items, loaded)
const reveal: TreeSelection['reveal'] = (found) => {
setExpanded((prev) => new Set([...prev, ...found.ancestors]))
exp.open(found.ancestors)
select(found.item.id)
}
const toggle = (id: string, open: boolean) => {
if (!open && selectedId && isUnder(items, selectedId, id)) select(id)
setExpanded((prev) => {
const next = new Set(prev)
if (open) next.add(id)
else next.delete(id)
return next
})
exp.set(id, open)
}
const selected = items.find((item) => item.id === selectedId)
return { selectedId, selected, expanded, select, toggle, reveal }
return {
selectedId,
selected,
expanded: exp.expanded,
select,
toggle,
reveal,
}
}
/** The row the focus lands on after a move: set, applied once the dialogs are gone, cleared. */
@@ -215,12 +231,12 @@ function useLayerFollow(focus: EditorPlaceProps['focus'], ctx: TabContext) {
useSelectionOfLayer(layer, items, sel.reveal)
}
/** What the tab does with the layer: a creation turns into its element, a row opens its dialog, a deletion. */
/** What the tab does with the layer: creation, a row's dialog, deletion. */
function useFindingActions(ctx: TabContext) {
const { layer, items, sel, land } = ctx
const deletion = useFindingDeletion(items, sel.selectedId, {
const { layer, sel } = ctx
const deletion = useFindingDeletion(ctx.items, sel.selectedId, {
select: sel.select,
focusItem: land,
focusItem: ctx.land,
closeLayer: () => layer.replace(null),
})
const created = (
@@ -239,18 +255,29 @@ function useFindingActions(ctx: TabContext) {
return { ...deletion, created, activate }
}
/** Everything the tab shows and does, so the component only lays it out. */
function useFindingsTab(focus: EditorPlaceProps['focus'], layer: FindingLayer) {
/** The sheet's document and the tree built from it. */
function useFindingsData() {
const doc = useSheetDocument()
const items = useMemo(() => (doc ? buildItems(doc) : []), [doc])
const sel = useTreeSelection(items, doc !== null)
return { doc, items }
}
/** Everything the tab shows and does, so the component only lays it out. */
function useFindingsTab(focus: EditorPlaceProps['focus'], layer: FindingLayer) {
const data = useFindingsData()
const sel = useTreeSelection(data.items, data.doc !== null)
const landing = useFocusLanding()
const ctx = { layer, items, sel, land: landing.land }
const ctx = { layer, items: data.items, sel, land: landing.land }
useLayerFollow(focus, ctx)
useGoneRule(layer, doc !== null)
useGoneRule(layer, data.doc !== null)
const actions = useFindingActions(ctx)
const returnFocus = useReturnTarget(layer.view)
return { doc, items, sel, landing, actions, returnFocus }
return {
...data,
sel,
landing,
actions,
returnFocus: useReturnTarget(layer.view),
}
}
/** Constats: the tree zones → categories → nodes; each element opens in a dialog. */
+28 -17
View File
@@ -450,40 +450,51 @@ function useCitedBy(state: NavigationState, openers: Openers) {
}
/** Navigation of the draft editor: the reducer plus the DOM side (focus, live region). */
export function useEditorNavigation(
initialTab: EditorTabId,
initialView?: EditorView | null,
): EditorNavigation {
/** The reducer and the move machinery every other part of the hook builds on. */
function useNavBase(initialTab: EditorTabId, initialView?: EditorView | null) {
const [state, dispatch] = useReducer(navigationReducer, null, () =>
initialNavigation(initialTab, initialView),
)
const { trace, mark } = useMoveTrace()
const { move, go, live, announce } = useGo(dispatch, trace)
return { state, dispatch, trace, mark, ...useGo(dispatch, trace) }
}
/** Navigation of the draft editor: the reducer plus the DOM side (focus, live region). */
export function useEditorNavigation(
initialTab: EditorTabId,
initialView?: EditorView | null,
): EditorNavigation {
const base = useNavBase(initialTab, initialView)
const openers = useRef<Openers>({
citations: { current: null },
citedBy: { current: null },
section: { current: null },
}).current
const guards = useGuards()
const receipts = useReceipts(dispatch)
useMoveFocus(move, state, receipts.outcomes, dispatch, openers)
useCitedBy(state, openers)
const ctx = { dispatch, announce, guards, mark }
const receipts = useReceipts(base.dispatch)
useMoveFocus(base.move, base.state, receipts.outcomes, base.dispatch, openers)
useCitedBy(base.state, openers)
const ctx = {
dispatch: base.dispatch,
announce: base.announce,
guards,
mark: base.mark,
}
return {
state,
live,
announce,
state: base.state,
live: base.live,
announce: base.announce,
consumed: receipts.consumed,
selectTab: useTabSelect(dispatch, mark),
...useSectionMoves(go, openers),
selectTab: useTabSelect(base.dispatch, base.mark),
...useSectionMoves(base.go, openers),
...useFindingLayer(ctx),
...useSheetLayer(ctx, openers),
...useLeavingMoves(go, guards),
...useLeavingMoves(base.go, guards),
citationsTrigger: useCallback(() => triggerOf(openers), [openers]),
guards,
trace,
trace: base.trace,
restoreView: useCallback(
(view: EditorView) => dispatch({ type: 'restore_view', view }),
(view: EditorView) => base.dispatch({ type: 'restore_view', view }),
[],
),
}