feat(editor): cite references from the finding edit form only

This commit is contained in:
bchanot committed 2026-11-14 14:11:13 +01:00
1 parent afc1051313
commit f0e49fd447
16 files changed
+519 -395

No files matched your search

@@ -1,16 +1,12 @@
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 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). */
@@ -48,15 +44,15 @@ function SheetTrigger({
)
}
/** A family's inline list of cited references, each removable (« Retirer »). */
function CitationList({
/** A family's inline 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
remove?: (id: string) => void
}) {
const t = useT()
const doc = useSheetDocument()
@@ -67,85 +63,69 @@ function CitationList({
{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>
{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>
)
}
/** The finding's cited ids, the update that changes them and the references still citable. */
function useCitationEdit(item: FindingItem, edit: EditCommandApi) {
/** « Références citées » and « X références »: the heading row of both modes. */
export function CitationsHeader({
item,
count,
sheetOpen,
onShowReferences,
}: Pick<CitationsProps, 'item' | 'sheetOpen' | 'onShowReferences'> & {
count: number
}) {
const t = useT()
const doc = useSheetDocument()
const ids =
item.element.kind === 'zone' ? [] : item.element.value.reference_ids
const patch = (reference_ids: string[]) =>
edit.run('references', {
op: 'update',
key: item.key,
element: patchElement(item, { reference_ids }),
})
const options = (doc?.references ?? [])
.filter((r) => !ids.includes(r.id))
.map((r) => ({ value: r.id, label: r.citation }))
return {
ids,
patch,
options: [{ value: '', label: t('editor.field.choose') }, ...options],
}
}
/**
* « 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 cited = useCitationEdit(item, edit)
if (item.element.kind === 'zone') return null
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>
{cited.ids.length > 0 && item.element.kind === 'finding_node' && (
<SheetTrigger {...props} count={cited.ids.length} />
)}
</div>
{cited.ids.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.findings.references_none')}
</p>
)}
{item.element.kind === 'finding_category' && (
<CitationList
ids={cited.ids}
readOnly={readOnly}
remove={(id) =>
cited.patch(cited.ids.filter((other) => other !== id))
}
/>
)}
{!readOnly && (
<SelectField
id="finding-add-reference"
label={t('editor.findings.reference_add')}
value=""
options={cited.options}
onCommit={(id) => id !== '' && cited.patch([...cited.ids, id])}
error={edit.fieldError('references')}
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="text-sm font-medium">{t('editor.findings.references')}</p>
{count > 0 && item.element.kind === 'finding_node' && (
<SheetTrigger
item={item}
count={count}
sheetOpen={sheetOpen}
onShowReferences={onShowReferences}
/>
)}
</div>
)
}
/**
* « Références citées » of a category or a node, read: a finding node shows « X références »
* (the sheet), a family its list. Nothing here cites or removes: that is the edit form's
* (FindingEditCitations).
*/
export default function FindingCitations(props: CitationsProps) {
const { item } = props
const t = useT()
if (item.element.kind === 'zone') return null
const ids = item.element.value.reference_ids
return (
<div className="space-y-2">
<CitationsHeader {...props} count={ids.length} />
{ids.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.findings.references_none')}
</p>
)}
{item.element.kind === 'finding_category' && (
<CitationList ids={ids} readOnly />
)}
</div>
)
}
@@ -66,6 +66,8 @@ function ItemBody(props: ItemBodyProps) {
const t = useT()
const mode = useItemMode()
const sheetOpen = !!layer.view && 'key' in layer.view && layer.view.citations
const showReferences = (opener: HTMLElement) =>
layer.openCitations(props.item.key, opener)
return (
<div className="space-y-2">
{mode.editing ? (
@@ -75,6 +77,8 @@ function ItemBody(props: ItemBodyProps) {
guards={layer.guards}
onDone={mode.done}
onDiscardClose={() => layer.close(true)}
sheetOpen={sheetOpen}
onShowReferences={showReferences}
/>
) : (
<FindingView
@@ -83,9 +87,7 @@ function ItemBody(props: ItemBodyProps) {
sheetOpen={sheetOpen}
onEdit={mode.startEdit}
onDelete={() => props.onDelete(props.item)}
onShowReferences={(opener) =>
layer.openCitations(props.item.key, opener)
}
onShowReferences={showReferences}
/>
)}
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
@@ -0,0 +1,63 @@
import SelectField from '@/components/editor/fields/SelectField'
import {
CitationList,
CitationsHeader,
} from '@/components/editor/findings/FindingCitations'
import type { FindingItem } from '@/editor/findings/tree'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useT } from '@/i18n/useT'
interface Props {
item: FindingItem
/** The draft's cited ids: what the form shows, counts and hands to the sheet. */
ids: readonly string[]
readOnly: boolean
sheetOpen: boolean
onChange: (ids: string[]) => void
onShowReferences: (opener: HTMLElement) => 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]
}
/**
* « Références citées » in the edit form of a category or a node: the draft's list, each
* « Retirer », and « Citer une référence ». Nothing is written before « Enregistrer ».
*/
export default function FindingEditCitations(props: Props) {
const { ids, readOnly, onChange } = props
const t = useT()
const options = useCitableOptions(ids)
return (
<div className="space-y-2">
<CitationsHeader {...props} count={ids.length} />
{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>
)
}
@@ -1,8 +1,10 @@
import { useState } from 'react'
import { useEffect, useState } from 'react'
import DraftField from '@/components/editor/fields/DraftField'
import { FormActions } from '@/components/editor/findings/DiscardConfirm'
import { useFormDraft } from '@/components/editor/findings/useDirtyGuard'
import FindingEditCitations from '@/components/editor/findings/FindingEditCitations'
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
import { useCitationDraft } from '@/editor/findings/citationDraft'
import { patchElement, type FindingItem } from '@/editor/findings/tree'
import { isBlank, optionalText } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
@@ -16,6 +18,7 @@ interface Draft {
descriptionFr: string
descriptionEn: string
vet: boolean
referenceIds: string[]
}
function draftOf(item: FindingItem): Draft {
@@ -27,6 +30,8 @@ function draftOf(item: FindingItem): Draft {
descriptionFr: described.fr ?? '',
descriptionEn: described.en ?? '',
vet: element.kind === 'finding_node' && element.value.requires_vet_referral,
referenceIds:
element.kind === 'zone' ? [] : [...element.value.reference_ids],
}
}
@@ -44,7 +49,7 @@ function normalized(draft: Draft): Draft {
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. */
/** The one `update` the form makes: names, and for a family or a node texts and citations. */
function patchOf(item: FindingItem, draft: Draft) {
const now = normalized(draft)
const { element } = item
@@ -60,6 +65,7 @@ function patchOf(item: FindingItem, draft: Draft) {
return patchElement(item, {
name,
description,
reference_ids: now.referenceIds,
...(element.kind === 'finding_node' ? vet : {}),
})
}
@@ -72,6 +78,10 @@ export interface FindingEditFormProps {
onDone: (saved: boolean) => void
/** « Abandonner » after a close request: the draft goes, so does the dialog. */
onDiscardClose: () => void
/** The citations sheet is open over the dialog (the trigger reads « expanded »). */
sheetOpen: boolean
/** Opens the citations sheet, which then lists the draft's citations. */
onShowReferences: (opener: HTMLElement) => void
}
function VetCheckbox({
@@ -167,10 +177,20 @@ function useEditSave(props: FindingEditFormProps, form: EditDraft) {
type EditDraft = ReturnType<typeof useFormDraft<Draft>>
/** The sheet opened from the form lists the draft's citations: they are published there. */
function usePublishedCitations(item: FindingItem, ids: readonly string[]) {
const publish = useCitationDraft((s) => s.publish)
useEffect(() => {
publish({ key: item.key, ids })
return () => publish(null)
}, [publish, item.key, ids])
}
/** The form's state: draft, blank names, save and cancel. */
function useEditForm(props: FindingEditFormProps) {
const form = useFormDraft(draftOf(props.item), props.guards, sameDraft)
const saving = useEditSave(props, form)
usePublishedCitations(props.item, form.draft.referenceIds)
const cancel = () =>
form.dirty && !props.readOnly
? form.guard.askToLeave()
@@ -180,7 +200,7 @@ function useEditForm(props: FindingEditFormProps) {
/**
* 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
* « Enregistrer », citations included (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.
*/
@@ -217,6 +237,16 @@ export default function FindingEditForm(props: FindingEditFormProps) {
onChange={(vet) => form.set({ vet })}
/>
)}
{props.item.kind !== 'zone' && (
<FindingEditCitations
item={props.item}
ids={form.draft.referenceIds}
readOnly={props.readOnly}
sheetOpen={props.sheetOpen}
onChange={(referenceIds) => form.set({ referenceIds })}
onShowReferences={props.onShowReferences}
/>
)}
{form.error && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{form.error}
@@ -77,8 +77,6 @@ export default function FindingView(props: FindingViewProps) {
<Texts item={item} />
<FindingCitations
item={item}
readOnly={readOnly}
edit={edit}
sheetOpen={sheetOpen}
onShowReferences={props.onShowReferences}
/>
@@ -1,6 +1,5 @@
import 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 { targetOfKey, type EditorTarget } from '@/editor/navigation'
import { usePlural } from '@/editor/plural'
@@ -103,40 +102,20 @@ function Summary({
)
}
/** A cited id the sheet no longer holds (P30): named, and removable like any citation. */
function MissingRow({
entry,
readOnly,
onRemove,
}: {
entry: CitationEntry
readOnly: boolean
onRemove: () => void
}) {
/** A cited id the sheet no longer holds (P30): named; only the edit form removes it. */
function MissingRow({ entry }: { entry: CitationEntry }) {
const t = useT()
const missing = t('editor.references.missing')
return (
<li className="flex items-center gap-2 rounded-lg border border-[var(--color-border)] p-3 text-sm">
<span className="min-w-0 flex-1">
{missing}
<span className="ml-2 text-[var(--color-ink-muted)]">{entry.id}</span>
</span>
<ActionButton
readOnly={readOnly}
variant="secondary"
size="sm"
aria-label={`${t('editor.action.remove')} ${missing} ${entry.id}`}
onClick={onRemove}
>
{t('editor.action.remove')}
</ActionButton>
<li className="rounded-lg border border-[var(--color-border)] p-3 text-sm">
{t('editor.references.missing')}
<span className="ml-2 text-[var(--color-ink-muted)]">{entry.id}</span>
</li>
)
}
type Panel = ReturnType<typeof useCitationsPanel>
/** One cited reference as a tile (« Modifier », « Retirer de ce constat »). */
/** One cited reference as a tile (« Modifier »). */
function EntryTile({
entry,
reference,
@@ -148,13 +127,13 @@ function EntryTile({
panel: Panel
props: Props
}) {
const { tiles, keys, citers, entries, remove } = panel
const { tiles, keys, citers, entries } = panel
const { readOnly, citedBy, navigate } = props
const key = keys[entry.index]
return (
<ReferenceTile
host="panel"
panel={{ current: citedBy, onRemove: () => remove(entry.index) }}
panel={{ current: citedBy }}
reference={reference}
position={entry.index}
count={entries.length}
@@ -189,12 +168,7 @@ function Entries({ panel, props }: { panel: Panel; props: Props }) {
props={props}
/>
) : (
<MissingRow
key={`${entry.index}-${entry.id}`}
entry={entry}
readOnly={props.readOnly}
onRemove={() => panel.remove(entry.index)}
/>
<MissingRow key={`${entry.index}-${entry.id}`} entry={entry} />
),
)}
</ul>
@@ -203,7 +177,7 @@ function Entries({ panel, props }: { panel: Panel; props: Props }) {
/**
* 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
* the whole library. No search, add, remove or order (P7): citing is the edit form's. The content of the side sheet
* (CitationsSheet), which is the modal; opens from a finding's trigger only.
*/
export default function CitationsPanel(props: Props) {
@@ -227,11 +201,6 @@ export default function CitationsPanel(props: Props) {
{t('editor.references.panel_empty')}
</p>
)}
{panel.error && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{panel.error}
</p>
)}
<Entries panel={panel} props={props} />
</div>
</section>
@@ -20,15 +20,14 @@ export interface TileHandlers {
goTo: (key: ElementKey) => void
}
/** What a tile of the citations panel adds: the finding it belongs to and « Retirer ». */
/** What a tile of the citations panel adds: the finding it belongs to. */
export interface PanelTile {
current: ElementKey
onRemove: () => void
}
export interface TileProps {
host: ReferenceHost
/** Set for the citations panel: « ce constat » marks, « Retirer de ce constat ». */
/** Set for the citations panel: « ce constat » marks. */
panel?: PanelTile
reference: Reference
/** Position in the whole bibliography, not in a filtered list. */
@@ -99,34 +98,18 @@ function TileHeader({ base, props }: { base: string; props: TileProps }) {
)
}
/** The panel's actions (P7): « Modifier » and « Retirer de ce constat », nothing else. */
function PanelActions({
props,
panel,
}: {
props: TileProps
panel: PanelTile
}) {
/** The panel's one action (P7): « Modifier ». Removing a citation is the edit form's. */
function PanelActions({ props }: { props: TileProps }) {
const t = useT()
return (
<div className="flex flex-wrap items-center gap-2">
<ActionButton
readOnly={false}
variant="secondary"
size="sm"
onClick={(event) => props.on.edit(event.currentTarget)}
>
{t('editor.references.edit')}
</ActionButton>
<ActionButton
readOnly={false}
variant="secondary"
size="sm"
onClick={panel.onRemove}
>
{t('editor.references.remove_citation')}
</ActionButton>
</div>
<ActionButton
readOnly={false}
variant="secondary"
size="sm"
onClick={(event) => props.on.edit(event.currentTarget)}
>
{t('editor.references.edit')}
</ActionButton>
)
}
@@ -135,7 +118,7 @@ function TileActions({ props }: { props: TileProps }) {
const t = useT()
const { position, count, citers, readOnly, movable, on } = props
if (readOnly) return null
if (props.panel) return <PanelActions props={props} panel={props.panel} />
if (props.panel) return <PanelActions props={props} />
return (
<>
<div className="flex flex-wrap items-center gap-2">
@@ -1,11 +1,11 @@
import { useEffect, useMemo, useRef, useState, type FocusEvent } from 'react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import { patchElement, type FindingItem } from '@/editor/findings/tree'
import { draftIdsFor, useCitationDraft } from '@/editor/findings/citationDraft'
import type { FindingItem } from '@/editor/findings/tree'
import { citersOf } from '@/editor/references/citations'
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 { tileKeys, useTileState } from './useTileState'
export interface PanelHooks {
@@ -31,11 +31,11 @@ interface Held {
}
/**
* P20: when the row that holds the focus leaves the list (« Retirer de ce constat », an
* undo that removes the reference), the focus goes to the next row's button, else the
* P20: when the row that holds the focus leaves the list (an undo that removes the
* reference), the focus goes to the next row's button, else the
* previous row's, else the heading. A row swapped for another at the same index (a
* tile turned into « Référence introuvable ») counts as gone, so « next » is the one
* after it. `lost` registers a row that is about to go without having held the focus.
* after it.
*/
function useFocusRescue() {
const list = useRef<HTMLUListElement>(null)
@@ -65,29 +65,27 @@ function useFocusRescue() {
list,
heading,
track,
lost: (at: number) => {
const row = rowsOf()[at]
if (row) hold(row, at)
},
}
}
/**
* What the panel shows of the finding: its cited ids and its path. Once the finding is
* 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.
* while it slides out and a tile in edit can still be asked to apply its draft. Opened
* from the edit form, it lists the form's staged citations, not the document's.
*/
function useShownFinding(
doc: ReturnType<typeof useSheetDocument>,
item: FindingItem | null,
citedBy: ElementKey,
) {
const staged = useCitationDraft((s) => draftIdsFor(s.draft, citedBy))
const found = useMemo(
() =>
doc && item
? { ids: citedIds(item), path: findingPath(doc, citedBy) }
? { ids: staged ?? citedIds(item), path: findingPath(doc, citedBy) }
: null,
[doc, item, citedBy],
[doc, item, citedBy, staged],
)
const [last, setLast] = useState(found)
if (found !== null && found !== last) setLast(found)
@@ -99,25 +97,14 @@ function useCitedEntries(hooks: PanelHooks) {
const { doc, item } = useCitedFinding(hooks.citedBy)
const { ids, path } = useShownFinding(doc, item, hooks.citedBy)
const entries = citationEntries(doc?.references ?? [], ids)
return { doc, item, ids, path, entries, keys: tileKeys(entries) }
return { doc, path, entries, keys: tileKeys(entries) }
}
/** What the citations panel reads and does: the cited entries, tiles, « Retirer ». */
/** What the citations panel reads: the cited entries and their tiles. */
export function useCitationsPanel(hooks: PanelHooks) {
const { doc, item, ids, path, entries, keys } = useCitedEntries(hooks)
const edit = useEditCommand()
const { doc, path, entries, keys } = useCitedEntries(hooks)
const tiles = useTileState(doc ? keys : null)
const focus = useFocusRescue()
// « 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.
const remove = (at: number) => {
if (!item) return
const rest = ids.filter((_, index) => index !== at)
const element = patchElement(item, { reference_ids: rest })
const command = { op: 'update', key: item.key, element } as const
if (edit.run('references', command)) focus.lost(at)
}
return {
doc,
entries,
@@ -125,8 +112,6 @@ export function useCitationsPanel(hooks: PanelHooks) {
keys,
citers: doc ? citersOf(doc) : new Map<string, never[]>(),
path,
error: edit.fieldError('references'),
remove,
list: focus.list,
heading: focus.heading,
trackFocus: focus.track,
@@ -0,0 +1,27 @@
import { create } from 'zustand'
import type { ElementKey } from '@faunosteo/core-wasm/types'
/** The citations an open edit form holds, for the side sheet opened from that form. */
interface CitationDraft {
key: ElementKey
ids: readonly string[]
}
interface CitationDraftStore {
draft: CitationDraft | null
publish: (draft: CitationDraft | null) => void
}
export const useCitationDraft = create<CitationDraftStore>((set) => ({
draft: null,
publish: (draft) => set({ draft }),
}))
/** The ids the sheet of `key` lists instead of the document's, null when none are staged. */
export function draftIdsFor(
draft: CitationDraft | null,
key: ElementKey,
): readonly string[] | null {
if (!draft || JSON.stringify(draft.key) !== JSON.stringify(key)) return null
return draft.ids
}
-1
View File
@@ -1234,7 +1234,6 @@ export const en: Dict = {
'editor.references.panel_count_other': '{count} references cited by this finding',
'editor.references.panel_show_all': 'Show all in the References tab',
'editor.references.panel_empty': 'This finding no longer cites any reference.',
'editor.references.remove_citation': 'Remove from this finding',
'editor.references.this_finding': 'this finding',
'editor.references.missing': 'Reference not found',
'editor.references.cited_one': 'Cited {count} time',
-1
View File
@@ -1265,7 +1265,6 @@ export const fr: Dict = {
'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',
'editor.references.panel_empty': 'Ce constat ne cite plus aucune référence.',
'editor.references.remove_citation': 'Retirer de ce constat',
'editor.references.this_finding': 'ce constat',
'editor.references.missing': 'Référence introuvable',
'editor.references.cited_one': 'Citée {count} fois',