fix(editor): final review round, history, dialogs, Plus and limits
I1 scroll restored at once on a Back into layers; I2 Aller a opens the target dialog in one push; M1-M9, criteria 8 and 17 (left-draft notice), entry caps, no exhaustive-deps disables, locals within 5.
This commit is contained in:
1 parent
ce171427c0
commit
6bf9290da7
25 files changed
+1002
-202
No files matched your search
@@ -7,8 +7,13 @@ import { AnnounceContext, FocusConsumedContext } from '@/editor/focusRequest'
|
||||
import { saveFailureMessage } from '@/editor/messages'
|
||||
import type { EditorMode } from '@/editor/mode'
|
||||
import { useEditorStore } from '@/editor/state/editorStore'
|
||||
import { ownedEntry, withoutForms } from '@/editor/history/entry'
|
||||
import {
|
||||
ownedEntry,
|
||||
withoutForms,
|
||||
type HistoryOwner,
|
||||
} from '@/editor/history/entry'
|
||||
import useEditorHistory from '@/editor/history/useEditorHistory'
|
||||
import { useLeftDraft } from '@/editor/leftDraft'
|
||||
import { citationsOfView, defaultView } from '@/editor/navigation'
|
||||
import { findingLayerOf, referenceLayerOf } from '@/editor/findingLayer'
|
||||
import { initialTab } from '@/editor/tabs'
|
||||
@@ -119,44 +124,72 @@ function Places({ nav, readOnly, reloadSheet }: PlacesProps) {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The draft page once the version is ready: header, notices, tab row, the citations
|
||||
* panel and the shown place. Owns the navigation state, so the first tab is known at
|
||||
* mount (`initialTab`) and later edits never move the user off their tab.
|
||||
*/
|
||||
export default function EditorWorkspace(props: Props) {
|
||||
const { sheet, mode, readOnly, tier, reloadSheet } = props
|
||||
const previewState = useEditorStore((s) => s.previewState)
|
||||
const tab = previewState ? initialTab(previewState, tier) : 'annotations'
|
||||
/** The sheet and the account the history entries of this editor belong to. */
|
||||
function useOwner(sheetId: string): HistoryOwner {
|
||||
const userId = useAuthStore((s) => s.user?.id ?? '')
|
||||
const owner = useMemo(
|
||||
() => ({ sheetId: sheet.sheet_id, userId }),
|
||||
[sheet.sheet_id, userId],
|
||||
)
|
||||
// A reload or a reopened entry shows the view the history kept, never a layer.
|
||||
return useMemo(() => ({ sheetId, userId }), [sheetId, userId])
|
||||
}
|
||||
|
||||
/** A reload or a reopened entry shows the view the history kept, never a layer. */
|
||||
function useRestoredView(owner: HistoryOwner) {
|
||||
const { state } = useLocation()
|
||||
const [view] = useState(() => {
|
||||
const entry = ownedEntry(state, owner)
|
||||
return entry && withoutForms(entry.view)
|
||||
})
|
||||
const nav = useEditorNavigation(tab, view)
|
||||
return view
|
||||
}
|
||||
|
||||
/**
|
||||
* The navigation of this sheet for this account: the first tab known at mount
|
||||
* (`initialTab`), the view a kept entry holds, the browser history in step with it, and
|
||||
* whether the last editor left a dirty dialog behind.
|
||||
*/
|
||||
function useWorkspaceNavigation(sheetId: string, tier: TabTier) {
|
||||
const previewState = useEditorStore((s) => s.previewState)
|
||||
const tab = previewState ? initialTab(previewState, tier) : 'annotations'
|
||||
const owner = useOwner(sheetId)
|
||||
const nav = useEditorNavigation(tab, useRestoredView(owner))
|
||||
useEditorHistory(nav, owner, defaultView(tab))
|
||||
return { nav, left: useLeftDraft(nav, owner) }
|
||||
}
|
||||
|
||||
/** The last editor of this sheet was left with a dirty dialog: said once. */
|
||||
function LeftDraftNotice({ shown }: { shown: boolean }) {
|
||||
const t = useT()
|
||||
if (!shown) return null
|
||||
return <Notice tone="info">{t('editor.leave.draft_dropped')}</Notice>
|
||||
}
|
||||
|
||||
/**
|
||||
* The draft page once the version is ready: header, notices, tab row, the citations
|
||||
* panel and the shown place. Owns the navigation state, so the first tab is known at
|
||||
* mount and later edits never move the user off their tab.
|
||||
*/
|
||||
export default function EditorWorkspace(props: Props) {
|
||||
const { sheet, mode, readOnly } = props
|
||||
const { nav, left } = useWorkspaceNavigation(sheet.sheet_id, props.tier)
|
||||
return (
|
||||
<EditingState readOnly={readOnly} mode={mode}>
|
||||
<div className="space-y-4" data-editor-workspace>
|
||||
<DraftHeader sheet={sheet} mode={mode} />
|
||||
<ModeNotice mode={mode} sheet={sheet} />
|
||||
<LeftDraftNotice shown={left} />
|
||||
<SaveFailureNotice />
|
||||
<RecoveryNotice />
|
||||
<CopyIssueNotice />
|
||||
<EditorTabs
|
||||
active={nav.state.tab}
|
||||
tier={tier}
|
||||
tier={props.tier}
|
||||
onSelect={nav.selectTab}
|
||||
/>
|
||||
<FocusConsumedContext value={nav.consumed}>
|
||||
<AnnounceContext value={nav.announce}>
|
||||
<Places nav={nav} readOnly={readOnly} reloadSheet={reloadSheet} />
|
||||
<Places
|
||||
nav={nav}
|
||||
readOnly={readOnly}
|
||||
reloadSheet={props.reloadSheet}
|
||||
/>
|
||||
</AnnounceContext>
|
||||
</FocusConsumedContext>
|
||||
<p aria-live="polite" className="sr-only">
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { useState } from 'react'
|
||||
import type {
|
||||
EditCommand,
|
||||
FindingCategoryKind,
|
||||
@@ -44,15 +43,17 @@ export interface FindingCreateFormProps {
|
||||
onClose: (forced: boolean) => void
|
||||
}
|
||||
|
||||
/** What the form holds before « Créer »; the zone of a category is part of it. */
|
||||
interface Draft {
|
||||
fr: string
|
||||
en: string
|
||||
kind: string
|
||||
zone: string
|
||||
}
|
||||
|
||||
const EMPTY: Draft = { fr: '', en: '', kind: '' }
|
||||
const EMPTY: Draft = { fr: '', en: '', kind: '', zone: '' }
|
||||
const sameDraft = (a: Draft, b: Draft) =>
|
||||
a.fr === b.fr && a.en === b.en && a.kind === b.kind
|
||||
a.fr === b.fr && a.en === b.en && a.kind === b.kind && a.zone === b.zone
|
||||
|
||||
/** What the core requires before an insert: both names, a zone and a kind for a category. */
|
||||
function isComplete(draft: Draft, pending: PendingFinding, parent: unknown) {
|
||||
@@ -76,14 +77,23 @@ function insertNew(
|
||||
return added ? createdId : null
|
||||
}
|
||||
|
||||
/** With exactly one zone it is preselected: the form starts on it, nothing typed yet. */
|
||||
const preselected = (zones: readonly FindingItem[]) =>
|
||||
zones.length === 1 ? zones[0].zoneId : ''
|
||||
|
||||
/** The form's state and its one `insert` (« Créer »), refused on a missing field. */
|
||||
function useCreateForm(props: FindingCreateFormProps) {
|
||||
const edit = useEditCommand()
|
||||
const zones = useZoneChoice()
|
||||
const form = useFormDraft(EMPTY, props.guards, sameDraft)
|
||||
const zones = useZones()
|
||||
const form = useFormDraft(
|
||||
{ ...EMPTY, zone: preselected(zones) },
|
||||
props.guards,
|
||||
sameDraft,
|
||||
)
|
||||
const chosen = zones.find((zone) => zone.zoneId === form.draft.zone) ?? null
|
||||
const create = () => {
|
||||
const { pending } = props
|
||||
const parent = pending.kind === 'category' ? zones.chosen : pending.parent
|
||||
const parent = pending.kind === 'category' ? chosen : pending.parent
|
||||
if (!isComplete(form.draft, pending, parent)) {
|
||||
edit.reject('form', 'editor.findings.required')
|
||||
return
|
||||
@@ -91,7 +101,7 @@ function useCreateForm(props: FindingCreateFormProps) {
|
||||
const id = insertNew(edit, pending, parent, form.draft)
|
||||
if (id !== null) props.onCreated(id, parent)
|
||||
}
|
||||
return { ...form, zones, create, error: edit.fieldError('form') }
|
||||
return { ...form, zones, chosen, create, error: edit.fieldError('form') }
|
||||
}
|
||||
|
||||
/** The kind choice of a category and its two names, as draft fields. */
|
||||
@@ -108,7 +118,14 @@ function CreateFields(props: {
|
||||
}))
|
||||
return (
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{category && <ZoneSelect zones={form.zones} readOnly={readOnly} />}
|
||||
{category && (
|
||||
<ZoneSelect
|
||||
zones={form.zones}
|
||||
value={form.draft.zone}
|
||||
readOnly={readOnly}
|
||||
onCommit={(zone) => form.set({ zone })}
|
||||
/>
|
||||
)}
|
||||
{category && (
|
||||
<SelectField
|
||||
id="finding-new-kind"
|
||||
@@ -153,7 +170,7 @@ export default function FindingCreateForm(props: FindingCreateFormProps) {
|
||||
}}
|
||||
>
|
||||
{props.readOnly && <ReadOnlyNotice />}
|
||||
{category && form.zones.chosen && <ZoneTitle zone={form.zones.chosen} />}
|
||||
{category && form.chosen && <ZoneTitle zone={form.chosen} />}
|
||||
<CreateFields form={form} category={category} readOnly={props.readOnly} />
|
||||
{form.error && (
|
||||
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
|
||||
@@ -172,30 +189,17 @@ export default function FindingCreateForm(props: FindingCreateFormProps) {
|
||||
)
|
||||
}
|
||||
|
||||
interface ZoneChoice {
|
||||
zones: readonly FindingItem[]
|
||||
zoneId: string
|
||||
setZoneId: (id: string) => void
|
||||
chosen: FindingItem | null
|
||||
}
|
||||
|
||||
/** The zones to choose from; with exactly one, it is preselected, otherwise nothing is. */
|
||||
function useZoneChoice(): ZoneChoice {
|
||||
/** The zones a new category can go in. */
|
||||
function useZones(): readonly FindingItem[] {
|
||||
const doc = useSheetDocument()
|
||||
const zones = doc ? buildItems(doc).filter((i) => i.kind === 'zone') : []
|
||||
const [zoneId, setZoneId] = useState(
|
||||
zones.length === 1 ? zones[0].zoneId : '',
|
||||
)
|
||||
const chosen = zones.find((zone) => zone.zoneId === zoneId) ?? null
|
||||
return { zones, zoneId, setZoneId, chosen }
|
||||
return doc ? buildItems(doc).filter((i) => i.kind === 'zone') : []
|
||||
}
|
||||
|
||||
function ZoneSelect({
|
||||
zones,
|
||||
readOnly,
|
||||
}: {
|
||||
zones: ZoneChoice
|
||||
function ZoneSelect(props: {
|
||||
zones: readonly FindingItem[]
|
||||
value: string
|
||||
readOnly: boolean
|
||||
onCommit: (zoneId: string) => void
|
||||
}) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
@@ -203,16 +207,16 @@ function ZoneSelect({
|
||||
<SelectField
|
||||
id="finding-new-zone"
|
||||
label={t('editor.findings.zone')}
|
||||
value={zones.zoneId}
|
||||
readOnly={readOnly}
|
||||
value={props.value}
|
||||
readOnly={props.readOnly}
|
||||
options={[
|
||||
{ value: '', label: t('editor.field.choose') },
|
||||
...zones.zones.map((zone) => ({
|
||||
...props.zones.map((zone) => ({
|
||||
value: zone.zoneId,
|
||||
label: zone.name[locale],
|
||||
})),
|
||||
]}
|
||||
onCommit={zones.setZoneId}
|
||||
onCommit={props.onCommit}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useRef } from 'react'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { Reference } from '@faunosteo/core-wasm/types'
|
||||
import Dialog from '@/components/ui/Dialog'
|
||||
import { visibleElement } from '@/editor/focusRequest'
|
||||
@@ -60,12 +60,28 @@ function useReturnTarget(layer: ReferenceLayer) {
|
||||
}, [opener])
|
||||
}
|
||||
|
||||
/**
|
||||
* The reference a creation just handed its entry over to (`layer.created`): the dialog
|
||||
* still shows the creation while it closes, never « Modifier la référence ». Forgotten
|
||||
* once the layer is closed.
|
||||
*/
|
||||
function useHandOver(layer: ReferenceLayer) {
|
||||
const [handed, setHanded] = useState<string | null>(null)
|
||||
if (handed !== null && !layer.view) setHanded(null)
|
||||
return { handed, handOver: setHanded }
|
||||
}
|
||||
|
||||
/** A creation, or the reference a creation was just handed over to. */
|
||||
function isCreation(view: View, handed: string | null): boolean {
|
||||
return !!view && ('create' in view || view.edit === handed)
|
||||
}
|
||||
|
||||
/** What the layer shows: a creation, or the reference it edits (null once it is gone). */
|
||||
function useShownReference(layer: ReferenceLayer) {
|
||||
function useShownReference(layer: ReferenceLayer, handed: string | null) {
|
||||
const t = useT()
|
||||
const doc = useSheetDocument()
|
||||
const creating = !!layer.view && 'create' in layer.view
|
||||
const edited = editedIn(layer.view, doc?.references)
|
||||
const creating = isCreation(layer.view, handed)
|
||||
const edited = creating ? null : editedIn(layer.view, doc?.references)
|
||||
const title = creating
|
||||
? 'editor.reference.new'
|
||||
: 'editor.references.edit_title'
|
||||
@@ -73,10 +89,15 @@ function useShownReference(layer: ReferenceLayer) {
|
||||
}
|
||||
|
||||
/** What a save does: a creation is announced, then handed over; an edit closes the layer. */
|
||||
function useOnSaved(layer: ReferenceLayer, creating: boolean) {
|
||||
function useOnSaved(
|
||||
layer: ReferenceLayer,
|
||||
creating: boolean,
|
||||
handOver: (id: string) => void,
|
||||
) {
|
||||
const t = useT()
|
||||
return (id: string, citation: string) => {
|
||||
if (!creating) return void layer.close(true)
|
||||
handOver(id)
|
||||
layer.announce(t('editor.references.added').replace('{citation}', citation))
|
||||
layer.created(id)
|
||||
}
|
||||
@@ -92,9 +113,10 @@ export default function ReferenceDialog({
|
||||
layer,
|
||||
readOnly,
|
||||
}: ReferenceDialogProps) {
|
||||
const shown = useShownReference(layer)
|
||||
const creation = useHandOver(layer)
|
||||
const shown = useShownReference(layer, creation.handed)
|
||||
const returnFocus = useReturnTarget(layer)
|
||||
const onSaved = useOnSaved(layer, shown.creating)
|
||||
const onSaved = useOnSaved(layer, shown.creating, creation.handOver)
|
||||
useGoneRule(layer)
|
||||
return (
|
||||
<Dialog
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState, type RefObject } from 'react'
|
||||
import { useEffect, useRef, useState, type RefObject } from 'react'
|
||||
import type { ElementKey, Reference } from '@faunosteo/core-wasm/types'
|
||||
import {
|
||||
focusRow,
|
||||
@@ -31,10 +31,11 @@ function useFilterFinding(layer: ReferenceLayer) {
|
||||
const doc = useSheetDocument()
|
||||
const finding = doc ? citingFinding(doc, layer.filter) : null
|
||||
const gone = doc !== null && layer.filter !== null && finding === null
|
||||
// The vanished finding is the trigger; the move and its wording are the latest ones.
|
||||
const clear = useRef<() => void>(() => undefined)
|
||||
clear.current = () => layer.clearFilter(t('editor.references.filter_gone'))
|
||||
useEffect(() => {
|
||||
if (gone) layer.clearFilter(t('editor.references.filter_gone'))
|
||||
// The wording and the move are stable per render; the vanished finding is the trigger.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
if (gone) clear.current()
|
||||
}, [gone])
|
||||
return { finding, cited: finding ? new Set(citedIds(finding)) : null }
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import AddBar from '@/components/editor/findings/AddBar'
|
||||
import FindingDialog from '@/components/editor/findings/FindingDialog'
|
||||
import type { PendingFinding } from '@/components/editor/findings/FindingCreateForm'
|
||||
import FindingTree from '@/components/editor/findings/FindingTree'
|
||||
import { afterModalsClosed } from '@/components/ui/afterModalsClosed'
|
||||
import { landAfterModalsClosed } from '@/components/ui/afterModalsClosed'
|
||||
import {
|
||||
buildItems,
|
||||
createdItemId,
|
||||
@@ -62,13 +62,14 @@ function useFindingDeletion(
|
||||
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.
|
||||
// the focus lands on the nearest row once every dialog is closed, unless a newer
|
||||
// landing supersedes it.
|
||||
const closeDelete = () => {
|
||||
setAsk(null)
|
||||
if (!ask || currentItems().some((item) => item.id === selectedId)) return
|
||||
actions.select(ask.fallback)
|
||||
actions.closeLayer()
|
||||
afterModalsClosed(() => actions.focusItem(ask.fallback))
|
||||
landAfterModalsClosed(() => actions.focusItem(ask.fallback))
|
||||
}
|
||||
return { deleting: ask?.target ?? null, askDelete, closeDelete }
|
||||
}
|
||||
@@ -81,17 +82,18 @@ function useSelectionOfLayer(
|
||||
) {
|
||||
const { view } = layer
|
||||
const wanted = view && 'key' in view ? JSON.stringify(view.key) : null
|
||||
// `show` only sets state: the layer's key and the tree are what the effect follows.
|
||||
const reveal = useRef(show)
|
||||
reveal.current = show
|
||||
useEffect(() => {
|
||||
const found = wanted && itemForKey(items, JSON.parse(wanted))
|
||||
if (found) show(found)
|
||||
// `show` only sets state; the layer's key and the tree are what it follows.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
if (found) reveal.current(found)
|
||||
}, [wanted, items])
|
||||
}
|
||||
|
||||
/**
|
||||
* The element the dialog shows vanished (a reload after a conflict): the layer closes by
|
||||
* replace and says so; a creation whose parent vanished closes silently.
|
||||
* The element the dialog shows, or the parent of a creation, vanished (a reload after a
|
||||
* conflict): the layer closes by replace and says so, with the dropped entry if any.
|
||||
*/
|
||||
function useGoneRule(layer: FindingLayer, loaded: boolean) {
|
||||
const t = useT()
|
||||
@@ -100,8 +102,7 @@ function useGoneRule(layer: FindingLayer, loaded: boolean) {
|
||||
useEffect(() => {
|
||||
if (!view) handled.current = null
|
||||
if (!loaded || !view) return
|
||||
const named = 'key' in view
|
||||
const key = named ? view.key : view.create.parent
|
||||
const key = 'key' in view ? view.key : view.create.parent
|
||||
const stamp = JSON.stringify(view)
|
||||
const present = (i: FindingItem) => key !== null && sameKey(i.key, key)
|
||||
if (key === null || currentItems().some(present)) return
|
||||
@@ -109,9 +110,7 @@ function useGoneRule(layer: FindingLayer, loaded: boolean) {
|
||||
handled.current = stamp
|
||||
// After this commit's effects: a tile in edit re-registers its guard in them, and the
|
||||
// forced close below must still be able to ask it.
|
||||
queueMicrotask(() =>
|
||||
layer.replace(null, named ? t('editor.findings.gone') : undefined),
|
||||
)
|
||||
queueMicrotask(() => layer.replace(null, t('editor.findings.gone')))
|
||||
}, [loaded, view, layer, t])
|
||||
}
|
||||
|
||||
@@ -261,6 +260,11 @@ function useFindingsData() {
|
||||
return { doc, items }
|
||||
}
|
||||
|
||||
/** The element the layer's dialog shows, read from the tree; null for none or a creation. */
|
||||
function shownOf(view: FindingLayer['view'], items: readonly FindingItem[]) {
|
||||
return view && 'key' in view ? itemForKey(items, view.key) : null
|
||||
}
|
||||
|
||||
/** Everything the tab shows and does, so the component only lays it out. */
|
||||
function useFindingsTab(focus: EditorPlaceProps['focus'], layer: FindingLayer) {
|
||||
const data = useFindingsData()
|
||||
@@ -269,11 +273,14 @@ function useFindingsTab(focus: EditorPlaceProps['focus'], layer: FindingLayer) {
|
||||
const ctx = { layer, items: data.items, sel, land: landing.land }
|
||||
useLayerFollow(focus, ctx)
|
||||
useGoneRule(layer, data.doc !== null)
|
||||
const actions = useFindingActions(ctx)
|
||||
const returnFocus = useReturnTarget(layer.view)
|
||||
const { view } = layer
|
||||
const shown = view && 'key' in view ? itemForKey(data.items, view.key) : null
|
||||
return { ...data, sel, landing, actions, returnFocus, shown }
|
||||
return {
|
||||
...data,
|
||||
sel,
|
||||
landing,
|
||||
actions: useFindingActions(ctx),
|
||||
returnFocus: useReturnTarget(layer.view),
|
||||
shown: shownOf(layer.view, data.items),
|
||||
}
|
||||
}
|
||||
|
||||
/** Constats: the tree zones → categories → nodes; each element opens in a dialog. */
|
||||
|
||||
@@ -110,9 +110,29 @@ function useBackRequest(open: boolean, close: () => void) {
|
||||
}, [open, close])
|
||||
}
|
||||
|
||||
/**
|
||||
* Keyboard focus that leaves the trigger and the list closes « Plus »: the open overlay
|
||||
* would cover the control the focus reached (WCAG 2.4.11). A focus that goes nowhere in
|
||||
* the page (the browser's own interface) leaves it open.
|
||||
*/
|
||||
function useFocusLeave(open: boolean, close: () => void) {
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const onOut = (event: FocusEvent) => {
|
||||
const from = event.target instanceof Element ? event.target : null
|
||||
const to = event.relatedTarget
|
||||
if (!from?.closest(MENU_PARTS) || !(to instanceof Element)) return
|
||||
if (!to.closest(MENU_PARTS)) close()
|
||||
}
|
||||
document.addEventListener('focusout', onOut, true)
|
||||
return () => document.removeEventListener('focusout', onOut, true)
|
||||
}, [open, close])
|
||||
}
|
||||
|
||||
/** Every way « Plus » closes besides a selection and a tab change. */
|
||||
export function useMoreDismiss(open: boolean, close: () => void) {
|
||||
useMoreEscape(open, close)
|
||||
useOutsidePress(open, close)
|
||||
useBackRequest(open, close)
|
||||
useFocusLeave(open, close)
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { useIsPresent } from 'motion/react'
|
||||
import {
|
||||
useCallback,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
type KeyboardEvent,
|
||||
type ReactNode,
|
||||
type RefObject,
|
||||
type SyntheticEvent,
|
||||
} from 'react'
|
||||
import { flushAfterModals } from './afterModalsClosed'
|
||||
@@ -89,34 +91,27 @@ function restoreFocus(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Native modal `<dialog>` shown while mounted (D13): `showModal()` makes the
|
||||
* rest of the page inert and keeps focus in the top layer. The dialog never
|
||||
* closes itself: Escape and close requests call `onClose`, and it leaves the
|
||||
* screen when the consumer unmounts it. Focus starts on the first control and
|
||||
* then returns to the opener. Tab past the last control reaches the browser's
|
||||
* own interface, never the page, as the platform intends.
|
||||
*/
|
||||
export default function ModalDialog({
|
||||
onClose,
|
||||
returnFocus,
|
||||
layer,
|
||||
labelledBy,
|
||||
label,
|
||||
describedBy,
|
||||
className = '',
|
||||
children,
|
||||
}: ModalDialogProps) {
|
||||
const ref = useRef<HTMLDialogElement>(null)
|
||||
const latest = useRef({ returnFocus, onClose })
|
||||
latest.current = { returnFocus, onClose }
|
||||
const isPresent = useIsPresent()
|
||||
const present = useRef(true)
|
||||
present.current = isPresent
|
||||
// The `close` event of the cleanup's own `close()` is no request (a DOM that fires it
|
||||
// at once, as the test DOM does, would otherwise reach the consumer).
|
||||
const closingSelf = useRef(false)
|
||||
/** What the dialog's handlers read at the time they run, never a stale render's. */
|
||||
type Latest = () => Pick<ModalDialogProps, 'returnFocus' | 'onClose'>
|
||||
|
||||
/** A stable reader of the props the last render passed. */
|
||||
function useLatest(props: ReturnType<Latest>): Latest {
|
||||
const box = useRef(props)
|
||||
box.current = props
|
||||
return useCallback(() => box.current, [])
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the dialog on mount and closes it on unmount, focus in then back to the opener.
|
||||
* Answers whether the dialog is closing itself: the `close` event of the cleanup's own
|
||||
* `close()` is no request (a DOM that fires it at once, as the test DOM does, would
|
||||
* otherwise reach the consumer).
|
||||
*/
|
||||
function useShowModal(
|
||||
ref: RefObject<HTMLDialogElement | null>,
|
||||
latest: Latest,
|
||||
) {
|
||||
const closingSelf = useRef(false)
|
||||
useLayoutEffect(() => {
|
||||
const dialog = ref.current
|
||||
if (!dialog) return
|
||||
@@ -137,7 +132,7 @@ export default function ModalDialog({
|
||||
// After the commit: the render that closes the dialog may remove the opener
|
||||
// too. A dialog still on screen was only remounted (React StrictMode).
|
||||
queueMicrotask(() => {
|
||||
const resolve = latest.current.returnFocus
|
||||
const resolve = latest().returnFocus
|
||||
if (!dialog.isConnected && resolve !== null) {
|
||||
restoreFocus(resolve?.() ?? null, opener, ancestors)
|
||||
}
|
||||
@@ -146,8 +141,20 @@ export default function ModalDialog({
|
||||
queueMicrotask(flushAfterModals)
|
||||
})
|
||||
}
|
||||
}, [])
|
||||
// Shown once per mount: the ref and the latest props are read when it runs.
|
||||
}, [ref, latest])
|
||||
return closingSelf
|
||||
}
|
||||
|
||||
/** Escape, the platform's cancel and a close the platform made anyway: each asks. */
|
||||
function useCloseRequests(
|
||||
ref: RefObject<HTMLDialogElement | null>,
|
||||
latest: Latest,
|
||||
isPresent: boolean,
|
||||
closingSelf: RefObject<boolean>,
|
||||
) {
|
||||
const present = useRef(true)
|
||||
present.current = isPresent
|
||||
const onKeyDown = (event: KeyboardEvent<HTMLDialogElement>) => {
|
||||
if (event.key !== 'Escape' || event.nativeEvent.isComposing) return
|
||||
// A cancelled keydown is no close request: Chromium would otherwise close the
|
||||
@@ -156,21 +163,47 @@ export default function ModalDialog({
|
||||
event.stopPropagation()
|
||||
// A held key repeats: only the first press asks.
|
||||
if (event.repeat) return
|
||||
onClose()
|
||||
latest().onClose()
|
||||
}
|
||||
const onCancel = (event: SyntheticEvent<HTMLDialogElement>) => {
|
||||
event.preventDefault()
|
||||
onClose()
|
||||
latest().onClose()
|
||||
}
|
||||
// Closed by the platform anyway: keep the consumer's state in step. The check
|
||||
// ignores the `close` event queued by a cleanup the dialog has since reopened from.
|
||||
// A refused close shows the dialog again, never during an exit or once it is gone.
|
||||
const onClosed = () => {
|
||||
const onClose = () => {
|
||||
const dialog = ref.current
|
||||
if (!dialog || dialog.open || closingSelf.current) return
|
||||
const refused = latest.current.onClose() === 'kept'
|
||||
const refused = latest().onClose() === 'kept'
|
||||
if (refused && present.current && dialog.isConnected) dialog.showModal()
|
||||
}
|
||||
return { onKeyDown, onCancel, onClose }
|
||||
}
|
||||
|
||||
/**
|
||||
* Native modal `<dialog>` shown while mounted (D13): `showModal()` makes the
|
||||
* rest of the page inert and keeps focus in the top layer. The dialog never
|
||||
* closes itself: Escape and close requests call `onClose`, and it leaves the
|
||||
* screen when the consumer unmounts it. Focus starts on the first control and
|
||||
* then returns to the opener. Tab past the last control reaches the browser's
|
||||
* own interface, never the page, as the platform intends.
|
||||
*/
|
||||
export default function ModalDialog({
|
||||
onClose,
|
||||
returnFocus,
|
||||
layer,
|
||||
labelledBy,
|
||||
label,
|
||||
describedBy,
|
||||
className = '',
|
||||
children,
|
||||
}: ModalDialogProps) {
|
||||
const ref = useRef<HTMLDialogElement>(null)
|
||||
const latest = useLatest({ returnFocus, onClose })
|
||||
const isPresent = useIsPresent()
|
||||
const closingSelf = useShowModal(ref, latest)
|
||||
const requests = useCloseRequests(ref, latest, isPresent, closingSelf)
|
||||
|
||||
return (
|
||||
<dialog
|
||||
@@ -181,9 +214,9 @@ export default function ModalDialog({
|
||||
aria-labelledby={labelledBy}
|
||||
aria-label={label}
|
||||
aria-describedby={describedBy}
|
||||
onKeyDown={onKeyDown}
|
||||
onCancel={onCancel}
|
||||
onClose={onClosed}
|
||||
onKeyDown={requests.onKeyDown}
|
||||
onCancel={requests.onCancel}
|
||||
onClose={requests.onClose}
|
||||
className={`${SURFACE} ${className}`}
|
||||
>
|
||||
{children}
|
||||
|
||||
@@ -29,11 +29,35 @@ export function flushAfterModals(): void {
|
||||
ready.forEach((fn) => fn())
|
||||
}
|
||||
|
||||
/**
|
||||
* The focus landing still waiting, as its cancel. The page has one focus, so one landing:
|
||||
* a newer one supersedes it (a stale move never takes the focus once the dialogs close).
|
||||
*/
|
||||
let pendingLanding: () => void = () => undefined
|
||||
|
||||
/**
|
||||
* `afterModalsClosed` for a focus landing: a dialog closed in the same commit restores
|
||||
* its own focus in a microtask queued before this call, so the landing waits one more
|
||||
* microtask and is never undone by it.
|
||||
* microtask and is never undone by it. It cancels the landing still waiting, and answers
|
||||
* its own cancel.
|
||||
*/
|
||||
export function landAfterModalsClosed(fn: () => void): () => void {
|
||||
return afterModalsClosed(() => queueMicrotask(fn))
|
||||
pendingLanding()
|
||||
let live = true
|
||||
const unwait = afterModalsClosed(() =>
|
||||
queueMicrotask(() => {
|
||||
if (live) fn()
|
||||
}),
|
||||
)
|
||||
const cancel = () => {
|
||||
live = false
|
||||
unwait()
|
||||
}
|
||||
pendingLanding = cancel
|
||||
return cancel
|
||||
}
|
||||
|
||||
/** Drops the landing still waiting: a Back onto a dialog, an editor that goes. */
|
||||
export function cancelLanding(): void {
|
||||
pendingLanding()
|
||||
}
|
||||
@@ -92,7 +92,10 @@ function rowOf(key: ElementKey): HTMLElement | null {
|
||||
)
|
||||
}
|
||||
|
||||
/** Scrolls to and focuses the visible row tagged with `key`; false unless the row now holds the focus. */
|
||||
/**
|
||||
* 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 row = rowOf(key)
|
||||
if (!row) return false
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ElementKey } from '@faunosteo/core-wasm/types'
|
||||
import { MAX_FINDING_PATH } from '../findings/tree'
|
||||
import {
|
||||
ANNOTATION_SECTIONS,
|
||||
isFindingNode,
|
||||
@@ -34,16 +35,23 @@ export const ENTRY_KEY = 'editorEntry'
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === 'object' && value !== null
|
||||
|
||||
/** Longest id or key read back: a longer one is no id this editor wrote. */
|
||||
const MAX_ID_LENGTH = 128
|
||||
|
||||
const isId = (value: unknown): value is string =>
|
||||
typeof value === 'string' && value.length <= MAX_ID_LENGTH
|
||||
|
||||
/** A finding path no deeper than the tree allows, each id within the cap. */
|
||||
const isPath = (path: unknown): path is string[] =>
|
||||
Array.isArray(path) && path.length <= MAX_FINDING_PATH && path.every(isId)
|
||||
|
||||
/** 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 }
|
||||
}
|
||||
if (raw.kind === 'zone' && isId(raw.id)) 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[] }
|
||||
if (raw.kind !== 'finding' || !isId(zoneId) || !isPath(path)) return null
|
||||
return { kind: 'finding', zone_id: zoneId, path }
|
||||
}
|
||||
|
||||
const CREATION_KINDS = ['zone', 'category', 'node']
|
||||
@@ -82,7 +90,7 @@ function sanitizeReference(
|
||||
const sheet = !!finding && 'key' in finding && finding.citations
|
||||
if (raw.create === true) return tab === 'references' ? { create: true } : null
|
||||
const id = raw.edit
|
||||
if (typeof id !== 'string' || id === '') return null
|
||||
if (!isId(id) || id === '') return null
|
||||
return tab === 'references' || sheet ? { edit: id } : null
|
||||
}
|
||||
|
||||
@@ -121,16 +129,22 @@ export function withoutForms(view: EditorView): EditorView {
|
||||
return sanitizeView(view, false) ?? view
|
||||
}
|
||||
|
||||
/** The entry's id and owner, each a string within the cap, or null. */
|
||||
function idsOf(raw: Record<string, unknown>) {
|
||||
const { id, sheetId, userId } = raw
|
||||
const valid = isId(id) && isId(sheetId) && isId(userId)
|
||||
return valid ? { id, sheetId, userId } : 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 ids = idsOf(raw)
|
||||
if (!view || !ids) return null
|
||||
const below = raw.below === null ? null : sanitizeView(raw.below)
|
||||
return { id, view, below, sheetId, userId }
|
||||
return { ...ids, view, below }
|
||||
}
|
||||
|
||||
/** An entry restores only for the sheet and the account that wrote it. */
|
||||
@@ -164,7 +178,7 @@ 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.
|
||||
// Another tab is a move of its own (« Tout afficher »): it pushes.
|
||||
if (view.tab !== top.tab) return false
|
||||
if (layerCount(view) < layerCount(top)) return true
|
||||
const backToDrawing = view.tab === top.tab && isStepOver(top)
|
||||
@@ -186,18 +200,21 @@ export function showsFinding(view: EditorView, key: ElementKey): boolean {
|
||||
* au dessin"), goes back when the entry holds the view the move lands on (the entry that
|
||||
* opened it), else it replaces; a layer, tab or section added pushes, unless the move
|
||||
* asked for a replace. `backTo` (« Revenir au constat ») goes back when the entry below
|
||||
* shows that finding.
|
||||
* shows that finding. `own` (« Aller à ») is a move of its own: it pushes, even when it
|
||||
* leaves fewer layers on the same tab, so the place it left stays one Back away.
|
||||
*/
|
||||
export function planWrite(
|
||||
top: HistoryEntry,
|
||||
view: EditorView,
|
||||
replace: boolean,
|
||||
backTo: ElementKey | null = null,
|
||||
own = false,
|
||||
): HistoryWrite {
|
||||
if (sameView(top.view, view)) return 'none'
|
||||
if (replace) return 'replace'
|
||||
// « Revenir au constat »: the entry below already shows that finding, a Back is the move.
|
||||
if (backTo && top.below && showsFinding(top.below, backTo)) return 'back'
|
||||
if (own) return 'push'
|
||||
if (isRemoval(top.view, view)) {
|
||||
return top.below && sameView(top.below, view) ? 'back' : 'replace'
|
||||
}
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useLocation, useNavigate, useNavigationType } from 'react-router-dom'
|
||||
import { landAfterModalsClosed } from '@/components/ui/afterModalsClosed'
|
||||
import {
|
||||
useLocation,
|
||||
useNavigate,
|
||||
useNavigationType,
|
||||
type Location,
|
||||
} from 'react-router-dom'
|
||||
import {
|
||||
cancelLanding,
|
||||
landAfterModalsClosed,
|
||||
} from '@/components/ui/afterModalsClosed'
|
||||
import { focusActiveTab } from '../focusRequest'
|
||||
import { sameView, type EditorView } from '../navigation'
|
||||
import {
|
||||
@@ -8,15 +16,18 @@ import {
|
||||
shownPlace,
|
||||
useMoveText,
|
||||
type EditorNavigation,
|
||||
type MoveTrace,
|
||||
} from '../useEditorNavigation'
|
||||
import {
|
||||
createWriteBudget,
|
||||
entryState,
|
||||
layerCount,
|
||||
ownedEntry,
|
||||
planWrite,
|
||||
withoutForms,
|
||||
type HistoryEntry,
|
||||
type HistoryOwner,
|
||||
type HistoryWrite,
|
||||
} from './entry'
|
||||
|
||||
/** Well under WebKit's 100 history writes per 10 s: past it a view stays in memory. */
|
||||
@@ -29,28 +40,55 @@ 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 entry the browser holds on top: not `entry` once a push stayed in memory. */
|
||||
sent: HistoryEntry | null
|
||||
/** The pathname the editor mounted on: a location elsewhere is not this editor's. */
|
||||
path: 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. */
|
||||
scrolls: Map<string, number>
|
||||
/** Entry ids: a prefix drawn once per mount, so a reload never reuses one, a counter. */
|
||||
prefix: string
|
||||
counter: number
|
||||
takeWrite: (now: number) => boolean
|
||||
}
|
||||
|
||||
/** A random prefix: entries left by an earlier mount of this tab keep their own ids. */
|
||||
function mountPrefix(): string {
|
||||
const words = crypto.getRandomValues(new Uint32Array(2))
|
||||
return Array.from(words, (word) => word.toString(36)).join('')
|
||||
}
|
||||
|
||||
function newBook(): Book {
|
||||
return {
|
||||
entry: null,
|
||||
sent: null,
|
||||
path: null,
|
||||
seen: null,
|
||||
pendingBack: false,
|
||||
backTimer: undefined,
|
||||
scrolls: new Map(),
|
||||
prefix: mountPrefix(),
|
||||
counter: 0,
|
||||
takeWrite: createWriteBudget(WRITE_LIMIT, WRITE_WINDOW_MS),
|
||||
}
|
||||
}
|
||||
|
||||
/** An entry read from the browser's history: it is the top, as the browser holds it. */
|
||||
function adopt(book: Book, entry: HistoryEntry): void {
|
||||
book.entry = entry
|
||||
book.sent = entry
|
||||
}
|
||||
|
||||
const placeOf = ({ pathname, search, hash }: Location) => ({
|
||||
pathname,
|
||||
search,
|
||||
hash,
|
||||
})
|
||||
|
||||
/** A Back or Forward that changed the view: what the landing scrolls to, focuses and says. */
|
||||
interface Landing {
|
||||
entry: HistoryEntry
|
||||
@@ -61,7 +99,8 @@ interface Landing {
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* budget keeps the entry in memory only; `replace` swallows a refused write. Nothing is
|
||||
* written over a location that is not the editor's (it is leaving).
|
||||
*/
|
||||
function useWriter(book: Book, owner: HistoryOwner) {
|
||||
const navigate = useNavigate()
|
||||
@@ -71,31 +110,38 @@ function useWriter(book: Book, owner: HistoryOwner) {
|
||||
return useMemo(() => {
|
||||
const send = (entry: HistoryEntry, replace: boolean) => {
|
||||
const { navigate, location } = latest.current
|
||||
const { pathname, search, hash } = location
|
||||
const to = { pathname, search, hash }
|
||||
if (location.pathname !== book.path) return
|
||||
try {
|
||||
navigate(to, { replace, state: entryState(entry) })
|
||||
navigate(placeOf(location), { replace, state: entryState(entry) })
|
||||
book.sent = 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 }
|
||||
return { id: `${book.prefix}-${book.counter}`, view, below, ...owner }
|
||||
}
|
||||
const write = (entry: HistoryEntry, replace: boolean) => {
|
||||
book.entry = entry
|
||||
// shortcut: past the write budget a push is kept in memory only, so a later Back
|
||||
// lands on the real previous entry. Fine at one push per user move; upgrade path:
|
||||
// coalesce the skipped views into one replace once the window slides.
|
||||
// shortcut: past the write budget a push is kept in memory only (`settle` closes it
|
||||
// without a Back), so a browser Back lands on the real previous entry. Fine at one
|
||||
// push per user move; upgrade path: coalesce the skipped views into one replace once
|
||||
// the window slides.
|
||||
if (replace || book.takeWrite(Date.now())) send(entry, replace)
|
||||
}
|
||||
const replace = (view: EditorView) => {
|
||||
const kept = book.entry ?? fresh(view, null)
|
||||
write({ ...kept, view }, true)
|
||||
}
|
||||
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)
|
||||
replace,
|
||||
/** A close over a push kept in memory: the browser's top is the place, no Back. */
|
||||
settle: (view: EditorView) => {
|
||||
book.entry = book.sent
|
||||
if (!book.sent || !sameView(book.sent.view, view)) replace(view)
|
||||
},
|
||||
first: (view: EditorView) => write(fresh(view, null), true),
|
||||
back: () => {
|
||||
@@ -112,6 +158,31 @@ function useWriter(book: Book, owner: HistoryOwner) {
|
||||
|
||||
type Writer = ReturnType<typeof useWriter>
|
||||
|
||||
/** What the last move left for the adapter, read once: the trace is reset. */
|
||||
function takeTrace(trace: MoveTrace): MoveTrace {
|
||||
const taken = { ...trace }
|
||||
Object.assign(trace, {
|
||||
scrollY: null,
|
||||
replace: false,
|
||||
backTo: null,
|
||||
own: false,
|
||||
})
|
||||
return taken
|
||||
}
|
||||
|
||||
/** Carries a planned write out; a Back over a push kept in memory settles instead. */
|
||||
function follow(
|
||||
plan: HistoryWrite,
|
||||
view: EditorView,
|
||||
book: Book,
|
||||
writer: Writer,
|
||||
) {
|
||||
if (plan === 'push') writer.push(view)
|
||||
else if (plan === 'replace') writer.replace(view)
|
||||
else if (book.entry !== book.sent) writer.settle(view)
|
||||
else writer.back()
|
||||
}
|
||||
|
||||
/** User moves: the view changed, the history follows (R2F-1). */
|
||||
function useReconcile(
|
||||
nav: EditorNavigation,
|
||||
@@ -120,18 +191,13 @@ function useReconcile(
|
||||
writer: Writer,
|
||||
) {
|
||||
useEffect(() => {
|
||||
const { scrollY, replace, backTo } = nav.trace
|
||||
nav.trace.scrollY = null
|
||||
nav.trace.replace = false
|
||||
nav.trace.backTo = null
|
||||
const move = takeTrace(nav.trace)
|
||||
const top = book.entry
|
||||
if (!top || book.pendingBack) return
|
||||
const plan = planWrite(top, view, replace, backTo)
|
||||
const plan = planWrite(top, view, move.replace, move.backTo, move.own)
|
||||
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)
|
||||
book.scrolls.set(top.id, move.scrollY ?? window.scrollY)
|
||||
follow(plan, view, book, writer)
|
||||
}, [view, nav.trace, book, writer])
|
||||
}
|
||||
|
||||
@@ -183,7 +249,7 @@ function landOnForeign(ctx: PopContext): Landing | null {
|
||||
*/
|
||||
function refusePop(ctx: PopContext, landed: HistoryEntry | null): null {
|
||||
const { book, writer, view } = ctx
|
||||
if (landed) book.entry = landed
|
||||
if (landed) adopt(book, landed)
|
||||
writer.push(view)
|
||||
return null
|
||||
}
|
||||
@@ -205,7 +271,7 @@ function landOn(ctx: PopContext, state: unknown): Landing | null {
|
||||
const entry = ownedEntry(state, ctx.owner)
|
||||
if (!expected && popRefused(ctx, entry)) return refusePop(ctx, entry)
|
||||
if (!entry) return landOnForeign(ctx)
|
||||
book.entry = entry
|
||||
adopt(book, entry)
|
||||
if (sameView(entry.view, view)) return null
|
||||
nav.restoreView(entry.view)
|
||||
return {
|
||||
@@ -216,14 +282,15 @@ function landOn(ctx: PopContext, state: unknown): Landing | null {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* The first location of the editor: its pathname is the editor's from now on. 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)
|
||||
function mount(ctx: PopContext, location: Location): void {
|
||||
ctx.book.path = location.pathname
|
||||
const entry = ownedEntry(location.state, ctx.owner)
|
||||
if (!entry) return ctx.writer.first(ctx.view)
|
||||
ctx.book.entry = entry
|
||||
adopt(ctx.book, entry)
|
||||
const kept = withoutForms(entry.view)
|
||||
if (!sameView(kept, entry.view)) ctx.writer.replace(kept)
|
||||
}
|
||||
@@ -236,29 +303,42 @@ function landFocus({ entry, tabChanged, layerChanged }: Landing): void {
|
||||
else focusActiveTab({ preventScroll: true })
|
||||
}
|
||||
|
||||
/** Scroll, focus and announcement once a Back or Forward has restored a view. */
|
||||
interface Speech {
|
||||
nav: EditorNavigation
|
||||
moveText: ReturnType<typeof useMoveText>
|
||||
}
|
||||
|
||||
/** Focus and announcement of a landing, once the dialogs it closed are gone. */
|
||||
function land(landing: Landing, { nav, moveText }: Speech): void {
|
||||
landFocus(landing)
|
||||
if (landing.layerChanged && !landing.tabChanged) return
|
||||
const { view } = landing.entry
|
||||
const section = view.tab === 'annotations' ? view.section : null
|
||||
nav.announce(moveText({ place: 'tab', tab: view.tab, section, key: null }))
|
||||
}
|
||||
|
||||
/**
|
||||
* Scroll, focus and announcement once a Back or Forward has restored a view. The effect
|
||||
* follows the landing only (the rest is read from a ref): a later render, a dialog closed
|
||||
* by ✕ or a locale switch, never cancels what it waits for.
|
||||
*/
|
||||
function useLanding(
|
||||
nav: EditorNavigation,
|
||||
book: Book,
|
||||
landing: Landing | null,
|
||||
) {
|
||||
const moveText = useMoveText()
|
||||
const landed = useRef<Landing | null>(null)
|
||||
const latest = useRef<Speech>({ nav, moveText })
|
||||
latest.current = { nav, moveText }
|
||||
useEffect(() => {
|
||||
// A new wording (locale switch) re-creates `moveText`: the landing stays one.
|
||||
if (!landing || landed.current === landing) return
|
||||
landed.current = landing
|
||||
const { id, view } = landing.entry
|
||||
return landAfterModalsClosed(() => {
|
||||
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 }),
|
||||
)
|
||||
})
|
||||
}, [landing, book, nav, moveText])
|
||||
if (!landing) return
|
||||
// The page behind a dialog scrolls too: the offset is applied at once.
|
||||
window.scrollTo(0, book.scrolls.get(landing.entry.id) ?? 0)
|
||||
// A dialog landed on keeps its own focus (then its return target): no older landing
|
||||
// takes the focus once it is closed.
|
||||
if (layerCount(landing.entry.view) > 0) return cancelLanding()
|
||||
return landAfterModalsClosed(() => land(landing, latest.current))
|
||||
}, [landing, book])
|
||||
}
|
||||
|
||||
/** The view the reducer holds, as one object that changes only when the view does. */
|
||||
@@ -284,6 +364,11 @@ function useManualScroll(): void {
|
||||
}, [])
|
||||
}
|
||||
|
||||
/** A Back still awaited when the editor goes: its timer goes with it. */
|
||||
function useBackTimerCleanup(book: Book): void {
|
||||
useEffect(() => () => clearTimeout(book.backTimer), [book])
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -294,15 +379,19 @@ function usePop(ctx: PopContext): Landing | null {
|
||||
const location = useLocation()
|
||||
const navType = useNavigationType()
|
||||
const [landing, setLanding] = useState<Landing | null>(null)
|
||||
const { book } = ctx
|
||||
// Read once per location: the context is the one the render of that location holds.
|
||||
const latest = useRef(ctx)
|
||||
latest.current = ctx
|
||||
useEffect(() => {
|
||||
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])
|
||||
const now = latest.current
|
||||
if (now.book.seen === location) return
|
||||
now.book.seen = location
|
||||
if (now.book.entry === null) mount(now, location)
|
||||
// Another page (another sheet's editor, the list): the editor is leaving, it is the
|
||||
// new page's location, and a dirty dialog goes like on any leave.
|
||||
else if (location.pathname !== now.book.path) return
|
||||
else if (navType === 'POP') setLanding(landOn(now, location.state))
|
||||
}, [location, navType])
|
||||
return landing
|
||||
}
|
||||
|
||||
@@ -329,4 +418,5 @@ export default function useEditorHistory(
|
||||
useReconcile(nav, view, book, writer)
|
||||
useLanding(nav, book, landing)
|
||||
useManualScroll()
|
||||
useBackTimerCleanup(book)
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { HistoryOwner } from './history/entry'
|
||||
import type { NavigationState } from './navigation'
|
||||
import type { EditorNavigation, LayerName } from './useEditorNavigation'
|
||||
|
||||
/**
|
||||
* A dirty dialog lost when the editor goes (a Back of several entries, BDR-078: a Back
|
||||
* cannot be refused, and a draft is never stored). One flag in this tab's sessionStorage
|
||||
* says so to the next mount of the same sheet for the same account (criterion 17).
|
||||
*/
|
||||
const PREFIX = 'faunosteo:editor:left-draft:'
|
||||
|
||||
export const leftDraftKey = ({ sheetId, userId }: HistoryOwner) =>
|
||||
`${PREFIX}${sheetId}:${userId}`
|
||||
|
||||
/** The top layer first: the dialog the user was typing in when they left. */
|
||||
const LAYERS_TOP_DOWN: readonly LayerName[] = ['reference', 'finding']
|
||||
|
||||
function storage(): Storage | null {
|
||||
try {
|
||||
return typeof sessionStorage === 'undefined' ? null : sessionStorage
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** The element the layer showed: a key, a reference, a creation's parent. Never text. */
|
||||
function elementOf(state: NavigationState, layer: LayerName): unknown {
|
||||
if (layer === 'reference') {
|
||||
const { reference } = state
|
||||
return reference && 'edit' in reference
|
||||
? { kind: 'reference', id: reference.edit }
|
||||
: null
|
||||
}
|
||||
const { finding } = state
|
||||
if (!finding) return null
|
||||
return 'key' in finding ? finding.key : finding.create.parent
|
||||
}
|
||||
|
||||
/** Called as the editor goes: a layer whose form holds changes leaves the flag. */
|
||||
function flagIfDirty(owner: HistoryOwner, nav: EditorNavigation): void {
|
||||
if (!owner.sheetId || !owner.userId) return
|
||||
// A forced ask has no side effect: a dirty form answers with its note.
|
||||
const layer = LAYERS_TOP_DOWN.find((l) => nav.guards.ask(l, true).note)
|
||||
if (!layer) return
|
||||
const flag = { kind: layer, key: elementOf(nav.state, layer) }
|
||||
try {
|
||||
storage()?.setItem(leftDraftKey(owner), JSON.stringify(flag))
|
||||
} catch {
|
||||
// A full or blocked storage: the leave goes unsaid, as before.
|
||||
}
|
||||
}
|
||||
|
||||
/** True when the flag is there; read once per mount. */
|
||||
function readFlag(owner: HistoryOwner): boolean {
|
||||
try {
|
||||
return storage()?.getItem(leftDraftKey(owner)) != null
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function clearFlag(owner: HistoryOwner): void {
|
||||
try {
|
||||
storage()?.removeItem(leftDraftKey(owner))
|
||||
} catch {
|
||||
// Nothing to clear.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the last editor of this sheet and account left with a dirty dialog: shown once,
|
||||
* then cleared. The editor's own cleanup runs before its dialogs' (a deleted tree is
|
||||
* cleaned up from its root), so their guards still answer when it flags.
|
||||
*/
|
||||
export function useLeftDraft(
|
||||
nav: EditorNavigation,
|
||||
owner: HistoryOwner,
|
||||
): boolean {
|
||||
const latest = useRef(nav)
|
||||
latest.current = nav
|
||||
const [left] = useState(() => readFlag(owner))
|
||||
useEffect(() => {
|
||||
clearFlag(owner)
|
||||
return () => flagIfDirty(owner, latest.current)
|
||||
}, [owner])
|
||||
return left
|
||||
}
|
||||
@@ -217,6 +217,12 @@ function openFinding(state: NavigationState, key: ElementKey): NavigationState {
|
||||
return shown({ ...state, ...LEFT_REFERENCES, tab: 'findings', finding })
|
||||
}
|
||||
|
||||
/** The finding dialog closes with the reference dialog opened over its sheet. */
|
||||
function closeFinding(state: NavigationState): NavigationState {
|
||||
const reference = state.finding ? null : state.reference
|
||||
return { ...state, finding: null, reference }
|
||||
}
|
||||
|
||||
/** The creation form of a zone, a category or a node, on the Constats tab. */
|
||||
function createFinding(
|
||||
state: NavigationState,
|
||||
@@ -226,6 +232,17 @@ function createFinding(
|
||||
return shown({ ...state, ...LEFT_REFERENCES, tab: 'findings', finding })
|
||||
}
|
||||
|
||||
/** The dialog a move to `target` opens with it: a zone's or a finding's, in view mode. */
|
||||
function dialogOf(target: EditorTarget): EditorView['finding'] {
|
||||
const { key } = target
|
||||
const element = key?.kind === 'zone' || key?.kind === 'finding'
|
||||
return key && element ? { key, citations: false } : null
|
||||
}
|
||||
|
||||
/**
|
||||
* « Aller à »: every layer closes and the target is shown. A zone or a finding opens its
|
||||
* dialog in the same move, so the history writes one entry and keeps the place it left.
|
||||
*/
|
||||
function goTo(state: NavigationState, target: EditorTarget): NavigationState {
|
||||
const serial = state.serial + 1
|
||||
// The filter survives only a move to the tab itself that names no reference.
|
||||
@@ -234,7 +251,7 @@ function goTo(state: NavigationState, target: EditorTarget): NavigationState {
|
||||
...state,
|
||||
tab: target.tab,
|
||||
section: target.section ?? state.section,
|
||||
finding: null,
|
||||
finding: dialogOf(target),
|
||||
reference: null,
|
||||
referenceFilter: keep ? state.referenceFilter : null,
|
||||
focus: { target, serial },
|
||||
@@ -295,7 +312,7 @@ export function navigationReducer(
|
||||
case 'create_finding':
|
||||
return createFinding(state, { kind: action.kind, parent: action.parent })
|
||||
case 'close_finding':
|
||||
return { ...state, finding: null }
|
||||
return closeFinding(state)
|
||||
case 'open_citations':
|
||||
return openCitations(state, action.citedBy)
|
||||
case 'close_citations':
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import type { ElementKey } from '@faunosteo/core-wasm/types'
|
||||
import {
|
||||
afterModalsClosed,
|
||||
cancelLanding,
|
||||
landAfterModalsClosed,
|
||||
} from '@/components/ui/afterModalsClosed'
|
||||
import { useT } from '@/i18n/useT'
|
||||
@@ -75,6 +76,11 @@ export interface MoveTrace {
|
||||
replace: boolean
|
||||
/** « Revenir au constat »: a Back when the entry below shows this finding. */
|
||||
backTo: ElementKey | null
|
||||
/**
|
||||
* « Aller à »: a move of its own, it pushes. Set by the move, read and reset by the
|
||||
* adapter only: a place answering the move in the same commit (`mark`) keeps it.
|
||||
*/
|
||||
own: boolean
|
||||
}
|
||||
|
||||
/** Options of a tab choice. */
|
||||
@@ -100,8 +106,9 @@ export interface EditorNavigation {
|
||||
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.
|
||||
* element's dialog, or `null` for none (the reference dialog over its sheet goes too).
|
||||
* 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. */
|
||||
@@ -209,6 +216,7 @@ function useMoveTrace() {
|
||||
scrollY: null,
|
||||
replace: false,
|
||||
backTo: null,
|
||||
own: false,
|
||||
}).current
|
||||
const mark = useCallback(
|
||||
(replace = false) => {
|
||||
@@ -241,6 +249,7 @@ function useGo(dispatch: Dispatch<NavigationAction>, trace: MoveTrace) {
|
||||
trace.scrollY = window.scrollY
|
||||
trace.replace = false
|
||||
trace.backTo = null
|
||||
trace.own = kind === 'go_to'
|
||||
dispatch(action)
|
||||
setMove({ kind })
|
||||
},
|
||||
@@ -428,6 +437,11 @@ function useMoveFocus(
|
||||
}, [move, state, outcomes, dispatch, openers])
|
||||
}
|
||||
|
||||
/** A focus landing still waiting when the editor goes is dropped with it. */
|
||||
function useLandingCleanup() {
|
||||
useEffect(() => cancelLanding, [])
|
||||
}
|
||||
|
||||
/** The outcomes the places report for each focus request. */
|
||||
function useReceipts(dispatch: Dispatch<NavigationAction>) {
|
||||
const outcomes = useRef(new Map<number, FocusOutcome>())
|
||||
@@ -496,6 +510,7 @@ export function useEditorNavigation(
|
||||
const guards = useGuards()
|
||||
const receipts = useReceipts(base.dispatch)
|
||||
useMoveFocus(base.move, base.state, receipts.outcomes, base.dispatch, openers)
|
||||
useLandingCleanup()
|
||||
useCitedBy(base.state, openers)
|
||||
const ctx = {
|
||||
dispatch: base.dispatch,
|
||||
|
||||
@@ -56,10 +56,9 @@ function useOpening({ dispatch, mark }: LayerContext, held: RefObject<Opener>) {
|
||||
return { open, start }
|
||||
}
|
||||
|
||||
/** The moves that take it away: a user close, and the replace that is no Back step. */
|
||||
function useClosing(ctx: LayerContext) {
|
||||
const { dispatch, announce, guards, mark } = ctx
|
||||
const close = useCallback(
|
||||
/** A user close: the form may refuse it (a dirty draft asks first). */
|
||||
function useClose({ dispatch, guards, mark }: LayerContext) {
|
||||
return useCallback(
|
||||
(forced = false) => {
|
||||
if (!guards.ask('reference', forced).allowed) return false
|
||||
mark()
|
||||
@@ -68,7 +67,11 @@ function useClosing(ctx: LayerContext) {
|
||||
},
|
||||
[guards, dispatch, mark],
|
||||
)
|
||||
const replace = useCallback(
|
||||
}
|
||||
|
||||
/** The replace that is no Back step; with `text`, forced and said with a dropped draft. */
|
||||
function useReplace({ dispatch, announce, guards, mark }: LayerContext) {
|
||||
return useCallback(
|
||||
(id: string | null, text?: string) => {
|
||||
const note = text ? guards.ask('reference', true).note : undefined
|
||||
if (text) announce(note ? `${note}. ${text}` : text)
|
||||
@@ -79,7 +82,11 @@ function useClosing(ctx: LayerContext) {
|
||||
},
|
||||
[guards, announce, dispatch, mark],
|
||||
)
|
||||
return { close, replace }
|
||||
}
|
||||
|
||||
/** The moves that take it away: a user close, and the replace that is no Back step. */
|
||||
function useClosing(ctx: LayerContext) {
|
||||
return { close: useClose(ctx), replace: useReplace(ctx) }
|
||||
}
|
||||
|
||||
/** A creation that succeeded: its entry becomes the reference's own, then it closes. */
|
||||
|
||||
@@ -1645,6 +1645,9 @@ export const en: Dict = {
|
||||
'editor.findings.discard': 'Discard',
|
||||
'editor.findings.draft_dropped': 'Entry discarded',
|
||||
'editor.findings.gone': 'This finding no longer exists',
|
||||
// Provisional EN, pending the owner's wording.
|
||||
'editor.leave.draft_dropped':
|
||||
'An unsaved entry was discarded when you left the editor',
|
||||
'editor.findings.flip_narrow': 'Widen the window to continue: your entry is kept.',
|
||||
'editor.findings.flip_blocked': 'Editing is no longer possible: your entry is kept, you can only discard it.',
|
||||
'editor.verification.title': 'Draft check',
|
||||
|
||||
@@ -1676,6 +1676,8 @@ export const fr: Dict = {
|
||||
'editor.findings.discard': 'Abandonner',
|
||||
'editor.findings.draft_dropped': 'Saisie abandonnée',
|
||||
'editor.findings.gone': "Ce constat n'existe plus",
|
||||
'editor.leave.draft_dropped':
|
||||
"Une saisie non enregistrée a été abandonnée en quittant l'éditeur",
|
||||
'editor.findings.flip_narrow': 'Élargissez la fenêtre pour poursuivre : votre saisie est conservée.',
|
||||
'editor.findings.flip_blocked': "La modification n'est plus possible : votre saisie est conservée, vous pouvez seulement l'abandonner.",
|
||||
'editor.verification.title': 'Contrôle du brouillon',
|
||||
|
||||
Reference in new issue
Block a user