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

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

No files matched your search

@@ -1,21 +1,16 @@
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { useMemo, useState, type ReactNode } from 'react'
import { useLocation } from 'react-router-dom'
import { AnimatePresence } from 'motion/react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import type { OfficialSheetAdmin } from '@faunosteo/supabase'
import Notice from '@/components/ui/Notice'
import { ReadOnlyContext, ReferencesOpenContext } from '@/editor/editingContext'
import {
AnnounceContext,
FocusConsumedContext,
isTextField,
} from '@/editor/focusRequest'
import { EditorModeContext, ReadOnlyContext } from '@/editor/editingContext'
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 } from '@/editor/history/entry'
import { ownedEntry, withoutForms } from '@/editor/history/entry'
import useEditorHistory from '@/editor/history/useEditorHistory'
import { defaultView } from '@/editor/navigation'
import { citationsOfView, defaultView } from '@/editor/navigation'
import { findingLayerOf } from '@/editor/findingLayer'
import { initialTab } from '@/editor/tabs'
import {
useEditorNavigation,
@@ -31,7 +26,7 @@ import EditorTabBody from './EditorTabBody'
import EditorTabs from './EditorTabs'
import ModeNotice from './ModeNotice'
import RecoveryNotice from './RecoveryNotice'
import CitationsLayer from './references/CitationsLayer'
import CitationsSheet from './references/CitationsSheet'
interface Props {
sheet: OfficialSheetAdmin
@@ -61,18 +56,16 @@ function SaveFailureNotice() {
/** What dialogs and edit-only parts below need of the editor's state. */
function EditingState({
readOnly,
citationsOf,
mode,
children,
}: {
readOnly: boolean
citationsOf: ElementKey | null
mode: EditorMode
children: ReactNode
}) {
return (
<ReadOnlyContext value={readOnly}>
<ReferencesOpenContext value={citationsOf}>
{children}
</ReferencesOpenContext>
<EditorModeContext value={mode}>{children}</EditorModeContext>
</ReadOnlyContext>
)
}
@@ -84,75 +77,42 @@ interface PlacesProps {
}
/**
* Under the tab row: the tab panels and the citations panel of a finding beside them. The
* container starts after the tab row, so the panel and its scrim never cover the header or
* the tabs; from the opening to the end of the exit the tab panels are inert. Its minimum
* height is permanent (never toggled): the panel and the scrim reach the bottom of the
* window and the document never changes size when the panel opens or closes (P16').
* The tab panels, then the citations sheet: the sheet comes after the tab body (which
* holds the finding dialog) so it is shown after it and lies over it.
*/
function Places({ nav, readOnly, reloadSheet }: PlacesProps) {
const { state } = nav
const open = state.citationsOf !== null
return (
<div className="relative min-h-[calc(100dvh-3.5rem)]">
<AnimatePresence onExitComplete={nav.exitComplete}>
{state.citationsOf && !nav.exiting && (
<CitationsLayer
key="citations"
readOnly={readOnly}
citedBy={state.citationsOf}
onClose={nav.closeCitations}
onGone={nav.dropCitations}
onShowAll={nav.showAllReferences}
navigate={nav.navigate}
registerCanLeave={nav.registerCanLeave}
/>
)}
</AnimatePresence>
<div inert={open}>
<EditorTabBody
tab={state.tab}
visited={state.visitedTabs}
readOnly={readOnly}
navigate={nav.navigate}
openCitations={nav.openCitations}
libraryReset={state.libraryReset}
focus={state.focus}
reloadSheet={reloadSheet}
annotations={{
section: state.section,
visited: state.visitedSections,
onOpenSection: nav.openSection,
onBack: nav.backToDrawing,
}}
/>
</div>
</div>
<>
<EditorTabBody
tab={state.tab}
visited={state.visitedTabs}
readOnly={readOnly}
navigate={nav.navigate}
layer={findingLayerOf(nav)}
libraryReset={state.libraryReset}
focus={state.focus}
reloadSheet={reloadSheet}
annotations={{
section: state.section,
visited: state.visitedSections,
onOpenSection: nav.openSection,
onBack: nav.backToDrawing,
}}
/>
<CitationsSheet
citedBy={citationsOfView(state)}
readOnly={readOnly}
guards={nav.guards}
onClose={nav.closeCitations}
onShowAll={nav.showAllReferences}
navigate={nav.navigate}
returnFocus={nav.citationsTrigger}
/>
</>
)
}
/**
* A keydown aimed at `body` (nothing focused) never reaches the workspace's own handler:
* while the citations panel is open, Escape there closes it all the same, unless a
* modal dialog is open or the key was already handled.
*/
function useBodyEscape(open: boolean, close: () => void) {
const closeRef = useRef(close)
closeRef.current = close
useEffect(() => {
if (!open) return
const onKey = (event: KeyboardEvent) => {
if (event.key !== 'Escape' || event.defaultPrevented) return
if (event.isComposing || event.target !== document.body) return
if (document.querySelector('dialog[open]')) return
event.preventDefault()
closeRef.current()
}
document.addEventListener('keydown', onKey)
return () => document.removeEventListener('keydown', onKey)
}, [open])
}
/**
* 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
@@ -169,24 +129,15 @@ export default function EditorWorkspace(props: Props) {
)
// A reload or a reopened entry shows the view the history kept, never a layer.
const { state } = useLocation()
const [entry] = useState(() => ownedEntry(state, owner))
const nav = useEditorNavigation(tab, entry?.view)
const [view] = useState(() => {
const entry = ownedEntry(state, owner)
return entry && withoutForms(entry.view)
})
const nav = useEditorNavigation(tab, view)
useEditorHistory(nav, owner, defaultView(tab))
const open = nav.state.citationsOf !== null
useBodyEscape(open, nav.closeCitations)
return (
<EditingState readOnly={readOnly} citationsOf={nav.state.citationsOf}>
<div
className="space-y-4"
data-editor-workspace
onKeyDown={(event) => {
if (event.key !== 'Escape' || event.defaultPrevented) return
if (event.nativeEvent.isComposing || !open) return
if (isTextField(event.target)) return
event.preventDefault()
nav.closeCitations()
}}
>
<EditingState readOnly={readOnly} mode={mode}>
<div className="space-y-4" data-editor-workspace>
<DraftHeader sheet={sheet} mode={mode} />
<ModeNotice mode={mode} sheet={sheet} />
<SaveFailureNotice />
@@ -3,7 +3,7 @@ import Input from '@/components/ui/Input'
import Textarea from '@/components/ui/Textarea'
/**
* A controlled field of a creation form: it never commits, the form's own button does
* A controlled field of a form: it never commits, the form's own button does
* (BDR-050). The committed fields of existing elements are `TextField`.
*/
export default function DraftField({
@@ -13,6 +13,7 @@ export default function DraftField({
onChange,
onBlur,
multiline,
readOnly,
hint,
error,
}: {
@@ -23,6 +24,8 @@ export default function DraftField({
/** Optional: a form field that applies its text when it loses the focus. */
onBlur?: () => void
multiline?: boolean
/** Shown but not editable (the editor turned read-only under a form that is kept). */
readOnly?: boolean
hint?: string
error?: string
}) {
@@ -31,6 +34,8 @@ export default function DraftField({
value,
onChange: (e: { target: { value: string } }) => onChange(e.target.value),
onBlur,
readOnly,
'aria-readonly': readOnly || undefined,
'aria-invalid': Boolean(error),
'aria-describedby': fieldDescribedBy(id, hint, error),
}
@@ -22,6 +22,7 @@ export default function AddBar({
return (
<div className="flex flex-wrap gap-2">
<ActionButton
id="finding-add-zone"
readOnly={readOnly}
variant="secondary"
size="sm"
@@ -30,6 +31,7 @@ export default function AddBar({
{t('editor.findings.add_zone')}
</ActionButton>
<ActionButton
id="finding-add-category"
readOnly={readOnly}
variant="secondary"
size="sm"
@@ -39,6 +41,7 @@ export default function AddBar({
{t('editor.findings.add_category')}
</ActionButton>
<ActionButton
id="finding-add-node"
readOnly={readOnly}
variant="secondary"
size="sm"
@@ -0,0 +1,41 @@
import { useEffect, useRef } from 'react'
import Button from '@/components/ui/Button'
import { useT } from '@/i18n/useT'
/**
* The footer of a form with changes that a close request reached: keep typing (focused),
* or discard. It is part of the dialog, never inert.
*/
export default function DiscardConfirm({
onKeepTyping,
onDiscard,
}: {
onKeepTyping: () => void
onDiscard: () => void
}) {
const t = useT()
const keep = useRef<HTMLButtonElement>(null)
useEffect(() => keep.current?.focus(), [])
return (
<div
role="group"
aria-label={t('editor.findings.discard_ask')}
className="space-y-2 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-strong)] p-3"
>
<p className="text-sm font-medium">{t('editor.findings.discard_ask')}</p>
<div className="flex flex-wrap justify-end gap-2">
<Button
ref={keep}
type="button"
variant="secondary"
onClick={onKeepTyping}
>
{t('editor.findings.keep_typing')}
</Button>
<Button type="button" variant="danger" onClick={onDiscard}>
{t('editor.findings.discard')}
</Button>
</div>
</div>
)
}
@@ -1,113 +1,10 @@
import type { EditCommand } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import MoveButtons from '@/components/editor/fields/MoveButtons'
import TextField from '@/components/editor/fields/TextField'
import FindingContent from '@/components/editor/findings/FindingContent'
import StatusBadge from '@/components/editor/findings/StatusBadge'
import { patchElement, type FindingItem } from '@/editor/findings/tree'
import { isBlank } from '@/editor/sheetDocument'
import { useEditCommand, type EditCommandApi } from '@/editor/useEditCommand'
import type { Locale } from '@/i18n/types'
import type { FindingItem } from '@/editor/findings/tree'
import type { EditCommandApi } from '@/editor/useEditCommand'
import { useT } from '@/i18n/useT'
export interface FindingDetailProps {
item: FindingItem
readOnly: boolean
onDelete: () => void
/** Opens the citations panel of this finding (a family has none). */
onShowReferences?: (opener: HTMLElement) => void
}
/** The selected element: its names, its review state and the actions on it. */
export default function FindingDetail({
item,
readOnly,
onDelete,
onShowReferences,
}: FindingDetailProps) {
const t = useT()
const edit = useEditCommand()
return (
<div className="space-y-3 rounded-lg border border-[var(--color-border)] p-3">
<div className="flex flex-wrap items-center gap-2">
<p className="text-sm font-medium">
{t(`editor.findings.type.${item.kind}`)}
</p>
{item.status && <StatusBadge status={item.status} />}
</div>
<Names item={item} readOnly={readOnly} edit={edit} />
<FindingContent
item={item}
readOnly={readOnly}
edit={edit}
onShowReferences={onShowReferences}
/>
<div className="flex flex-wrap items-center justify-end gap-1">
<ReviewActions item={item} readOnly={readOnly} edit={edit} />
<MoveButtons
index={item.index}
count={item.siblings}
readOnly={readOnly}
onMove={(position) =>
edit.run('actions', { op: 'move', key: item.key, position })
}
/>
<ActionButton
readOnly={readOnly}
variant="danger"
size="sm"
onClick={onDelete}
>
{t('editor.action.delete')}
</ActionButton>
</div>
{edit.fieldError('actions') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('actions')}
</p>
)}
</div>
)
}
function Names({
item,
readOnly,
edit,
}: {
item: FindingItem
readOnly: boolean
edit: EditCommandApi
}) {
const t = useT()
const rename = (locale: Locale) => (value: string) =>
isBlank(value)
? edit.reject(locale, 'editor.field.required')
: edit.run(locale, {
op: 'update',
key: item.key,
element: patchElement(item, {
name: { ...item.name, [locale]: value },
}),
})
return (
<div className="grid gap-3 md:grid-cols-2">
{(['fr', 'en'] as const).map((locale) => (
<TextField
key={`${item.id}-${locale}`}
id={`finding-name-${locale}`}
label={t(`editor.general.name_${locale}`)}
value={item.name[locale]}
onCommit={rename(locale)}
readOnly={readOnly}
trim
error={edit.fieldError(locale)}
/>
))}
</div>
)
}
function statusCommand(
item: FindingItem,
status: 'reviewed' | 'to_confirm',
@@ -155,3 +52,54 @@ function ReviewActions({
</>
)
}
interface ActionsProps {
item: FindingItem
readOnly: boolean
edit: EditCommandApi
onEdit: () => void
onDelete: () => void
}
/** The view mode's actions (edit tier only): « Modifier », review, order, « Supprimer ». */
export default function FindingActions(props: ActionsProps) {
const { item, readOnly, edit, onEdit, onDelete } = props
const t = useT()
return (
<>
<div className="flex flex-wrap items-center justify-end gap-1">
<ActionButton
id="finding-edit-button"
readOnly={readOnly}
variant="secondary"
size="sm"
onClick={onEdit}
>
{t('editor.findings.edit')}
</ActionButton>
<ReviewActions item={item} readOnly={readOnly} edit={edit} />
<MoveButtons
index={item.index}
count={item.siblings}
readOnly={readOnly}
onMove={(position) =>
edit.run('actions', { op: 'move', key: item.key, position })
}
/>
<ActionButton
readOnly={readOnly}
variant="danger"
size="sm"
onClick={onDelete}
>
{t('editor.action.delete')}
</ActionButton>
</div>
{edit.fieldError('actions') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('actions')}
</p>
)}
</>
)
}
@@ -0,0 +1,138 @@
import Icon from '@/components/ui/Icon'
import ActionButton from '@/components/editor/fields/ActionButton'
import SelectField from '@/components/editor/fields/SelectField'
import { patchElement, type FindingItem } from '@/editor/findings/tree'
import { usePlural } from '@/editor/plural'
import { useSheetDocument } from '@/editor/sheetDocument'
import type { EditCommandApi } from '@/editor/useEditCommand'
import { useT } from '@/i18n/useT'
interface CitationsProps {
item: FindingItem
readOnly: boolean
edit: EditCommandApi
/** The citations sheet is open over the dialog (the trigger reads « expanded »). */
sheetOpen: boolean
/** Opens the citations sheet; a family has none (it lists its citations here). */
onShowReferences: (opener: HTMLElement) => void
}
const RING =
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
/** « X références »: the way to the sheet of a finding node's citations. */
function SheetTrigger({
item,
count,
sheetOpen,
onShowReferences,
}: Pick<CitationsProps, 'item' | 'sheetOpen' | 'onShowReferences'> & {
count: number
}) {
const plural = usePlural()
return (
<button
type="button"
data-citations-trigger={JSON.stringify(item.key)}
aria-expanded={sheetOpen}
aria-controls="editor-citations-panel"
onClick={(event) => onShowReferences(event.currentTarget)}
className={`inline-flex min-h-11 items-center gap-1 rounded-full border border-[var(--color-border)] px-3 text-sm ${RING}`}
>
<Icon name="book" size={16} />
{plural('editor.findings.references_open', count)}
</button>
)
}
/** A family's inline list of cited references, each removable (« Retirer »). */
function CitationList({
ids,
readOnly,
remove,
}: {
ids: readonly string[]
readOnly: boolean
remove: (id: string) => void
}) {
const t = useT()
const doc = useSheetDocument()
const citation = (id: string) =>
doc?.references.find((r) => r.id === id)?.citation ?? id
return (
<ul className="space-y-1">
{ids.map((id) => (
<li key={id} className="flex items-center gap-2 text-sm">
<span className="min-w-0 flex-1">{citation(id)}</span>
<ActionButton
readOnly={readOnly}
variant="ghost"
size="sm"
aria-label={`${t('editor.action.remove')} ${citation(id)}`}
onClick={() => remove(id)}
>
{t('editor.action.remove')}
</ActionButton>
</li>
))}
</ul>
)
}
/**
* « Références citées » of a category or a node. A finding node shows « X références »
* (the sheet), a family its list. « Citer une référence » acts at once, one entry in the
* document's history, in view mode too (it is no part of the transactional form).
*/
export default function FindingCitations(props: CitationsProps) {
const { item, readOnly, edit } = props
const t = useT()
const doc = useSheetDocument()
const { element } = item
if (element.kind === 'zone') return null
const ids = element.value.reference_ids
const patch = (reference_ids: string[]) =>
edit.run('references', {
op: 'update',
key: item.key,
element: patchElement(item, { reference_ids }),
})
const options = [
{ value: '', label: t('editor.field.choose') },
...(doc?.references ?? [])
.filter((r) => !ids.includes(r.id))
.map((r) => ({ value: r.id, label: r.citation })),
]
return (
<div className="space-y-2">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="text-sm font-medium">{t('editor.findings.references')}</p>
{ids.length > 0 && element.kind === 'finding_node' && (
<SheetTrigger {...props} count={ids.length} />
)}
</div>
{ids.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.findings.references_none')}
</p>
)}
{element.kind === 'finding_category' && (
<CitationList
ids={ids}
readOnly={readOnly}
remove={(id) => patch(ids.filter((other) => other !== id))}
/>
)}
{!readOnly && (
<SelectField
id="finding-add-reference"
label={t('editor.findings.reference_add')}
value=""
options={options}
onCommit={(id) => id !== '' && patch([...ids, id])}
error={edit.fieldError('references')}
/>
)}
</div>
)
}
@@ -1,211 +0,0 @@
import { useContext } from 'react'
import ActionButton from '@/components/editor/fields/ActionButton'
import ReadOnlyValue from '@/components/editor/fields/ReadOnlyValue'
import SelectField from '@/components/editor/fields/SelectField'
import TextField from '@/components/editor/fields/TextField'
import Icon from '@/components/ui/Icon'
import { ReferencesOpenContext } from '@/editor/editingContext'
import {
patchElement,
sameKey,
type FindingItem,
type FindingPatch,
} from '@/editor/findings/tree'
import { usePlural } from '@/editor/plural'
import { optionalText, useSheetDocument } from '@/editor/sheetDocument'
import type { EditCommandApi } from '@/editor/useEditCommand'
import type { Locale } from '@/i18n/types'
import { useT } from '@/i18n/useT'
interface ContentProps {
item: FindingItem
readOnly: boolean
edit: EditCommandApi
/** Opens the citations panel; given for a finding only, a family has no panel. */
onShowReferences?: (opener: HTMLElement) => void
}
/** The content of a category or a node: descriptions, vet referral, cited references. */
export default function FindingContent(props: ContentProps) {
const { element } = props.item
if (element.kind === 'zone') return null
const patch = (field: string, change: FindingPatch) =>
props.edit.run(field, {
op: 'update',
key: props.item.key,
element: patchElement(props.item, change),
})
return (
<div className="space-y-3">
<Descriptions
{...props}
current={element.value.description}
patch={patch}
/>
{element.kind === 'finding_node' && (
<VetFlag
{...props}
value={element.value.requires_vet_referral}
patch={patch}
/>
)}
<Citations
{...props}
ids={element.value.reference_ids}
patch={patch}
onShowReferences={
element.kind === 'finding_node' ? props.onShowReferences : undefined
}
/>
</div>
)
}
type Patch = (field: string, change: FindingPatch) => boolean
function Descriptions({
item,
readOnly,
edit,
current,
patch,
}: ContentProps & {
current: { fr?: string; en?: string }
patch: Patch
}) {
const t = useT()
const commit = (locale: Locale) => (value: string) =>
patch(`description-${locale}`, {
description: optionalText(current, locale, value),
})
return (
<div className="grid gap-3 md:grid-cols-2">
{(['fr', 'en'] as const).map((locale) => (
<TextField
key={`${item.id}-${locale}`}
id={`finding-description-${locale}`}
label={t(`editor.findings.description_${locale}`)}
value={current[locale] ?? ''}
onCommit={commit(locale)}
readOnly={readOnly}
multiline
error={edit.fieldError(`description-${locale}`)}
/>
))}
</div>
)
}
function VetFlag({
readOnly,
edit,
value,
patch,
}: ContentProps & { value: boolean; patch: Patch }) {
const t = useT()
const label = t('editor.findings.vet_referral')
if (readOnly) {
const answer = t(value ? 'editor.findings.yes' : 'editor.findings.no')
return <ReadOnlyValue id="finding-vet" label={label} value={answer} />
}
return (
<div>
<label className="flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={value}
onChange={(e) =>
patch('vet', { requires_vet_referral: e.target.checked })
}
/>
{label}
</label>
{edit.fieldError('vet') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('vet')}
</p>
)}
</div>
)
}
function Citations({
item,
readOnly,
edit,
ids,
patch,
onShowReferences,
}: ContentProps & { ids: readonly string[]; patch: Patch }) {
const t = useT()
const plural = usePlural()
const doc = useSheetDocument()
const citationsOf = useContext(ReferencesOpenContext)
const panelOpen = citationsOf !== null && sameKey(citationsOf, item.key)
const references = doc?.references ?? []
const citation = (id: string) =>
references.find((r) => r.id === id)?.citation ?? id
const options = [
{ value: '', label: t('editor.field.choose') },
...references
.filter((r) => !ids.includes(r.id))
.map((r) => ({ value: r.id, label: r.citation })),
]
return (
<div className="space-y-2">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="text-sm font-medium">{t('editor.findings.references')}</p>
{ids.length > 0 && onShowReferences && (
<button
type="button"
data-citations-trigger={JSON.stringify(item.key)}
aria-expanded={panelOpen}
aria-controls="editor-citations-panel"
onClick={(event) => onShowReferences(event.currentTarget)}
className="inline-flex min-h-11 items-center gap-1 rounded-full border border-[var(--color-border)] px-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
>
<Icon name="book" size={16} />
{plural('editor.findings.references_open', ids.length)}
</button>
)}
</div>
{ids.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.findings.references_none')}
</p>
)}
<ul className="space-y-1">
{ids.map((id) => (
<li key={id} className="flex items-center gap-2 text-sm">
<span className="min-w-0 flex-1">{citation(id)}</span>
<ActionButton
readOnly={readOnly}
variant="ghost"
size="sm"
aria-label={`${t('editor.action.remove')} ${citation(id)}`}
onClick={() =>
patch('references', {
reference_ids: ids.filter((other) => other !== id),
})
}
>
{t('editor.action.remove')}
</ActionButton>
</li>
))}
</ul>
{!readOnly && (
<SelectField
id="finding-add-reference"
label={t('editor.findings.reference_add')}
value=""
options={options}
onCommit={(id) =>
id !== '' && patch('references', { reference_ids: [...ids, id] })
}
error={edit.fieldError('references')}
/>
)}
</div>
)
}
@@ -4,9 +4,12 @@ import type {
FindingCategoryKind,
FindingNode,
} from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import DraftField from '@/components/editor/fields/DraftField'
import SelectField from '@/components/editor/fields/SelectField'
import DiscardConfirm from '@/components/editor/findings/DiscardConfirm'
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
import { useDirtyGuard } from '@/components/editor/findings/useDirtyGuard'
import Button from '@/components/ui/Button'
import {
buildItems,
type FindingItem,
@@ -15,6 +18,7 @@ import {
import type { IdPrefix } from '@/editor/ids'
import { isBlank, useSheetDocument } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import type { Guards } from '@/editor/useEditorNavigation'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
@@ -31,26 +35,30 @@ export interface PendingFinding {
parent: FindingItem | null
}
export interface FindingCreateFormProps {
pending: PendingFinding
readOnly: boolean
guards: Guards
/** `created` is the new element's id, `parent` the element it went under. */
onCreated: (id: string, parent: FindingItem | null) => void
/** A close of the dialog; forced after « Abandonner ». */
onClose: (forced: boolean) => void
}
/**
* Collects what the core requires (names FR/EN, the kind of a category), then one
* `insert`: no element exists with default labels.
* `insert`: no element exists with default labels. The fields are a local draft: nothing
* is written before « Créer », a close or a move never creates (R2F-3).
*/
export default function FindingCreateForm({
pending,
onCreated,
onCancel,
}: {
pending: PendingFinding
onCreated: (id: string, parent: FindingItem | null) => void
onCancel: () => void
}) {
export default function FindingCreateForm(props: FindingCreateFormProps) {
const { pending, readOnly, guards, onCreated, onClose } = props
const t = useT()
const edit = useEditCommand()
const zones = useZoneChoice()
const title = useFormTitle(pending, zones.chosen)
const [fr, setFr] = useState('')
const [en, setEn] = useState('')
const [kind, setKind] = useState('')
const guard = useDirtyGuard(guards, fr !== '' || en !== '' || kind !== '')
const create = () => {
const parent = pending.kind === 'category' ? zones.chosen : pending.parent
const missingParent = pending.kind === 'category' && !parent
@@ -71,16 +79,27 @@ export default function FindingCreateForm({
})
if (added) onCreated(createdId, parent)
}
const category = pending.kind === 'category'
return (
<div className="space-y-2 rounded-lg border border-dashed border-[var(--color-border)] p-3">
<p className="text-sm font-medium">{title}</p>
<form
data-draft-form
className="space-y-3"
noValidate
onSubmit={(event) => {
event.preventDefault()
create()
}}
>
{readOnly && <ReadOnlyNotice />}
{category && zones.chosen && <ZoneTitle zone={zones.chosen} />}
<div className="grid gap-3 md:grid-cols-2">
{pending.kind === 'category' && <ZoneSelect zones={zones} />}
{pending.kind === 'category' && (
{category && <ZoneSelect zones={zones} readOnly={readOnly} />}
{category && (
<SelectField
id="finding-new-kind"
label={t('editor.findings.kind')}
value={kind}
readOnly={readOnly}
options={[
{ value: '', label: t('editor.field.choose') },
...CATEGORY_KINDS.map((k) => ({
@@ -96,12 +115,14 @@ export default function FindingCreateForm({
label={t('editor.general.name_fr')}
value={fr}
onChange={setFr}
readOnly={readOnly}
/>
<DraftField
id="finding-new-name-en"
label={t('editor.general.name_en')}
value={en}
onChange={setEn}
readOnly={readOnly}
/>
</div>
{edit.fieldError('form') && (
@@ -109,15 +130,26 @@ export default function FindingCreateForm({
{edit.fieldError('form')}
</p>
)}
<div className="flex gap-2">
<ActionButton readOnly={false} variant="secondary" onClick={create}>
{t('editor.findings.create')}
</ActionButton>
<ActionButton readOnly={false} variant="ghost" onClick={onCancel}>
{t('editor.findings.cancel')}
</ActionButton>
</div>
</div>
{guard.confirming ? (
<DiscardConfirm
onKeepTyping={guard.keepTyping}
onDiscard={() => onClose(true)}
/>
) : (
<div className="flex flex-wrap justify-end gap-2">
<Button
type="button"
variant="ghost"
onClick={() => onClose(readOnly)}
>
{t(readOnly ? 'editor.findings.discard' : 'editor.findings.cancel')}
</Button>
<Button type="submit" disabled={readOnly}>
{t('editor.findings.create')}
</Button>
</div>
)}
</form>
)
}
@@ -139,7 +171,13 @@ function useZoneChoice(): ZoneChoice {
return { zones, zoneId, setZoneId, chosen }
}
function ZoneSelect({ zones }: { zones: ZoneChoice }) {
function ZoneSelect({
zones,
readOnly,
}: {
zones: ZoneChoice
readOnly: boolean
}) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
return (
@@ -147,6 +185,7 @@ function ZoneSelect({ zones }: { zones: ZoneChoice }) {
id="finding-new-zone"
label={t('editor.findings.zone')}
value={zones.zoneId}
readOnly={readOnly}
options={[
{ value: '', label: t('editor.field.choose') },
...zones.zones.map((zone) => ({
@@ -159,19 +198,17 @@ function ZoneSelect({ zones }: { zones: ZoneChoice }) {
)
}
/** A category lands at zone level: its title names the zone chosen in the form. */
function useFormTitle(
pending: PendingFinding,
zone: FindingItem | null,
): string {
/** A category lands at zone level: the line under the dialog's title names the zone chosen. */
function ZoneTitle({ zone }: { zone: FindingItem }) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
if (pending.kind !== 'category')
return t(`editor.findings.new.${pending.kind}`)
if (!zone) return t('editor.findings.add_category')
return t('editor.findings.new.category_in_zone').replace(
'{zone}',
zone.name[locale],
return (
<p className="text-sm font-medium">
{t('editor.findings.new.category_in_zone').replace(
'{zone}',
zone.name[locale],
)}
</p>
)
}
@@ -0,0 +1,133 @@
import { useEffect, useRef, useState } from 'react'
import FindingCreateForm, {
type PendingFinding,
} from '@/components/editor/findings/FindingCreateForm'
import FindingEditForm from '@/components/editor/findings/FindingEditForm'
import FindingView from '@/components/editor/findings/FindingView'
import Dialog from '@/components/ui/Dialog'
import { usePlaceVisible } from '@/lib/placeVisibility'
import type { FindingItem, FindingKind } from '@/editor/findings/tree'
import type { FindingLayer } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
export interface FindingDialogProps {
layer: FindingLayer
/** The element the dialog shows; null while it creates one or is closed. */
item: FindingItem | null
/** The creation the dialog holds, null for the view of an element. */
pending: PendingFinding | null
readOnly: boolean
/** Where the focus goes once the dialog is closed (the tree row, the add button). */
returnFocus: () => HTMLElement | null
onDelete: (item: FindingItem) => void
onCreated: (id: string, parent: FindingItem | null, kind: FindingKind) => void
}
interface ItemBodyProps {
item: FindingItem
layer: FindingLayer
readOnly: boolean
onDelete: (item: FindingItem) => void
}
const EDIT_BUTTON_ID = 'finding-edit-button'
/** After the form closes its button is gone: « Modifier » takes the focus back. */
function useFocusEditButton(editing: boolean) {
const wanted = useRef(false)
useEffect(() => {
if (editing || !wanted.current) return
wanted.current = false
document.getElementById(EDIT_BUTTON_ID)?.focus()
}, [editing])
return () => {
wanted.current = true
}
}
/** View mode, or the edit form: a local mode of the one dialog, no history entry. */
function ItemBody({ item, layer, readOnly, onDelete }: ItemBodyProps) {
const t = useT()
const [editing, setEditing] = useState(false)
const [saved, setSaved] = useState(false)
const returnToEdit = useFocusEditButton(editing)
const { view } = layer
const sheetOpen = view !== null && 'key' in view && view.citations
return (
<div className="space-y-2">
{editing ? (
<FindingEditForm
item={item}
readOnly={readOnly}
guards={layer.guards}
onDone={(wrote) => {
returnToEdit()
setSaved(wrote)
setEditing(false)
}}
onDiscardClose={() => layer.close(true)}
/>
) : (
<FindingView
item={item}
readOnly={readOnly}
sheetOpen={sheetOpen}
onEdit={() => {
setSaved(false)
setEditing(true)
}}
onDelete={() => onDelete(item)}
onShowReferences={(opener) => layer.openCitations(item.key, opener)}
/>
)}
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{saved ? t('editor.findings.saved') : ''}
</p>
</div>
)
}
/**
* The finding dialog (R2F-3): one `ModalDialog` kept across its modes (view, edit,
* creation). The view layer of the browser history drives it; it opens only while its
* place is shown (no native modal inside a hidden part).
*/
export default function FindingDialog(props: FindingDialogProps) {
const { layer, item, pending, readOnly } = props
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const visible = usePlaceVisible()
const title = pending
? t(`editor.findings.new.${pending.kind}`)
: (item?.name[locale] ?? '')
return (
<Dialog
open={visible && (item !== null || pending !== null)}
layer
size="lg"
title={title}
returnFocus={props.returnFocus}
onClose={() => (layer.close() ? undefined : 'kept')}
>
{pending && (
<FindingCreateForm
pending={pending}
readOnly={readOnly}
guards={layer.guards}
onCreated={(id, parent) => props.onCreated(id, parent, pending.kind)}
onClose={(forced) => layer.close(forced)}
/>
)}
{item && (
<ItemBody
key={item.id}
item={item}
layer={layer}
readOnly={readOnly}
onDelete={props.onDelete}
/>
)}
</Dialog>
)
}
@@ -0,0 +1,209 @@
import { useRef, useState } from 'react'
import DraftField from '@/components/editor/fields/DraftField'
import DiscardConfirm from '@/components/editor/findings/DiscardConfirm'
import { useDirtyGuard } from '@/components/editor/findings/useDirtyGuard'
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
import Button from '@/components/ui/Button'
import { patchElement, type FindingItem } from '@/editor/findings/tree'
import { isBlank, optionalText } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import type { Guards } from '@/editor/useEditorNavigation'
import { useT } from '@/i18n/useT'
/** What the form edits, as plain strings: nothing is written before « Enregistrer ». */
interface Draft {
fr: string
en: string
descriptionFr: string
descriptionEn: string
vet: boolean
}
function draftOf(item: FindingItem): Draft {
const { element } = item
const described = element.kind === 'zone' ? {} : element.value.description
return {
fr: item.name.fr,
en: item.name.en,
descriptionFr: described.fr ?? '',
descriptionEn: described.en ?? '',
vet: element.kind === 'finding_node' && element.value.requires_vet_referral,
}
}
/** The draft as it would be saved: names trimmed, a blank description absent. */
function normalized(draft: Draft): Draft {
return {
...draft,
fr: draft.fr.trim(),
en: draft.en.trim(),
descriptionFr: isBlank(draft.descriptionFr) ? '' : draft.descriptionFr,
descriptionEn: isBlank(draft.descriptionEn) ? '' : draft.descriptionEn,
}
}
const sameDraft = (a: Draft, b: Draft) =>
JSON.stringify(normalized(a)) === JSON.stringify(normalized(b))
/** The one `update` the form makes: names, and for a family or a node the texts. */
function patchOf(item: FindingItem, draft: Draft) {
const now = normalized(draft)
const { element } = item
const name = { fr: now.fr, en: now.en }
if (element.kind === 'zone') return patchElement(item, { name })
let description = optionalText(
element.value.description,
'fr',
now.descriptionFr,
)
description = optionalText(description, 'en', now.descriptionEn)
const vet = { requires_vet_referral: now.vet }
return patchElement(item, {
name,
description,
...(element.kind === 'finding_node' ? vet : {}),
})
}
export interface FindingEditFormProps {
item: FindingItem
readOnly: boolean
guards: Guards
/** Back to the view mode; `saved` is true when a command was written. */
onDone: (saved: boolean) => void
/** « Abandonner » after a close request: the draft goes, so does the dialog. */
onDiscardClose: () => void
}
function VetCheckbox({
checked,
readOnly,
onChange,
}: {
checked: boolean
readOnly: boolean
onChange: (value: boolean) => void
}) {
const t = useT()
return (
<label className="flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={checked}
disabled={readOnly}
onChange={(event) => onChange(event.target.checked)}
/>
{t('editor.findings.vet_referral')}
</label>
)
}
/**
* The element edited in the finding dialog (R2F-3): a local draft, one `update` on
* « Enregistrer » (none when nothing changed), nothing on « Annuler » or a close. When the
* editor turns read-only the draft stays, its fields read-only, and only « Abandonner »
* is left.
*/
export default function FindingEditForm(props: FindingEditFormProps) {
const { item, readOnly, guards, onDone, onDiscardClose } = props
const t = useT()
const edit = useEditCommand()
const initial = useRef(draftOf(item)).current
const [draft, setDraft] = useState(initial)
const [blank, setBlank] = useState<readonly string[]>([])
const dirty = !sameDraft(draft, initial)
const guard = useDirtyGuard(guards, dirty)
const set = (change: Partial<Draft>) => setDraft({ ...draft, ...change })
const save = () => {
const missing = (['fr', 'en'] as const).filter((l) => isBlank(draft[l]))
setBlank(missing)
if (missing.length > 0) {
document.getElementById(`finding-edit-name-${missing[0]}`)?.focus()
return
}
if (!dirty) return onDone(false)
const command = {
op: 'update',
key: item.key,
element: patchOf(item, draft),
} as const
if (edit.run('save', command)) onDone(true)
}
const cancel = () => (dirty && !readOnly ? guard.askToLeave() : onDone(false))
const described = item.kind !== 'zone'
const fieldError = (l: 'fr' | 'en') =>
blank.includes(l) ? t('editor.field.required') : undefined
return (
<form
data-draft-form
className="space-y-3"
noValidate
onSubmit={(event) => {
event.preventDefault()
save()
}}
>
{readOnly && <ReadOnlyNotice />}
<div className="grid gap-3 md:grid-cols-2">
{(['fr', 'en'] as const).map((l) => (
<DraftField
key={l}
id={`finding-edit-name-${l}`}
label={t(`editor.general.name_${l}`)}
value={draft[l]}
onChange={(value) => set({ [l]: value })}
readOnly={readOnly}
error={fieldError(l)}
/>
))}
{described &&
(['fr', 'en'] as const).map((l) => (
<DraftField
key={`d-${l}`}
id={`finding-edit-description-${l}`}
label={t(`editor.findings.description_${l}`)}
value={l === 'fr' ? draft.descriptionFr : draft.descriptionEn}
onChange={(value) =>
set(
l === 'fr'
? { descriptionFr: value }
: { descriptionEn: value },
)
}
readOnly={readOnly}
multiline
/>
))}
</div>
{item.element.kind === 'finding_node' && (
<VetCheckbox
checked={draft.vet}
readOnly={readOnly}
onChange={(vet) => set({ vet })}
/>
)}
{edit.fieldError('save') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('save')}
</p>
)}
{guard.confirming ? (
<DiscardConfirm
onKeepTyping={guard.keepTyping}
onDiscard={() =>
guard.confirming === 'dialog' ? onDiscardClose() : onDone(false)
}
/>
) : (
<div className="flex flex-wrap justify-end gap-2">
<Button type="button" variant="ghost" onClick={cancel}>
{t(readOnly ? 'editor.findings.discard' : 'editor.findings.cancel')}
</Button>
<Button type="submit" disabled={readOnly}>
{t('editor.findings.save')}
</Button>
</div>
)}
</form>
)
}
@@ -1,4 +1,5 @@
import { useEffect, useRef, type KeyboardEvent } from 'react'
import { afterModalsClosed } from '@/components/ui/afterModalsClosed'
import StatusBadge from '@/components/editor/findings/StatusBadge'
import { keyMove, type FindingItem } from '@/editor/findings/tree'
import { useT } from '@/i18n/useT'
@@ -9,6 +10,8 @@ export interface FindingTreeProps {
selectedId: string | null
expanded: ReadonlySet<string>
onSelect: (id: string) => void
/** Click, Enter or Space on a row: the row is selected and its dialog opens. */
onActivate: (item: FindingItem) => void
onToggle: (id: string, open: boolean) => void
/** Moves focus to this item (after a deletion); null leaves focus alone. */
focusId: { id: string } | null
@@ -26,6 +29,7 @@ export default function FindingTree(props: FindingTreeProps) {
const refs = useRef(new Map<string, HTMLElement>())
const focusAfter = useRef<string | null>(null)
const { visible, selectedId, expanded, onSelect, onToggle } = props
const { onActivate } = props
const { focusId, onFocused } = props
useEffect(() => {
if (focusAfter.current) refs.current.get(focusAfter.current)?.focus()
@@ -33,11 +37,17 @@ export default function FindingTree(props: FindingTreeProps) {
})
useEffect(() => {
if (!focusId) return
refs.current.get(focusId.id)?.focus()
// After the dialogs a move closed: the page behind them is inert until then.
afterModalsClosed(() => refs.current.get(focusId.id)?.focus())
onFocused()
}, [focusId, onFocused])
const current = visible.find((item) => item.id === selectedId) ?? visible[0]
const onKeyDown = (event: KeyboardEvent, item: FindingItem) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
onActivate(item)
return
}
const move = keyMove(visible, item, expanded, event.key)
if (!move) return
event.preventDefault()
@@ -66,7 +76,7 @@ export default function FindingTree(props: FindingTreeProps) {
else refs.current.delete(item.id)
}}
onKeyDown={onKeyDown}
onSelect={onSelect}
onActivate={onActivate}
onToggle={onToggle}
/>
))}
@@ -81,7 +91,7 @@ interface TreeRowProps {
open: boolean
register: (el: HTMLElement | null) => void
onKeyDown: (event: KeyboardEvent, item: FindingItem) => void
onSelect: (id: string) => void
onActivate: (item: FindingItem) => void
onToggle: (id: string, open: boolean) => void
}
@@ -92,7 +102,7 @@ function TreeRow({
open,
register,
onKeyDown,
onSelect,
onActivate,
onToggle,
}: TreeRowProps) {
const locale = useLocaleStore((s) => s.locale)
@@ -107,10 +117,11 @@ function TreeRow({
aria-expanded={item.hasChildren ? open : undefined}
tabIndex={tabbable ? 0 : -1}
data-testid="finding-item"
data-finding-key={JSON.stringify(item.key)}
onKeyDown={(event) => {
if (event.target === event.currentTarget) onKeyDown(event, item)
}}
onClick={() => onSelect(item.id)}
onClick={() => onActivate(item)}
style={{ paddingLeft: `${(item.level - 1) * 1.25 + 0.5}rem` }}
className={`flex cursor-pointer items-center gap-2 rounded-md py-1.5 pr-2 text-sm ${
selected
@@ -0,0 +1,94 @@
import ReadOnlyValue from '@/components/editor/fields/ReadOnlyValue'
import FindingActions from '@/components/editor/findings/FindingActions'
import FindingCitations from '@/components/editor/findings/FindingCitations'
import StatusBadge from '@/components/editor/findings/StatusBadge'
import type { FindingItem } from '@/editor/findings/tree'
import { useEditCommand } from '@/editor/useEditCommand'
import { useT } from '@/i18n/useT'
export interface FindingViewProps {
item: FindingItem
readOnly: boolean
sheetOpen: boolean
onEdit: () => void
onDelete: () => void
onShowReferences: (opener: HTMLElement) => void
}
/** The texts of a category or a node, read: descriptions, then the vet referral of a node. */
function Texts({ item }: { item: FindingItem }) {
const t = useT()
const { element } = item
if (element.kind === 'zone') return null
return (
<>
<div className="grid gap-3 md:grid-cols-2">
{(['fr', 'en'] as const).map((locale) => (
<ReadOnlyValue
key={locale}
id={`finding-description-${locale}`}
label={t(`editor.findings.description_${locale}`)}
value={element.value.description[locale] ?? ''}
multiline
/>
))}
</div>
{element.kind === 'finding_node' && (
<ReadOnlyValue
id="finding-vet"
label={t('editor.findings.vet_referral')}
value={t(
element.value.requires_vet_referral
? 'editor.findings.yes'
: 'editor.findings.no',
)}
/>
)}
</>
)
}
/**
* The element read in the finding dialog (R2F-3): type and status, names, texts, its
* citations, and the actions of the edit tier. Nothing here edits a field in place.
*/
export default function FindingView(props: FindingViewProps) {
const { item, readOnly, sheetOpen } = props
const t = useT()
const edit = useEditCommand()
return (
<div className="space-y-3">
<div className="flex flex-wrap items-center gap-2">
<p className="text-sm font-medium">
{t(`editor.findings.type.${item.kind}`)}
</p>
{item.status && <StatusBadge status={item.status} />}
</div>
<div className="grid gap-3 md:grid-cols-2">
{(['fr', 'en'] as const).map((locale) => (
<ReadOnlyValue
key={locale}
id={`finding-name-${locale}`}
label={t(`editor.general.name_${locale}`)}
value={item.name[locale]}
/>
))}
</div>
<Texts item={item} />
<FindingCitations
item={item}
readOnly={readOnly}
edit={edit}
sheetOpen={sheetOpen}
onShowReferences={props.onShowReferences}
/>
<FindingActions
item={item}
readOnly={readOnly}
edit={edit}
onEdit={props.onEdit}
onDelete={props.onDelete}
/>
</div>
)
}
@@ -0,0 +1,14 @@
import Notice from '@/components/ui/Notice'
import { useEditorMode } from '@/editor/editingContext'
import { useT } from '@/i18n/useT'
/**
* The editor turned read-only under a form the dialog keeps: why, worded from the mode.
* A narrow window comes back on widening; any other mode leaves only « Abandonner ».
*/
export default function ReadOnlyNotice() {
const t = useT()
const mode = useEditorMode()
const key = mode === 'narrow' ? 'flip_narrow' : 'flip_blocked'
return <Notice tone="info">{t(`editor.findings.${key}`)}</Notice>
}
@@ -0,0 +1,32 @@
import { useEffect, useRef, useState } from 'react'
import { useBeforeUnload } from '@/app/useLeaveGuard'
import type { Guards } from '@/editor/useEditorNavigation'
/** What the footer's « Abandonner » does: leave the form, or the whole dialog. */
export type DiscardTarget = 'form' | 'dialog'
/**
* The finding layer's guard while a form holds changes (R2F-3): a user close that reaches
* the layer (✕, Escape, scrim, Back) is refused and the form asks « Abandonner les
* modifications ? » (`confirming`). A forced close, or a form with nothing typed, goes
* ahead. `askToLeave` is the form's own « Annuler ». The browser's unload is guarded too.
*/
export function useDirtyGuard(guards: Guards, dirty: boolean) {
const [confirming, setConfirming] = useState<DiscardTarget | null>(null)
const latest = useRef(dirty)
latest.current = dirty
useBeforeUnload(dirty)
useEffect(() => {
guards.register('finding', (forced) => {
if (forced || !latest.current) return { allowed: true }
setConfirming('dialog')
return { allowed: false }
})
return () => guards.register('finding', null)
}, [guards])
return {
confirming,
askToLeave: () => setConfirming('form'),
keepTyping: () => setConfirming(null),
}
}
@@ -1,122 +0,0 @@
import { useEffect, useLayoutEffect, useRef, type RefObject } from 'react'
import { motion, useIsPresent, useReducedMotion } from 'motion/react'
import { PANEL_ENTER_S, PANEL_EXIT_S } from '@/editor/useCitationsExit'
import KeptPlace from '../KeptPlace'
import CitationsPanel from './CitationsPanel'
type Props = Parameters<typeof CitationsPanel>[0]
/** The top bar (`h-14`): the panel sticks right under it. */
const TOP_BAR_REM = 3.5
/**
* The panel's visible height: from its top (under the top bar once the page has scrolled)
* to the nearer of the container's bottom and the viewport's bottom. Kept right on scroll,
* resize and visual-viewport changes (mobile URL bar, keyboard); only the panel's own
* height is written, so the document never changes size.
*/
function useFitToViewport(panel: RefObject<HTMLElement | null>) {
useLayoutEffect(() => {
const element = panel.current
const container = element?.parentElement
if (!element || !container) return
const bar =
TOP_BAR_REM *
parseFloat(getComputedStyle(document.documentElement).fontSize)
const fit = () => {
const box = container.getBoundingClientRect()
const viewport = window.visualViewport?.height ?? window.innerHeight
const visible = Math.min(box.bottom, viewport) - Math.max(box.top, bar)
element.style.height = `${Math.max(visible, 0)}px`
}
fit()
const watched: EventTarget[] = [window]
if (window.visualViewport) watched.push(window.visualViewport)
for (const target of watched) {
target.addEventListener('scroll', fit, { passive: true })
target.addEventListener('resize', fit)
}
const observer =
typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(fit)
// Content above the container reflowing moves its top without resizing it.
observer?.observe(container)
observer?.observe(document.documentElement)
return () => {
for (const target of watched) {
target.removeEventListener('scroll', fit)
target.removeEventListener('resize', fit)
}
observer?.disconnect()
}
}, [panel])
}
/**
* The citations panel and its scrim over the places (board 25). The panel slides in from
* the right (translateX only), the scrim fades on the same timings; under reduced motion
* both change at once, the callbacks still fire (P29). While it exits, the panel is inert
* (the page behind stays inert until the workspace lifts it, P9).
*
* Geometry (P16, P16'): the wrapper fills the Places container, clips the slide on the x
* axis only (`clip`, never `hidden`) and is 34 rem at most; the panel inside sticks under
* the top bar, is exactly as tall as what is visible (`useFitToViewport`) and scrolls its
* own list, so the page's size never changes.
*/
export default function CitationsLayer(props: Props) {
const reduced = useReducedMotion()
const present = useIsPresent()
const layer = useRef<HTMLDivElement>(null)
const focused = useRef(false)
useFitToViewport(layer)
// A reopen during a slow exit reuses this instance: it focuses its heading again.
useEffect(() => {
if (!present) focused.current = false
}, [present])
const slide = { x: reduced ? 0 : '100%' }
const enter = {
duration: reduced ? 0 : PANEL_ENTER_S,
ease: 'easeOut',
} as const
const leave = {
duration: reduced ? 0 : PANEL_EXIT_S,
ease: 'easeIn',
} as const
// The heading takes the focus once the panel is in place (P9, P29).
const entered = () => {
if (!present || focused.current) return
focused.current = true
layer.current
?.querySelector<HTMLElement>('[data-place-heading]')
?.focus({ preventScroll: true })
}
return (
<>
<motion.div
aria-hidden="true"
data-testid="references-scrim"
onClick={props.onClose}
className="absolute inset-0 z-10 bg-[rgba(31,27,22,0.25)]"
initial={{ opacity: 0 }}
animate={{ opacity: 1, transition: enter }}
exit={{ opacity: 0, transition: leave }}
/>
<KeptPlace
name="citations"
visible
inert={!present}
className="absolute inset-y-0 right-0 z-20 w-[min(34rem,100%)] overflow-x-clip"
>
<motion.div
ref={layer}
className="sticky top-14"
initial={slide}
animate={{ x: 0, transition: enter }}
exit={{ ...slide, transition: leave }}
onAnimationComplete={entered}
>
<CitationsPanel {...props} />
</motion.div>
</KeptPlace>
</>
)
}
@@ -1,14 +1,7 @@
import {
useCallback,
useLayoutEffect,
useRef,
type KeyboardEvent,
type RefObject,
} from 'react'
import { useCallback, useLayoutEffect, useRef, type RefObject } from 'react'
import type { LocalizedText, Reference } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import Icon from '@/components/ui/Icon'
import { isTextField } from '@/editor/focusRequest'
import { targetOfKey, type EditorTarget } from '@/editor/navigation'
import { usePlural } from '@/editor/plural'
import type { CitationEntry } from '@/editor/references/panel'
@@ -18,7 +11,7 @@ import ReferenceTile from './ReferenceTile'
import { useCitationsPanel, type PanelHooks } from './useCitationsPanel'
interface Props extends PanelHooks {
/** ✕, Escape and the scrim: a close the tile in edit may refuse. */
/** ✕ (Escape and the scrim close the sheet itself): a close the tile in edit may refuse. */
onClose: () => void
/** « Tout afficher dans l'onglet Références ». */
onShowAll: () => void
@@ -231,20 +224,10 @@ function Entries({ panel, props }: { panel: Panel; props: Props }) {
)
}
/** Escape closes the panel, unless a field of it is being typed in (A5, P27). */
function closeOnEscape(onClose: () => void) {
return (event: KeyboardEvent) => {
if (event.key !== 'Escape' || event.defaultPrevented) return
if (event.nativeEvent.isComposing || isTextField(event.target)) return
event.stopPropagation()
onClose()
}
}
/**
* The citations of one finding (board 25): the references it cites as tiles, « Tout
* afficher » for the whole library. No search, add, delete or order (P7). Not a dialog:
* the workspace makes the page behind it inert. Opens from a finding's trigger only.
* The citations of one finding: the references it cites as tiles, « Tout afficher » for
* the whole library. No search, add, delete or order (P7). The content of the side sheet
* (CitationsSheet), which is the modal; opens from a finding's trigger only.
*/
export default function CitationsPanel(props: Props) {
const { onClose, onShowAll } = props
@@ -256,7 +239,6 @@ export default function CitationsPanel(props: Props) {
id="editor-citations-panel"
data-testid="editor-citations-panel"
aria-labelledby="editor-citations-title"
onKeyDown={closeOnEscape(onClose)}
className="flex h-full flex-col gap-3 border-l border-[var(--color-border)] bg-[var(--color-surface)] p-4 shadow-xl"
>
<PanelHeader onClose={onClose} headingRef={panel.heading} />
@@ -0,0 +1,86 @@
import { AnimatePresence, motion, useReducedMotion } from 'motion/react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import ModalDialog from '@/components/ui/ModalDialog'
import { isTextField } from '@/editor/focusRequest'
import type { EditorTarget } from '@/editor/navigation'
import type { Guards } from '@/editor/useEditorNavigation'
import CitationsPanel from './CitationsPanel'
/** Sheet motion (board 25): enter decelerates, the shorter exit accelerates (P9). */
const ENTER_S = 0.18
const EXIT_S = 0.14
export interface CitationsSheetProps {
/** The finding whose citations the view shows; null while the sheet is closed. */
citedBy: ElementKey | null
readOnly: boolean
guards: Guards
/** A user close (✕, Escape, scrim): false when a tile in edit refused it. */
onClose: () => boolean
/** « Tout afficher dans l'onglet Références ». */
onShowAll: () => void
/** « Aller à » a citing finding or a reference. */
navigate: (target: EditorTarget) => void
/** « X références » of the dialog under the sheet, where the focus returns. */
returnFocus: () => HTMLElement | null
}
/**
* The citations of a finding as a modal side sheet at the right edge, over the finding
* dialog (R2F-4): the host sits after the tab body in the tree, so it is shown after the
* dialog and lies on top of it. Escape and the scrim close the sheet only. Interim until
* the tiles stop editing inline: an Escape typed in a tile's field is the field's.
*/
function SheetSurface(props: CitationsSheetProps & { citedBy: ElementKey }) {
const { citedBy, onClose } = props
const reduced = useReducedMotion()
const slide = reduced ? { x: 0 } : { x: '100%' }
const enter = { duration: reduced ? 0 : ENTER_S, ease: 'easeOut' } as const
const leave = { duration: reduced ? 0 : EXIT_S, ease: 'easeIn' } as const
const close = () => (onClose() ? undefined : 'kept')
return (
<ModalDialog
layer
onClose={close}
returnFocus={props.returnFocus}
ignoreEscape={isTextField}
labelledBy="editor-citations-title"
className="open:block"
>
<motion.div
aria-hidden="true"
data-testid="references-scrim"
onClick={close}
className="absolute inset-0 bg-[rgba(31,27,22,0.25)]"
initial={{ opacity: 0 }}
animate={{ opacity: 1, transition: enter }}
exit={{ opacity: 0, transition: leave }}
/>
<motion.div
data-place="citations"
className="absolute inset-y-0 right-0 w-[min(34rem,100vw)]"
initial={slide}
animate={{ x: 0, transition: enter }}
exit={{ ...slide, transition: leave }}
>
<CitationsPanel
readOnly={props.readOnly}
citedBy={citedBy}
guards={props.guards}
onClose={onClose}
onShowAll={props.onShowAll}
navigate={props.navigate}
/>
</motion.div>
</ModalDialog>
)
}
export default function CitationsSheet(props: CitationsSheetProps) {
const { citedBy } = props
return (
<AnimatePresence>
{citedBy && <SheetSurface key="citations" {...props} citedBy={citedBy} />}
</AnimatePresence>
)
}
@@ -6,16 +6,15 @@ import { citedIds, citingFinding } from '@/editor/references/filter'
import { citationEntries, findingPath } from '@/editor/references/panel'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import type { CanLeave } from '@/editor/useEditorNavigation'
import type { Guards, LeaveAnswer } from '@/editor/useEditorNavigation'
import { useDroppedText } from './useReferenceEdit'
import { tileKeys, useTileState } from './useTileState'
export interface PanelHooks {
readOnly: boolean
citedBy: ElementKey
/** The finding vanished: a close nobody can refuse. */
onGone: () => void
registerCanLeave: (guard: CanLeave | null) => void
/** The layers' guards: the tile in edit registers its own for the sheet. */
guards: Guards
}
/** The finding read from the current document; null once the document lacks it. */
@@ -29,32 +28,26 @@ function useCitedFinding(citedBy: ElementKey) {
}
/**
* The panel closes once its finding is gone: a forced close. It runs after the leave
* check registered itself (effects of one component run in order), so a tile in edit is
* still asked. A read-only flip does not close it: the panel stays, as the crossing
* specs expect, and its tiles stop being editable.
* P22'': a move that leaves the sheet asks the tile in edit first (a refusal cancels the
* move); a forced one (the finding vanished) drops a refused draft and says so. Interim
* until the reference dialog replaces the inline tile edit.
*/
function useCloseWhenGone(gone: boolean, onGone: () => void) {
useEffect(() => {
if (gone) onGone()
}, [gone, onGone])
}
/** P22'': a user close asks the tile in edit first; a forced one drops a refused draft. */
function useLeaveCheck(
tiles: ReturnType<typeof useTileState>,
register: PanelHooks['registerCanLeave'],
) {
function useLeaveCheck(tiles: ReturnType<typeof useTileState>, guards: Guards) {
const droppedText = useDroppedText()
const check = (forced: boolean): LeaveAnswer => {
const refused = tiles.leave()
if (refused.length === 0) return { allowed: true }
if (!forced) return { allowed: false }
return { allowed: true, note: droppedText(refused) }
}
// Registered once and kept: the layers' effects of one commit run cleanups first, so a
// guard re-registered on every render would be absent when another layer asks.
const latest = useRef(check)
latest.current = check
useEffect(() => {
register((forced) => {
const refused = tiles.leave()
if (refused.length === 0) return { allowed: true }
if (!forced) return { allowed: false }
return { allowed: true, note: droppedText(refused) }
})
return () => register(null)
})
guards.register('citations', (forced) => latest.current(forced))
return () => guards.register('citations', null)
}, [guards])
}
/** The row the focus is in: its element, its index in the list and the list's length. */
@@ -108,7 +101,7 @@ function useFocusRescue() {
/**
* What the panel shows of the finding: its cited ids and its path. Once the finding is
* gone (the panel is leaving) the last known answer stays, so the panel does not empty
* gone (the sheet is leaving) the last known answer stays, so the sheet does not empty
* while it slides out and a tile in edit can still be asked to apply its draft.
*/
function useShownFinding(
@@ -142,8 +135,7 @@ export function useCitationsPanel(hooks: PanelHooks) {
const edit = useEditCommand()
const tiles = useTileState(doc ? keys : null)
const focus = useFocusRescue()
useLeaveCheck(tiles, hooks.registerCanLeave)
useCloseWhenGone(doc !== null && item === null, hooks.onGone)
useLeaveCheck(tiles, hooks.guards)
// « Retirer de ce constat » is the detail's « Retirer »: the same update of the finding's
// reference_ids, so the core marks the finding « À confirmer » (P15) and one « Défaire »
// restores the citation and the status together. The reference itself stays in the sheet.
@@ -2,6 +2,7 @@ import { useEffect, useState, type RefObject } from 'react'
import type { ElementKey, Reference } from '@faunosteo/core-wasm/types'
import {
focusRow,
focusRowLater,
useFocusRequest,
type FocusRequest,
} from '@/editor/focusRequest'
@@ -59,7 +60,7 @@ function useReferenceFocus(
if (target.key === null || at < 0) return 'none'
tiles.reveal(keys[at])
if (referenceMatches(all[at], shown.view.query)) {
return focusRow(target.key) ? 'found' : 'none'
return focusRowLater(target.key) ? 'found' : 'none'
}
shown.update({ query: '' })
later(target.key)
@@ -1,27 +1,28 @@
import { useCallback, useMemo, useState } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import DeleteDialog, {
type DeleteTarget,
} from '@/components/editor/DeleteDialog'
import EditOnly from '@/components/editor/EditOnly'
import AddBar from '@/components/editor/findings/AddBar'
import FindingCreateForm, {
type PendingFinding,
} from '@/components/editor/findings/FindingCreateForm'
import FindingDetail from '@/components/editor/findings/FindingDetail'
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 {
buildItems,
createdItemId,
createdKey,
fallbackAfterRemoval,
isUnder,
itemForKey,
sameKey,
visibleItems,
type FindingItem,
type FindingKind,
} from '@/editor/findings/tree'
import { useFocusRequest } from '@/editor/focusRequest'
import { useFocusRequest, visibleElement } from '@/editor/focusRequest'
import { useEditorStore } from '@/editor/state/editorStore'
import { useSheetDocument } from '@/editor/sheetDocument'
import type { EditorPlaceProps } from '@/editor/tabs'
import type { EditorPlaceProps, FindingLayer } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
@@ -35,12 +36,37 @@ function currentItems(): FindingItem[] {
}
}
/** A place mounted without the navigation (a test harness): no layer ever opens. */
const NO_LAYER: FindingLayer = {
view: null,
guards: {
register: () => undefined,
ask: () => ({ allowed: true }),
askAll: () => ({ allowed: true }),
},
open: () => undefined,
start: () => undefined,
close: () => true,
replace: () => undefined,
openCitations: () => undefined,
announce: () => undefined,
}
const ADD_BUTTON: Record<string, string> = {
zone: 'finding-add-zone',
category: 'finding-add-category',
node: 'finding-add-node',
}
/** The deletion flow: the target, the item to select after it, and the focus left behind. */
function useFindingDeletion(
items: readonly FindingItem[],
selectedId: string | null,
select: (id: string | null) => void,
focusItem: (id: string | null) => void,
actions: {
select: (id: string | null) => void
focusItem: (id: string | null) => void
closeLayer: () => void
},
) {
const locale = useLocaleStore((s) => s.locale)
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
@@ -49,29 +75,100 @@ function useFindingDeletion(
setFallback(fallbackAfterRemoval(items, item))
setDeleting({ key: item.key, label: item.name[locale] })
}
// 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.
const closeDelete = () => {
setDeleting(null)
const gone = !currentItems().some((item) => item.id === selectedId)
if (gone) {
select(fallback)
focusItem(fallback)
}
if (currentItems().some((item) => item.id === selectedId)) return
actions.select(fallback)
actions.closeLayer()
afterModalsClosed(() => actions.focusItem(fallback))
}
return { deleting, askDelete, closeDelete }
}
/** Constats: the tree zones → categories → nodes, edited one command at a time. */
/** The layer's element follows the view: a Back or a reload selects and shows its row. */
function useSelectionOfLayer(
layer: FindingLayer,
items: readonly FindingItem[],
show: (found: { item: FindingItem; ancestors: string[] }) => void,
) {
const { view } = layer
const wanted = view && 'key' in view ? JSON.stringify(view.key) : null
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
}, [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.
*/
function useGoneRule(layer: FindingLayer, loaded: boolean) {
const t = useT()
const { view } = layer
const handled = useRef<string | null>(null)
useEffect(() => {
if (!view) handled.current = null
if (!loaded || !view) return
const named = 'key' in view
const key = named ? 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
if (handled.current === stamp) return
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),
)
}, [loaded, view, layer, t])
}
/** Where a closed dialog returns the focus: its tree row, or the button that started it. */
function useReturnTarget(view: FindingLayer['view']) {
const last = useRef(view)
if (view) last.current = view
return useCallback((): HTMLElement | null => {
const shown = last.current
if (!shown) return null
if ('create' in shown) {
return document.getElementById(ADD_BUTTON[shown.create.kind])
}
const wanted = JSON.stringify(shown.key)
return visibleElement('[data-finding-key]', (el) => {
return el.dataset.findingKey === wanted
})
}, [])
}
/** The creation the view holds, with its parent read from the tree; null when none. */
function pendingOf(
view: FindingLayer['view'],
items: readonly FindingItem[],
): PendingFinding | null {
if (!view || !('create' in view)) return null
const { kind, parent } = view.create
const found = parent ? itemForKey(items, parent) : null
if (parent && !found) return null
return { kind: kind as FindingKind, parent: found?.item ?? null }
}
/** Constats: the tree zones → categories → nodes; each element opens in a dialog. */
export default function FindingsTab({
readOnly,
focus,
openCitations,
layer = NO_LAYER,
}: EditorPlaceProps) {
const t = useT()
const doc = useSheetDocument()
const [selectedId, setSelectedId] = useState<string | null>(null)
const [expanded, setExpanded] = useState<ReadonlySet<string>>(new Set())
const [seeded, setSeeded] = useState(false)
const [pending, setPending] = useState<PendingFinding | null>(null)
const [focusId, setFocusId] = useState<{ id: string } | null>(null)
const clearFocusId = useCallback(() => setFocusId(null), [])
const items = useMemo(() => (doc ? buildItems(doc) : []), [doc])
@@ -82,6 +179,10 @@ export default function FindingsTab({
)
}
const selected = items.find((item) => item.id === selectedId)
const reveal = (found: { item: FindingItem; ancestors: string[] }) => {
setExpanded((prev) => new Set([...prev, ...found.ancestors]))
setSelectedId(found.item.id)
}
const toggle = (id: string, open: boolean) => {
if (!open && selectedId && isUnder(items, selectedId, id)) {
setSelectedId(id)
@@ -96,23 +197,32 @@ export default function FindingsTab({
useFocusRequest(focus, (target) => {
const found = target.key && itemForKey(items, target.key)
if (!found) return 'none'
setExpanded((prev) => new Set([...prev, ...found.ancestors]))
setSelectedId(found.item.id)
reveal(found)
setFocusId({ id: found.item.id })
return 'found'
})
const created = (id: string, parent: FindingItem | null) => {
if (!pending) return
useSelectionOfLayer(layer, items, reveal)
useGoneRule(layer, doc !== null)
const created = (
id: string,
parent: FindingItem | null,
kind: FindingKind,
) => {
if (parent) toggle(parent.id, true)
setSelectedId(createdItemId(pending.kind, parent, id))
setPending(null)
setSelectedId(createdItemId(kind, parent, id))
layer.replace(createdKey(kind, parent, id))
}
const { deleting, askDelete, closeDelete } = useFindingDeletion(
items,
selectedId,
setSelectedId,
(id) => setFocusId(id ? { id } : null),
{
select: setSelectedId,
focusItem: (id) => setFocusId(id ? { id } : null),
closeLayer: () => layer.replace(null),
},
)
const { view } = layer
const shown = view && 'key' in view ? itemForKey(items, view.key) : null
return (
<section
data-testid="editor-tab-findings"
@@ -123,18 +233,8 @@ export default function FindingsTab({
selected={selected}
hasZone={items.some((item) => item.kind === 'zone')}
readOnly={readOnly}
onStart={setPending}
onStart={(p) => layer.start(p.kind, p.parent?.key ?? null)}
/>
{pending && (
<EditOnly readOnly={readOnly}>
<FindingCreateForm
key={`${pending.kind}-${pending.parent?.id ?? ''}`}
pending={pending}
onCreated={created}
onCancel={() => setPending(null)}
/>
</EditOnly>
)}
{doc && items.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.findings.empty')}
@@ -145,21 +245,23 @@ export default function FindingsTab({
selectedId={selected?.id ?? null}
expanded={expanded}
onSelect={setSelectedId}
onActivate={(item) => {
setSelectedId(item.id)
layer.open(item.key)
}}
onToggle={toggle}
focusId={focusId}
onFocused={clearFocusId}
/>
{selected && (
<FindingDetail
key={selected.id}
item={selected}
readOnly={readOnly}
onDelete={() => askDelete(selected)}
onShowReferences={
openCitations && ((opener) => openCitations(selected.key, opener))
}
/>
)}
<FindingDialog
layer={layer}
item={shown?.item ?? null}
pending={pendingOf(view, items)}
readOnly={readOnly}
returnFocus={useReturnTarget(view)}
onDelete={askDelete}
onCreated={created}
/>
<DeleteDialog target={deleting} onClose={closeDelete} />
</section>
)
+4
View File
@@ -9,6 +9,8 @@ export interface DialogProps {
onClose: () => unknown
/** Where the focus goes after the close (ModalDialog): a target, or null when a move owns it. */
returnFocus?: ModalDialogProps['returnFocus']
/** A view layer of the editor (ModalDialog): a Back may close it. */
layer?: boolean
title: string
/** The dialog's message, announced with its name (aria-describedby). */
description?: ReactNode
@@ -32,6 +34,7 @@ export default function Dialog({ open, ...surface }: DialogProps) {
function DialogSurface({
onClose,
returnFocus,
layer,
title,
description,
children,
@@ -46,6 +49,7 @@ function DialogSurface({
<ModalDialog
onClose={onClose}
returnFocus={returnFocus}
layer={layer}
labelledBy={titleId}
describedBy={description ? descriptionId : undefined}
className="open:flex items-center justify-center p-3 sm:p-4"
+36 -7
View File
@@ -20,6 +20,16 @@ export interface ModalDialogProps {
* move that closed it.
*/
returnFocus?: (() => HTMLElement | null) | null
/**
* Escape typed where this answers true is swallowed: no close request. For a part that
* still edits inline (the citations sheet's tiles) and keeps Escape for the field.
*/
ignoreEscape?: (target: EventTarget) => boolean
/**
* A view layer of the editor (R2F-1): its state is in the browser history, so a Back
* may close it. Any other modal open refuses a Back.
*/
layer?: boolean
/** Id of the visible title; `label` names a dialog that shows none. */
labelledBy?: string
label?: string
@@ -62,8 +72,9 @@ function ancestorsOf(element: HTMLElement | null): HTMLElement[] {
}
/**
* The resolved target when it takes focus, else the opener when it still does, else the
* first control of its nearest container still on the page.
* The resolved target when it takes focus; else, if the focus is nowhere (`body`), the
* opener when it still does, else the first control of its nearest container still on
* the page. A focus another closing dialog already placed is left alone.
*/
function restoreFocus(
target: HTMLElement | null,
@@ -71,6 +82,8 @@ function restoreFocus(
ancestors: HTMLElement[],
): void {
if (target && tryFocus(target, true)) return
const active = document.activeElement
if (active && active !== document.body) return
if (!opener || tryFocus(opener)) return
for (const container of ancestors) {
if (!container.isConnected) continue
@@ -92,6 +105,8 @@ function restoreFocus(
export default function ModalDialog({
onClose,
returnFocus,
ignoreEscape,
layer,
labelledBy,
label,
describedBy,
@@ -101,8 +116,12 @@ export default function ModalDialog({
const ref = useRef<HTMLDialogElement>(null)
const latest = useRef({ returnFocus, onClose })
latest.current = { returnFocus, onClose }
const isPresent = useIsPresent()
const present = useRef(true)
present.current = useIsPresent()
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)
useLayoutEffect(() => {
const dialog = ref.current
@@ -116,7 +135,11 @@ export default function ModalDialog({
// panel when the content is long, the close button otherwise.
dialog.querySelector<HTMLElement>(FOCUSABLE)?.focus()
return () => {
if (dialog.open) dialog.close()
if (dialog.open) {
closingSelf.current = true
dialog.close()
closingSelf.current = false
}
// 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(() => {
@@ -124,7 +147,9 @@ export default function ModalDialog({
if (!dialog.isConnected && resolve !== null) {
restoreFocus(resolve?.() ?? null, opener, ancestors)
}
flushAfterModals()
// After the restores of every dialog closed in this commit: a landing that
// waited for them must not be undone by a later one.
queueMicrotask(flushAfterModals)
})
}
}, [])
@@ -136,7 +161,8 @@ export default function ModalDialog({
event.preventDefault()
event.stopPropagation()
// A held key repeats: only the first press asks.
if (!event.repeat) onClose()
if (event.repeat || ignoreEscape?.(event.target)) return
onClose()
}
const onCancel = (event: SyntheticEvent<HTMLDialogElement>) => {
event.preventDefault()
@@ -147,7 +173,7 @@ export default function ModalDialog({
// A refused close shows the dialog again, never during an exit or once it is gone.
const onClosed = () => {
const dialog = ref.current
if (!dialog || dialog.open) return
if (!dialog || dialog.open || closingSelf.current) return
const refused = latest.current.onClose() === 'kept'
if (refused && present.current && dialog.isConnected) dialog.showModal()
}
@@ -155,6 +181,9 @@ export default function ModalDialog({
return (
<dialog
ref={ref}
// A dialog playing its exit answers nothing: a second click or key is lost.
inert={!isPresent}
data-layer={layer ? '' : undefined}
aria-labelledby={labelledBy}
aria-label={label}
aria-describedby={describedBy}
+1 -3
View File
@@ -7,7 +7,6 @@ import {
isTextField,
visibleElement,
} from '@/editor/focusRequest'
import { ReferencesOpenContext } from '@/editor/editingContext'
import { CANVAS_BOX } from '@/editor/useEditorNavigation'
import { useT } from '@/i18n/useT'
@@ -102,8 +101,7 @@ export function useSelectionEscape(
) {
const asideRef = useRef<HTMLElement>(null)
const deselect = useDeselect(id, clear)
const citationsOf = useContext(ReferencesOpenContext)
useEscapeDeselect(active && citationsOf === null, (event) =>
useEscapeDeselect(active, (event) =>
deselect.byKey(asideRef.current?.contains(event.target as Node) ?? false),
)
return { asideRef, byDrawing: deselect.byDrawing }
+11 -12
View File
@@ -1,31 +1,30 @@
import { createContext, useContext, useState } from 'react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import type { EditorMode } from './mode'
import { usePlaceVisible } from '@/lib/placeVisibility'
/** The editor cannot be edited now (route rule: mode, recovery, store not in step). */
export const ReadOnlyContext = createContext(false)
/**
* The finding whose citations panel is open, null when none. Set from the opening to the
* end of the exit animation: a place beside the panel is not where a modal may open, and
* only that finding's trigger reads « expanded ».
*/
export const ReferencesOpenContext = createContext<ElementKey | null>(null)
/** Why the editor is read-only, or `edit`: a kept form words its notice from it. */
export const EditorModeContext = createContext<EditorMode>('edit')
export function useEditorMode(): EditorMode {
return useContext(EditorModeContext)
}
export function useEditorReadOnly(): boolean {
return useContext(ReadOnlyContext)
}
/**
* Whether a decision dialog of a kept part may open: only while editing, in a shown
* place, with the citations panel closed, so no native modal ever sits inside a hidden
* subtree and focus is never lost to `body`.
* Whether a decision dialog of a kept part may open: only while editing and in a shown
* place, so no native modal ever sits inside a hidden subtree and focus is never lost
* to `body`.
*/
export function useDecisionsOpen(): boolean {
const readOnly = useContext(ReadOnlyContext)
const citationsOf = useContext(ReferencesOpenContext)
const visible = usePlaceVisible()
return !readOnly && visible && citationsOf === null
return !readOnly && visible
}
/**
+16
View File
@@ -0,0 +1,16 @@
import type { FindingLayer } from './tabs'
import type { EditorNavigation } from './useEditorNavigation'
/** What Constats needs of the navigation for its dialog and the sheet over it. */
export function findingLayerOf(nav: EditorNavigation): FindingLayer {
return {
view: nav.state.finding,
guards: nav.guards,
open: nav.openFinding,
start: nav.startFinding,
close: nav.closeFinding,
replace: nav.replaceFinding,
openCitations: nav.openCitations,
announce: nav.announce,
}
}
+11
View File
@@ -246,6 +246,17 @@ export function createdItemId(
return itemId(parent.zoneId, path)
}
/** The key of a just-inserted element, appended under `parent` (null = a zone). */
export function createdKey(
kind: FindingKind,
parent: FindingItem | null,
id: string,
): ElementKey {
if (kind === 'zone' || !parent) return { kind: 'zone', id }
const path = kind === 'category' ? [id] : [...parent.path, id]
return { kind: 'finding', zone_id: parent.zoneId, path }
}
/** The item a focus request names (a zone or a finding), with its ancestors' ids. */
export function itemForKey(
items: readonly FindingItem[],
+40 -12
View File
@@ -1,5 +1,6 @@
import { createContext, useContext, useEffect, useRef } from 'react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import { afterModalsClosed } from '@/components/ui/afterModalsClosed'
import type {
AnnotationSection,
EditorTarget,
@@ -82,21 +83,34 @@ export function visibleElement(
)
}
/** The visible row tagged with `key`. */
function rowOf(key: ElementKey): HTMLElement | null {
const wanted = JSON.stringify(key)
return visibleElement(
'[data-focus-key]',
(candidate) => candidate.dataset.focusKey === wanted,
)
}
/** Scrolls to and focuses the visible row tagged with `key`; false unless the row now holds the focus. */
export function focusRow(key: ElementKey): boolean {
const wanted = JSON.stringify(key)
const row = [
...document.querySelectorAll<HTMLElement>('[data-focus-key]'),
].find(
(candidate) =>
candidate.dataset.focusKey === wanted && !candidate.closest('[hidden]'),
)
const row = rowOf(key)
if (!row) return false
row.scrollIntoView?.({ block: 'center' })
row.focus()
return document.activeElement === row
}
/**
* The row is there: its focus waits for the dialogs a move closed (the page behind them
* is inert until then). False when no visible row carries `key`.
*/
export function focusRowLater(key: ElementKey): boolean {
if (!rowOf(key)) return false
afterModalsClosed(() => void focusRow(key))
return true
}
/** Row-based places (Général, Vues, Catégories, Régions): focus the named row. */
export function useRowFocus(focus: FocusRequest | undefined): void {
useFocusRequest(focus, (target) =>
@@ -132,13 +146,17 @@ export function isTextField(target: EventTarget | null): boolean {
/**
* Commits the text being typed before a place is left: blurs the focused field, so its
* `TextField` commits on blur. Safari and iPadOS do not move the focus to a tapped button,
* so the blur is forced rather than assumed. Answers whether a field was blurred.
* so the blur is forced rather than assumed. A field of a transactional form
* (`data-draft-form`) is a local draft nothing commits: it keeps its focus. Answers
* whether a field was blurred.
*/
export function commitFocusedField(): boolean {
const active = document.activeElement
const isField = isTextField(active)
if (isField) (active as HTMLElement).blur()
return isField
if (!isTextField(active)) return false
const field = active as HTMLElement
if (field.closest('[data-draft-form]')) return false
field.blur()
return true
}
/** The tab shown, or « Plus » while the shown tab sits in the closed list. */
@@ -154,6 +172,15 @@ export function focusActiveTab(options?: FocusOptions): void {
activeTabButton()?.focus(options)
}
/**
* The element sits in a transactional form of an open dialog: the form keeps its draft
* and its focus when the editor turns read-only, nothing moves it. (The citations
* sheet's tiles still edit inline until the reference dialog: they are not drafts.)
*/
function inOpenDialog(element: HTMLElement): boolean {
return element.closest('dialog[open] [data-draft-form]') !== null
}
/** The element holding the focus, when it is something other than `body`. */
export function heldElement(): HTMLElement | null {
const active = document.activeElement
@@ -178,7 +205,7 @@ export function refocusIfHidden(
held: HTMLElement | null,
home: HTMLElement | null = null,
): void {
if (!held) return
if (!held || inOpenDialog(held)) return
const gone = !held.isConnected || held.closest('[hidden]')
if (!gone && document.activeElement !== held) held.focus()
if (!gone && document.activeElement === held) return
@@ -193,6 +220,7 @@ export function refocusIfHidden(
*/
export function releaseEditFocus(): void {
const held = heldElement()
if (held && inOpenDialog(held)) return
commitFocusedField()
refocusIfHidden(held)
}
+60 -8
View File
@@ -1,5 +1,7 @@
import type { ElementKey } from '@faunosteo/core-wasm/types'
import {
ANNOTATION_SECTIONS,
isFindingNode,
sameView,
type AnnotationSection,
type EditorView,
@@ -32,24 +34,66 @@ export const ENTRY_KEY = 'editorEntry'
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null
/** A finding or zone key as the tree builds it, or null when `raw` is no such key. */
function sanitizeKey(raw: unknown): ElementKey | null {
if (!isRecord(raw)) return null
if (raw.kind === 'zone' && typeof raw.id === 'string') {
return { kind: 'zone', id: raw.id }
}
const { zone_id: zoneId, path } = raw
const ids = Array.isArray(path) && path.every((id) => typeof id === 'string')
if (raw.kind !== 'finding' || typeof zoneId !== 'string' || !ids) return null
return { kind: 'finding', zone_id: zoneId, path: path as string[] }
}
const CREATION_KINDS = ['zone', 'category', 'node']
/** A finding creation, a form: only read back where forms are kept. */
function sanitizeCreation(raw: unknown): EditorView['finding'] {
if (!isRecord(raw) || !isRecord(raw.create)) return null
const { kind, parent } = raw.create
if (typeof kind !== 'string' || !CREATION_KINDS.includes(kind)) return null
const key = parent === null ? null : sanitizeKey(parent)
if (parent !== null && key === null) return null
return { create: { kind, parent: key } }
}
/** The finding layer of a view: its dialog, with its citations sheet over it. */
function sanitizeFinding(raw: unknown, forms: boolean): EditorView['finding'] {
if (!isRecord(raw)) return null
if ('create' in raw) return forms ? sanitizeCreation(raw) : null
const key = sanitizeKey(raw.key)
if (!key) return null
const sheet = raw.citations === true && isFindingNode(key)
return { key, citations: sheet }
}
/**
* A view read back from a history entry, or null when it is no view. Vanished keys drop
* their layer: no layer is ever written yet, so the three layer fields come back null.
* shortcut: later layers validate their key against the loaded sheet here.
* A view read back from a history entry, or null when it is no view. The finding layer
* must name a well-formed key and sit on the Constats tab; whether the element still
* exists is the dialog's own gone rule. `forms` false drops the creation form (a reload
* never reopens a form). The reference layer and the filter stay null until they exist.
*/
export function sanitizeView(raw: unknown): EditorView | null {
export function sanitizeView(raw: unknown, forms = true): EditorView | null {
if (!isRecord(raw)) return null
if (!EDITOR_TABS.includes(raw.tab as EditorTabId)) return null
const known = ANNOTATION_SECTIONS.includes(raw.section as AnnotationSection)
const finding =
raw.tab === 'findings' ? sanitizeFinding(raw.finding, forms) : null
return {
tab: raw.tab as EditorTabId,
section: known ? (raw.section as AnnotationSection) : 'drawing',
finding: null,
finding,
reference: null,
referenceFilter: null,
}
}
/** The view a reload shows for an entry: its reading layers, never a form. */
export function withoutForms(view: EditorView): EditorView {
return sanitizeView(view, false) ?? view
}
/** The entry `state` (a `location.state`) carries, or null when it carries none. */
export function readEntry(state: unknown): HistoryEntry | null {
const raw = isRecord(state) ? state[ENTRY_KEY] : null
@@ -76,9 +120,14 @@ export function ownedEntry(
export const entryState = (entry: HistoryEntry) => ({ [ENTRY_KEY]: entry })
/** Layers over the place: a finding dialog or a reference dialog each count one. */
/**
* Layers over the place: the finding dialog and the citations sheet over it, the
* reference dialog, each count one.
*/
export function layerCount(view: EditorView): number {
return (view.finding ? 1 : 0) + (view.reference ? 1 : 0)
const { finding } = view
const sheet = finding && 'key' in finding && finding.citations
return (finding ? 1 : 0) + (sheet ? 1 : 0) + (view.reference ? 1 : 0)
}
/** An Annotations section other than the drawing is a step over it, like a layer. */
@@ -88,6 +137,8 @@ function isStepOver(view: EditorView): boolean {
/** True when the move took a layer away, or left a section for its drawing. */
function isRemoval(top: EditorView, view: EditorView): boolean {
// Another tab is a move of its own (« Tout afficher », « Aller à »): it pushes.
if (view.tab !== top.tab) return false
if (layerCount(view) < layerCount(top)) return true
const backToDrawing = view.tab === top.tab && isStepOver(top)
return backToDrawing && !isStepOver(view) && layerCount(view) === 0
@@ -108,10 +159,11 @@ export function planWrite(
replace: boolean,
): HistoryWrite {
if (sameView(top.view, view)) return 'none'
if (replace) return 'replace'
if (isRemoval(top.view, view)) {
return top.below && sameView(top.below, view) ? 'back' : 'replace'
}
return replace ? 'replace' : 'push'
return 'push'
}
/** Sliding-window budget of history writes: past it a view stays in memory. */
+71 -31
View File
@@ -14,6 +14,7 @@ import {
entryState,
ownedEntry,
planWrite,
withoutForms,
type HistoryEntry,
type HistoryOwner,
} from './entry'
@@ -28,8 +29,8 @@ const BACK_TIMEOUT_MS = 1_000
interface Book {
/** The entry on top of the history as the adapter knows it (null before the mount). */
entry: HistoryEntry | null
/** The router key last looked at, so each location is read once. */
handled: string | null
/** The router location last read: each location object is read once (see `usePop`). */
seen: object | null
pendingBack: boolean
backTimer: ReturnType<typeof setTimeout> | undefined
/** Scroll position of the entries left, by entry id. */
@@ -41,7 +42,7 @@ interface Book {
function newBook(): Book {
return {
entry: null,
handled: null,
seen: null,
pendingBack: false,
backTimer: undefined,
scrolls: new Map(),
@@ -54,6 +55,8 @@ function newBook(): Book {
interface Landing {
entry: HistoryEntry
tabChanged: boolean
/** A dialog opened or closed: its own focus (first control, return target) stands. */
layerChanged: boolean
}
/**
@@ -131,14 +134,29 @@ function useReconcile(
}, [view, nav.trace, book, writer])
}
/** The page shows something the history does not carry: a POP must not unmount it. */
function popRefused(nav: EditorNavigation): boolean {
/** The layers (dialogs) two views show: a POP between them opens or closes a dialog. */
function sameLayers(a: EditorView, b: EditorView): boolean {
return (
document.querySelector('dialog[open]') !== null ||
nav.state.citationsOf !== null
JSON.stringify([a.finding, a.reference]) ===
JSON.stringify([b.finding, b.reference])
)
}
/**
* A POP the page must not follow: a modal that is no layer is open (its place-scoped
* state is not in the history), or a dirty layer would be removed. Either way the layers
* are asked, so a dirty form shows its own confirmation.
*/
function popRefused(ctx: PopContext, entry: HistoryEntry | null): boolean {
const { nav, view, defaultView } = ctx
if (document.querySelector('dialog[open]:not([data-layer])')) {
nav.guards.askAll(false)
return true
}
if (sameLayers(entry?.view ?? defaultView, view)) return false
return !nav.guards.askAll(false).allowed
}
interface PopContext {
nav: EditorNavigation
book: Book
@@ -153,47 +171,65 @@ function landOnForeign(ctx: PopContext): Landing | null {
const { nav, writer, defaultView, book } = ctx
writer.first(defaultView)
nav.restoreView(defaultView)
return book.entry && { entry: book.entry, tabChanged: true }
return (
book.entry && { entry: book.entry, tabChanged: true, layerChanged: false }
)
}
/**
* Something the history does not carry is on screen: the view stays, the pre-POP view is
* pushed again above the entry landed on. A dirty form shows its own confirmation.
* pushed again above the entry landed on.
*/
function refusePop(ctx: PopContext, landed: HistoryEntry | null): null {
const { nav, book, writer, view } = ctx
nav.guards.askAll(false)
const { book, writer, view } = ctx
if (landed) book.entry = landed
writer.push(view)
return null
}
/** What the page does with the entry a Back or Forward landed on. */
function landOn(ctx: PopContext, state: unknown): Landing | null {
const { nav, book, owner, view } = ctx
// Scrolling is manual while the editor is mounted: the leaving page's offset is intact.
if (book.entry) book.scrolls.set(book.entry.id, window.scrollY)
/** A `back()` this adapter asked for is expected: reads and clears the flag. */
function takePendingBack(book: Book): boolean {
const expected = book.pendingBack
book.pendingBack = false
clearTimeout(book.backTimer)
const entry = ownedEntry(state, owner)
if (!expected && popRefused(nav)) return refusePop(ctx, entry)
return expected
}
/** What the page does with the entry a Back or Forward landed on. */
function landOn(ctx: PopContext, state: unknown): Landing | null {
const { nav, book, view } = ctx
// Scrolling is manual while the editor is mounted: the leaving page's offset is intact.
if (book.entry) book.scrolls.set(book.entry.id, window.scrollY)
const expected = takePendingBack(book)
const entry = ownedEntry(state, ctx.owner)
if (!expected && popRefused(ctx, entry)) return refusePop(ctx, entry)
if (!entry) return landOnForeign(ctx)
book.entry = entry
if (sameView(entry.view, view)) return null
nav.restoreView(entry.view)
return { entry, tabChanged: entry.view.tab !== view.tab }
return {
entry,
tabChanged: entry.view.tab !== view.tab,
layerChanged: !sameLayers(entry.view, view),
}
}
/** The first location of the editor: an entry of this sheet and account is kept, else replaced. */
/**
* The first location of the editor: an entry of this sheet and account is kept (a
* reload never reopens a form, so a form layer is replaced by the view without it),
* any other is replaced by the current view.
*/
function mount(ctx: PopContext, state: unknown): void {
const entry = ownedEntry(state, ctx.owner)
if (entry) ctx.book.entry = entry
else ctx.writer.first(ctx.view)
if (!entry) return ctx.writer.first(ctx.view)
ctx.book.entry = entry
const kept = withoutForms(entry.view)
if (!sameView(kept, entry.view)) ctx.writer.replace(kept)
}
/** Focus after a Back or Forward: the tab button, or the heading of a section reached. */
function landFocus({ entry, tabChanged }: Landing): void {
function landFocus({ entry, tabChanged, layerChanged }: Landing): void {
if (layerChanged && !tabChanged) return
const heading = tabChanged ? null : headingOf(shownPlace(entry.view))
if (heading) heading.focus({ preventScroll: true })
else focusActiveTab({ preventScroll: true })
@@ -215,6 +251,7 @@ function useLanding(
return afterModalsClosed(() => {
window.scrollTo(0, book.scrolls.get(id) ?? 0)
landFocus(landing)
if (landing.layerChanged && !landing.tabChanged) return
const section = view.tab === 'annotations' ? view.section : null
nav.announce(
moveText({ place: 'tab', tab: view.tab, section, key: null }),
@@ -246,23 +283,25 @@ function useManualScroll(): void {
}, [])
}
/** Each new location is read once: the first is the mount, a POP after it is a landing. */
/**
* Each new location is read once: the first is the mount, a POP after it is a landing.
* The router makes a new location object per navigation, so a Back onto a key this
* adapter already read (the entry it mounted on, or one whose push never rendered) is a
* new object and is read; the second run of an effect (StrictMode) sees the same one.
*/
function usePop(ctx: PopContext): Landing | null {
const location = useLocation()
const navType = useNavigationType()
const [landing, setLanding] = useState<Landing | null>(null)
const { book } = ctx
useEffect(() => {
// The type is part of the stamp: a POP back onto a key this adapter pushed, with the
// transition of a later push never rendered, is still a landing to read.
const stamp = `${location.key}|${navType}`
if (book.handled === stamp) return
book.handled = stamp
if (book.seen === location) return
book.seen = location
if (book.entry === null) mount(ctx, location.state)
else if (navType === 'POP') setLanding(landOn(ctx, location.state))
// Read once per location: the context is the one this render holds.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [location.key, navType])
}, [location])
return landing
}
@@ -271,7 +310,8 @@ function usePop(ctx: PopContext): Landing | null {
* reducer holds. A move dispatches at once and the history follows from one effect that
* compares the view with the last entry this adapter wrote (a ref, never `useLocation()`,
* which lags a transition). A Back or Forward restores the view of the entry it lands on,
* unless a dialog or the citations panel is open: then the pre-move view is pushed back.
* unless a modal that is no layer is open or a dirty layer would go: then the pre-move
* view is pushed back.
* Foreign entries (another sheet, another account) and entries without a view are replaced
* by the default view.
*/
+46 -16
View File
@@ -28,9 +28,10 @@ export interface FocusRequest {
/**
* What the browser history records of the editor (R2F-1): where the user is, never what
* they typed. A layer (`finding`, `reference`) is a dialog over a place; `referenceFilter`
* narrows the references library to the citers of an element. Only `tab` and `section`
* are ever set so far: the three others are the room later layers fill.
* they typed. A layer (`finding`, `reference`) is a dialog over a place; `citations` is
* the side sheet over the finding dialog; `referenceFilter` narrows the references
* library to the citers of an element. `reference` and `referenceFilter` stay null until
* the reference dialog and the filter exist.
*/
export interface EditorView {
tab: EditorTabId
@@ -44,8 +45,6 @@ export interface EditorView {
}
export interface NavigationState extends EditorView {
/** The finding whose citations panel is open; null while it is closed. */
citationsOf: ElementKey | null
/** Bumped by `show_all_references`: the library resets its search once per bump. */
libraryReset: number
/** Places already shown, so a body mounts on first visit and stays mounted. */
@@ -60,6 +59,9 @@ export type NavigationAction =
| { type: 'select_tab'; tab: EditorTabId }
| { type: 'open_section'; section: AnnotationSection }
| { type: 'back_to_drawing' }
| { type: 'open_finding'; key: ElementKey }
| { type: 'create_finding'; kind: string; parent: ElementKey | null }
| { type: 'close_finding' }
| { type: 'open_citations'; citedBy: ElementKey }
| { type: 'close_citations' }
| { type: 'show_all_references' }
@@ -120,8 +122,8 @@ const DEFAULT_VIEW = {
referenceFilter: null,
} as const
/** The finding whose citations panel the view shows, null when it shows none. */
function citationsOfView(view: EditorView): ElementKey | null {
/** The finding whose citations sheet the view shows, null when it shows none. */
export function citationsOfView(view: EditorView): ElementKey | null {
const { finding } = view
return finding && 'key' in finding && finding.citations ? finding.key : null
}
@@ -139,7 +141,6 @@ export function initialNavigation(
const start = view ?? defaultView(tab)
return shown({
...start,
citationsOf: citationsOfView(start),
libraryReset: 0,
visitedTabs: [],
visitedSections: [],
@@ -178,7 +179,6 @@ function restoreView(
...state,
...view,
section,
citationsOf: citationsOfView(view),
focus: undefined,
})
}
@@ -191,9 +191,31 @@ export function isFindingNode(key: ElementKey): boolean {
return key.kind === 'finding' && key.path.length > 1
}
/** Only a finding node has a citations panel: any other key leaves the state as it is. */
/** Only a finding node has a citations sheet: any other key leaves the state as it is. */
function openCitations(state: NavigationState, citedBy: ElementKey) {
return isFindingNode(citedBy) ? { ...state, citationsOf: citedBy } : state
const finding = { key: citedBy, citations: true }
return isFindingNode(citedBy) ? shown({ ...state, finding }) : state
}
/** Closes the sheet only: the finding dialog under it stays. */
function closeCitations(state: NavigationState): NavigationState {
const { finding } = state
if (!finding || !('key' in finding)) return state
return { ...state, finding: { key: finding.key, citations: false } }
}
/** The finding dialog of `key`, in view mode, on the Constats tab. */
function openFinding(state: NavigationState, key: ElementKey): NavigationState {
const finding = { key, citations: false }
return shown({ ...state, tab: 'findings', finding })
}
/** The creation form of a zone, a category or a node, on the Constats tab. */
function createFinding(
state: NavigationState,
create: { kind: string; parent: ElementKey | null },
): NavigationState {
return shown({ ...state, tab: 'findings', finding: { create } })
}
function goTo(state: NavigationState, target: EditorTarget): NavigationState {
@@ -202,19 +224,19 @@ function goTo(state: NavigationState, target: EditorTarget): NavigationState {
...state,
tab: target.tab,
section: target.section ?? state.section,
citationsOf: null,
finding: null,
focus: { target, serial },
serial,
}
return shown(moved)
}
/** « Tout afficher dans l'onglet Références »: the panel closes, the library starts afresh. */
/** « Tout afficher dans l'onglet Références »: the layers close, the library starts afresh. */
function showAllReferences(state: NavigationState): NavigationState {
const moved = {
...state,
tab: 'references' as const,
citationsOf: null,
finding: null,
libraryReset: state.libraryReset + 1,
}
return shown(moved)
@@ -226,20 +248,28 @@ export function navigationReducer(
): NavigationState {
switch (action.type) {
case 'select_tab':
return shown({ ...state, tab: action.tab, citationsOf: null })
return shown({ ...state, tab: action.tab, finding: null })
case 'open_section':
return shown({ ...state, section: action.section })
case 'back_to_drawing':
return shown({ ...state, section: 'drawing' })
case 'open_finding':
return openFinding(state, action.key)
case 'create_finding':
return createFinding(state, { kind: action.kind, parent: action.parent })
case 'close_finding':
console.trace('CLOSE_FINDING')
return { ...state, finding: null }
case 'open_citations':
return openCitations(state, action.citedBy)
case 'close_citations':
return { ...state, citationsOf: null }
return closeCitations(state)
case 'show_all_references':
return showAllReferences(state)
case 'go_to':
return goTo(state, action.target)
case 'restore_view':
console.trace('RESTORE', JSON.stringify(action.view.finding))
return restoreView(state, action.view)
case 'focus_consumed':
return state.focus?.serial === action.serial
+19 -3
View File
@@ -1,7 +1,8 @@
import type { ElementKey, PreviewState } from '@faunosteo/core-wasm/types'
import type { EditorTarget, FocusRequest } from './navigation'
import type { EditorTarget, EditorView, FocusRequest } from './navigation'
import { unmeasuredViews } from './issues'
import type { TabTier } from './useViewport'
import type { Guards } from './useEditorNavigation'
export const EDITOR_TABS = [
'general',
@@ -38,6 +39,21 @@ export function initialTab(state: PreviewState, tier: TabTier): EditorTabId {
return SHOWN[tier].includes(wanted) ? wanted : 'annotations'
}
/**
* What Constats needs of the navigation for its dialog (R2F-3): the layer the view
* holds and the moves on it. A user close answers false when a form refused it.
*/
export interface FindingLayer {
view: EditorView['finding']
guards: Guards
open: (key: ElementKey) => void
start: (kind: string, parent: ElementKey | null) => void
close: (forced?: boolean) => boolean
replace: (key: ElementKey | null, text?: string) => void
openCitations: (citedBy: ElementKey, opener?: HTMLElement | null) => void
announce: (text: string) => void
}
/** Props of every place (tab body, Annotations section). */
export interface EditorPlaceProps {
/** Not editable now: a mode that cannot save, or a recovery offer not answered yet. */
@@ -46,8 +62,8 @@ export interface EditorPlaceProps {
navigate: (target: EditorTarget) => void
/** « Aller à … » with an element: the place seeds its own selection from it once. */
focus?: FocusRequest
/** Opens the citations panel of one finding (only Constats offers it). */
openCitations?: (citedBy: ElementKey, opener?: HTMLElement | null) => void
/** The finding dialog and the citations sheet over it (only Constats has them). */
layer?: FindingLayer
/** Bumped by « Tout afficher »: the references library resets its search once per bump. */
libraryReset?: number
/** Reads the sheet's overview again (after a submission: the round freezes the draft). */
-61
View File
@@ -1,61 +0,0 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import type { NavigationAction } from './navigation'
/** Panel motion (board 25): enter decelerates, the shorter exit accelerates (P9). */
export const PANEL_ENTER_S = 0.18
export const PANEL_EXIT_S = 0.14
/** The exit plus a margin: past it, a callback that never came is applied by the timer. */
const FALLBACK_MS = PANEL_EXIT_S * 1000 + 100
export type PendingKind =
| 'go_to'
| 'citations_closed'
| 'show_all'
| 'tab_selected'
/** The one move a close records: applied when the exit is over (P9). */
export interface PendingClose {
action: NavigationAction
kind: PendingKind
text: string
/** Said before `text`: a draft dropped by a forced close. It survives a replacement. */
note?: string
}
/**
* The close of the citations panel as a two-step move (P9, P28): `record` starts the exit
* (the page stays inert, the panel is inert too); `complete` runs once, from the panel's
* `onExitComplete` or from a one-shot timer when that never fires, and hands the pending
* move to `apply`. A second close is a no-op; a tab choice replaces the pending move.
*/
export function useCitationsExit(apply: (move: PendingClose) => void) {
const [exiting, setExiting] = useState(false)
const pending = useRef<PendingClose | null>(null)
const timer = useRef<number | undefined>(undefined)
const complete = useCallback(() => {
const move = pending.current
if (move === null) return
pending.current = null
window.clearTimeout(timer.current)
setExiting(false)
apply(move)
}, [apply])
const record = useCallback(
(move: PendingClose) => {
if (pending.current !== null) {
if (move.kind !== 'tab_selected') return
const note = pending.current.note ?? move.note
pending.current = note ? { ...move, note } : move
return
}
pending.current = move
setExiting(true)
timer.current = window.setTimeout(complete, FALLBACK_MS)
},
[complete],
)
const busy = useCallback(() => pending.current !== null, [])
useEffect(() => () => window.clearTimeout(timer.current), [])
return { exiting, record, complete, busy }
}
+114 -175
View File
@@ -13,13 +13,13 @@ import { afterModalsClosed } from '@/components/ui/afterModalsClosed'
import { useT } from '@/i18n/useT'
import {
commitFocusedField,
focusActiveTab,
placeOf,
visibleElement,
type FocusOutcome,
type PlaceName,
} from './focusRequest'
import {
citationsOfView,
initialNavigation,
isFindingNode,
navigationReducer,
@@ -30,27 +30,17 @@ import {
type NavigationState,
} from './navigation'
import { MORE_BUTTON_ID, tabDomId, type EditorTabId } from './tabs'
import {
useCitationsExit,
type PendingClose,
type PendingKind,
} from './useCitationsExit'
type MoveKind = PendingKind | 'section' | 'back'
type MoveKind = 'go_to' | 'show_all' | 'tab_selected' | 'section' | 'back'
/**
* A programmatic move: a new object per move, so the effect after it runs once.
* `afterExit`: it is the pending move of a closed panel, so a focus the user already
* placed elsewhere during the exit is left alone (P28).
*/
/** A programmatic move: a new object per move, so the effect after it runs once. */
interface Move {
kind: MoveKind
afterExit?: boolean
}
/**
* The panel's answer before a close (P22''): `allowed` false cancels a user close. A forced
* close always goes ahead; `note` (a draft dropped) is said with the close.
* A layer's answer before it is left (P22''): `allowed` false cancels a user move. A
* forced one always goes ahead; `note` (a draft dropped) is said with the move.
*/
export interface LeaveAnswer {
allowed: boolean
@@ -93,24 +83,29 @@ export interface EditorNavigation {
/** The polite live region's text; a repeat alternates a trailing no-break space. */
live: string
navigate: (target: EditorTarget) => void
/** False when the open panel refused the tab change (a refused field keeps the page). */
selectTab: (tab: EditorTabId, options?: SelectOptions) => boolean
openSection: (section: AnnotationSection, opener?: Opener) => void
backToDrawing: () => void
/** Opens the citations panel of a finding node; any other key is ignored. */
/** The finding dialog of `key`, in view mode. */
openFinding: (key: ElementKey) => void
/** The creation form of a zone, a category or a node, in the finding dialog. */
startFinding: (kind: string, parent: ElementKey | null) => void
/** A user close of the finding dialog; false when a layer refused it (a dirty form). */
closeFinding: (forced?: boolean) => boolean
/**
* The finding layer becomes another view of itself, by replace (no Back entry): the new
* element's dialog, or `null` for none. With `text`, a close the user did not ask for
* (the element vanished): forced, said once the dialogs are closed.
*/
replaceFinding: (key: ElementKey | null, text?: string) => void
/** Opens the citations sheet of a finding node; any other key is ignored. */
openCitations: (citedBy: ElementKey, opener?: Opener) => void
/** A user close (✕, Escape, scrim): the panel exits, then the focus goes to P6's fallbacks. */
closeCitations: () => void
/** The finding vanished: the same close, never refused (a refused draft is dropped, said). */
dropCitations: () => void
/** « Tout afficher dans l'onglet Références »: panel closed, tab shown, library reset. */
/** A user close of the sheet; false when a tile in edit refused it. */
closeCitations: () => boolean
/** « X références », where the focus returns once the sheet is closed. */
citationsTrigger: () => HTMLElement | null
/** « Tout afficher dans l'onglet Références »: layers closed, tab shown, library reset. */
showAllReferences: () => void
/** The panel is playing its exit: the state still holds it, the page stays inert. */
exiting: boolean
/** The panel's `onExitComplete`: applies the pending move. */
exitComplete: () => void
/** The citations panel hands its `canLeave` over while it is mounted (P22''). */
registerCanLeave: (guard: CanLeave | null) => void
guards: Guards
trace: MoveTrace
/** A Back or Forward landed on `view` (the history adapter's way in): no move, no request. */
@@ -170,7 +165,7 @@ function useLiveRegion() {
waiting.current()
waiting.current = afterModalsClosed(() => {
const joined = queued.current.splice(0).join('. ')
setLive((previous) => (previous === joined ? `${joined} ` : joined))
setLive((previous) => (previous === joined ? `${joined} ` : joined))
})
}, [])
return { live, announce }
@@ -211,7 +206,7 @@ function useMoveTrace() {
}
interface Openers {
/** The trigger that opened the citations panel, and the finding it belongs to. */
/** The trigger that opened the citations sheet, and the finding it belongs to. */
citations: RefObject<HTMLElement | null>
citedBy: RefObject<ElementKey | null>
section: RefObject<HTMLElement | null>
@@ -219,22 +214,10 @@ interface Openers {
type Go = (action: NavigationAction, kind: MoveKind, text: string) => void
/**
* The one way to move: commit the typed text, announce, dispatch, record the move.
* `finish` is the same without the commit, for the move a closed panel recorded.
*/
/** The one way to move: commit the typed text, announce, dispatch, record the move. */
function useGo(dispatch: Dispatch<NavigationAction>, trace: MoveTrace) {
const { live, announce } = useLiveRegion()
const [move, setMove] = useState<Move | null>(null)
const finish = useCallback(
(move: PendingClose) => {
announce(move.note ? `${move.note}. ${move.text}` : move.text)
trace.scrollY = window.scrollY
dispatch(move.action)
setMove({ kind: move.kind, afterExit: true })
},
[announce, dispatch, trace],
)
const go: Go = useCallback(
(action, kind, text) => {
commitFocusedField()
@@ -246,18 +229,12 @@ function useGo(dispatch: Dispatch<NavigationAction>, trace: MoveTrace) {
},
[announce, dispatch, trace],
)
return { move, go, finish, live, announce }
return { move, go, live, announce }
}
/** Tab and section moves: « Aller à », a section entry, « Retour au dessin ». */
function useSectionMoves(go: Go, openers: Openers) {
const t = useT()
const moveText = useMoveText()
const navigate = useCallback(
(target: EditorTarget) =>
go({ type: 'go_to', target }, 'go_to', moveText(target)),
[go, moveText],
)
const openSection = useCallback(
(section: AnnotationSection, opener?: Opener) => {
openers.section.current = opener ?? null
@@ -271,101 +248,98 @@ function useSectionMoves(go: Go, openers: Openers) {
const text = `${t('editor.tab.annotations')} · ${t('editor.place.drawing')}`
go({ type: 'back_to_drawing' }, 'back', text)
}, [go, t])
return { navigate, openSection, backToDrawing }
return { openSection, backToDrawing }
}
/** What the panel's moves need of the hook: its state, the exit and the leave check. */
interface PanelContext {
open: boolean
go: Go
openers: Openers
/** What the layers' moves need of the hook. */
interface LayerContext {
dispatch: Dispatch<NavigationAction>
announce: (text: string) => void
exit: ReturnType<typeof useCitationsExit>
guards: Guards
mark: (replace?: boolean) => void
}
/**
* Records a close of the panel. A user close asks the panel first (P22''): a refused
* draft cancels it (false). While an exit is playing, a close is a no-op (a tab choice
* replaces the pending move) and asks nothing: the draft was settled by the first close.
* The finding dialog (R2F-3). A user close asks every layer first: a dirty form shows its
* own confirmation and the close is cancelled. `replaceFinding` is the move that is no
* Back step: the creation turned into its element, a deletion, an element that vanished.
*/
function useRequestClose(ctx: PanelContext) {
const { open, exit, guards, mark } = ctx
const { busy, record } = exit
return useCallback(
(move: PendingClose, forced: boolean): boolean => {
if (!open) return true
function useFindingLayer({ dispatch, announce, guards, mark }: LayerContext) {
const openFinding = useCallback(
(key: ElementKey) => {
mark()
if (busy()) {
record(move)
return true
}
commitFocusedField()
const { allowed, note } = guards.ask('citations', forced)
if (!allowed) return false
record(note ? { ...move, note } : move)
dispatch({ type: 'open_finding', key })
},
[dispatch, mark],
)
const startFinding = useCallback(
(kind: string, parent: ElementKey | null) => {
mark()
dispatch({ type: 'create_finding', kind, parent })
},
[dispatch, mark],
)
const closeFinding = useCallback(
(forced = false) => {
console.trace('closeFinding', forced)
if (!guards.askAll(forced).allowed) return false
mark()
dispatch({ type: 'close_finding' })
return true
},
[open, busy, record, guards, mark],
[guards, dispatch, mark],
)
const replaceFinding = useCallback(
(key: ElementKey | null, text?: string) => {
const note = text ? guards.askAll(true).note : undefined
if (text) announce(note ? `${note}. ${text}` : text)
mark(true)
dispatch(key ? { type: 'open_finding', key } : { type: 'close_finding' })
},
[guards, announce, dispatch, mark],
)
return { openFinding, startFinding, closeFinding, replaceFinding }
}
/** Opens the panel of a finding node: no move is recorded, the panel focuses itself. */
function useOpenCitations(ctx: PanelContext) {
const t = useT()
const { openers, dispatch, announce } = ctx
return useCallback(
/** The citations sheet over the finding dialog: opened from a finding node only. */
function useSheetLayer(ctx: LayerContext, openers: Openers) {
const { dispatch, guards, mark } = ctx
const openCitations = useCallback(
(citedBy: ElementKey, opener?: Opener) => {
if (!isFindingNode(citedBy)) return
commitFocusedField()
openers.citations.current = opener ?? null
openers.citedBy.current = citedBy
announce(t('editor.references.panel_title'))
mark()
dispatch({ type: 'open_citations', citedBy })
},
[openers, dispatch, announce, t],
[openers, dispatch, mark],
)
const closeCitations = useCallback(() => {
if (!guards.ask('citations', false).allowed) return false
mark()
dispatch({ type: 'close_citations' })
return true
}, [guards, dispatch, mark])
return { openCitations, closeCitations }
}
/** The panel's closes: ✕ / Escape / scrim, the vanished finding, « Tout afficher », « Aller à ». */
function useCloseMoves(ctx: PanelContext) {
/** « Aller à » and « Tout afficher » leave every layer: a layer in edit may refuse. */
function useLeavingMoves(go: Go, guards: Guards) {
const t = useT()
const moveText = useMoveText()
const { open, go } = ctx
const request = useRequestClose(ctx)
const closing = useCallback(
(forced: boolean) => {
const text = t('editor.live.references_closed')
request(
{ action: { type: 'close_citations' }, kind: 'citations_closed', text },
forced,
)
},
[request, t],
)
// With no panel open there is nothing to exit: the tab shows at once.
const showAllReferences = useCallback(() => {
const action = { type: 'show_all_references' } as const
const text = t('editor.tab.references')
if (!open) return go(action, 'show_all', text)
request({ action, kind: 'show_all', text }, false)
}, [open, go, request, t])
const navigate = useCallback(
(target: EditorTarget) => {
const action = { type: 'go_to', target } as const
request({ action, kind: 'go_to', text: moveText(target) }, false)
if (!guards.askAll(false).allowed) return
go({ type: 'go_to', target }, 'go_to', moveText(target))
},
[request, moveText],
[go, guards, moveText],
)
return {
closeCitations: useCallback(() => closing(false), [closing]),
dropCitations: useCallback(() => closing(true), [closing]),
showAllReferences,
navigate,
request,
}
const showAllReferences = useCallback(() => {
if (!guards.askAll(false).allowed) return
const text = t('editor.tab.references')
go({ type: 'show_all_references' }, 'show_all', text)
}, [go, guards, t])
return { navigate, showAllReferences }
}
/** « Retour au dessin »: the entry that opened the section, else the canvas box. */
@@ -386,27 +360,6 @@ function triggerOf(openers: Openers): HTMLElement | null {
})
}
/** Focuses `element` and says whether it really holds the focus now. */
function focusHeld(element: HTMLElement | null): boolean {
element?.focus()
return element !== null && document.activeElement === element
}
/** Panel closed (P6): the trigger when it is shown, else the active tab's button. */
function focusAfterClose(openers: Openers) {
if (!focusHeld(triggerOf(openers))) focusActiveTab()
}
/** Nothing the user chose holds the focus: `body`, or what the closing panel still has. */
function focusIsFree(): boolean {
const active = document.activeElement
return (
active === null ||
active === document.body ||
active.closest('[data-place="citations"]') !== null
)
}
/** Where the focus lands after a programmatic move; never `body`. */
function landingOf(move: Move, state: NavigationState): HTMLElement | null {
if (move.kind === 'show_all') {
@@ -419,7 +372,8 @@ function landingOf(move: Move, state: NavigationState): HTMLElement | null {
/**
* After each move: a request an element answered is done; else (no owner answered, or
* the move had no request) the focus goes to the heading or the tab button.
* the move had no request) the focus goes to the heading or the tab button. Once the
* dialogs a move closed are gone: the page behind them was inert.
*/
function useMoveFocus(
move: Move | null,
@@ -439,10 +393,10 @@ function useMoveFocus(
if (outcome === 'found' || outcome === 'kept') return
dispatch({ type: 'focus_consumed', serial })
}
if (move.afterExit && !focusIsFree()) return
if (move.kind === 'citations_closed') focusAfterClose(openers)
else if (move.kind === 'back') backTarget(openers.section.current)?.focus()
else landingOf(move, state)?.focus()
afterModalsClosed(() => {
if (move.kind === 'back') backTarget(openers.section.current)?.focus()
else landingOf(move, state)?.focus()
})
}, [move, state, outcomes, dispatch, openers])
}
@@ -459,32 +413,30 @@ function useReceipts(dispatch: Dispatch<NavigationAction>) {
return { outcomes, consumed }
}
/** A tab choice; with the citations panel open it closes and the new tab takes the focus. */
/** A tab choice: the typed text is committed, the history asked for a push or a replace. */
function useTabSelect(
request: ReturnType<typeof useCloseMoves>['request'],
dispatch: Dispatch<NavigationAction>,
open: boolean,
mark: (replace?: boolean) => void,
) {
const t = useT()
return useCallback(
(tab: EditorTabId, options?: SelectOptions): boolean => {
const action = { type: 'select_tab', tab } as const
if (open) {
const text = t(`editor.tab.${tab}`)
const allowed = request({ action, kind: 'tab_selected', text }, false)
if (allowed) mark(options?.replace)
return allowed
}
commitFocusedField()
mark(options?.replace)
dispatch(action)
dispatch({ type: 'select_tab', tab })
return true
},
[request, dispatch, open, t, mark],
[dispatch, mark],
)
}
/** The sheet's finding is the one « X références » belongs to, even after a Back. */
function useCitedBy(state: NavigationState, openers: Openers) {
const citedBy = citationsOfView(state)
useEffect(() => {
if (citedBy) openers.citedBy.current = citedBy
}, [citedBy, openers])
}
/** Navigation of the draft editor: the reducer plus the DOM side (focus, live region). */
export function useEditorNavigation(
initialTab: EditorTabId,
@@ -494,41 +446,28 @@ export function useEditorNavigation(
initialNavigation(initialTab, initialView),
)
const { trace, mark } = useMoveTrace()
const { move, go, finish, live, announce } = useGo(dispatch, trace)
const { move, go, live, announce } = useGo(dispatch, trace)
const openers = useRef<Openers>({
citations: { current: null },
citedBy: { current: null },
section: { current: null },
}).current
const guards = useGuards()
const exit = useCitationsExit(finish)
const registerCanLeave = useCallback(
(guard: CanLeave | null) => guards.register('citations', guard),
[guards],
)
const open = state.citationsOf !== null
const receipts = useReceipts(dispatch)
useMoveFocus(move, state, receipts.outcomes, dispatch, openers)
const sections = useSectionMoves(go, openers)
const ctx = { open, go, openers, dispatch, announce, exit, guards, mark }
const openCitations = useOpenCitations(ctx)
const panel = useCloseMoves(ctx)
useCitedBy(state, openers)
const ctx = { dispatch, announce, guards, mark }
return {
state,
live,
announce,
consumed: receipts.consumed,
selectTab: useTabSelect(panel.request, dispatch, open, mark),
openSection: sections.openSection,
backToDrawing: sections.backToDrawing,
navigate: open ? panel.navigate : sections.navigate,
openCitations,
closeCitations: panel.closeCitations,
dropCitations: panel.dropCitations,
showAllReferences: panel.showAllReferences,
exiting: exit.exiting,
exitComplete: exit.complete,
registerCanLeave,
selectTab: useTabSelect(dispatch, mark),
...useSectionMoves(go, openers),
...useFindingLayer(ctx),
...useSheetLayer(ctx, openers),
...useLeavingMoves(go, guards),
citationsTrigger: useCallback(() => triggerOf(openers), [openers]),
guards,
trace,
restoreView: useCallback(
+9 -1
View File
@@ -1207,7 +1207,6 @@ export const en: Dict = {
'editor.section.back': 'Back to the drawing',
'editor.live.creation_kept': "A creation is in progress: finish or abandon it to reach this annotation.",
'editor.live.tracing_kept': "A tracing is in progress: finish or cancel it to reach this annotation.",
'editor.live.references_closed': 'References closed',
'editor.overview.label': 'Sheet overview',
'editor.overview.views': 'Views',
'editor.overview.view_main': 'Main view',
@@ -1635,6 +1634,15 @@ export const en: Dict = {
'editor.findings.references': 'Cited references',
'editor.findings.references_none': 'No reference cited.',
'editor.findings.reference_add': 'Cite a reference',
'editor.findings.edit': 'Edit',
'editor.findings.save': 'Save',
'editor.findings.saved': 'Changes saved',
'editor.findings.discard_ask': 'Discard your changes?',
'editor.findings.keep_typing': 'Keep editing',
'editor.findings.discard': 'Discard',
'editor.findings.gone': 'This finding no longer exists',
'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',
'editor.verification.errors_one': '{count} blocking error',
'editor.verification.errors_other': '{count} blocking errors',
+9 -1
View File
@@ -1238,7 +1238,6 @@ export const fr: Dict = {
'editor.section.back': 'Retour au dessin',
'editor.live.creation_kept': "Une création est en cours : terminez-la ou abandonnez-la pour atteindre cette annotation.",
'editor.live.tracing_kept': "Un tracé est en cours : terminez-le ou annulez-le pour atteindre cette annotation.",
'editor.live.references_closed': 'Références fermées',
'editor.overview.label': 'Aperçu de la fiche',
'editor.overview.views': 'Vues',
'editor.overview.view_main': 'Vue principale',
@@ -1666,6 +1665,15 @@ export const fr: Dict = {
'editor.findings.references': 'Références citées',
'editor.findings.references_none': 'Aucune référence citée.',
'editor.findings.reference_add': 'Citer une référence',
'editor.findings.edit': 'Modifier',
'editor.findings.save': 'Enregistrer',
'editor.findings.saved': 'Modifications enregistrées',
'editor.findings.discard_ask': 'Abandonner les modifications ?',
'editor.findings.keep_typing': 'Continuer la saisie',
'editor.findings.discard': 'Abandonner',
'editor.findings.gone': "Ce constat n'existe plus",
'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',
'editor.verification.errors_one': '{count} erreur bloquante',
'editor.verification.errors_other': '{count} erreurs bloquantes',