feat(editor): browser history for tabs, sections and Aller a

EditorView held by the navigation reducer (restore_view), a history
adapter hook mounted in EditorWorkspace (push, replace, back, mount
rule, ownership, write budget, scroll map, refused POP), a guard stack
by layer, an announcer queue joined after open dialogs.
This commit is contained in:
bchanot committed 2026-11-13 17:57:52 +01:00
1 parent 69e225ca7a
commit 792394d3b2
11 files changed
+1268 -40

No files matched your search

+111
View File
@@ -0,0 +1,111 @@
import {
ANNOTATION_SECTIONS,
sameView,
type AnnotationSection,
type EditorView,
} from '../navigation'
import { EDITOR_TABS, type EditorTabId } from '../tabs'
/**
* What one browser history entry of the editor holds (R2F-1): the view, the view below
* it (the place a Back returns to), and whose editor wrote it. Navigation only: never
* typed text, a search term or a draft.
*/
export interface HistoryEntry {
/** Keys the scroll map: one per entry written, kept by a replace. */
id: string
view: EditorView
below: EditorView | null
sheetId: string
userId: string
}
/** The sheet and the account an entry may be restored for. */
export interface HistoryOwner {
sheetId: string
userId: string
}
/** The key of the entry inside the router's `location.state`. */
export const ENTRY_KEY = 'editorEntry'
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null
/**
* A view read back from a history entry, or null when it is no view. Vanished keys drop
* their layer: no layer is ever written yet, so the three layer fields come back null.
* shortcut: later layers validate their key against the loaded sheet here.
*/
export function sanitizeView(raw: unknown): EditorView | null {
if (!isRecord(raw)) return null
if (!EDITOR_TABS.includes(raw.tab as EditorTabId)) return null
const known = ANNOTATION_SECTIONS.includes(raw.section as AnnotationSection)
return {
tab: raw.tab as EditorTabId,
section: known ? (raw.section as AnnotationSection) : 'drawing',
finding: null,
reference: null,
referenceFilter: null,
}
}
/** The entry `state` (a `location.state`) carries, or null when it carries none. */
export function readEntry(state: unknown): HistoryEntry | null {
const raw = isRecord(state) ? state[ENTRY_KEY] : null
if (!isRecord(raw)) return null
const view = sanitizeView(raw.view)
const { id, sheetId, userId } = raw
if (!view || typeof id !== 'string') return null
if (typeof sheetId !== 'string' || typeof userId !== 'string') return null
const below = raw.below === null ? null : sanitizeView(raw.below)
return { id, view, below, sheetId, userId }
}
/** An entry restores only for the sheet and the account that wrote it. */
export function ownedEntry(
state: unknown,
owner: HistoryOwner,
): HistoryEntry | null {
const entry = readEntry(state)
const mine = entry?.sheetId === owner.sheetId && entry.userId === owner.userId
return mine ? entry : null
}
export const entryState = (entry: HistoryEntry) => ({ [ENTRY_KEY]: entry })
/** Layers over the place: a finding dialog or a reference dialog each count one. */
export function layerCount(view: EditorView): number {
return (view.finding ? 1 : 0) + (view.reference ? 1 : 0)
}
/** What a changed view asks of the history. */
export type HistoryWrite = 'none' | 'push' | 'replace' | 'back'
/**
* A user move to `view`. A layer taken away goes back when the entry holds the view the
* move lands on (the entry that opened the layer), else it replaces; a layer, tab or
* section added pushes, unless the move asked for a replace.
*/
export function planWrite(
top: HistoryEntry,
view: EditorView,
replace: boolean,
): HistoryWrite {
if (sameView(top.view, view)) return 'none'
if (layerCount(view) < layerCount(top.view)) {
return top.below && sameView(top.below, view) ? 'back' : 'replace'
}
return replace ? 'replace' : 'push'
}
/** Sliding-window budget of history writes: past it a view stays in memory. */
export function createWriteBudget(limit: number, windowMs: number) {
const stamps: number[] = []
return (now: number): boolean => {
while (stamps.length > 0 && now - stamps[0] >= windowMs) stamps.shift()
if (stamps.length >= limit) return false
stamps.push(now)
return true
}
}
@@ -0,0 +1,256 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { useLocation, useNavigate, useNavigationType } from 'react-router-dom'
import { afterModalsClosed } from '@/components/ui/afterModalsClosed'
import { focusActiveTab } from '../focusRequest'
import { sameView, type EditorView } from '../navigation'
import {
headingOf,
shownPlace,
useMoveText,
type EditorNavigation,
} from '../useEditorNavigation'
import {
createWriteBudget,
entryState,
ownedEntry,
planWrite,
type HistoryEntry,
type HistoryOwner,
} from './entry'
/** Well under WebKit's 100 history writes per 10 s: past it a view stays in memory. */
const WRITE_LIMIT = 40
const WRITE_WINDOW_MS = 10_000
/** A `back()` that never lands (nothing to go back to) stops blocking writes after this. */
const BACK_TIMEOUT_MS = 1_000
/** What the adapter keeps between renders; none of it is rendered. */
interface Book {
/** The entry on top of the history as the adapter knows it (null before the mount). */
entry: HistoryEntry | null
/** The router key last looked at, so each location is read once. */
handled: string | null
pendingBack: boolean
backTimer: ReturnType<typeof setTimeout> | undefined
/** Scroll position of the entries left, by entry id. */
scrolls: Map<string, number>
lastScroll: number
counter: number
takeWrite: (now: number) => boolean
}
function newBook(): Book {
return {
entry: null,
handled: null,
pendingBack: false,
backTimer: undefined,
scrolls: new Map(),
lastScroll: 0,
counter: 0,
takeWrite: createWriteBudget(WRITE_LIMIT, WRITE_WINDOW_MS),
}
}
/** A Back or Forward that changed the view: what the landing scrolls to, focuses and says. */
interface Landing {
entry: HistoryEntry
tabChanged: boolean
}
/**
* The writes, through the router so its own location follows. `push` over the write
* budget keeps the entry in memory only; `replace` swallows a refused write.
*/
function useWriter(book: Book, owner: HistoryOwner) {
const navigate = useNavigate()
const location = useLocation()
const latest = useRef({ navigate, location })
latest.current = { navigate, location }
return useMemo(() => {
const send = (entry: HistoryEntry, replace: boolean) => {
const { navigate, location } = latest.current
const { pathname, search, hash } = location
const to = { pathname, search, hash }
try {
navigate(to, { replace, state: entryState(entry) })
} catch {
// The view stays in memory; the next move writes again.
}
}
const fresh = (view: EditorView, below: EditorView | null) => {
book.counter += 1
return { id: `e${book.counter}`, view, below, ...owner }
}
const write = (entry: HistoryEntry, replace: boolean) => {
book.entry = entry
if (replace || book.takeWrite(Date.now())) send(entry, replace)
}
return {
push: (view: EditorView) =>
write(fresh(view, book.entry?.view ?? null), false),
replace: (view: EditorView) => {
const kept = book.entry ?? fresh(view, null)
write({ ...kept, view }, true)
},
first: (view: EditorView) => write(fresh(view, null), true),
back: () => {
book.pendingBack = true
clearTimeout(book.backTimer)
book.backTimer = setTimeout(() => {
book.pendingBack = false
}, BACK_TIMEOUT_MS)
latest.current.navigate(-1)
},
}
}, [book, owner])
}
type Writer = ReturnType<typeof useWriter>
/** User moves: the view changed, the history follows (R2F-1). */
function useReconcile(
nav: EditorNavigation,
view: EditorView,
book: Book,
writer: Writer,
) {
useEffect(() => {
const { scrollY, replace } = nav.trace
nav.trace.scrollY = null
nav.trace.replace = false
const top = book.entry
if (!top || book.pendingBack) return
const plan = planWrite(top, view, replace)
if (plan === 'none') return
book.scrolls.set(top.id, scrollY ?? window.scrollY)
if (plan === 'back') writer.back()
else if (plan === 'push') writer.push(view)
else writer.replace(view)
}, [view, nav.trace, book, writer])
}
/** The page shows something the history does not carry: a POP must not unmount it. */
function popRefused(nav: EditorNavigation): boolean {
return (
document.querySelector('dialog[open]') !== null ||
nav.state.citationsOf !== null
)
}
interface PopContext {
nav: EditorNavigation
book: Book
writer: Writer
owner: HistoryOwner
defaultView: EditorView
view: EditorView
}
/** The entry of a Back or Forward is not this editor's: the default view replaces it. */
function landOnForeign(ctx: PopContext): Landing | null {
const { nav, writer, defaultView, book } = ctx
writer.first(defaultView)
nav.restoreView(defaultView)
return book.entry && { entry: book.entry, tabChanged: true }
}
/** What the page does with the entry a Back or Forward landed on. */
function landOn(ctx: PopContext, state: unknown): Landing | null {
const { nav, book, writer, owner, view } = ctx
if (book.entry) book.scrolls.set(book.entry.id, book.lastScroll)
const expected = book.pendingBack
book.pendingBack = false
clearTimeout(book.backTimer)
const entry = ownedEntry(state, owner)
if (!entry) return landOnForeign(ctx)
if (!expected && popRefused(nav)) {
// The dirty form, if any, says so itself; the page keeps everything mounted.
nav.guards.askAll(false)
book.entry = entry
writer.push(view)
return null
}
book.entry = entry
if (sameView(entry.view, view)) return null
nav.restoreView(entry.view)
return { entry, tabChanged: entry.view.tab !== view.tab }
}
/** The first location of the editor: an entry of this sheet and account is kept, else replaced. */
function mount(ctx: PopContext, state: unknown): void {
const entry = ownedEntry(state, ctx.owner)
if (entry) ctx.book.entry = entry
else ctx.writer.first(ctx.view)
}
/** Scroll, focus and announcement once a Back or Forward has restored a view. */
function useLanding(
nav: EditorNavigation,
book: Book,
landing: Landing | null,
) {
const moveText = useMoveText()
const { announce } = nav
const landed = useRef<Landing | null>(null)
useEffect(() => {
// A new wording (locale switch) re-creates `moveText`: the landing stays one.
if (!landing || landed.current === landing) return
landed.current = landing
const { entry, tabChanged } = landing
const { tab, section } = entry.view
return afterModalsClosed(() => {
window.scrollTo(0, book.scrolls.get(entry.id) ?? 0)
const heading = tabChanged ? null : headingOf(shownPlace(entry.view))
if (heading) heading.focus({ preventScroll: true })
else focusActiveTab({ preventScroll: true })
const shown = tab === 'annotations' ? section : null
announce(moveText({ place: 'tab', tab, section: shown, key: null }))
})
}, [landing, book, announce, moveText])
}
/**
* The browser's history of the editor (R2F-1), kept in step with the view the navigation
* reducer holds. A move dispatches at once and the history follows from one effect that
* compares the view with the last entry this adapter wrote (a ref, never `useLocation()`,
* which lags a transition). A Back or Forward restores the view of the entry it lands on,
* unless a dialog or the citations panel is open: then the pre-move view is pushed back.
* Foreign entries (another sheet, another account) and entries without a view are replaced
* by the default view.
*/
export default function useEditorHistory(
nav: EditorNavigation,
owner: HistoryOwner,
defaultView: EditorView,
): void {
const location = useLocation()
const navType = useNavigationType()
const bookRef = useRef<Book | null>(null)
const book = (bookRef.current ??= newBook())
const writer = useWriter(book, owner)
const [landing, setLanding] = useState<Landing | null>(null)
const { tab, section, finding, reference, referenceFilter } = nav.state
const view = useMemo(
() => ({ tab, section, finding, reference, referenceFilter }),
[tab, section, finding, reference, referenceFilter],
)
const ctx = { nav, book, writer, owner, defaultView, view }
useEffect(() => {
if (book.handled === location.key) return
book.handled = location.key
if (book.entry === null) mount(ctx, location.state)
else if (navType === 'POP') setLanding(landOn(ctx, location.state))
// Read once per location: the context is the one this render holds.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [location.key])
useReconcile(nav, view, book, writer)
useLanding(nav, book, landing)
useEffect(() => {
const onScroll = () => {
book.lastScroll = window.scrollY
}
window.addEventListener('scroll', onScroll, { passive: true })
return () => window.removeEventListener('scroll', onScroll)
}, [book])
}
+80 -5
View File
@@ -26,9 +26,24 @@ export interface FocusRequest {
serial: number
}
export interface NavigationState {
/**
* What the browser history records of the editor (R2F-1): where the user is, never what
* they typed. A layer (`finding`, `reference`) is a dialog over a place; `referenceFilter`
* narrows the references library to the citers of an element. Only `tab` and `section`
* are ever set so far: the three others are the room later layers fill.
*/
export interface EditorView {
tab: EditorTabId
section: AnnotationSection
finding:
| { key: ElementKey; citations: boolean }
| { create: { kind: string; parent: ElementKey | null } }
| null
reference: { edit: string } | { create: true } | null
referenceFilter: ElementKey | null
}
export interface NavigationState extends EditorView {
/** The finding whose citations panel is open; null while it is closed. */
citationsOf: ElementKey | null
/** Bumped by `show_all_references`: the library resets its search once per bump. */
@@ -49,6 +64,7 @@ export type NavigationAction =
| { type: 'close_citations' }
| { type: 'show_all_references' }
| { type: 'go_to'; target: EditorTarget }
| { type: 'restore_view'; view: EditorView }
| { type: 'focus_consumed'; serial: number }
const TAB_OF_KIND = {
@@ -97,11 +113,33 @@ function shown(state: NavigationState): NavigationState {
return { ...state, visitedTabs, visitedSections }
}
export function initialNavigation(tab: EditorTabId): NavigationState {
const DEFAULT_VIEW = {
section: 'drawing',
finding: null,
reference: null,
referenceFilter: null,
} as const
/** The finding whose citations panel the view shows, null when it shows none. */
function citationsOfView(view: EditorView): ElementKey | null {
const { finding } = view
return finding && 'key' in finding && finding.citations ? finding.key : null
}
/** The view a fresh editor shows on `tab`: the drawing, no layer. */
export function defaultView(tab: EditorTabId): EditorView {
return { ...DEFAULT_VIEW, tab }
}
/** `view` (a history entry read at mount) or the plain default view of `tab`. */
export function initialNavigation(
tab: EditorTabId,
view?: EditorView | null,
): NavigationState {
const start = view ?? defaultView(tab)
return shown({
tab,
section: 'drawing',
citationsOf: null,
...start,
citationsOf: citationsOfView(start),
libraryReset: 0,
visitedTabs: [],
visitedSections: [],
@@ -110,6 +148,41 @@ export function initialNavigation(tab: EditorTabId): NavigationState {
})
}
/** The part of the state the browser history records. */
export function viewOf(state: NavigationState): EditorView {
const { tab, section, finding, reference, referenceFilter } = state
return { tab, section, finding, reference, referenceFilter }
}
/**
* The same place for the history: a section only counts on Annotations (the other tabs
* keep the last one in memory, nobody sees it).
*/
export function sameView(a: EditorView, b: EditorView): boolean {
const section = a.tab !== 'annotations' || a.section === b.section
return (
a.tab === b.tab &&
section &&
JSON.stringify([a.finding, a.reference, a.referenceFilter]) ===
JSON.stringify([b.finding, b.reference, b.referenceFilter])
)
}
/** A Back or Forward landed on `view`: the page shows it, no request to answer. */
function restoreView(
state: NavigationState,
view: EditorView,
): NavigationState {
const section = view.tab === 'annotations' ? view.section : state.section
return shown({
...state,
...view,
section,
citationsOf: citationsOfView(view),
focus: undefined,
})
}
/**
* A finding node (kind `finding` below its family, path of two or more ids). A zone and a
* family list their citations inline and have no panel.
@@ -166,6 +239,8 @@ export function navigationReducer(
return showAllReferences(state)
case 'go_to':
return goTo(state, action.target)
case 'restore_view':
return restoreView(state, action.view)
case 'focus_consumed':
return state.focus?.serial === action.serial
? { ...state, focus: undefined }
+128 -28
View File
@@ -1,6 +1,7 @@
import {
useCallback,
useEffect,
useMemo,
useReducer,
useRef,
useState,
@@ -8,6 +9,7 @@ import {
type RefObject,
} from 'react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import { afterModalsClosed } from '@/components/ui/afterModalsClosed'
import { useT } from '@/i18n/useT'
import {
commitFocusedField,
@@ -23,6 +25,7 @@ import {
navigationReducer,
type AnnotationSection,
type EditorTarget,
type EditorView,
type NavigationAction,
type NavigationState,
} from './navigation'
@@ -55,6 +58,34 @@ export interface LeaveAnswer {
}
export type CanLeave = (forced: boolean) => LeaveAnswer
/** The layers that can hold a form the user must settle before leaving, top one last. */
const LAYERS = ['citations', 'finding', 'reference'] as const
export type LayerName = (typeof LAYERS)[number]
/** One guard per layer (R2F-1): each layer registers its own check while it is mounted. */
export interface Guards {
register: (layer: LayerName, guard: CanLeave | null) => void
/** The answer of one layer; allowed when the layer registered nothing. */
ask: (layer: LayerName, forced: boolean) => LeaveAnswer
/** The layers asked top down; one refusal refuses, and each one still shows its own. */
askAll: (forced: boolean) => LeaveAnswer
}
/**
* What a move leaves for the history adapter to read once the view has changed: the
* scroll position taken before the dispatch, and whether the move replaces its entry
* (an arrow-key tab move) instead of adding one. The adapter resets it.
*/
export interface MoveTrace {
scrollY: number | null
replace: boolean
}
/** Options of a tab choice. */
export interface SelectOptions {
replace?: boolean
}
type Opener = HTMLElement | null | undefined
export interface EditorNavigation {
@@ -63,7 +94,7 @@ export interface EditorNavigation {
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
selectTab: (tab: EditorTabId, options?: SelectOptions) => boolean
openSection: (section: AnnotationSection, opener?: Opener) => void
backToDrawing: () => void
/** Opens the citations panel of a finding node; any other key is ignored. */
@@ -78,8 +109,12 @@ export interface EditorNavigation {
exiting: boolean
/** The panel's `onExitComplete`: applies the pending move. */
exitComplete: () => void
/** The panel hands its `canLeave` over while it is mounted (P22''). */
/** The citations panel hands its `canLeave` over while it is mounted (P22''). */
registerCanLeave: (guard: CanLeave | null) => void
guards: Guards
trace: MoveTrace
/** A Back or Forward landed on `view` (the history adapter's way in): no move, no request. */
restoreView: (view: EditorView) => void
consumed: (serial: number, outcome: FocusOutcome) => void
announce: (text: string) => void
}
@@ -87,7 +122,7 @@ export interface EditorNavigation {
const isShown = (element: HTMLElement | null): boolean =>
element !== null && element.isConnected && !element.closest('[hidden]')
const headingOf = (place: PlaceName) =>
export const headingOf = (place: PlaceName) =>
visibleElement(`[data-place="${place}"] [data-place-heading]`)
export const CANVAS_BOX =
@@ -99,14 +134,16 @@ const tabButton = (tab: EditorTabId) =>
document.getElementById(MORE_BUTTON_ID)
/** The place the shown tab and section name. */
function shownPlace(state: NavigationState): PlaceName {
export function shownPlace(
state: Pick<EditorView, 'tab' | 'section'>,
): 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 {
export function useMoveText(): (target: EditorTarget) => string {
const t = useT()
return useCallback(
(target) => {
@@ -118,14 +155,59 @@ function useMoveText(): (target: EditorTarget) => string {
)
}
/**
* The live region's text. While a modal dialog is open the page is inert and a screen
* reader would drop the message: what is said meanwhile waits, then goes out as ONE
* announcement once the last dialog has closed.
*/
function useLiveRegion() {
const [live, setLive] = useState('')
const queued = useRef<string[]>([])
const announce = useCallback((text: string) => {
setLive((previous) => (previous === text ? `${text} ` : text))
queued.current.push(text)
if (queued.current.length > 1) return
afterModalsClosed(() => {
const joined = queued.current.splice(0).join('. ')
setLive((previous) => (previous === joined ? `${joined} ` : joined))
})
}, [])
return { live, announce }
}
/** The guards of the open layers, keyed by layer so a re-registration keeps its place. */
function useGuards(): Guards {
const guards = useRef(new Map<LayerName, CanLeave>()).current
return useMemo(() => {
const ask = (layer: LayerName, forced: boolean): LeaveAnswer =>
guards.get(layer)?.(forced) ?? { allowed: true }
return {
register: (layer, guard) => {
if (guard) guards.set(layer, guard)
else guards.delete(layer)
},
ask,
askAll: (forced) => {
const answers = [...LAYERS].reverse().map((l) => ask(l, forced))
const notes = answers.flatMap((a) => (a.note ? [a.note] : []))
const note = notes.length > 0 ? notes.join('. ') : undefined
return { allowed: answers.every((a) => a.allowed), note }
},
}
}, [guards])
}
function useMoveTrace() {
const trace = useRef<MoveTrace>({ scrollY: null, replace: false }).current
const mark = useCallback(
(replace = false) => {
trace.scrollY = window.scrollY
trace.replace = replace
},
[trace],
)
return { trace, mark }
}
interface Openers {
/** The trigger that opened the citations panel, and the finding it belongs to. */
citations: RefObject<HTMLElement | null>
@@ -139,25 +221,28 @@ 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<NavigationAction>) {
function useGo(dispatch: Dispatch<NavigationAction>, trace: MoveTrace) {
const { live, announce } = useLiveRegion()
const [move, setMove] = useState<Move | null>(null)
const finish = useCallback(
(move: PendingClose) => {
announce(move.note ? `${move.note}. ${move.text}` : move.text)
trace.scrollY = window.scrollY
dispatch(move.action)
setMove({ kind: move.kind, afterExit: true })
},
[announce, dispatch],
[announce, dispatch, trace],
)
const go: Go = useCallback(
(action, kind, text) => {
commitFocusedField()
announce(text)
trace.scrollY = window.scrollY
trace.replace = false
dispatch(action)
setMove({ kind })
},
[announce, dispatch],
[announce, dispatch, trace],
)
return { move, go, finish, live, announce }
}
@@ -195,7 +280,8 @@ interface PanelContext {
dispatch: Dispatch<NavigationAction>
announce: (text: string) => void
exit: ReturnType<typeof useCitationsExit>
canLeave: RefObject<CanLeave | null>
guards: Guards
mark: (replace?: boolean) => void
}
/**
@@ -204,22 +290,23 @@ interface PanelContext {
* 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 { open, exit, guards, mark } = ctx
const { busy, record } = exit
return useCallback(
(move: PendingClose, forced: boolean): boolean => {
if (!open) return true
mark()
if (busy()) {
record(move)
return true
}
commitFocusedField()
const { allowed, note } = canLeave.current?.(forced) ?? { allowed: true }
const { allowed, note } = guards.ask('citations', forced)
if (!allowed) return false
record(note ? { ...move, note } : move)
return true
},
[open, busy, record, canLeave],
[open, busy, record, guards, mark],
)
}
@@ -375,46 +462,53 @@ function useTabSelect(
request: ReturnType<typeof useCloseMoves>['request'],
dispatch: Dispatch<NavigationAction>,
open: boolean,
mark: (replace?: boolean) => void,
) {
const t = useT()
return useCallback(
(tab: EditorTabId): boolean => {
(tab: EditorTabId, options?: SelectOptions): 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)
const allowed = request({ action, kind: 'tab_selected', text }, false)
if (allowed) mark(options?.replace)
return allowed
}
commitFocusedField()
mark(options?.replace)
dispatch(action)
return true
},
[request, dispatch, open, t],
[request, dispatch, open, t, mark],
)
}
/** 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,
export function useEditorNavigation(
initialTab: EditorTabId,
initialView?: EditorView | null,
): EditorNavigation {
const [state, dispatch] = useReducer(navigationReducer, null, () =>
initialNavigation(initialTab, initialView),
)
const { move, go, finish, live, announce } = useGo(dispatch)
const { trace, mark } = useMoveTrace()
const { move, go, finish, live, announce } = useGo(dispatch, trace)
const openers = useRef<Openers>({
citations: { current: null },
citedBy: { current: null },
section: { current: null },
}).current
const canLeave = useRef<CanLeave | null>(null)
const guards = useGuards()
const exit = useCitationsExit(finish)
const registerCanLeave = useCallback((guard: CanLeave | null) => {
canLeave.current = guard
}, [])
const registerCanLeave = useCallback(
(guard: CanLeave | null) => guards.register('citations', guard),
[guards],
)
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 ctx = { open, go, openers, dispatch, announce, exit, guards, mark }
const openCitations = useOpenCitations(ctx)
const panel = useCloseMoves(ctx)
return {
@@ -422,7 +516,7 @@ export function useEditorNavigation(initialTab: EditorTabId): EditorNavigation {
live,
announce,
consumed: receipts.consumed,
selectTab: useTabSelect(panel.request, dispatch, open),
selectTab: useTabSelect(panel.request, dispatch, open, mark),
openSection: sections.openSection,
backToDrawing: sections.backToDrawing,
navigate: open ? panel.navigate : sections.navigate,
@@ -433,5 +527,11 @@ export function useEditorNavigation(initialTab: EditorTabId): EditorNavigation {
exiting: exit.exiting,
exitComplete: exit.complete,
registerCanLeave,
guards,
trace,
restoreView: useCallback(
(view: EditorView) => dispatch({ type: 'restore_view', view }),
[],
),
}
}