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()
|
||||
}
|
||||
Reference in new issue
Block a user