feat(editor): a reference made in the citations draft saves with it

This commit is contained in:
bchanot committed 2026-11-15 19:55:41 +01:00
1 parent 8c3fcca0b9
commit 70eb2fcbb4
15 files changed
+671 -162

No files matched your search

@@ -54,10 +54,12 @@ interface BodyProps {
citedBy: ElementKey
mode: Mode
props: CitationsDialogProps
/** The edit mode's status line (a draft creation, a pending one removed; Rev 6). */
onNotice: (text: string) => void
}
/** The edit mode: where the finding sits, then the draft form. */
function EditBody({ citedBy, mode, props }: BodyProps) {
function EditBody({ citedBy, mode, props, onNotice }: BodyProps) {
const doc = useSheetDocument()
const readOnly = useEditorReadOnly()
return (
@@ -70,6 +72,7 @@ function EditBody({ citedBy, mode, props }: BodyProps) {
guards={props.guards}
references={props.references}
onDone={mode.done}
onNotice={onNotice}
onDiscardClose={() => props.onClose(true, true)}
/>
</>
@@ -102,10 +105,15 @@ function ViewBody({ citedBy, mode, props }: BodyProps) {
)
}
/** The place of the dialog's content, in both modes, then what a save says. */
function Body(body: BodyProps) {
/**
* The place of the dialog's content, in both modes, then its status line: what a save
* says, or what the edit mode's draft just did (never the editor's live region, Rev 6).
*/
function Body(body: Omit<BodyProps, 'onNotice'>) {
const t = useT()
const { mode } = body
const [notice, setNotice] = useState('')
if (!mode.editing && notice !== '') setNotice('')
return (
<section
id="editor-citations-panel"
@@ -114,9 +122,13 @@ function Body(body: BodyProps) {
aria-labelledby={CITATIONS_TITLE_ID}
className="space-y-3"
>
{mode.editing ? <EditBody {...body} /> : <ViewBody {...body} />}
{mode.editing ? (
<EditBody {...body} onNotice={setNotice} />
) : (
<ViewBody {...body} onNotice={setNotice} />
)}
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{mode.saved ? t('editor.findings.saved') : ''}
{notice || (mode.saved ? t('editor.findings.saved') : '')}
</p>
</section>
)
@@ -1,4 +1,6 @@
import { useEffect, useRef } from 'react'
import type { Reference } from '@faunosteo/core-wasm/types'
import Badge from '@/components/ui/Badge'
import Button from '@/components/ui/Button'
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
import Select from '@/components/ui/Select'
@@ -20,11 +22,13 @@ export interface CiteChoice {
export interface DraftListProps {
/** The draft's cited ids, in the order they will be saved. */
ids: readonly string[]
/** The references made in the draft (Rev 6): written only by « Enregistrer ». */
pending: readonly Reference[]
readOnly: boolean
choice: CiteChoice
onAdd: (id: string) => void
onRemove: (id: string) => void
/** « Modifier la référence »: the reference dialog over this one. */
/** « Modifier la référence »: the reference dialog over this one (a pending one too). */
onEditReference: (id: string, opener: HTMLElement) => void
/** « Nouvelle référence »: the creation dialog over this one. */
onNew: (opener: HTMLElement) => void
@@ -72,15 +76,28 @@ interface RowProps {
onRemove: () => void
}
/** One cited id: its citation (or « Référence introuvable »), its edit and its removal. */
/**
* One cited id: its citation (or « Référence introuvable »), « Nouvelle » when the draft
* made it, 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 pending = props.pending.some((r) => r.id === id)
const citation = [...props.pending, ...(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>
<span className="min-w-0 flex-1 text-sm">
<span>{shown}</span>
{pending && (
<Badge tone="accent" className="ms-2">
{t('editor.citations.pending')}
</Badge>
)}
</span>
{citation !== undefined && (
<Button
type="button"
@@ -179,7 +196,8 @@ function AddRow({ props }: { props: DraftListProps }) {
/**
* 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.
* « Modifier la référence » and « Retirer » (a dangling id too; a pending one, Rev 6,
* badged « Nouvelle »), then the ways to cite one.
* Nothing is written before « Enregistrer ». Read only: every control off.
*/
export default function CitationsDraftList(props: DraftListProps) {
@@ -1,13 +1,17 @@
import { useEffect, useRef, useState } from 'react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import type { ElementKey, Reference } 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 { patchElement, type FindingItem } from '@/editor/findings/tree'
import { newElementId } from '@/editor/ids'
import { isFamilyKey } from '@/editor/navigation'
import {
addId,
applyEdits,
citationCommands,
NO_EDITS,
putCreated,
removeId,
sameEdits,
type CitationEdits,
@@ -31,6 +35,8 @@ export interface CitationsEditFormProps {
references: Pick<ReferenceMoves, 'open' | 'start'>
/** Back to the view mode; `saved` is true when a command was written. */
onDone: (saved: boolean) => void
/** What the draft did that the dialog's status line says (a draft creation, Rev 6). */
onNotice: (text: string) => void
/** « Abandonner » after a close request: the draft goes, so does the dialog. */
onDiscardClose: () => void
}
@@ -46,30 +52,65 @@ 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>>
type Translate = ReturnType<typeof useT>
/** The save: the draft applied to the current citations, one `update`, none unchanged. */
/** The save's batch: the created references' inserts under fresh ids, then the `update`. */
function saveCommands(
item: FindingItem,
ids: readonly string[],
draft: CitationEdits,
) {
const update = (next: string[]) => {
const element = patchElement(item, { reference_ids: next })
return { op: 'update', key: item.key, element } as const
}
return citationCommands(draft, ids, update, () => newElementId('ref'))
}
/** A refused save with references made in the draft: the line names them, still pending. */
function savedError(
t: Translate,
error: string | undefined,
draft: CitationEdits,
) {
if (!error || draft.created.length === 0) return error
const citations = draft.created.map((r) => r.citation).join(' ; ')
return `${error} ${t('editor.citations.pending_kept').replace('{citation}', citations)}`
}
/**
* The save: one batch (the created references, then the element's `update`, one undo
* step), none when nothing changed; refused, the draft stays (an element gone too).
*/
function useCitationsSave(props: CitationsEditFormProps, form: Draft) {
const t = useT()
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)
if (!item) {
const gone = isFamilyKey(props.citedBy)
? 'editor.findings.gone_family'
: 'editor.findings.gone'
return void edit.reject('save', gone)
}
if (sameIds(applyEdits(ids, form.draft), ids)) return props.onDone(false)
const build = () => saveCommands(item, ids, form.draft)
if (edit.runBatch('save', build)) props.onDone(true)
}
return {
shown: applyEdits(ids, form.draft),
save,
error: edit.fieldError('save'),
error: savedError(t, edit.fieldError('save'), form.draft),
}
}
/**
* « 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).
* « Nouvelle référence », or « Modifier la référence » of a pending one (Rev 6): the
* reference dialog over this one writes nothing; its value joins the draft, only while
* this form is still there, and the status line says so.
*/
function useCreation(props: CitationsEditFormProps, form: Draft) {
const t = useT()
const latest = useRef(form)
latest.current = form
const alive = useRef(true)
@@ -79,11 +120,37 @@ function useCreation(props: CitationsEditFormProps, form: Draft) {
alive.current = false
}
}, [])
return (opener: HTMLElement) =>
props.references.start(opener, (id) => {
const now = latest.current
if (alive.current) now.set(addId(now.draft, id))
})
const cite = (value: Reference) => {
if (!alive.current) return
const now = latest.current
now.set(putCreated(now.draft, value))
const text = t('editor.citations.created_draft')
props.onNotice(text.replace('{citation}', value.citation))
}
return (opener: HTMLElement, initial?: Reference) =>
props.references.start(opener, cite, initial)
}
/** « Modifier la référence » and « Retirer » of a row: a pending one stays in the draft. */
function useRowMoves(props: CitationsEditFormProps, form: Draft) {
const t = useT()
const create = useCreation(props, form)
const pendingOf = (id: string) => form.draft.created.find((r) => r.id === id)
return {
create,
editReference: (id: string, opener: HTMLElement) => {
const pending = pendingOf(id)
if (pending) create(opener, pending)
else props.references.open(id, opener)
},
remove: (id: string) => {
const pending = pendingOf(id)
form.set(removeId(form.draft, id))
if (!pending) return
const text = t('editor.citations.pending_removed')
props.onNotice(text.replace('{citation}', pending.citation))
},
}
}
/**
@@ -109,7 +176,7 @@ function useCiteChoice(ids: readonly string[]) {
}
}
/** The form's state: the draft, its guard, its save, its cancel and its creation. */
/** The form's state: the draft, its guard, its save, its cancel and its rows' moves. */
function useCitationsForm(props: CitationsEditFormProps) {
const form = useFormDraft(NO_EDITS, props.guards, sameEdits, 'citations')
const saving = useCitationsSave(props, form)
@@ -125,16 +192,17 @@ function useCitationsForm(props: CitationsEditFormProps) {
choice,
cancel,
submit,
create: useCreation(props, form),
rows: useRowMoves(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; refused
* while a choice in the select waits for « Citer », Rev 6), 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.
* reference made in the draft, Rev 6), one batch on « Enregistrer » (the new references
* and the `update`, one undo step; none when nothing changed; refused while a choice in
* the select waits for « Citer »), 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()
@@ -157,12 +225,13 @@ export default function CitationsEditForm(props: CitationsEditFormProps) {
{props.readOnly && <ReadOnlyNotice />}
<CitationsDraftList
ids={form.shown}
pending={form.draft.created}
readOnly={props.readOnly}
choice={form.choice}
onAdd={(id) => form.set(addId(form.draft, id))}
onRemove={(id) => form.set(removeId(form.draft, id))}
onEditReference={props.references.open}
onNew={form.create}
onRemove={form.rows.remove}
onEditReference={form.rows.editReference}
onNew={(opener) => form.rows.create(opener)}
/>
{form.error && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
@@ -90,7 +90,10 @@ function useShownReference(layer: ReferenceLayer, handed: string | null) {
return { creating, edited, title: t(title), open: creating || !!edited }
}
/** What a save does: a creation is announced, then handed over; an edit closes the layer. */
/**
* What a save does: a library creation is announced, then handed over; an edit, or a
* draft creation (its value already with the citing form, which says it), closes the layer.
*/
function useOnSaved(
layer: ReferenceLayer,
creating: boolean,
@@ -98,7 +101,7 @@ function useOnSaved(
) {
const t = useT()
return (id: string, citation: string) => {
if (!creating) return void layer.close(true)
if (!creating || layer.drafting()) return void layer.close(true)
handOver(id)
layer.announce(t('editor.references.added').replace('{citation}', citation))
layer.created(id)
@@ -108,8 +111,10 @@ function useOnSaved(
/**
* 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.
* a new one. Over the edit mode it is a draft creation (Rev 6): titled « Nouvelle
* référence », it writes nothing and hands the value to the citing form. 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,
@@ -119,6 +124,8 @@ export default function ReferenceDialog({
const shown = useShownReference(layer, creation.handed)
const returnFocus = useReturnTarget(layer)
const onSaved = useOnSaved(layer, shown.creating, creation.handOver)
const drafting = layer.drafting()
const reference = drafting ? drafting.initial : shown.edited
useGoneRule(layer)
return (
<Dialog
@@ -130,11 +137,12 @@ export default function ReferenceDialog({
onClose={() => (layer.close() ? undefined : 'kept')}
>
<ReferenceForm
key={shown.edited?.id ?? 'new'}
reference={shown.edited}
key={reference?.id ?? 'new'}
reference={reference}
readOnly={readOnly}
guards={layer.guards}
onSaved={onSaved}
onValue={drafting?.cite}
onClose={(forced) => layer.close(forced)}
/>
</Dialog>
@@ -9,6 +9,7 @@ import SelectField from '@/components/editor/fields/SelectField'
import { FormActions } from '@/components/editor/findings/DiscardConfirm'
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
import { useFormDraft } from '@/components/editor/findings/useDirtyGuard'
import { newElementId } from '@/editor/ids'
import { webHref } from '@/editor/references/safeLink'
import { isBlank, nullable } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
@@ -77,36 +78,71 @@ export interface ReferenceFormProps {
reference: Reference | null
readOnly: boolean
guards: Guards
/** One command was written; `id` and `citation` are the reference's. */
/** One command was written, or the value handed over; `id` and `citation` are its. */
onSaved: (id: string, citation: string) => void
/**
* A draft creation (Rev 6): the save writes nothing and hands the value here instead;
* `reference` is then the pending value modified (its id kept), or null.
*/
onValue?: (value: Reference) => void
/** Nothing was written (pristine save, « Annuler », « Abandonner »); forced drops a draft. */
onClose: (forced: boolean) => void
}
type Form = ReturnType<typeof useFormDraft<Draft>>
type EditApi = ReturnType<typeof useEditCommand>
/** The one command of a library save: an `update`, or an `insert` under a new id. */
function writeCommand(
edit: EditApi,
reference: Reference | null,
draft: Draft,
): string | null {
if (reference) {
const element = { kind: 'reference', value: valueOf(draft, reference.id) }
const key = { kind: 'reference', id: reference.id }
const command = { op: 'update', key, element } as EditCommand
return edit.run('form', command) ? reference.id : null
}
let id = ''
const added = edit.runNew('form', 'ref', (fresh) => {
id = fresh
const element = { kind: 'reference', value: valueOf(draft, fresh) }
return { op: 'insert', element } as EditCommand
})
return added ? id : null
}
/**
* The one command of a save: an `update` of the reference, or an `insert` under a new id.
* The dialog closes after a save: a second submit while it plays its exit writes nothing.
* A draft creation (Rev 6): the value under the pending id or a fresh one, its insert
* dry-run on the current document (a refusal shows here, nothing is stored), then handed
* to the citing form.
*/
function useWrite(reference: Reference | null, draft: Draft) {
function offerValue(
edit: EditApi,
props: ReferenceFormProps,
draft: Draft,
onValue: (value: Reference) => void,
): string | null {
const value = valueOf(draft, props.reference?.id ?? newElementId('ref'))
const element = { kind: 'reference', value } as const
if (!edit.check('form', { op: 'insert', element })) return null
onValue(value)
return value.id
}
/**
* The save's one move: a command written, or a value handed to a citing form. The dialog
* closes after it: a second submit while it plays its exit does nothing.
*/
function useWrite(props: ReferenceFormProps, draft: Draft) {
const edit = useEditCommand()
const saved = useRef(false)
const run = (): string | null => {
if (reference) {
const element = { kind: 'reference', value: valueOf(draft, reference.id) }
const key = { kind: 'reference', id: reference.id }
const command = { op: 'update', key, element } as EditCommand
return edit.run('form', command) ? reference.id : null
}
let id = ''
const added = edit.runNew('form', 'ref', (fresh) => {
id = fresh
const element = { kind: 'reference', value: valueOf(draft, fresh) }
return { op: 'insert', element } as EditCommand
})
return added ? id : null
}
const run = (): string | null =>
props.onValue
? offerValue(edit, props, draft, props.onValue)
: writeCommand(edit, props.reference, draft)
const write = (): string | null => {
const id = saved.current ? null : run()
saved.current = saved.current || id !== null
@@ -117,7 +153,7 @@ function useWrite(reference: Reference | null, draft: Draft) {
/** The save: refused on its field, nothing written when unchanged, else one command. */
function useReferenceSave(props: ReferenceFormProps, form: Form) {
const { edit, write } = useWrite(props.reference, form.draft)
const { edit, write } = useWrite(props, form.draft)
const save = () => {
const refusal = refusalOf(form.draft, props.reference === null)
if (refusal) {
@@ -201,15 +237,21 @@ function FormFields({
/**
* A reference edited or created in the reference dialog (R2F-5): a local draft, one
* command on « Enregistrer » (none when nothing changed), nothing on « Annuler », a close
* or a move. When the editor turns read-only the draft stays, its fields read-only, and
* only « Abandonner » is left.
* command on « Enregistrer » (none when nothing changed; in a draft creation, none at all:
* the value goes to the citing form), nothing on « Annuler », a close or a move. When
* the editor turns read-only the draft stays, its fields read-only, and only
* « Abandonner » is left.
*/
export default function ReferenceForm(props: ReferenceFormProps) {
const t = useT()
const form = useReferenceForm(props)
const { guard } = form
const creating = props.reference === null
const submitLabel =
props.reference === null
? 'editor.reference.add'
: props.onValue
? 'common.confirm'
: 'editor.findings.save'
return (
<form
data-draft-form
@@ -230,9 +272,7 @@ export default function ReferenceForm(props: ReferenceFormProps) {
<FormActions
confirming={guard.confirming}
readOnly={props.readOnly}
submitLabel={t(
creating ? 'editor.reference.add' : 'editor.findings.save',
)}
submitLabel={t(submitLabel)}
onCancel={() =>
form.dirty && !props.readOnly
? guard.askToLeave()