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:
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>
|
||||
)
|
||||
}
|
||||
+53
-105
@@ -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>
|
||||
)
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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}
|
||||
|
||||
Reference in new issue
Block a user