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:
bchanot committed 2026-11-13 23:42:32 +01:00
1 parent ce171427c0
commit 6bf9290da7
25 files changed
+1002 -202

No files matched your search

+12 -1
View File
@@ -491,9 +491,20 @@ for (const reduced of [false, true]) {
// The sheet closes and the family opens in the dialog (view mode); closed, the
// row holds the focus.
await expect(place(page, 'citations')).toHaveCount(0)
const family = findingDialog(page).getByRole('heading', {
name: 'Dysfonction A',
})
await expect(family).toBeVisible()
// Back returns to the place « Aller à » left: Constat A with its sheet open.
await page.goBack()
await expect(page.locator('dialog[open]')).toHaveCount(2)
await expect(place(page, 'citations')).toBeVisible()
await expect(
findingDialog(page).getByRole('heading', { name: 'Dysfonction A' }),
findingDialog(page).getByRole('heading', { name: 'Constat A' }),
).toBeVisible()
await page.goForward()
await expect(place(page, 'citations')).toHaveCount(0)
await expect(family).toBeVisible()
await closeFinding(page, dict)
await expect(
page.getByRole('treeitem', { name: /Dysfonction A/ }),
@@ -80,6 +80,31 @@ async function entryHolds(page: Page, test: string) {
)
}
/** A Back restores the page offset within this many pixels. */
const SCROLL_SLACK = 4
const scrollY = (page: Page) => page.evaluate(() => window.scrollY)
/**
* Pads the page so it can scroll whatever the viewport, then moves it to `y` (a page
* behind a modal still scrolls by script). Answers the offset reached.
*/
async function scrollTreeTo(page: Page, y: number): Promise<number> {
await page.evaluate((top) => {
document.body.style.paddingBottom = '3000px'
window.scrollTo(0, top)
}, y)
const reached = await scrollY(page)
expect(reached).toBeGreaterThan(0)
return reached
}
async function expectScrollNear(page: Page, y: number) {
await expect
.poll(async () => Math.abs((await scrollY(page)) - y))
.toBeLessThanOrEqual(SCROLL_SLACK)
}
/** Whether the sheet is the dialog on top at the right edge of the viewport. */
const sheetOnTop = (page: Page) =>
page.evaluate(() => {
@@ -127,6 +152,9 @@ test.describe('the owner journey through the history', () => {
await expect(place(page, 'citations')).toBeVisible()
await expect(sheetHeaders(page)).toHaveCount(2)
await entryHolds(page, 'view.finding && view.finding.citations')
// The tree behind the dialogs sits at an offset of its own (the page is padded so it
// can scroll whatever the viewport): Back must return to it.
const left = await scrollTreeTo(page, 400)
// 5. « Tout afficher dans l'onglet Références »; 6. the tab filtered on A's two references.
await panel(page)
.getByRole('button', { name: dict['editor.references.panel_show_all'] })
@@ -141,6 +169,7 @@ test.describe('the owner journey through the history', () => {
await expect(
libraryRoot(page).getByText('2 références', { exact: true }),
).toBeVisible()
expect(Math.abs((await scrollY(page)) - left)).toBeGreaterThan(SCROLL_SLACK)
// 7. browser Back; 8. finding A with its sheet on top, as left.
await page.goBack()
await expect(dialogs(page)).toHaveCount(2)
@@ -148,6 +177,13 @@ test.describe('the owner journey through the history', () => {
await expect(findingDialog(page)).toContainText('Constat A')
expect(await sheetOnTop(page)).toBe(true)
await expect(sheetHeaders(page)).toHaveCount(2)
await expectScrollNear(page, left)
// Closed by Escape (sheet, then dialog): the tree stays where it was left.
await page.keyboard.press('Escape')
await expect(dialogs(page)).toHaveCount(1)
await page.keyboard.press('Escape')
await expectNoDialog(page)
await expectScrollNear(page, left)
})
test('eight steps: finding, sheet, filter, edit, Back, Forward, Revenir au constat, every Back', async ({
@@ -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)
}
+69 -36
View File
@@ -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()
}
+4 -1
View File
@@ -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
+30 -13
View File
@@ -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'
}
+144 -54
View File
@@ -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)
}
+88
View File
@@ -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
}
+19 -2
View File
@@ -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':
+17 -2
View File
@@ -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,
+13 -6
View File
@@ -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. */
+3
View File
@@ -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',
+2
View File
@@ -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',
@@ -452,3 +452,94 @@ describe('read-only flip and the gone rule', () => {
expect(findingDialog()).toBeNull()
})
})
const liveText = () =>
document.querySelector('p.sr-only[aria-live="polite"]')!.textContent
describe('final review: a creation whose parent vanishes (M-1)', () => {
it('says the dropped names with the gone text, never silently', async () => {
const user = await mount()
act(() => treeRow(/Cat A/).focus())
await user.keyboard('{ArrowUp}{ArrowDown}')
await user.click(screen.getByRole('button', { name: 'Ajouter un constat' }))
await waitFor(() => expect(findingDialog()).not.toBeNull())
await user.type(document.getElementById('finding-new-name-fr')!, 'Tête')
act(() => {
store.getState().commit({
op: 'remove',
key: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a'] },
})
})
await closed()
await waitFor(() =>
expect(liveText()).toBe("Saisie abandonnée. Ce constat n'existe plus"),
)
})
})
describe('final review: the zone of a new category is part of the draft (criterion 8)', () => {
it('a zone changed alone asks before « Annuler » closes', async () => {
serverHas(
insert(sheetText(), {
kind: 'zone',
value: { id: 'zone-b', name: name('Zone B'), categories: [] },
}),
3,
)
const user = userEvent.setup()
mountDraft({ width: 1280, probe })
await screen.findByRole('heading', {
level: 1,
name: 'Brouillon, version 4',
})
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await user.click(
screen.getByRole('button', { name: 'Ajouter une catégorie' }),
)
await waitFor(() => expect(findingDialog()).not.toBeNull())
await user.selectOptions(inDialog().getByLabelText('Zone'), 'zone-b')
await user.click(inDialog().getByRole('button', { name: 'Annuler' }))
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
await user.click(
inDialog().getByRole('button', { name: 'Continuer la saisie' }),
)
act(() => inDialog().getByLabelText('Zone').focus())
await user.keyboard('{Escape}')
expect(findingDialog()).not.toBeNull()
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
})
})
describe('final review: leaving the editor with a dirty dialog (criterion 17)', () => {
const flagKey = `faunosteo:editor:left-draft:${SHEET}:${USER}`
const notice =
"Une saisie non enregistrée a été abandonnée en quittant l'éditeur"
it('leaves one flag without the text, then a notice once on the next mount', async () => {
const user = await mount()
await openFinding(user, /Node A/)
await modify(user)
await user.type(nameField(), ' bis')
cleanup()
const flag = sessionStorage.getItem(flagKey)
expect(flag).not.toBeNull()
expect(flag).not.toContain('bis')
expect(JSON.parse(flag!)).toEqual({
kind: 'finding',
key: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a', 'fnode-a'] },
})
await mount()
expect(screen.getByText(notice)).toBeVisible()
expect(sessionStorage.getItem(flagKey)).toBeNull()
cleanup()
await mount()
expect(screen.queryByText(notice)).toBeNull()
})
it('a clean dialog leaves no flag', async () => {
const user = await mount()
await openFinding(user, /Node A/)
cleanup()
expect(sessionStorage.getItem(flagKey)).toBeNull()
})
})
@@ -331,3 +331,57 @@ describe('the view the reducer holds', () => {
expect(state.visitedTabs).toEqual(['findings'])
})
})
describe('final review: « Aller à » is a move of its own (I-2)', () => {
it('pushes over the sheet it leaves, even with fewer layers on the same tab', () => {
const sheet = view('findings', { finding: { key: node, citations: true } })
const other: ElementKey = {
kind: 'finding',
zone_id: 'z',
path: ['f', 'm'],
}
const target = view('findings', {
finding: { key: other, citations: false },
})
const top = entry({ view: sheet, below: view('findings') })
expect(planWrite(top, target, false)).toBe('replace')
expect(planWrite(top, target, false, null, true)).toBe('push')
// An arrow-key replace still wins.
expect(planWrite(top, target, true, null, true)).toBe('replace')
})
})
describe('final review: read-back values are capped', () => {
const long = 'x'.repeat(129)
const atCap = 'x'.repeat(128)
const deep = (length: number): ElementKey => ({
kind: 'finding',
zone_id: 'z',
path: Array.from({ length }, (_, i) => `p${i}`),
})
const onFindings = (key: ElementKey) =>
view('findings', { finding: { key, citations: false } })
it('drops an entry whose id, sheet or account is over 128 characters', () => {
expect(readEntry(stateOf(entry({ id: atCap })))).not.toBeNull()
expect(readEntry(stateOf(entry({ id: long })))).toBeNull()
expect(readEntry(stateOf(entry({ sheetId: long })))).toBeNull()
expect(readEntry(stateOf(entry({ userId: long })))).toBeNull()
})
it('drops a key with an over-long id or a path deeper than the tree allows', () => {
const zone: ElementKey = { kind: 'zone', id: long }
expect(
readEntry(stateOf(entry({ view: onFindings(zone) })))?.view.finding,
).toBeNull()
const wideZone: ElementKey = { kind: 'finding', zone_id: long, path: ['a'] }
expect(sanitizeView(onFindings(wideZone))?.finding).toBeNull()
const wideId: ElementKey = { kind: 'finding', zone_id: 'z', path: [long] }
expect(sanitizeView(onFindings(wideId))?.finding).toBeNull()
expect(sanitizeView(onFindings(deep(8)))?.finding).not.toBeNull()
expect(sanitizeView(onFindings(deep(9)))?.finding).toBeNull()
const edit = { ...onFindings(node), reference: { edit: long } }
const sheet = { ...edit, finding: { key: node, citations: true } }
expect(sanitizeView(sheet)?.reference).toBeNull()
})
})
@@ -3,9 +3,11 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import {
act,
cleanup,
fireEvent,
render,
renderHook,
screen,
waitFor,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { ElementKey } from '@faunosteo/core-wasm/types'
@@ -21,7 +23,7 @@ import { useBeforeUnload } from '@/app/useLeaveGuard'
import EditorTabs from '@/components/editor/EditorTabs'
import { ENTRY_KEY, type HistoryEntry } from '@/editor/history/entry'
import useEditorHistory from '@/editor/history/useEditorHistory'
import { defaultView } from '@/editor/navigation'
import { defaultView, targetOfKey } from '@/editor/navigation'
import { useEditorNavigation } from '@/editor/useEditorNavigation'
import { useLocaleStore } from '@/state/localeStore'
@@ -33,6 +35,11 @@ const finding: ElementKey = {
zone_id: 'zone',
path: ['family', 'node'],
}
const other: ElementKey = {
kind: 'finding',
zone_id: 'zone',
path: ['family', 'other'],
}
let navigate: NavigateFunction
let location: Location
@@ -48,6 +55,10 @@ function Page({ guard }: { guard?: () => { allowed: boolean } }) {
<EditorTabs active={nav.state.tab} tier="wide" onSelect={nav.selectTab} />
<button onClick={() => nav.openFinding(finding)}>open</button>
<button onClick={() => nav.openCitations(finding)}>cite</button>
<button onClick={() => nav.closeCitations()}>uncite</button>
<button onClick={() => nav.closeFinding()}>close</button>
<button onClick={() => nav.showAllReferences(finding)}>show all</button>
<button onClick={() => nav.navigate(targetOfKey(other))}>go to</button>
<button onClick={() => nav.guards.register('finding', guard ?? null)}>
guard
</button>
@@ -59,9 +70,12 @@ function Page({ guard }: { guard?: () => { allowed: boolean } }) {
)
}
const mount = (guard?: () => { allowed: boolean }) =>
const mount = (
guard?: () => { allowed: boolean },
entries: string[] = ['/x'],
) =>
render(
<MemoryRouter initialEntries={['/x']}>
<MemoryRouter initialEntries={entries} initialIndex={entries.length - 1}>
<Page guard={guard} />
</MemoryRouter>,
)
@@ -204,3 +218,144 @@ describe('useBeforeUnload', () => {
expect(second.defaultPrevented).toBe(false)
})
})
const click = (name: string) =>
userEvent.click(screen.getByRole('button', { name }))
const findingLayer = () => JSON.parse(screen.getByTestId('layer').textContent!)
/** A layer dialog on screen: what a Back that reopens the layers shows. */
function openLayerDialog() {
const dialog = document.createElement('dialog')
dialog.setAttribute('open', '')
dialog.setAttribute('data-layer', '')
document.body.append(dialog)
return dialog
}
async function settleDialogs(dialog: HTMLElement) {
dialog.remove()
await act(async () => {
flushAfterModals()
await Promise.resolve()
await Promise.resolve()
})
}
const setScrollY = (y: number) =>
Object.defineProperty(window, 'scrollY', {
configurable: true,
writable: true,
value: y,
})
describe('final review: a Back into the layers (I-1)', () => {
afterEach(() => {
setScrollY(0)
vi.restoreAllMocks()
})
it('restores the page scroll, however the dialogs are closed afterwards', async () => {
useLocaleStore.setState({ locale: 'fr' })
const scrollTo = vi.spyOn(window, 'scrollTo').mockImplementation(() => {})
mount()
await userEvent.click(screen.getByRole('tab', { name: 'Constats' }))
setScrollY(500)
await click('open')
await click('cite')
await click('show all')
setScrollY(0)
scrollTo.mockClear()
const dialog = openLayerDialog()
act(() => navigate(-1))
expect(findingLayer()).toMatchObject({ citations: true })
// Closed by ✕ / Escape: each close dispatches and renders again.
await click('uncite')
await click('close')
await settleDialogs(dialog)
expect(scrollTo).toHaveBeenCalledWith(0, 500)
})
})
describe('final review: « Aller à » from the sheet (I-2)', () => {
it('keeps the entry of the finding with its sheet: Back from the target returns to it', async () => {
useLocaleStore.setState({ locale: 'fr' })
mount()
await userEvent.click(screen.getByRole('tab', { name: 'Constats' }))
await click('open')
await click('cite')
await click('go to')
expect(findingLayer()).toEqual({ key: other, citations: false })
expect(entry().below?.finding).toEqual({ key: finding, citations: true })
act(() => navigate(-1))
expect(findingLayer()).toEqual({ key: finding, citations: true })
})
})
describe('final review: a location that is not the editor’s (M-3)', () => {
it('writes nothing and asks no layer on a Back to another page', async () => {
useLocaleStore.setState({ locale: 'fr' })
const guard = vi.fn(() => ({ allowed: false }))
mount(guard, ['/y', '/x'])
await click('guard')
await userEvent.click(screen.getByRole('tab', { name: 'Constats' }))
await click('open')
act(() => navigate(-3))
expect(location.pathname).toBe('/y')
expect(location.state).toBeNull()
expect(guard).not.toHaveBeenCalled()
})
})
describe('final review: entry ids (M-4)', () => {
it('two mounts never share an entry id', async () => {
mount()
await waitFor(() => expect(entry()).toBeTruthy())
const first = entry().id
cleanup()
mount()
await waitFor(() => expect(entry()).toBeTruthy())
expect(entry().id).not.toBe(first)
})
})
describe('final review: past the write budget (M-5)', () => {
it('a close over a push kept in memory never goes back a real entry', async () => {
useLocaleStore.setState({ locale: 'fr' })
mount()
const tabOf = (name: string) => screen.getByRole('tab', { name })
fireEvent.click(tabOf('Constats'))
for (let i = 0; i < 19; i += 1) {
fireEvent.click(tabOf('Général'))
fireEvent.click(tabOf('Constats'))
}
// The 40th write of the window: sent. The 41st (the sheet) stays in memory.
fireEvent.click(screen.getByRole('button', { name: 'open' }))
fireEvent.click(screen.getByRole('button', { name: 'cite' }))
const top = location.key
fireEvent.click(screen.getByRole('button', { name: 'uncite' }))
expect(findingLayer()).toEqual({ key: finding, citations: false })
expect(screen.getByRole('tab', { selected: true })).toHaveTextContent(
'Constats',
)
expect(location.key).toBe(top)
expect(entry().view.finding).toEqual({ key: finding, citations: false })
})
})
describe('final review: queued landings (M-6)', () => {
it('a Back during the exit cancels the stale « Tout afficher » landing', async () => {
useLocaleStore.setState({ locale: 'fr' })
mount()
await userEvent.click(screen.getByRole('tab', { name: 'Constats' }))
await click('open')
await click('cite')
const exiting = openLayerDialog()
await click('show all')
act(() => navigate(-1))
expect(findingLayer()).toMatchObject({ citations: true })
const focused: Element[] = []
const record = (event: FocusEvent) => focused.push(event.target as Element)
document.addEventListener('focusin', record)
await settleDialogs(exiting)
document.removeEventListener('focusin', record)
const references = screen.getByRole('tab', { name: 'Références' })
expect(focused).not.toContain(references)
})
})
@@ -231,3 +231,18 @@ describe('the platform back request', () => {
expect(more()).toHaveAttribute('aria-expanded', 'false')
})
})
describe('final review: keyboard focus leaving « Plus » (M-8)', () => {
it('closes when the focus moves out of the trigger and the list', async () => {
const { user } = mount()
await user.click(more())
const item = screen.getByRole('button', { name: 'Constats' })
act(() => item.focus())
expect(more()).toHaveAttribute('aria-expanded', 'true')
act(() => more().focus())
expect(more()).toHaveAttribute('aria-expanded', 'true')
act(() => screen.getByRole('button', { name: 'outside' }).focus())
expect(more()).toHaveAttribute('aria-expanded', 'false')
await gone()
})
})
+27 -2
View File
@@ -104,11 +104,11 @@ describe('navigationReducer', () => {
expect(state.focus?.target).toEqual(targetOfKey(key))
})
it('go_to a tab closes the finding layers', () => {
it('go_to a place that is no finding closes the finding layers', () => {
const state = run(
initialNavigation('general'),
{ type: 'open_citations', citedBy: node },
{ type: 'go_to', target: targetOfKey(finding) },
{ type: 'go_to', target: targetOfKey(view) },
)
expect(state.finding).toBeNull()
})
@@ -306,3 +306,28 @@ describe('navigationReducer', () => {
expect(state.visitedSections).toEqual(['drawing', 'categories'])
})
})
describe('final review', () => {
it('a go_to a finding or a zone opens its dialog in the same move (I-2)', () => {
const state = run(
initialNavigation('general'),
{ type: 'open_citations', citedBy: node },
{ type: 'go_to', target: targetOfKey(finding) },
)
expect(state.finding).toEqual({ key: finding, citations: false })
const zone: ElementKey = { kind: 'zone', id: 'z1' }
const onZone = run(state, { type: 'go_to', target: targetOfKey(zone) })
expect(onZone.finding).toEqual({ key: zone, citations: false })
})
it('close_finding takes the reference dialog over the sheet with it (M-2)', () => {
const state = run(
initialNavigation('findings'),
{ type: 'open_citations', citedBy: node },
{ type: 'open_reference', id: 'r1' },
{ type: 'close_finding' },
)
expect(state.finding).toBeNull()
expect(state.reference).toBeNull()
})
})
@@ -532,3 +532,30 @@ describe('the finding filter', () => {
expect(chip()).toBeVisible()
})
})
describe('final review: the creation dialog fades out as a creation (M-9)', () => {
it('never shows the edit title while it closes', async () => {
const user = await mount()
await user.click(
screen.getByRole('button', { name: 'Ajouter une référence' }),
)
await waitFor(() => expect(refDialog()).toBeDefined())
await user.selectOptions(field('Type'), 'book')
await user.type(field('Citation'), 'Nouvelle source')
const titles = new Set<string>()
const seen = new MutationObserver(() => {
document
.querySelectorAll('dialog h2')
.forEach((h) => titles.add(h.textContent ?? ''))
})
seen.observe(document.body, {
subtree: true,
childList: true,
characterData: true,
})
await save(user)
await closed()
seen.disconnect()
expect(titles).not.toContain('Modifier la référence')
})
})