feat(editor): edit mode of the references dialog

« Modifier » turns the references dialog into a draft of adds and removes,
saved as one update on the current citations. A new layer, citations,
guards it between the finding and the reference dialogs: close, Back,
POP refusal and the leave cascade ask it. « Modifier la référence » and
« Nouvelle référence » stack the reference dialog over it; a creation it
started joins its draft.
This commit is contained in:
bchanot committed 2026-11-15 16:39:43 +01:00
1 parent d9dbcf1609
commit 3dc5820e3a
29 files changed
+1489 -243

No files matched your search

@@ -118,6 +118,8 @@ function Places({ nav, readOnly, reloadSheet }: PlacesProps) {
onShowAll={() => cited && nav.showAllReferences(cited)}
navigate={nav.navigate}
returnFocus={nav.citationsTrigger}
guards={nav.guards}
references={nav.references}
/>
<ReferenceDialog layer={references} readOnly={readOnly} />
</>
@@ -10,10 +10,19 @@ import { useT } from '@/i18n/useT'
const BOX =
'space-y-2 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-strong)] p-3'
/** True when no open dialog lies over `host`: each open one is `host` or holds it. */
/**
* True when no open dialog lies over `host`: each open one is `host`, holds it, or comes
* before it in the page (the editor's layers are stacked in tree order: the references
* dialog after the finding dialog, the reference dialog after both).
*/
const onTop = (host: Element) =>
[...document.querySelectorAll('dialog[open]')].every(
(dialog) => dialog === host || dialog.contains(host),
(dialog) =>
dialog === host ||
dialog.contains(host) ||
!!(
host.compareDocumentPosition(dialog) & Node.DOCUMENT_POSITION_PRECEDING
),
)
/**
@@ -1,8 +1,6 @@
import Icon from '@/components/ui/Icon'
import ActionButton from '@/components/editor/fields/ActionButton'
import type { FindingItem } from '@/editor/findings/tree'
import { usePlural } from '@/editor/plural'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useT } from '@/i18n/useT'
interface CitationsProps {
@@ -38,42 +36,6 @@ function CitationsTrigger({
)
}
/** A list of cited references; removable only where `remove` is given. */
export 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>
{remove && (
<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 » and « X références » of a family or a node, the same in the view
* and the edit mode (Rev 5): the count is the document's, the citations are read and
@@ -1,9 +1,9 @@
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 { useItemMode } from '@/components/editor/findings/useItemMode'
import Dialog from '@/components/ui/Dialog'
import { usePlaceVisible } from '@/lib/placeVisibility'
import type { FindingItem, FindingKind } from '@/editor/findings/tree'
@@ -33,38 +33,11 @@ interface ItemBodyProps {
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
}
}
/** The local mode of the one dialog: view or edit, and whether a save was just made. */
function useItemMode() {
const [mode, setMode] = useState({ editing: false, saved: false })
const returnToEdit = useFocusEditButton(mode.editing)
return {
...mode,
startEdit: () => setMode({ editing: true, saved: false }),
done: (saved: boolean) => {
returnToEdit()
setMode({ editing: false, saved })
},
}
}
/** View mode, or the edit form: a local mode of the one dialog, no history entry. */
function ItemBody(props: ItemBodyProps) {
const { layer } = props
const t = useT()
const mode = useItemMode()
const mode = useItemMode(EDIT_BUTTON_ID)
const showReferences = (opener: HTMLElement) =>
layer.openCitations(props.item.key, opener)
return (
@@ -1,56 +0,0 @@
import SelectField from '@/components/editor/fields/SelectField'
import { CitationList } from '@/components/editor/findings/FindingCitations'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useT } from '@/i18n/useT'
interface Props {
/** The draft's cited ids: what the form shows. */
ids: readonly string[]
readOnly: boolean
onChange: (ids: string[]) => void
}
/** The references the draft does not cite yet, after the « choose » placeholder. */
function useCitableOptions(ids: readonly string[]) {
const t = useT()
const doc = useSheetDocument()
const options = (doc?.references ?? [])
.filter((r) => !ids.includes(r.id))
.map((r) => ({ value: r.id, label: r.citation }))
return [{ value: '', label: t('editor.field.choose') }, ...options]
}
/**
* The cited references of a draft: the list, each « Retirer », and « Citer une référence ».
* Nothing is written before « Enregistrer ». Mounted by no form since Rev 5 Task 11: the
* references dialog's edit mode (Task 12) takes it over.
*/
export default function FindingEditCitations(props: Props) {
const { ids, readOnly, onChange } = props
const t = useT()
const options = useCitableOptions(ids)
return (
<div className="space-y-2">
{ids.length === 0 ? (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.findings.references_none')}
</p>
) : (
<CitationList
ids={ids}
readOnly={readOnly}
remove={(id) => onChange(ids.filter((other) => other !== id))}
/>
)}
{!readOnly && (
<SelectField
id="finding-add-reference"
label={t('editor.findings.reference_add')}
value=""
options={options}
onCommit={(id) => id !== '' && onChange([...ids, id])}
/>
)}
</div>
)
}
@@ -0,0 +1,33 @@
import { useEffect, useRef, useState } from 'react'
/** After the form closes its button is gone: « Modifier » (`buttonId`) takes the focus back. */
function useFocusEditButton(editing: boolean, buttonId: string) {
const wanted = useRef(false)
useEffect(() => {
if (editing || !wanted.current) return
wanted.current = false
document.getElementById(buttonId)?.focus()
}, [editing, buttonId])
return () => {
wanted.current = true
}
}
/**
* The local mode of a dialog (the finding dialog, the references dialog): view or edit,
* and whether a save was just made. No history entry. `buttonId` is its « Modifier ».
*/
export function useItemMode(buttonId: string) {
const [mode, setMode] = useState({ editing: false, saved: false })
const returnToEdit = useFocusEditButton(mode.editing, buttonId)
return {
...mode,
startEdit: () => setMode({ editing: true, saved: false }),
done: (saved: boolean) => {
returnToEdit()
setMode({ editing: false, saved })
},
/** Back to the view mode, nothing said: the dialog shows another element. */
reset: () => setMode({ editing: false, saved: false }),
}
}
@@ -1,49 +1,149 @@
import { useState } from 'react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import { useItemMode } from '@/components/editor/findings/useItemMode'
import Dialog from '@/components/ui/Dialog'
import { useEditorReadOnly } from '@/editor/editingContext'
import type { EditorTarget } from '@/editor/navigation'
import { findingPath } from '@/editor/references/panel'
import { useSheetDocument } from '@/editor/sheetDocument'
import type { Guards } from '@/editor/useEditorNavigation'
import type { ReferenceMoves } from '@/editor/useReferenceMoves'
import { useT } from '@/i18n/useT'
import CitationsPanel from './CitationsPanel'
import CitationsEditForm from './CitationsEditForm'
import CitationsPanel, { FindingPath } from './CitationsPanel'
import { CITATIONS_TITLE_ID } from './useCitationsPanel'
export interface CitationsDialogProps {
/** The family or finding node whose citations it shows; null while it is closed. */
citedBy: ElementKey | null
/** A user close (✕, Escape, the backdrop). */
onClose: () => boolean
/** A close: a user one (✕, Escape, the backdrop) is refused by a draft; forced goes. */
onClose: (forced?: boolean) => 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 finding dialog under it, where the focus returns. */
returnFocus: () => HTMLElement | null
guards: Guards
/** The reference dialog over this one (the edit mode's edit and creation). */
references: Pick<ReferenceMoves, 'open' | 'start'>
}
/** The dialog's « Modifier »: the focus comes back to it after the edit mode. */
const EDIT_BUTTON_ID = 'citations-edit-button'
/** The local mode, back to the view for each element the dialog shows (no history entry). */
function useCitationsMode(citedBy: ElementKey | null) {
const shownFor = citedBy && JSON.stringify(citedBy)
const mode = useItemMode(EDIT_BUTTON_ID)
const [modeFor, setModeFor] = useState(shownFor)
if (modeFor !== shownFor) {
setModeFor(shownFor)
mode.reset()
}
return { ...mode, shownFor }
}
type Mode = ReturnType<typeof useCitationsMode>
interface BodyProps {
citedBy: ElementKey
mode: Mode
props: CitationsDialogProps
}
/** The edit mode: where the finding sits, then the draft form. */
function EditBody({ citedBy, mode, props }: BodyProps) {
const doc = useSheetDocument()
const readOnly = useEditorReadOnly()
return (
<>
<FindingPath path={doc ? findingPath(doc, citedBy) : []} />
<CitationsEditForm
key={mode.shownFor}
citedBy={citedBy}
readOnly={readOnly}
guards={props.guards}
references={props.references}
onDone={mode.done}
onDiscardClose={() => props.onClose(true)}
/>
</>
)
}
/** The view mode: the cited references, then « Modifier » (edit tier only). */
function ViewBody({ citedBy, mode, props }: BodyProps) {
const t = useT()
const readOnly = useEditorReadOnly()
return (
<>
<CitationsPanel
citedBy={citedBy}
onShowAll={props.onShowAll}
navigate={props.navigate}
/>
<div className="flex justify-end">
<ActionButton
id={EDIT_BUTTON_ID}
readOnly={readOnly}
variant="secondary"
size="sm"
onClick={mode.startEdit}
>
{t('editor.citations.edit')}
</ActionButton>
</div>
</>
)
}
/** The place of the dialog's content, in both modes, then what a save says. */
function Body(body: BodyProps) {
const t = useT()
const { mode } = body
return (
<section
id="editor-citations-panel"
data-testid="editor-citations-panel"
data-place="citations"
aria-labelledby={CITATIONS_TITLE_ID}
className="space-y-3"
>
{mode.editing ? <EditBody {...body} /> : <ViewBody {...body} />}
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{mode.saved ? t('editor.findings.saved') : ''}
</p>
</section>
)
}
/**
* The references dialog of a family or a finding node (Rev 5): a modal layer over the
* finding dialog. The host sits after the tab body in the tree, so it is shown after the
* finding dialog and lies on top of it; Escape, ✕ and the backdrop close it only. The
* view mode reads the cited references.
* view mode reads the cited references; its « Modifier » turns it into a form (local
* mode, no history entry) whose draft the layer `citations` guards.
*/
export default function CitationsDialog(props: CitationsDialogProps) {
const { citedBy, onClose } = props
const t = useT()
const mode = useCitationsMode(citedBy)
const title = mode.editing
? 'editor.citations.edit_title'
: 'editor.references.dialog_title'
return (
<Dialog
open={citedBy !== null}
layer
size="lg"
title={t('editor.references.dialog_title')}
title={t(title)}
titleId={CITATIONS_TITLE_ID}
returnFocus={props.returnFocus}
onClose={() => (onClose() ? undefined : 'kept')}
>
{citedBy && (
<CitationsPanel
citedBy={citedBy}
onShowAll={props.onShowAll}
navigate={props.navigate}
/>
)}
{citedBy && <Body citedBy={citedBy} mode={mode} props={props} />}
</Dialog>
)
}
@@ -0,0 +1,154 @@
import { useEffect, useRef } from 'react'
import SelectField from '@/components/editor/fields/SelectField'
import Button from '@/components/ui/Button'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useT } from '@/i18n/useT'
export interface DraftListProps {
/** The draft's cited ids, in the order they will be saved. */
ids: readonly string[]
readOnly: boolean
onAdd: (id: string) => void
onRemove: (id: string) => void
/** « Modifier la référence »: the reference dialog over this one. */
onEditReference: (id: string, opener: HTMLElement) => void
/** « Nouvelle référence »: the creation dialog over this one. */
onNew: (opener: HTMLElement) => void
}
/** The add choice: its id, so the focus can land on it once the last row is removed. */
const ADD_ID = 'citations-add-reference'
/** The references the draft does not cite yet, after the « choose » placeholder. */
function useCitableOptions(ids: readonly string[]) {
const t = useT()
const doc = useSheetDocument()
const options = (doc?.references ?? [])
.filter((r) => !ids.includes(r.id))
.map((r) => ({ value: r.id, label: r.citation }))
return [{ value: '', label: t('editor.field.choose') }, ...options]
}
/**
* A removed row takes its buttons with it: the focus goes to the row now at its place,
* else the one before, else the add choice.
*/
function useRemovalFocus(ids: readonly string[]) {
const list = useRef<HTMLUListElement>(null)
const removedAt = useRef<number | null>(null)
useEffect(() => {
const at = removedAt.current
if (at === null) return
removedAt.current = null
const rows = [...(list.current?.children ?? [])]
const row = rows[at] ?? rows[at - 1]
const target =
row?.querySelector('button') ?? document.getElementById(ADD_ID)
target?.focus()
}, [ids])
return { list, removing: (at: number) => (removedAt.current = at) }
}
interface RowProps {
id: string
props: DraftListProps
onRemove: () => void
}
/** One cited id: its citation (or « Référence introuvable »), its edit and its removal. */
function DraftRow({ id, props, onRemove }: RowProps) {
const t = useT()
const doc = useSheetDocument()
const citation = doc?.references.find((r) => r.id === id)?.citation
const shown = citation ?? `${t('editor.references.missing')} ${id}`
return (
<li data-citation-row={id} className="flex flex-wrap items-center gap-2">
<span className="min-w-0 flex-1 text-sm">{shown}</span>
{citation !== undefined && (
<Button
type="button"
variant="secondary"
size="sm"
disabled={props.readOnly}
aria-label={`${t('editor.citations.edit_reference')} ${citation}`}
onClick={(event) => props.onEditReference(id, event.currentTarget)}
>
{t('editor.citations.edit_reference')}
</Button>
)}
<Button
type="button"
variant="ghost"
size="sm"
disabled={props.readOnly}
aria-label={`${t('editor.action.remove')} ${citation ?? id}`}
onClick={onRemove}
>
{t('editor.action.remove')}
</Button>
</li>
)
}
/** « Citer une référence » among those not cited yet, and « Nouvelle référence ». */
function AddRow({ props }: { props: DraftListProps }) {
const t = useT()
const options = useCitableOptions(props.ids)
return (
<div className="flex flex-wrap items-end gap-2">
{!props.readOnly && (
<div className="min-w-0 flex-1">
<SelectField
id={ADD_ID}
label={t('editor.findings.reference_add')}
value=""
options={options}
onCommit={(id) => id !== '' && props.onAdd(id)}
/>
</div>
)}
<Button
type="button"
variant="secondary"
disabled={props.readOnly}
onClick={(event) => props.onNew(event.currentTarget)}
>
{t('editor.citations.new_reference')}
</Button>
</div>
)
}
/**
* The cited references of the draft (the references dialog's edit mode, Rev 5): each with
* « Modifier la référence » and « Retirer » (a dangling id too), then the ways to cite one.
* Nothing is written before « Enregistrer ». Read only: every control off.
*/
export default function CitationsDraftList(props: DraftListProps) {
const { ids } = props
const t = useT()
const focus = useRemovalFocus(ids)
return (
<div className="space-y-3">
{ids.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.findings.references_none')}
</p>
)}
<ul ref={focus.list} className="space-y-2">
{ids.map((id, at) => (
<DraftRow
key={id}
id={id}
props={props}
onRemove={() => {
focus.removing(at)
props.onRemove(id)
}}
/>
))}
</ul>
<AddRow props={props} />
</div>
)
}
@@ -0,0 +1,145 @@
import { useEffect, useRef } from 'react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import { FormActions } from '@/components/editor/findings/DiscardConfirm'
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
import { useFormDraft } from '@/components/editor/findings/useDirtyGuard'
import { patchElement } from '@/editor/findings/tree'
import {
addId,
applyEdits,
NO_EDITS,
removeId,
sameEdits,
type CitationEdits,
} from '@/editor/references/citationEdits'
import { citedIds, citingFinding } from '@/editor/references/filter'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import type { Guards } from '@/editor/useEditorNavigation'
import type { ReferenceMoves } from '@/editor/useReferenceMoves'
import { useT } from '@/i18n/useT'
import CitationsDraftList from './CitationsDraftList'
export interface CitationsEditFormProps {
citedBy: ElementKey
readOnly: boolean
guards: Guards
/** The reference dialog over this one: an edit, or a creation cited in the draft. */
references: Pick<ReferenceMoves, 'open' | 'start'>
/** 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
}
/** The family or node as the document holds it now, and the ids it cites now. */
function useCurrent(citedBy: ElementKey) {
const doc = useSheetDocument()
const item = doc ? citingFinding(doc, citedBy) : null
return { item, ids: item ? citedIds(item) : [] }
}
const sameIds = (a: readonly string[], b: readonly string[]) =>
a.length === b.length && a.every((id, at) => id === b[at])
type Draft = ReturnType<typeof useFormDraft<CitationEdits>>
/** The save: the draft applied to the current citations, one `update`, none unchanged. */
function useCitationsSave(props: CitationsEditFormProps, form: Draft) {
const { item, ids } = useCurrent(props.citedBy)
const edit = useEditCommand()
const save = () => {
const next = applyEdits(ids, form.draft)
if (!item || sameIds(next, ids)) return props.onDone(false)
const element = patchElement(item, { reference_ids: next })
const command = { op: 'update', key: item.key, element } as const
if (edit.run('save', command)) props.onDone(true)
}
return {
shown: applyEdits(ids, form.draft),
save,
error: edit.fieldError('save'),
}
}
/**
* « Nouvelle référence »: the creation dialog over this one; the new id joins the draft,
* only while this form is still there (an abandoned draft cites nothing).
*/
function useCreation(props: CitationsEditFormProps, form: Draft) {
const latest = useRef(form)
latest.current = form
const alive = useRef(true)
useEffect(() => {
alive.current = true
return () => {
alive.current = false
}
}, [])
return (opener: HTMLElement) =>
props.references.start(opener, (id) => {
const now = latest.current
if (alive.current) now.set(addId(now.draft, id))
})
}
/** The form's state: the draft, its guard, its save, its cancel and its creation. */
function useCitationsForm(props: CitationsEditFormProps) {
const form = useFormDraft(NO_EDITS, props.guards, sameEdits, 'citations')
const saving = useCitationsSave(props, form)
const cancel = () =>
form.dirty && !props.readOnly
? form.guard.askToLeave()
: props.onDone(false)
return { ...form, ...saving, cancel, create: useCreation(props, form) }
}
/**
* The references dialog's edit mode (Rev 5): a draft of the citations (cite, remove, a new
* reference cited), one `update` on « Enregistrer » (none when nothing changed), nothing on
* « Annuler » or a close. The draft's layer is `citations`: a dirty one is asked before a
* close, a Back or a leave. Read only: the draft stays, only « Abandonner » is left.
*/
export default function CitationsEditForm(props: CitationsEditFormProps) {
const t = useT()
const form = useCitationsForm(props)
const { guard } = form
const discard =
guard.confirming === 'dialog'
? props.onDiscardClose
: () => props.onDone(false)
return (
<form
data-draft-form
className="space-y-3"
noValidate
onSubmit={(event) => {
event.preventDefault()
form.save()
}}
>
{props.readOnly && <ReadOnlyNotice />}
<CitationsDraftList
ids={form.shown}
readOnly={props.readOnly}
onAdd={(id) => form.set(addId(form.draft, id))}
onRemove={(id) => form.set(removeId(form.draft, id))}
onEditReference={props.references.open}
onNew={form.create}
/>
{form.error && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{form.error}
</p>
)}
<FormActions
confirming={guard.confirming}
readOnly={props.readOnly}
submitLabel={t('editor.findings.save')}
onCancel={form.cancel}
onKeepTyping={guard.keepTyping}
onDiscard={guard.discard(discard)}
/>
</form>
)
}
@@ -6,11 +6,7 @@ import type { CitationEntry } from '@/editor/references/panel'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import ReferenceTile from './ReferenceTile'
import {
CITATIONS_TITLE_ID,
useCitationsPanel,
type PanelHooks,
} from './useCitationsPanel'
import { useCitationsPanel, type PanelHooks } from './useCitationsPanel'
interface Props extends PanelHooks {
/** « Tout afficher dans l'onglet Références ». */
@@ -23,7 +19,7 @@ const RING =
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
/** « Zone › Famille › **Constat** »: where the finding sits, the finding itself in bold. */
function FindingPath({ path }: { path: readonly LocalizedText[] }) {
export function FindingPath({ path }: { path: readonly LocalizedText[] }) {
const locale = useLocaleStore((s) => s.locale)
const names = path.map((name) => name[locale])
const own = names.pop()
@@ -143,10 +139,10 @@ function Entries({ panel, props }: { panel: Panel; props: Props }) {
}
/**
* The citations of one family or finding node, the body of the references dialog
* The citations of one family or finding node, the view mode of the references dialog
* (CitationsDialog): where it sits, the references it cites as tiles, the dangling ids
* named, « Tout afficher » for the whole library. The view mode: no search, add, remove,
* order or « Modifier » (P7).
* named, « Tout afficher » for the whole library. No search, add, remove, order or
* « Modifier » on a tile (P7): the dialog's own « Modifier » opens the edit mode.
*/
export default function CitationsPanel(props: Props) {
const { onShowAll } = props
@@ -154,13 +150,7 @@ export default function CitationsPanel(props: Props) {
const panel = useCitationsPanel(props)
const count = panel.entries.length
return (
<section
id="editor-citations-panel"
data-testid="editor-citations-panel"
data-place="citations"
aria-labelledby={CITATIONS_TITLE_ID}
className="space-y-3"
>
<>
<FindingPath path={panel.path} />
<Summary count={count} onShowAll={onShowAll} />
{count === 0 && (
@@ -169,6 +159,6 @@ export default function CitationsPanel(props: Props) {
</p>
)}
<Entries panel={panel} props={props} />
</section>
</>
)
}
@@ -41,7 +41,7 @@ function useGoneRule(layer: ReferenceLayer) {
}, [view, doc, layer, t])
}
/** Where a closed dialog returns the focus: the tile's header, or the add button. */
/** Where a closed dialog returns the focus: its opener, else the tile header or « Ajouter ». */
function useReturnTarget(layer: ReferenceLayer) {
const last = useRef(layer.view)
if (layer.view) last.current = layer.view
@@ -49,7 +49,9 @@ function useReturnTarget(layer: ReferenceLayer) {
return useCallback((): HTMLElement | null => {
const shown = last.current
if (!shown) return null
if ('create' in shown) return document.getElementById(ADD_BUTTON_ID)
// A creation over the citations dialog returns to its « Nouvelle référence ».
if ('create' in shown)
return opener() ?? document.getElementById(ADD_BUTTON_ID)
const wanted = JSON.stringify({ kind: 'reference', id: shown.edit })
return (
opener() ??
@@ -104,10 +106,10 @@ function useOnSaved(
}
/**
* The reference dialog (R2F-5): one `Dialog` over the References tab or the citations
* sheet, a form for a reference's type, DOI, citation and URL, or for a new one. The view
* layer of the browser history drives it; it is no part of a kept place, so it is never a
* native modal inside a hidden one.
* The reference dialog (R2F-5): one `Dialog` over the References tab or the references
* dialog's edit mode (Rev 5), a form for a reference's type, DOI, citation and URL, or for
* a new one. The view layer of the browser history drives it; it is no part of a kept
* place, so it is never a native modal inside a hidden one.
*/
export default function ReferenceDialog({
layer,
+26 -19
View File
@@ -11,9 +11,10 @@ import {
} from '@/components/ui/afterModalsClosed'
import { focusActiveTab } from '../focusRequest'
import { LAYERS_TOP_DOWN } from '../leftDraft'
import { sameView, type EditorView } from '../navigation'
import { citationsOfView, sameView, type EditorView } from '../navigation'
import {
headingOf,
layersAbove,
shownPlace,
useMoveText,
type EditorNavigation,
@@ -211,23 +212,26 @@ function sameLayers(a: EditorView, b: EditorView): boolean {
)
}
/** The finding dialog a view shows, without its citations dialog: that one holds no form. */
/** The finding dialog a view shows, without its citations dialog (a layer of its own). */
function dialogOf({ finding }: EditorView): unknown {
return finding && 'key' in finding ? { key: finding.key } : finding
}
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
/**
* The layers holding a form that a POP from `from` to `to` takes away, top down: the
* citations dialog alone is no such layer, so a Back that only closes it asks nothing.
* The layers that a POP from `from` to `to` takes away, top down: the reference dialog
* changed, the citations dialog closed or shown for another finding, the finding dialog
* changed. Each is asked; one holding no draft (no guard, or a clean one) lets it go.
*/
function leavingLayers(from: EditorView, to: EditorView): LayerName[] {
const same = (a: unknown, b: unknown) =>
JSON.stringify(a) === JSON.stringify(b)
const reference = from.reference && !same(from.reference, to.reference)
const finding = from.finding && !same(dialogOf(from), dialogOf(to))
return LAYERS_TOP_DOWN.filter((l) =>
l === 'reference' ? reference : finding,
)
const cited = citationsOfView(from)
const leaving = {
reference: !!from.reference && !same(from.reference, to.reference),
citations: !!cited && !same(cited, citationsOfView(to)),
finding: !!from.finding && !same(dialogOf(from), dialogOf(to)),
}
return LAYERS_TOP_DOWN.filter((layer) => leaving[layer])
}
/**
@@ -249,12 +253,14 @@ function refusal(
return leaving.find((layer) => !nav.guards.ask(layer, false).allowed) ?? null
}
/** The finding dialog alone: the clean citations and reference dialogs over it go. */
function bareFinding(view: EditorView): EditorView {
/** `view` without the dialogs over `layer`: the clean layers above the one that asks. */
function upTo(view: EditorView, layer: LayerName): EditorView {
const above = layersAbove(layer)
const { finding } = view
const shown =
finding && 'key' in finding ? { ...finding, citations: false } : finding
return { ...view, finding: shown, reference: null }
const closes = above.includes('citations') && finding && 'key' in finding
const shown = closes ? { ...finding, citations: false } : finding
const reference = above.includes('reference') ? null : view.reference
return { ...view, finding: shown, reference }
}
interface PopContext {
@@ -278,15 +284,16 @@ function landOnForeign(ctx: PopContext): Landing | null {
/**
* A POP refused (see `refusal`): the view stays, pushed again above the entry landed on.
* When the finding dialog refused, the clean citations and reference dialogs over it close
* first, so its question is not hidden under them. True when refused.
* The clean dialogs over the layer that refused close first (the reference dialog over a
* citations draft; both over a finding draft), so its question is not hidden under them.
* True when refused.
*/
function refusePop(ctx: PopContext, landed: HistoryEntry | null): boolean {
const refused = refusal(ctx, landed)
if (!refused) return false
const { book, writer, view } = ctx
if (landed) adopt(book, landed)
const kept = refused === 'finding' ? bareFinding(view) : view
const kept = refused === 'modal' ? view : upTo(view, refused)
if (!sameView(kept, view)) ctx.nav.restoreView(kept)
writer.push(kept)
return true
+26 -20
View File
@@ -1,11 +1,13 @@
import { useCallback, useEffect, useRef } from 'react'
import { useLocation } from 'react-router-dom'
import { topDirtyLayer } from '../leftDraft'
import type {
EditorNavigation,
Guards,
LayerExit,
LayerName,
import { citationsOfView } from '../navigation'
import {
layersAbove,
type EditorNavigation,
type Guards,
type LayerExit,
type LayerName,
} from '../useEditorNavigation'
/** The part of a Navigation API `navigate` event this guard reads (not in the DOM types). */
@@ -41,10 +43,11 @@ function leavesEditor(event: NavigateEventLike, path: string): boolean {
interface Watch {
guards: Guards
/**
* Closes the citations dialog and a reference dialog over it: they lie over the finding
* dialog, so its question would be hidden under them.
* Closes the dialogs over `layer` (clean: it is the top dirty one), so its question is
* not hidden under them: the reference dialog over the citations dialog, both over the
* finding dialog.
*/
clearAbove: () => void
clearAbove: (layer: LayerName) => void
path: string
/** The key of the jump the user confirmed: it passes, and leaves no flag. */
passing: { current: string | null }
@@ -72,15 +75,14 @@ function jumpTo({ api, key, watch }: Jump, keep: () => void): void {
}
/**
* `layer` asks « Abandonner les modifications ? » and holds the jump. Its « Abandonner »
* closes it, with the citations dialog it may have been opened from (so the next question
* is not hidden under the citations dialog), and the next dirty layer under it asks in turn; the
* last one lets the jump go. Any « Continuer la saisie » drops the jump. The finding
* dialog asks once the layers over it are closed (they are clean: it is the top dirty one).
* `layer` asks « Abandonner les modifications ? » and holds the jump, once the layers over
* it are closed (they are clean: it is the top dirty one). Its « Abandonner » closes it,
* and the next dirty layer under it asks in turn; the last one lets the jump go. Any
* « Continuer la saisie » drops the jump.
*/
function askLeave(jump: Jump, layer: LayerName): void {
const { guards, clearAbove } = jump.watch
if (layer === 'finding') clearAbove()
clearAbove(layer)
guards.ask(layer, false)
guards.holdLeave({
layer,
@@ -113,13 +115,17 @@ type LeaveNav = Pick<
'guards' | 'state' | 'closeCitations' | 'references'
>
/** Closes the citations and reference dialogs of the navigation `latest` holds, if open. */
function clearerOf(latest: { current: LeaveNav }): () => void {
return () => {
/**
* Closes the open dialogs over `layer` of the navigation `latest` holds. Forced: they hold
* no draft, or one just abandoned (the state read may still show it, one commit behind).
*/
function clearerOf(latest: { current: LeaveNav }): (layer: LayerName) => void {
return (layer) => {
const { state, closeCitations, references } = latest.current
const { finding } = state
if (finding && 'key' in finding && finding.citations) closeCitations()
if (state.reference) references.close(true)
const above = layersAbove(layer)
if (above.includes('reference') && state.reference) references.close(true)
const cited = above.includes('citations') && citationsOfView(state)
if (cited) closeCitations(true)
}
}
+8 -2
View File
@@ -2,7 +2,12 @@ import { useEffect, useRef, useState } from 'react'
import type { HistoryOwner } from './history/entry'
import { fingerprintOf, randomHex } from './history/fingerprint'
import type { NavigationState } from './navigation'
import type { EditorNavigation, Guards, LayerName } from './useEditorNavigation'
import {
LAYERS,
type EditorNavigation,
type Guards,
type LayerName,
} from './useEditorNavigation'
/**
* A dirty dialog lost when the editor goes (a Back of several entries the browser does
@@ -24,7 +29,7 @@ export const leftDraftKey = ({ sheetId, tag }: HistoryOwner) =>
`${PREFIX}${sheetId}:${tag}`
/** The top layer first: the dialog the user was typing in when they left. */
export const LAYERS_TOP_DOWN: readonly LayerName[] = ['reference', 'finding']
export const LAYERS_TOP_DOWN: readonly LayerName[] = [...LAYERS].reverse()
/**
* The top layer whose form holds changes, or the first one under `below`; a forced ask
@@ -55,6 +60,7 @@ function elementOf(state: NavigationState, layer: LayerName): unknown {
? { kind: 'reference', id: reference.edit }
: null
}
// The citations dialog's element is the finding whose citations it edits.
const { finding } = state
if (!finding) return null
return 'key' in finding ? finding.key : finding.create.parent
+7 -2
View File
@@ -291,9 +291,14 @@ function openReference(state: NavigationState, id: string): NavigationState {
return shown({ ...state, reference: { edit: id } })
}
/** The creation form of a reference: only the References tab adds one. */
/**
* The creation form of a reference: over the References tab, or over the citations dialog
* (its edit mode cites the new reference, Rev 5), which keeps its tab.
*/
function createReference(state: NavigationState): NavigationState {
return shown({ ...state, tab: 'references', reference: { create: true } })
const reference = { create: true } as const
if (citationsOfView(state)) return shown({ ...state, reference })
return shown({ ...state, tab: 'references', reference })
}
export function navigationReducer(
@@ -0,0 +1,41 @@
/**
* The draft of the references dialog's edit mode (Rev 5): what the user added and removed,
* never a whole list. It is applied to the element's CURRENT citations at save, so a
* change made elsewhere meanwhile (an undo, a reload) is kept, never overwritten.
*/
export interface CitationEdits {
added: readonly string[]
removed: readonly string[]
}
export const NO_EDITS: CitationEdits = { added: [], removed: [] }
export const sameEdits = (a: CitationEdits, b: CitationEdits) =>
JSON.stringify(a) === JSON.stringify(b)
/** `current` with the removals dropped and the additions appended, each id once. */
export function applyEdits(
current: readonly string[],
edits: CitationEdits,
): string[] {
const kept = current.filter((id) => !edits.removed.includes(id))
return [...kept, ...edits.added.filter((id) => !kept.includes(id))]
}
/** Cites `id`: undoes its removal, else adds it. */
export function addId(edits: CitationEdits, id: string): CitationEdits {
if (edits.removed.includes(id)) {
return { ...edits, removed: edits.removed.filter((other) => other !== id) }
}
if (edits.added.includes(id)) return edits
return { ...edits, added: [...edits.added, id] }
}
/** Removes `id`: undoes its addition, else records the removal. */
export function removeId(edits: CitationEdits, id: string): CitationEdits {
if (edits.added.includes(id)) {
return { ...edits, added: edits.added.filter((other) => other !== id) }
}
if (edits.removed.includes(id)) return edits
return { ...edits, removed: [...edits.removed, id] }
}
+39 -19
View File
@@ -53,8 +53,12 @@ export interface LeaveAnswer {
}
export type CanLeave = (forced: boolean) => LeaveAnswer
/** The layers that can hold a form the user must settle before leaving, top one last. */
const LAYERS = ['finding', 'reference'] as const
/**
* The layers that can hold a form the user must settle before leaving, in stacking order
* (top one last): the finding dialog, the citations dialog over it (its edit mode, Rev 5),
* the reference dialog over either.
*/
export const LAYERS = ['finding', 'citations', 'reference'] as const
export type LayerName = (typeof LAYERS)[number]
/** One guard per layer (R2F-1): each layer registers its own check while it is mounted. */
@@ -132,8 +136,11 @@ export interface EditorNavigation {
replaceFinding: (key: ElementKey | null, text?: string) => void
/** Opens the citations dialog of a family or a node; any other key is ignored. */
openCitations: (citedBy: ElementKey, opener?: Opener) => void
/** A user close of the citations dialog. */
closeCitations: () => boolean
/**
* A close of the citations dialog: a user one is refused by its draft (it asks first),
* a forced one goes (the draft is dropped).
*/
closeCitations: (forced?: boolean) => boolean
/** « X références », where the focus returns once the citations dialog is closed. */
citationsTrigger: () => HTMLElement | null
/**
@@ -386,7 +393,7 @@ function useFindingClosing({ dispatch, announce, guards, mark }: LayerContext) {
/** The citations dialog over the finding dialog: opened for a family or a node only. */
function useCitationsLayer(ctx: LayerContext, openers: Openers) {
const { dispatch, mark } = ctx
const { dispatch, guards, mark } = ctx
const openCitations = useCallback(
(citedBy: ElementKey, opener?: Opener) => {
if (!isCitable(citedBy)) return
@@ -397,35 +404,48 @@ function useCitationsLayer(ctx: LayerContext, openers: Openers) {
},
[openers, dispatch, mark],
)
const closeCitations = useCallback(() => {
mark()
dispatch({ type: 'close_citations' })
return true
}, [dispatch, mark])
const closeCitations = useCallback(
(forced = false) => {
if (!guards.ask('citations', forced).allowed) return false
mark()
dispatch({ type: 'close_citations' })
return true
},
[guards, dispatch, mark],
)
return { openCitations, closeCitations }
}
/** The layers stacked over `layer`, top one last. */
export const layersAbove = (layer: LayerName): LayerName[] =>
LAYERS.slice(LAYERS.indexOf(layer) + 1)
/**
* Asks every layer, top down, before a move that leaves them all; true when none refused.
* When the finding dialog is the top one to refuse, the clean dialogs over it close first
* so its question is the one in view (as a refused Back, `bareFinding`).
* The clean dialogs over the top one to refuse close first so its question is the one in
* view (as a refused Back, `refusePop`).
*/
function useAskLeaving(ctx: LayerContext, state: NavigationState) {
const { guards, dispatch, mark } = ctx
const cited = citationsOfView(state) !== null
const citations = citationsOfView(state) !== null
const reference = state.reference !== null
return useCallback((): boolean => {
const refused = [...LAYERS]
.reverse()
.filter((layer) => !guards.ask(layer, false).allowed)
if (refused[0] !== 'finding' || !(cited || reference)) {
return refused.length === 0
}
if (refused.length === 0) return true
const above = layersAbove(refused[0])
const shown = { finding: false, citations, reference }
if (!above.some((layer) => shown[layer])) return false
mark()
if (reference) dispatch({ type: 'close_reference' })
if (cited) dispatch({ type: 'close_citations' })
if (above.includes('reference') && reference) {
dispatch({ type: 'close_reference' })
}
if (above.includes('citations') && citations) {
dispatch({ type: 'close_citations' })
}
return false
}, [guards, dispatch, mark, cited, reference])
}, [guards, dispatch, mark, citations, reference])
}
/** « Aller à » and « Tout afficher » leave every layer: a layer in edit may refuse. */
+39 -14
View File
@@ -1,4 +1,4 @@
import { useCallback, useRef, useState, type RefObject } from 'react'
import { useCallback, useRef, useState } from 'react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import type { LayerContext, MoveTrace } from './useEditorNavigation'
@@ -10,12 +10,19 @@ export interface AddedReference {
type Opener = HTMLElement | null | undefined
/** What a creation started from the citations dialog's edit form does with the new id. */
export type CiteCreated = (id: string) => void
/** What the reference dialog (R2F-5) and the References tab's filter (R2F-6) do to the view. */
export interface ReferenceMoves {
/** The dialog of reference `id`, over the place the view shows. */
open: (id: string, opener?: Opener) => void
/** The creation dialog, over the References tab. */
start: (opener?: Opener) => void
/**
* The creation dialog, over the References tab or the citations dialog. `cite` is the
* citations edit form that started it (Rev 5): the new id goes to its draft, and the
* library shows no « added » notice for it.
*/
start: (opener?: Opener, cite?: CiteCreated) => void
/** A user close; false when the form refused it (a dirty draft asks first). */
close: (forced?: boolean) => boolean
/**
@@ -35,19 +42,27 @@ export interface ReferenceMoves {
backToFinding: (key: ElementKey) => void
}
/** What the open dialog was started from: its opener, and a citing form for a creation. */
interface Held {
opener: Opener
cite: CiteCreated | null
}
/** The moves that add the dialog: an edit of a reference, a creation. */
function useOpening({ dispatch, mark }: LayerContext, held: RefObject<Opener>) {
function useOpening({ dispatch, mark }: LayerContext, held: Held) {
const open = useCallback(
(id: string, opener?: Opener) => {
held.current = opener
held.opener = opener
held.cite = null
mark()
dispatch({ type: 'open_reference', id })
},
[dispatch, mark, held],
)
const start = useCallback(
(opener?: Opener) => {
held.current = opener
(opener?: Opener, cite?: CiteCreated) => {
held.opener = opener
held.cite = cite ?? null
mark()
dispatch({ type: 'create_reference' })
},
@@ -89,14 +104,24 @@ function useClosing(ctx: LayerContext) {
return { close: useClose(ctx), replace: useReplace(ctx) }
}
/** A creation that succeeded: its entry becomes the reference's own, then it closes. */
function useCreated(ctx: LayerContext, replace: ReferenceMoves['replace']) {
/**
* A creation that succeeded: its entry becomes the reference's own, then it closes. The
* citing form that started it takes the id (no notice); else the library says it.
*/
function useCreated(
ctx: LayerContext,
replace: ReferenceMoves['replace'],
held: Held,
) {
const { dispatch, mark } = ctx
const [added, setAdded] = useState<AddedReference | null>(null)
const created = useCallback(
(id: string) => {
const citing = held.cite
held.cite = null
replace(id)
setAdded((last) => ({ id, serial: (last?.serial ?? 0) + 1 }))
if (citing) citing(id)
else setAdded((last) => ({ id, serial: (last?.serial ?? 0) + 1 }))
// Precondition: the caller is a discrete event (the form's submit). React then
// renders the replace and runs the history effect before this microtask, so the
// entry is the reference's own before the close goes back over it and a Forward
@@ -108,7 +133,7 @@ function useCreated(ctx: LayerContext, replace: ReferenceMoves['replace']) {
dispatch({ type: 'close_reference' })
})
},
[replace, mark, dispatch],
[replace, mark, dispatch, held],
)
return { created, added }
}
@@ -139,16 +164,16 @@ export function useReferenceMoves(
ctx: LayerContext,
trace: MoveTrace,
): ReferenceMoves {
const held = useRef<Opener>(null)
const held = useRef<Held>({ opener: null, cite: null }).current
const opener = useCallback((): HTMLElement | null => {
const element = held.current
const element = held.opener
return element?.isConnected && !element.closest('[hidden]') ? element : null
}, [held])
const closing = useClosing(ctx)
return {
...useOpening(ctx, held),
...closing,
...useCreated(ctx, closing.replace),
...useCreated(ctx, closing.replace, held),
...useFilter(ctx, trace),
opener,
}
+4
View File
@@ -1229,6 +1229,10 @@ export const en: Dict = {
'editor.annotations.deselected': 'No annotation selected.',
'editor.references.search': 'Search a reference',
'editor.references.dialog_title': 'References of the finding',
'editor.citations.edit': 'Edit',
'editor.citations.edit_title': 'Edit the references of the finding',
'editor.citations.edit_reference': 'Edit the reference',
'editor.citations.new_reference': 'New reference',
'editor.references.panel_count_one': '{count} reference cited by this finding',
'editor.references.panel_count_other': '{count} references cited by this finding',
'editor.references.panel_show_all': 'Show all in the References tab',
+4
View File
@@ -1260,6 +1260,10 @@ export const fr: Dict = {
'editor.annotations.deselected': 'Aucune annotation sélectionnée.',
'editor.references.search': 'Rechercher une référence',
'editor.references.dialog_title': 'Références du constat',
'editor.citations.edit': 'Modifier',
'editor.citations.edit_title': 'Modifier les références du constat',
'editor.citations.edit_reference': 'Modifier la référence',
'editor.citations.new_reference': 'Nouvelle référence',
'editor.references.panel_count_one': '{count} référence citée par ce constat',
'editor.references.panel_count_other': '{count} références citées par ce constat',
'editor.references.panel_show_all': 'Tout afficher dans l\'onglet Références',