Files
faunosteo/apps/app/src/components/editor/findings/FindingEditForm.tsx
T
bchanot abc781df52 feat(editor): references dialog over the finding, view mode
A modal Dialog replaces the citations side sheet; families open it too
(isCitable). The finding dialog shows only « Références citées » and
« X références », also at zero; its edit form no longer carries
reference_ids. A dirty form refusing « Aller à » or « Tout afficher »
closes the clean references dialog first.
2026-11-15 16:13:57 +01:00

251 lines
7.8 KiB
TypeScript

import { 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 CitationsHeader from '@/components/editor/findings/FindingCitations'
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
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 its texts. The
* citations are the element's current ones (`patchElement` keeps them): the references
* dialog changes them, never this save.
*/
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
/** The references dialog is open over the finding dialog (the trigger reads « expanded »). */
citationsOpen: boolean
/** Opens the references dialog, which lists the element's citations. */
onShowReferences: (opener: HTMLElement) => 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>
)
}
type Locale2 = 'fr' | 'en'
const LOCALES: readonly Locale2[] = ['fr', 'en']
interface FieldsProps {
draft: Draft
set: (change: Partial<Draft>) => void
readOnly: boolean
described: boolean
blank: readonly string[]
}
/** The names, then the descriptions of a family or a node, as draft fields. */
const textKey = (l: Locale2) => (l === 'fr' ? 'descriptionFr' : 'descriptionEn')
function EditFields(props: FieldsProps) {
const { draft, set } = props
const t = useT()
return (
<div className="grid gap-3 md:grid-cols-2">
{LOCALES.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={props.readOnly}
error={
props.blank.includes(l) ? t('editor.field.required') : undefined
}
/>
))}
{props.described &&
LOCALES.map((l) => (
<DraftField
key={`d-${l}`}
id={`finding-edit-description-${l}`}
label={t(`editor.findings.description_${l}`)}
value={draft[textKey(l)]}
onChange={(value) => set({ [textKey(l)]: value })}
readOnly={props.readOnly}
multiline
/>
))}
</div>
)
}
/** The one save: blank names refused on their field, nothing written when unchanged. */
function useEditSave(props: FindingEditFormProps, form: EditDraft) {
const edit = useEditCommand()
const [blank, setBlank] = useState<readonly string[]>([])
const save = () => {
const missing = LOCALES.filter((l) => isBlank(form.draft[l]))
setBlank(missing)
if (missing.length > 0) {
document.getElementById(`finding-edit-name-${missing[0]}`)?.focus()
} else if (!form.dirty) {
props.onDone(false)
} else {
const element = patchOf(props.item, form.draft)
const command = { op: 'update', key: props.item.key, element } as const
if (edit.run('save', command)) props.onDone(true)
}
}
return { blank, save, error: edit.fieldError('save') }
}
type EditDraft = ReturnType<typeof useFormDraft<Draft>>
/** 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)
const cancel = () =>
form.dirty && !props.readOnly
? form.guard.askToLeave()
: props.onDone(false)
return { ...form, ...saving, cancel }
}
/**
* The element edited in the finding dialog (R2F-3): a local draft of its properties, one
* `update` on « Enregistrer » (none when nothing changed), nothing on « Annuler » or a
* close. Its citations are shown as « X références » only (Rev 5). 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 t = useT()
const form = useEditForm(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 />}
<EditFields
draft={form.draft}
set={form.set}
readOnly={props.readOnly}
described={props.item.kind !== 'zone'}
blank={form.blank}
/>
{props.item.element.kind === 'finding_node' && (
<VetCheckbox
checked={form.draft.vet}
readOnly={props.readOnly}
onChange={(vet) => form.set({ vet })}
/>
)}
<CitationsHeader
item={props.item}
citationsOpen={props.citationsOpen}
onShowReferences={props.onShowReferences}
/>
{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>
)
}