import { useCallback, useEffect, useReducer, useRef, useState, type Dispatch, type RefObject, } from 'react' import type { ElementKey } from '@faunosteo/core-wasm/types' import { useT } from '@/i18n/useT' import { commitFocusedField, focusActiveTab, placeOf, visibleElement, type FocusOutcome, type PlaceName, } from './focusRequest' import { initialNavigation, isFindingNode, navigationReducer, type AnnotationSection, type EditorTarget, type NavigationAction, type NavigationState, } from './navigation' import { MORE_BUTTON_ID, tabDomId, type EditorTabId } from './tabs' import { useCitationsExit, type PendingClose, type PendingKind, } from './useCitationsExit' type MoveKind = PendingKind | 'section' | 'back' /** * A programmatic move: a new object per move, so the effect after it runs once. * `afterExit`: it is the pending move of a closed panel, so a focus the user already * placed elsewhere during the exit is left alone (P28). */ interface Move { kind: MoveKind afterExit?: boolean } /** * The panel's answer before a close (P22''): `allowed` false cancels a user close. A forced * close always goes ahead; `note` (a draft dropped) is said with the close. */ export interface LeaveAnswer { allowed: boolean note?: string } export type CanLeave = (forced: boolean) => LeaveAnswer type Opener = HTMLElement | null | undefined export interface EditorNavigation { state: NavigationState /** The polite live region's text; a repeat alternates a trailing no-break space. */ live: string navigate: (target: EditorTarget) => 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). */ dropCitations: () => void /** « Tout afficher dans l'onglet Références »: panel closed, tab shown, library reset. */ showAllReferences: () => void /** The panel is playing its exit: the state still holds it, the page stays inert. */ exiting: boolean /** The panel's `onExitComplete`: applies the pending move. */ exitComplete: () => void /** The panel hands its `canLeave` over while it is mounted (P22''). */ registerCanLeave: (guard: CanLeave | null) => void consumed: (serial: number, outcome: FocusOutcome) => void announce: (text: string) => void } const isShown = (element: HTMLElement | null): boolean => element !== null && element.isConnected && !element.closest('[hidden]') const headingOf = (place: PlaceName) => visibleElement(`[data-place="${place}"] [data-place-heading]`) export const CANVAS_BOX = '[data-place="annotations.drawing"] [role="group"][tabindex="0"]' /** The tab's button, or « Plus » while the tab sits in the closed list. */ const tabButton = (tab: EditorTabId) => document.getElementById(tabDomId(tab)) ?? document.getElementById(MORE_BUTTON_ID) /** The place the shown tab and section name. */ function shownPlace(state: NavigationState): PlaceName { return state.tab === 'annotations' ? `annotations.${state.section}` : state.tab } /** The text the live region says for a move to `target`. */ function useMoveText(): (target: EditorTarget) => string { const t = useT() return useCallback( (target) => { const tab = t(`editor.tab.${target.tab}`) if (!target.section) return tab return `${tab} · ${t(`editor.place.${target.section}`)}` }, [t], ) } function useLiveRegion() { const [live, setLive] = useState('') const announce = useCallback((text: string) => { setLive((previous) => (previous === text ? `${text} ` : text)) }, []) return { live, announce } } interface Openers { /** The trigger that opened the citations panel, and the finding it belongs to. */ citations: RefObject citedBy: RefObject section: RefObject } type Go = (action: NavigationAction, kind: MoveKind, text: string) => void /** * The one way to move: commit the typed text, announce, dispatch, record the move. * `finish` is the same without the commit, for the move a closed panel recorded. */ function useGo(dispatch: Dispatch) { const { live, announce } = useLiveRegion() const [move, setMove] = useState(null) const finish = useCallback( (move: PendingClose) => { announce(move.note ? `${move.note}. ${move.text}` : move.text) dispatch(move.action) setMove({ kind: move.kind, afterExit: true }) }, [announce, dispatch], ) const go: Go = useCallback( (action, kind, text) => { commitFocusedField() announce(text) dispatch(action) setMove({ kind }) }, [announce, dispatch], ) return { move, go, finish, live, announce } } /** Tab and section moves: « Aller à », a section entry, « Retour au dessin ». */ function useSectionMoves(go: Go, openers: Openers) { const t = useT() const moveText = useMoveText() const navigate = useCallback( (target: EditorTarget) => go({ type: 'go_to', target }, 'go_to', moveText(target)), [go, moveText], ) const openSection = useCallback( (section: AnnotationSection, opener?: Opener) => { openers.section.current = opener ?? null const place = t(`editor.place.${section}`) const text = `${t('editor.tab.annotations')} · ${place}` go({ type: 'open_section', section }, 'section', text) }, [go, openers, t], ) const backToDrawing = useCallback(() => { const text = `${t('editor.tab.annotations')} · ${t('editor.place.drawing')}` go({ type: 'back_to_drawing' }, 'back', text) }, [go, t]) return { navigate, openSection, backToDrawing } } /** What the panel's moves need of the hook: its state, the exit and the leave check. */ interface PanelContext { open: boolean go: Go openers: Openers dispatch: Dispatch announce: (text: string) => void exit: ReturnType canLeave: RefObject } /** * Records a close of the panel. A user close asks the panel first (P22''): a refused * 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): boolean => { if (!open) return true if (busy()) { record(move) return true } commitFocusedField() const { allowed, note } = canLeave.current?.(forced) ?? { allowed: true } if (!allowed) return false record(note ? { ...move, note } : move) return true }, [open, busy, record, canLeave], ) } /** Opens the panel of a finding node: no move is recorded, the panel focuses itself. */ function useOpenCitations(ctx: PanelContext) { const t = useT() const { openers, dispatch, announce } = ctx return useCallback( (citedBy: ElementKey, opener?: Opener) => { if (!isFindingNode(citedBy)) return commitFocusedField() openers.citations.current = opener ?? null openers.citedBy.current = citedBy announce(t('editor.references.panel_title')) dispatch({ type: 'open_citations', citedBy }) }, [openers, dispatch, announce, t], ) } /** The panel's closes: ✕ / Escape / scrim, the vanished finding, « Tout afficher », « Aller à ». */ function useCloseMoves(ctx: PanelContext) { const t = useT() const moveText = useMoveText() const { open, go } = ctx const request = useRequestClose(ctx) const closing = useCallback( (forced: boolean) => { const text = t('editor.live.references_closed') request( { action: { type: 'close_citations' }, kind: 'citations_closed', text }, forced, ) }, [request, t], ) // With no panel open there is nothing to exit: the tab shows at once. const showAllReferences = useCallback(() => { const action = { type: 'show_all_references' } as const const text = t('editor.tab.references') if (!open) return go(action, 'show_all', text) request({ action, kind: 'show_all', text }, false) }, [open, go, request, t]) const navigate = useCallback( (target: EditorTarget) => { const action = { type: 'go_to', target } as const request({ action, kind: 'go_to', text: moveText(target) }, false) }, [request, moveText], ) return { closeCitations: useCallback(() => closing(false), [closing]), dropCitations: useCallback(() => closing(true), [closing]), showAllReferences, navigate, request, } } /** « Retour au dessin »: the entry that opened the section, else the canvas box. */ function backTarget(opener: HTMLElement | null): HTMLElement | null { if (opener && isShown(opener)) return opener const entry = opener?.dataset.sectionEntry const again = entry && visibleElement(`[data-section-entry="${entry}"]`) return again || visibleElement(CANVAS_BOX) } /** The trigger of a finding's citations, found by comparing `dataset` values. */ function triggerOf(openers: Openers): HTMLElement | null { const opener = openers.citations.current if (opener && isShown(opener)) return opener const wanted = JSON.stringify(openers.citedBy.current) return visibleElement('[data-citations-trigger]', (element) => { return element.dataset.citationsTrigger === wanted }) } /** Focuses `element` and says whether it really holds the focus now. */ function focusHeld(element: HTMLElement | null): boolean { element?.focus() return element !== null && document.activeElement === element } /** Panel closed (P6): the trigger when it is shown, else the active tab's button. */ function focusAfterClose(openers: Openers) { if (!focusHeld(triggerOf(openers))) focusActiveTab() } /** Nothing the user chose holds the focus: `body`, or what the closing panel still has. */ function focusIsFree(): boolean { const active = document.activeElement return ( active === null || active === document.body || active.closest('[data-place="citations"]') !== null ) } /** Where the focus lands after a programmatic move; never `body`. */ function landingOf(move: Move, state: NavigationState): HTMLElement | null { if (move.kind === 'show_all') { return headingOf('references') ?? tabButton(state.tab) } if (move.kind === 'tab_selected') return tabButton(state.tab) const place = state.focus ? placeOf(state.focus.target) : shownPlace(state) return headingOf(place) ?? tabButton(state.tab) } /** * After each move: a request an element answered is done; else (no owner answered, or * the move had no request) the focus goes to the heading or the tab button. */ function useMoveFocus( move: Move | null, state: NavigationState, outcomes: RefObject>, dispatch: Dispatch, openers: Openers, ) { const handled = useRef(null) useEffect(() => { if (!move || handled.current === move) return handled.current = move const serial = state.focus?.serial if (move.kind === 'go_to' && serial !== undefined) { const outcome = outcomes.current.get(serial) outcomes.current.delete(serial) if (outcome === 'found' || outcome === 'kept') return dispatch({ type: 'focus_consumed', serial }) } if (move.afterExit && !focusIsFree()) return if (move.kind === 'citations_closed') focusAfterClose(openers) else if (move.kind === 'back') backTarget(openers.section.current)?.focus() else landingOf(move, state)?.focus() }, [move, state, outcomes, dispatch, openers]) } /** The outcomes the places report for each focus request. */ function useReceipts(dispatch: Dispatch) { const outcomes = useRef(new Map()) const consumed = useCallback( (serial: number, outcome: FocusOutcome) => { outcomes.current.set(serial, outcome) dispatch({ type: 'focus_consumed', serial }) }, [dispatch], ) return { outcomes, consumed } } /** A tab choice; with the citations panel open it closes and the new tab takes the focus. */ function useTabSelect( request: ReturnType['request'], dispatch: Dispatch, open: boolean, ) { const t = useT() return useCallback( (tab: EditorTabId): boolean => { const action = { type: 'select_tab', tab } as const if (open) { const text = t(`editor.tab.${tab}`) return request({ action, kind: 'tab_selected', text }, false) } commitFocusedField() dispatch(action) return true }, [request, dispatch, open, t], ) } /** Navigation of the draft editor: the reducer plus the DOM side (focus, live region). */ export function useEditorNavigation(initialTab: EditorTabId): EditorNavigation { const [state, dispatch] = useReducer( navigationReducer, initialTab, initialNavigation, ) const { move, go, finish, live, announce } = useGo(dispatch) const openers = useRef({ citations: { current: null }, citedBy: { current: null }, section: { current: null }, }).current const canLeave = useRef(null) const exit = useCitationsExit(finish) const registerCanLeave = useCallback((guard: CanLeave | null) => { canLeave.current = guard }, []) const open = state.citationsOf !== null const receipts = useReceipts(dispatch) useMoveFocus(move, state, receipts.outcomes, dispatch, openers) const sections = useSectionMoves(go, openers) const ctx = { open, go, openers, dispatch, announce, exit, canLeave } const openCitations = useOpenCitations(ctx) const panel = useCloseMoves(ctx) return { state, live, announce, consumed: receipts.consumed, selectTab: useTabSelect(panel.request, dispatch, open), openSection: sections.openSection, backToDrawing: sections.backToDrawing, navigate: open ? panel.navigate : sections.navigate, openCitations, closeCitations: panel.closeCitations, dropCitations: panel.dropCitations, showAllReferences: panel.showAllReferences, exiting: exit.exiting, exitComplete: exit.complete, registerCanLeave, } }