feat(editor): finding dialog and citations side sheet in the history

Constats opens each element in one modal dialog (view, edit with a
local draft, creation) driven by the editor view layer of the browser
history. The citations panel becomes a modal side sheet stacked over
it; its geometry, exit machinery and page inertness are removed.
Back and Forward restore the layers, a dirty form asks first.
This commit is contained in:
bchanot committed 2026-11-13 18:51:35 +01:00
1 parent 8e4f02620a
commit 18085cecf8
50 files changed
+2642 -1504

No files matched your search

+1 -3
View File
@@ -7,7 +7,6 @@ import {
isTextField,
visibleElement,
} from '@/editor/focusRequest'
import { ReferencesOpenContext } from '@/editor/editingContext'
import { CANVAS_BOX } from '@/editor/useEditorNavigation'
import { useT } from '@/i18n/useT'
@@ -102,8 +101,7 @@ export function useSelectionEscape(
) {
const asideRef = useRef<HTMLElement>(null)
const deselect = useDeselect(id, clear)
const citationsOf = useContext(ReferencesOpenContext)
useEscapeDeselect(active && citationsOf === null, (event) =>
useEscapeDeselect(active, (event) =>
deselect.byKey(asideRef.current?.contains(event.target as Node) ?? false),
)
return { asideRef, byDrawing: deselect.byDrawing }
+11 -12
View File
@@ -1,31 +1,30 @@
import { createContext, useContext, useState } from 'react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import type { EditorMode } from './mode'
import { usePlaceVisible } from '@/lib/placeVisibility'
/** The editor cannot be edited now (route rule: mode, recovery, store not in step). */
export const ReadOnlyContext = createContext(false)
/**
* The finding whose citations panel is open, null when none. Set from the opening to the
* end of the exit animation: a place beside the panel is not where a modal may open, and
* only that finding's trigger reads « expanded ».
*/
export const ReferencesOpenContext = createContext<ElementKey | null>(null)
/** Why the editor is read-only, or `edit`: a kept form words its notice from it. */
export const EditorModeContext = createContext<EditorMode>('edit')
export function useEditorMode(): EditorMode {
return useContext(EditorModeContext)
}
export function useEditorReadOnly(): boolean {
return useContext(ReadOnlyContext)
}
/**
* Whether a decision dialog of a kept part may open: only while editing, in a shown
* place, with the citations panel closed, so no native modal ever sits inside a hidden
* subtree and focus is never lost to `body`.
* Whether a decision dialog of a kept part may open: only while editing and in a shown
* place, so no native modal ever sits inside a hidden subtree and focus is never lost
* to `body`.
*/
export function useDecisionsOpen(): boolean {
const readOnly = useContext(ReadOnlyContext)
const citationsOf = useContext(ReferencesOpenContext)
const visible = usePlaceVisible()
return !readOnly && visible && citationsOf === null
return !readOnly && visible
}
/**
+16
View File
@@ -0,0 +1,16 @@
import type { FindingLayer } from './tabs'
import type { EditorNavigation } from './useEditorNavigation'
/** What Constats needs of the navigation for its dialog and the sheet over it. */
export function findingLayerOf(nav: EditorNavigation): FindingLayer {
return {
view: nav.state.finding,
guards: nav.guards,
open: nav.openFinding,
start: nav.startFinding,
close: nav.closeFinding,
replace: nav.replaceFinding,
openCitations: nav.openCitations,
announce: nav.announce,
}
}
+11
View File
@@ -246,6 +246,17 @@ export function createdItemId(
return itemId(parent.zoneId, path)
}
/** The key of a just-inserted element, appended under `parent` (null = a zone). */
export function createdKey(
kind: FindingKind,
parent: FindingItem | null,
id: string,
): ElementKey {
if (kind === 'zone' || !parent) return { kind: 'zone', id }
const path = kind === 'category' ? [id] : [...parent.path, id]
return { kind: 'finding', zone_id: parent.zoneId, path }
}
/** The item a focus request names (a zone or a finding), with its ancestors' ids. */
export function itemForKey(
items: readonly FindingItem[],
+40 -12
View File
@@ -1,5 +1,6 @@
import { createContext, useContext, useEffect, useRef } from 'react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import { afterModalsClosed } from '@/components/ui/afterModalsClosed'
import type {
AnnotationSection,
EditorTarget,
@@ -82,21 +83,34 @@ export function visibleElement(
)
}
/** The visible row tagged with `key`. */
function rowOf(key: ElementKey): HTMLElement | null {
const wanted = JSON.stringify(key)
return visibleElement(
'[data-focus-key]',
(candidate) => candidate.dataset.focusKey === wanted,
)
}
/** Scrolls to and focuses the visible row tagged with `key`; false unless the row now holds the focus. */
export function focusRow(key: ElementKey): boolean {
const wanted = JSON.stringify(key)
const row = [
...document.querySelectorAll<HTMLElement>('[data-focus-key]'),
].find(
(candidate) =>
candidate.dataset.focusKey === wanted && !candidate.closest('[hidden]'),
)
const row = rowOf(key)
if (!row) return false
row.scrollIntoView?.({ block: 'center' })
row.focus()
return document.activeElement === row
}
/**
* The row is there: its focus waits for the dialogs a move closed (the page behind them
* is inert until then). False when no visible row carries `key`.
*/
export function focusRowLater(key: ElementKey): boolean {
if (!rowOf(key)) return false
afterModalsClosed(() => void focusRow(key))
return true
}
/** Row-based places (Général, Vues, Catégories, Régions): focus the named row. */
export function useRowFocus(focus: FocusRequest | undefined): void {
useFocusRequest(focus, (target) =>
@@ -132,13 +146,17 @@ export function isTextField(target: EventTarget | null): boolean {
/**
* Commits the text being typed before a place is left: blurs the focused field, so its
* `TextField` commits on blur. Safari and iPadOS do not move the focus to a tapped button,
* so the blur is forced rather than assumed. Answers whether a field was blurred.
* so the blur is forced rather than assumed. A field of a transactional form
* (`data-draft-form`) is a local draft nothing commits: it keeps its focus. Answers
* whether a field was blurred.
*/
export function commitFocusedField(): boolean {
const active = document.activeElement
const isField = isTextField(active)
if (isField) (active as HTMLElement).blur()
return isField
if (!isTextField(active)) return false
const field = active as HTMLElement
if (field.closest('[data-draft-form]')) return false
field.blur()
return true
}
/** The tab shown, or « Plus » while the shown tab sits in the closed list. */
@@ -154,6 +172,15 @@ export function focusActiveTab(options?: FocusOptions): void {
activeTabButton()?.focus(options)
}
/**
* The element sits in a transactional form of an open dialog: the form keeps its draft
* and its focus when the editor turns read-only, nothing moves it. (The citations
* sheet's tiles still edit inline until the reference dialog: they are not drafts.)
*/
function inOpenDialog(element: HTMLElement): boolean {
return element.closest('dialog[open] [data-draft-form]') !== null
}
/** The element holding the focus, when it is something other than `body`. */
export function heldElement(): HTMLElement | null {
const active = document.activeElement
@@ -178,7 +205,7 @@ export function refocusIfHidden(
held: HTMLElement | null,
home: HTMLElement | null = null,
): void {
if (!held) return
if (!held || inOpenDialog(held)) return
const gone = !held.isConnected || held.closest('[hidden]')
if (!gone && document.activeElement !== held) held.focus()
if (!gone && document.activeElement === held) return
@@ -193,6 +220,7 @@ export function refocusIfHidden(
*/
export function releaseEditFocus(): void {
const held = heldElement()
if (held && inOpenDialog(held)) return
commitFocusedField()
refocusIfHidden(held)
}
+60 -8
View File
@@ -1,5 +1,7 @@
import type { ElementKey } from '@faunosteo/core-wasm/types'
import {
ANNOTATION_SECTIONS,
isFindingNode,
sameView,
type AnnotationSection,
type EditorView,
@@ -32,24 +34,66 @@ export const ENTRY_KEY = 'editorEntry'
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null
/** A finding or zone key as the tree builds it, or null when `raw` is no such key. */
function sanitizeKey(raw: unknown): ElementKey | null {
if (!isRecord(raw)) return null
if (raw.kind === 'zone' && typeof raw.id === 'string') {
return { kind: 'zone', id: raw.id }
}
const { zone_id: zoneId, path } = raw
const ids = Array.isArray(path) && path.every((id) => typeof id === 'string')
if (raw.kind !== 'finding' || typeof zoneId !== 'string' || !ids) return null
return { kind: 'finding', zone_id: zoneId, path: path as string[] }
}
const CREATION_KINDS = ['zone', 'category', 'node']
/** A finding creation, a form: only read back where forms are kept. */
function sanitizeCreation(raw: unknown): EditorView['finding'] {
if (!isRecord(raw) || !isRecord(raw.create)) return null
const { kind, parent } = raw.create
if (typeof kind !== 'string' || !CREATION_KINDS.includes(kind)) return null
const key = parent === null ? null : sanitizeKey(parent)
if (parent !== null && key === null) return null
return { create: { kind, parent: key } }
}
/** The finding layer of a view: its dialog, with its citations sheet over it. */
function sanitizeFinding(raw: unknown, forms: boolean): EditorView['finding'] {
if (!isRecord(raw)) return null
if ('create' in raw) return forms ? sanitizeCreation(raw) : null
const key = sanitizeKey(raw.key)
if (!key) return null
const sheet = raw.citations === true && isFindingNode(key)
return { key, citations: sheet }
}
/**
* 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.
* A view read back from a history entry, or null when it is no view. The finding layer
* must name a well-formed key and sit on the Constats tab; whether the element still
* exists is the dialog's own gone rule. `forms` false drops the creation form (a reload
* never reopens a form). The reference layer and the filter stay null until they exist.
*/
export function sanitizeView(raw: unknown): EditorView | null {
export function sanitizeView(raw: unknown, forms = true): 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)
const finding =
raw.tab === 'findings' ? sanitizeFinding(raw.finding, forms) : null
return {
tab: raw.tab as EditorTabId,
section: known ? (raw.section as AnnotationSection) : 'drawing',
finding: null,
finding,
reference: null,
referenceFilter: null,
}
}
/** The view a reload shows for an entry: its reading layers, never a form. */
export function withoutForms(view: EditorView): EditorView {
return sanitizeView(view, false) ?? view
}
/** 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
@@ -76,9 +120,14 @@ export function ownedEntry(
export const entryState = (entry: HistoryEntry) => ({ [ENTRY_KEY]: entry })
/** Layers over the place: a finding dialog or a reference dialog each count one. */
/**
* Layers over the place: the finding dialog and the citations sheet over it, the
* reference dialog, each count one.
*/
export function layerCount(view: EditorView): number {
return (view.finding ? 1 : 0) + (view.reference ? 1 : 0)
const { finding } = view
const sheet = finding && 'key' in finding && finding.citations
return (finding ? 1 : 0) + (sheet ? 1 : 0) + (view.reference ? 1 : 0)
}
/** An Annotations section other than the drawing is a step over it, like a layer. */
@@ -88,6 +137,8 @@ function isStepOver(view: EditorView): boolean {
/** True when the move took a layer away, or left a section for its drawing. */
function isRemoval(top: EditorView, view: EditorView): boolean {
// Another tab is a move of its own (« Tout afficher », « Aller à »): it pushes.
if (view.tab !== top.tab) return false
if (layerCount(view) < layerCount(top)) return true
const backToDrawing = view.tab === top.tab && isStepOver(top)
return backToDrawing && !isStepOver(view) && layerCount(view) === 0
@@ -108,10 +159,11 @@ export function planWrite(
replace: boolean,
): HistoryWrite {
if (sameView(top.view, view)) return 'none'
if (replace) return 'replace'
if (isRemoval(top.view, view)) {
return top.below && sameView(top.below, view) ? 'back' : 'replace'
}
return replace ? 'replace' : 'push'
return 'push'
}
/** Sliding-window budget of history writes: past it a view stays in memory. */
+71 -31
View File
@@ -14,6 +14,7 @@ import {
entryState,
ownedEntry,
planWrite,
withoutForms,
type HistoryEntry,
type HistoryOwner,
} from './entry'
@@ -28,8 +29,8 @@ const BACK_TIMEOUT_MS = 1_000
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
/** The router location last read: each location object is read once (see `usePop`). */
seen: object | null
pendingBack: boolean
backTimer: ReturnType<typeof setTimeout> | undefined
/** Scroll position of the entries left, by entry id. */
@@ -41,7 +42,7 @@ interface Book {
function newBook(): Book {
return {
entry: null,
handled: null,
seen: null,
pendingBack: false,
backTimer: undefined,
scrolls: new Map(),
@@ -54,6 +55,8 @@ function newBook(): Book {
interface Landing {
entry: HistoryEntry
tabChanged: boolean
/** A dialog opened or closed: its own focus (first control, return target) stands. */
layerChanged: boolean
}
/**
@@ -131,14 +134,29 @@ function useReconcile(
}, [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 {
/** The layers (dialogs) two views show: a POP between them opens or closes a dialog. */
function sameLayers(a: EditorView, b: EditorView): boolean {
return (
document.querySelector('dialog[open]') !== null ||
nav.state.citationsOf !== null
JSON.stringify([a.finding, a.reference]) ===
JSON.stringify([b.finding, b.reference])
)
}
/**
* A POP the page must not follow: a modal that is no layer is open (its place-scoped
* state is not in the history), or a dirty layer would be removed. Either way the layers
* are asked, so a dirty form shows its own confirmation.
*/
function popRefused(ctx: PopContext, entry: HistoryEntry | null): boolean {
const { nav, view, defaultView } = ctx
if (document.querySelector('dialog[open]:not([data-layer])')) {
nav.guards.askAll(false)
return true
}
if (sameLayers(entry?.view ?? defaultView, view)) return false
return !nav.guards.askAll(false).allowed
}
interface PopContext {
nav: EditorNavigation
book: Book
@@ -153,47 +171,65 @@ 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 }
return (
book.entry && { entry: book.entry, tabChanged: true, layerChanged: false }
)
}
/**
* Something the history does not carry is on screen: the view stays, the pre-POP view is
* pushed again above the entry landed on. A dirty form shows its own confirmation.
* pushed again above the entry landed on.
*/
function refusePop(ctx: PopContext, landed: HistoryEntry | null): null {
const { nav, book, writer, view } = ctx
nav.guards.askAll(false)
const { book, writer, view } = ctx
if (landed) book.entry = landed
writer.push(view)
return null
}
/** What the page does with the entry a Back or Forward landed on. */
function landOn(ctx: PopContext, state: unknown): Landing | null {
const { nav, book, owner, view } = ctx
// Scrolling is manual while the editor is mounted: the leaving page's offset is intact.
if (book.entry) book.scrolls.set(book.entry.id, window.scrollY)
/** A `back()` this adapter asked for is expected: reads and clears the flag. */
function takePendingBack(book: Book): boolean {
const expected = book.pendingBack
book.pendingBack = false
clearTimeout(book.backTimer)
const entry = ownedEntry(state, owner)
if (!expected && popRefused(nav)) return refusePop(ctx, entry)
return expected
}
/** What the page does with the entry a Back or Forward landed on. */
function landOn(ctx: PopContext, state: unknown): Landing | null {
const { nav, book, view } = ctx
// Scrolling is manual while the editor is mounted: the leaving page's offset is intact.
if (book.entry) book.scrolls.set(book.entry.id, window.scrollY)
const expected = takePendingBack(book)
const entry = ownedEntry(state, ctx.owner)
if (!expected && popRefused(ctx, entry)) return refusePop(ctx, entry)
if (!entry) return landOnForeign(ctx)
book.entry = entry
if (sameView(entry.view, view)) return null
nav.restoreView(entry.view)
return { entry, tabChanged: entry.view.tab !== view.tab }
return {
entry,
tabChanged: entry.view.tab !== view.tab,
layerChanged: !sameLayers(entry.view, view),
}
}
/** The first location of the editor: an entry of this sheet and account is kept, else replaced. */
/**
* The first location of the editor: an entry of this sheet and account is kept (a
* reload never reopens a form, so a form layer is replaced by the view without it),
* any other is replaced by the current view.
*/
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)
if (!entry) return ctx.writer.first(ctx.view)
ctx.book.entry = entry
const kept = withoutForms(entry.view)
if (!sameView(kept, entry.view)) ctx.writer.replace(kept)
}
/** Focus after a Back or Forward: the tab button, or the heading of a section reached. */
function landFocus({ entry, tabChanged }: Landing): void {
function landFocus({ entry, tabChanged, layerChanged }: Landing): void {
if (layerChanged && !tabChanged) return
const heading = tabChanged ? null : headingOf(shownPlace(entry.view))
if (heading) heading.focus({ preventScroll: true })
else focusActiveTab({ preventScroll: true })
@@ -215,6 +251,7 @@ function useLanding(
return afterModalsClosed(() => {
window.scrollTo(0, book.scrolls.get(id) ?? 0)
landFocus(landing)
if (landing.layerChanged && !landing.tabChanged) return
const section = view.tab === 'annotations' ? view.section : null
nav.announce(
moveText({ place: 'tab', tab: view.tab, section, key: null }),
@@ -246,23 +283,25 @@ function useManualScroll(): void {
}, [])
}
/** Each new location is read once: the first is the mount, a POP after it is a landing. */
/**
* Each new location is read once: the first is the mount, a POP after it is a landing.
* The router makes a new location object per navigation, so a Back onto a key this
* adapter already read (the entry it mounted on, or one whose push never rendered) is a
* new object and is read; the second run of an effect (StrictMode) sees the same one.
*/
function usePop(ctx: PopContext): Landing | null {
const location = useLocation()
const navType = useNavigationType()
const [landing, setLanding] = useState<Landing | null>(null)
const { book } = ctx
useEffect(() => {
// The type is part of the stamp: a POP back onto a key this adapter pushed, with the
// transition of a later push never rendered, is still a landing to read.
const stamp = `${location.key}|${navType}`
if (book.handled === stamp) return
book.handled = stamp
if (book.seen === location) return
book.seen = location
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, navType])
}, [location])
return landing
}
@@ -271,7 +310,8 @@ function usePop(ctx: PopContext): Landing | null {
* 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.
* unless a modal that is no layer is open or a dirty layer would go: 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.
*/
+46 -16
View File
@@ -28,9 +28,10 @@ export interface FocusRequest {
/**
* 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.
* they typed. A layer (`finding`, `reference`) is a dialog over a place; `citations` is
* the side sheet over the finding dialog; `referenceFilter` narrows the references
* library to the citers of an element. `reference` and `referenceFilter` stay null until
* the reference dialog and the filter exist.
*/
export interface EditorView {
tab: EditorTabId
@@ -44,8 +45,6 @@ export interface EditorView {
}
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. */
libraryReset: number
/** Places already shown, so a body mounts on first visit and stays mounted. */
@@ -60,6 +59,9 @@ export type NavigationAction =
| { type: 'select_tab'; tab: EditorTabId }
| { type: 'open_section'; section: AnnotationSection }
| { type: 'back_to_drawing' }
| { type: 'open_finding'; key: ElementKey }
| { type: 'create_finding'; kind: string; parent: ElementKey | null }
| { type: 'close_finding' }
| { type: 'open_citations'; citedBy: ElementKey }
| { type: 'close_citations' }
| { type: 'show_all_references' }
@@ -120,8 +122,8 @@ const DEFAULT_VIEW = {
referenceFilter: null,
} as const
/** The finding whose citations panel the view shows, null when it shows none. */
function citationsOfView(view: EditorView): ElementKey | null {
/** The finding whose citations sheet the view shows, null when it shows none. */
export function citationsOfView(view: EditorView): ElementKey | null {
const { finding } = view
return finding && 'key' in finding && finding.citations ? finding.key : null
}
@@ -139,7 +141,6 @@ export function initialNavigation(
const start = view ?? defaultView(tab)
return shown({
...start,
citationsOf: citationsOfView(start),
libraryReset: 0,
visitedTabs: [],
visitedSections: [],
@@ -178,7 +179,6 @@ function restoreView(
...state,
...view,
section,
citationsOf: citationsOfView(view),
focus: undefined,
})
}
@@ -191,9 +191,31 @@ export function isFindingNode(key: ElementKey): boolean {
return key.kind === 'finding' && key.path.length > 1
}
/** Only a finding node has a citations panel: any other key leaves the state as it is. */
/** Only a finding node has a citations sheet: any other key leaves the state as it is. */
function openCitations(state: NavigationState, citedBy: ElementKey) {
return isFindingNode(citedBy) ? { ...state, citationsOf: citedBy } : state
const finding = { key: citedBy, citations: true }
return isFindingNode(citedBy) ? shown({ ...state, finding }) : state
}
/** Closes the sheet only: the finding dialog under it stays. */
function closeCitations(state: NavigationState): NavigationState {
const { finding } = state
if (!finding || !('key' in finding)) return state
return { ...state, finding: { key: finding.key, citations: false } }
}
/** The finding dialog of `key`, in view mode, on the Constats tab. */
function openFinding(state: NavigationState, key: ElementKey): NavigationState {
const finding = { key, citations: false }
return shown({ ...state, tab: 'findings', finding })
}
/** The creation form of a zone, a category or a node, on the Constats tab. */
function createFinding(
state: NavigationState,
create: { kind: string; parent: ElementKey | null },
): NavigationState {
return shown({ ...state, tab: 'findings', finding: { create } })
}
function goTo(state: NavigationState, target: EditorTarget): NavigationState {
@@ -202,19 +224,19 @@ function goTo(state: NavigationState, target: EditorTarget): NavigationState {
...state,
tab: target.tab,
section: target.section ?? state.section,
citationsOf: null,
finding: null,
focus: { target, serial },
serial,
}
return shown(moved)
}
/** « Tout afficher dans l'onglet Références »: the panel closes, the library starts afresh. */
/** « Tout afficher dans l'onglet Références »: the layers close, the library starts afresh. */
function showAllReferences(state: NavigationState): NavigationState {
const moved = {
...state,
tab: 'references' as const,
citationsOf: null,
finding: null,
libraryReset: state.libraryReset + 1,
}
return shown(moved)
@@ -226,20 +248,28 @@ export function navigationReducer(
): NavigationState {
switch (action.type) {
case 'select_tab':
return shown({ ...state, tab: action.tab, citationsOf: null })
return shown({ ...state, tab: action.tab, finding: null })
case 'open_section':
return shown({ ...state, section: action.section })
case 'back_to_drawing':
return shown({ ...state, section: 'drawing' })
case 'open_finding':
return openFinding(state, action.key)
case 'create_finding':
return createFinding(state, { kind: action.kind, parent: action.parent })
case 'close_finding':
console.trace('CLOSE_FINDING')
return { ...state, finding: null }
case 'open_citations':
return openCitations(state, action.citedBy)
case 'close_citations':
return { ...state, citationsOf: null }
return closeCitations(state)
case 'show_all_references':
return showAllReferences(state)
case 'go_to':
return goTo(state, action.target)
case 'restore_view':
console.trace('RESTORE', JSON.stringify(action.view.finding))
return restoreView(state, action.view)
case 'focus_consumed':
return state.focus?.serial === action.serial
+19 -3
View File
@@ -1,7 +1,8 @@
import type { ElementKey, PreviewState } from '@faunosteo/core-wasm/types'
import type { EditorTarget, FocusRequest } from './navigation'
import type { EditorTarget, EditorView, FocusRequest } from './navigation'
import { unmeasuredViews } from './issues'
import type { TabTier } from './useViewport'
import type { Guards } from './useEditorNavigation'
export const EDITOR_TABS = [
'general',
@@ -38,6 +39,21 @@ export function initialTab(state: PreviewState, tier: TabTier): EditorTabId {
return SHOWN[tier].includes(wanted) ? wanted : 'annotations'
}
/**
* What Constats needs of the navigation for its dialog (R2F-3): the layer the view
* holds and the moves on it. A user close answers false when a form refused it.
*/
export interface FindingLayer {
view: EditorView['finding']
guards: Guards
open: (key: ElementKey) => void
start: (kind: string, parent: ElementKey | null) => void
close: (forced?: boolean) => boolean
replace: (key: ElementKey | null, text?: string) => void
openCitations: (citedBy: ElementKey, opener?: HTMLElement | null) => void
announce: (text: string) => void
}
/** Props of every place (tab body, Annotations section). */
export interface EditorPlaceProps {
/** Not editable now: a mode that cannot save, or a recovery offer not answered yet. */
@@ -46,8 +62,8 @@ export interface EditorPlaceProps {
navigate: (target: EditorTarget) => void
/** « Aller à … » with an element: the place seeds its own selection from it once. */
focus?: FocusRequest
/** Opens the citations panel of one finding (only Constats offers it). */
openCitations?: (citedBy: ElementKey, opener?: HTMLElement | null) => void
/** The finding dialog and the citations sheet over it (only Constats has them). */
layer?: FindingLayer
/** Bumped by « Tout afficher »: the references library resets its search once per bump. */
libraryReset?: number
/** Reads the sheet's overview again (after a submission: the round freezes the draft). */
-61
View File
@@ -1,61 +0,0 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import type { NavigationAction } from './navigation'
/** Panel motion (board 25): enter decelerates, the shorter exit accelerates (P9). */
export const PANEL_ENTER_S = 0.18
export const PANEL_EXIT_S = 0.14
/** The exit plus a margin: past it, a callback that never came is applied by the timer. */
const FALLBACK_MS = PANEL_EXIT_S * 1000 + 100
export type PendingKind =
| 'go_to'
| 'citations_closed'
| 'show_all'
| 'tab_selected'
/** The one move a close records: applied when the exit is over (P9). */
export interface PendingClose {
action: NavigationAction
kind: PendingKind
text: string
/** Said before `text`: a draft dropped by a forced close. It survives a replacement. */
note?: string
}
/**
* The close of the citations panel as a two-step move (P9, P28): `record` starts the exit
* (the page stays inert, the panel is inert too); `complete` runs once, from the panel's
* `onExitComplete` or from a one-shot timer when that never fires, and hands the pending
* move to `apply`. A second close is a no-op; a tab choice replaces the pending move.
*/
export function useCitationsExit(apply: (move: PendingClose) => void) {
const [exiting, setExiting] = useState(false)
const pending = useRef<PendingClose | null>(null)
const timer = useRef<number | undefined>(undefined)
const complete = useCallback(() => {
const move = pending.current
if (move === null) return
pending.current = null
window.clearTimeout(timer.current)
setExiting(false)
apply(move)
}, [apply])
const record = useCallback(
(move: PendingClose) => {
if (pending.current !== null) {
if (move.kind !== 'tab_selected') return
const note = pending.current.note ?? move.note
pending.current = note ? { ...move, note } : move
return
}
pending.current = move
setExiting(true)
timer.current = window.setTimeout(complete, FALLBACK_MS)
},
[complete],
)
const busy = useCallback(() => pending.current !== null, [])
useEffect(() => () => window.clearTimeout(timer.current), [])
return { exiting, record, complete, busy }
}
+114 -175
View File
@@ -13,13 +13,13 @@ import { afterModalsClosed } from '@/components/ui/afterModalsClosed'
import { useT } from '@/i18n/useT'
import {
commitFocusedField,
focusActiveTab,
placeOf,
visibleElement,
type FocusOutcome,
type PlaceName,
} from './focusRequest'
import {
citationsOfView,
initialNavigation,
isFindingNode,
navigationReducer,
@@ -30,27 +30,17 @@ import {
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'
type MoveKind = 'go_to' | 'show_all' | 'tab_selected' | '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).
*/
/** A programmatic move: a new object per move, so the effect after it runs once. */
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.
* A layer's answer before it is left (P22''): `allowed` false cancels a user move. A
* forced one always goes ahead; `note` (a draft dropped) is said with the move.
*/
export interface LeaveAnswer {
allowed: boolean
@@ -93,24 +83,29 @@ export interface EditorNavigation {
/** 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, options?: SelectOptions) => boolean
openSection: (section: AnnotationSection, opener?: Opener) => void
backToDrawing: () => void
/** Opens the citations panel of a finding node; any other key is ignored. */
/** The finding dialog of `key`, in view mode. */
openFinding: (key: ElementKey) => void
/** The creation form of a zone, a category or a node, in the finding dialog. */
startFinding: (kind: string, parent: ElementKey | null) => void
/** A user close of the finding dialog; false when a layer refused it (a dirty form). */
closeFinding: (forced?: boolean) => boolean
/**
* The finding layer becomes another view of itself, by replace (no Back entry): the new
* element's dialog, or `null` for none. With `text`, a close the user did not ask for
* (the element vanished): forced, said once the dialogs are closed.
*/
replaceFinding: (key: ElementKey | null, text?: string) => void
/** Opens the citations sheet 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. */
/** A user close of the sheet; false when a tile in edit refused it. */
closeCitations: () => boolean
/** « X références », where the focus returns once the sheet is closed. */
citationsTrigger: () => HTMLElement | null
/** « Tout afficher dans l'onglet Références »: layers 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 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. */
@@ -170,7 +165,7 @@ function useLiveRegion() {
waiting.current()
waiting.current = afterModalsClosed(() => {
const joined = queued.current.splice(0).join('. ')
setLive((previous) => (previous === joined ? `${joined} ` : joined))
setLive((previous) => (previous === joined ? `${joined} ` : joined))
})
}, [])
return { live, announce }
@@ -211,7 +206,7 @@ function useMoveTrace() {
}
interface Openers {
/** The trigger that opened the citations panel, and the finding it belongs to. */
/** The trigger that opened the citations sheet, and the finding it belongs to. */
citations: RefObject<HTMLElement | null>
citedBy: RefObject<ElementKey | null>
section: RefObject<HTMLElement | null>
@@ -219,22 +214,10 @@ interface Openers {
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.
*/
/** The one way to move: commit the typed text, announce, dispatch, record the move. */
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, trace],
)
const go: Go = useCallback(
(action, kind, text) => {
commitFocusedField()
@@ -246,18 +229,12 @@ function useGo(dispatch: Dispatch<NavigationAction>, trace: MoveTrace) {
},
[announce, dispatch, trace],
)
return { move, go, finish, live, announce }
return { move, go, 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
@@ -271,101 +248,98 @@ function useSectionMoves(go: Go, openers: Openers) {
const text = `${t('editor.tab.annotations')} · ${t('editor.place.drawing')}`
go({ type: 'back_to_drawing' }, 'back', text)
}, [go, t])
return { navigate, openSection, backToDrawing }
return { 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
/** What the layers' moves need of the hook. */
interface LayerContext {
dispatch: Dispatch<NavigationAction>
announce: (text: string) => void
exit: ReturnType<typeof useCitationsExit>
guards: Guards
mark: (replace?: boolean) => void
}
/**
* 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.
* The finding dialog (R2F-3). A user close asks every layer first: a dirty form shows its
* own confirmation and the close is cancelled. `replaceFinding` is the move that is no
* Back step: the creation turned into its element, a deletion, an element that vanished.
*/
function useRequestClose(ctx: PanelContext) {
const { open, exit, guards, mark } = ctx
const { busy, record } = exit
return useCallback(
(move: PendingClose, forced: boolean): boolean => {
if (!open) return true
function useFindingLayer({ dispatch, announce, guards, mark }: LayerContext) {
const openFinding = useCallback(
(key: ElementKey) => {
mark()
if (busy()) {
record(move)
return true
}
commitFocusedField()
const { allowed, note } = guards.ask('citations', forced)
if (!allowed) return false
record(note ? { ...move, note } : move)
dispatch({ type: 'open_finding', key })
},
[dispatch, mark],
)
const startFinding = useCallback(
(kind: string, parent: ElementKey | null) => {
mark()
dispatch({ type: 'create_finding', kind, parent })
},
[dispatch, mark],
)
const closeFinding = useCallback(
(forced = false) => {
console.trace('closeFinding', forced)
if (!guards.askAll(forced).allowed) return false
mark()
dispatch({ type: 'close_finding' })
return true
},
[open, busy, record, guards, mark],
[guards, dispatch, mark],
)
const replaceFinding = useCallback(
(key: ElementKey | null, text?: string) => {
const note = text ? guards.askAll(true).note : undefined
if (text) announce(note ? `${note}. ${text}` : text)
mark(true)
dispatch(key ? { type: 'open_finding', key } : { type: 'close_finding' })
},
[guards, announce, dispatch, mark],
)
return { openFinding, startFinding, closeFinding, replaceFinding }
}
/** 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(
/** The citations sheet over the finding dialog: opened from a finding node only. */
function useSheetLayer(ctx: LayerContext, openers: Openers) {
const { dispatch, guards, mark } = ctx
const openCitations = 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'))
mark()
dispatch({ type: 'open_citations', citedBy })
},
[openers, dispatch, announce, t],
[openers, dispatch, mark],
)
const closeCitations = useCallback(() => {
if (!guards.ask('citations', false).allowed) return false
mark()
dispatch({ type: 'close_citations' })
return true
}, [guards, dispatch, mark])
return { openCitations, closeCitations }
}
/** The panel's closes: ✕ / Escape / scrim, the vanished finding, « Tout afficher », « Aller à ». */
function useCloseMoves(ctx: PanelContext) {
/** « Aller à » and « Tout afficher » leave every layer: a layer in edit may refuse. */
function useLeavingMoves(go: Go, guards: Guards) {
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)
if (!guards.askAll(false).allowed) return
go({ type: 'go_to', target }, 'go_to', moveText(target))
},
[request, moveText],
[go, guards, moveText],
)
return {
closeCitations: useCallback(() => closing(false), [closing]),
dropCitations: useCallback(() => closing(true), [closing]),
showAllReferences,
navigate,
request,
}
const showAllReferences = useCallback(() => {
if (!guards.askAll(false).allowed) return
const text = t('editor.tab.references')
go({ type: 'show_all_references' }, 'show_all', text)
}, [go, guards, t])
return { navigate, showAllReferences }
}
/** « Retour au dessin »: the entry that opened the section, else the canvas box. */
@@ -386,27 +360,6 @@ function triggerOf(openers: Openers): HTMLElement | null {
})
}
/** 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') {
@@ -419,7 +372,8 @@ function landingOf(move: Move, state: NavigationState): HTMLElement | null {
/**
* 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.
* the move had no request) the focus goes to the heading or the tab button. Once the
* dialogs a move closed are gone: the page behind them was inert.
*/
function useMoveFocus(
move: Move | null,
@@ -439,10 +393,10 @@ function useMoveFocus(
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()
afterModalsClosed(() => {
if (move.kind === 'back') backTarget(openers.section.current)?.focus()
else landingOf(move, state)?.focus()
})
}, [move, state, outcomes, dispatch, openers])
}
@@ -459,32 +413,30 @@ function useReceipts(dispatch: Dispatch<NavigationAction>) {
return { outcomes, consumed }
}
/** A tab choice; with the citations panel open it closes and the new tab takes the focus. */
/** A tab choice: the typed text is committed, the history asked for a push or a replace. */
function useTabSelect(
request: ReturnType<typeof useCloseMoves>['request'],
dispatch: Dispatch<NavigationAction>,
open: boolean,
mark: (replace?: boolean) => void,
) {
const t = useT()
return useCallback(
(tab: EditorTabId, options?: SelectOptions): boolean => {
const action = { type: 'select_tab', tab } as const
if (open) {
const text = t(`editor.tab.${tab}`)
const allowed = request({ action, kind: 'tab_selected', text }, false)
if (allowed) mark(options?.replace)
return allowed
}
commitFocusedField()
mark(options?.replace)
dispatch(action)
dispatch({ type: 'select_tab', tab })
return true
},
[request, dispatch, open, t, mark],
[dispatch, mark],
)
}
/** The sheet's finding is the one « X références » belongs to, even after a Back. */
function useCitedBy(state: NavigationState, openers: Openers) {
const citedBy = citationsOfView(state)
useEffect(() => {
if (citedBy) openers.citedBy.current = citedBy
}, [citedBy, openers])
}
/** Navigation of the draft editor: the reducer plus the DOM side (focus, live region). */
export function useEditorNavigation(
initialTab: EditorTabId,
@@ -494,41 +446,28 @@ export function useEditorNavigation(
initialNavigation(initialTab, initialView),
)
const { trace, mark } = useMoveTrace()
const { move, go, finish, live, announce } = useGo(dispatch, trace)
const { move, go, live, announce } = useGo(dispatch, trace)
const openers = useRef<Openers>({
citations: { current: null },
citedBy: { current: null },
section: { current: null },
}).current
const guards = useGuards()
const exit = useCitationsExit(finish)
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, guards, mark }
const openCitations = useOpenCitations(ctx)
const panel = useCloseMoves(ctx)
useCitedBy(state, openers)
const ctx = { dispatch, announce, guards, mark }
return {
state,
live,
announce,
consumed: receipts.consumed,
selectTab: useTabSelect(panel.request, dispatch, open, mark),
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,
selectTab: useTabSelect(dispatch, mark),
...useSectionMoves(go, openers),
...useFindingLayer(ctx),
...useSheetLayer(ctx, openers),
...useLeavingMoves(go, guards),
citationsTrigger: useCallback(() => triggerOf(openers), [openers]),
guards,
trace,
restoreView: useCallback(