import { useState } from 'react' import type { EditCommand, FindingCategoryKind, FindingNode, } from '@faunosteo/core-wasm/types' import DraftField from '@/components/editor/fields/DraftField' 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 { buildItems, type FindingItem, type FindingKind, } from '@/editor/findings/tree' import type { IdPrefix } from '@/editor/ids' import { isBlank, useSheetDocument } from '@/editor/sheetDocument' import { useEditCommand, type EditCommandApi } from '@/editor/useEditCommand' import type { Guards } from '@/editor/useEditorNavigation' import { useT } from '@/i18n/useT' import { useLocaleStore } from '@/state/localeStore' export const CATEGORY_KINDS: readonly FindingCategoryKind[] = [ 'dysfunction', 'consultation_reason', 'anamnesis', 'custom', ] export interface PendingFinding { kind: FindingKind /** The category or node a node goes under; null for a zone and a category. */ parent: FindingItem | null } export interface FindingCreateFormProps { pending: PendingFinding readOnly: boolean guards: Guards /** `created` is the new element's id, `parent` the element it went under. */ onCreated: (id: string, parent: FindingItem | null) => void /** A close of the dialog; forced after « Abandonner ». */ onClose: (forced: boolean) => void } interface Draft { fr: string en: string kind: string } const EMPTY: Draft = { fr: '', en: '', kind: '' } const sameDraft = (a: Draft, b: Draft) => a.fr === b.fr && a.en === b.en && a.kind === b.kind /** What the core requires before an insert: both names, a zone and a kind for a category. */ function isComplete(draft: Draft, pending: PendingFinding, parent: unknown) { if (isBlank(draft.fr) || isBlank(draft.en)) return false return pending.kind !== 'category' || (parent !== null && draft.kind !== '') } /** The one `insert`, under a fresh id; the new id, or null when the core refused it. */ function insertNew( edit: EditCommandApi, pending: PendingFinding, parent: FindingItem | null, draft: Draft, ): string | null { let createdId = '' const name = { fr: draft.fr.trim(), en: draft.en.trim() } const added = edit.runNew('form', PREFIX[pending.kind], (id) => { createdId = id return insertCommand({ ...pending, parent }, id, name, draft.kind) }) return added ? createdId : null } /** The form's state and its one `insert` (« Créer »), refused on a missing field. */ function useCreateForm(props: FindingCreateFormProps) { const edit = useEditCommand() const zones = useZoneChoice() const form = useFormDraft(EMPTY, props.guards, sameDraft) const create = () => { const { pending } = props const parent = pending.kind === 'category' ? zones.chosen : pending.parent if (!isComplete(form.draft, pending, parent)) { edit.reject('form', 'editor.findings.required') return } const id = insertNew(edit, pending, parent, form.draft) if (id !== null) props.onCreated(id, parent) } return { ...form, zones, create, error: edit.fieldError('form') } } /** The kind choice of a category and its two names, as draft fields. */ function CreateFields(props: { form: ReturnType category: boolean readOnly: boolean }) { const { form, category, readOnly } = props const t = useT() const kinds = CATEGORY_KINDS.map((k) => ({ value: k, label: t(`editor.findings.kind.${k}`), })) return (
{category && } {category && ( form.set({ kind })} /> )} {(['fr', 'en'] as const).map((l) => ( form.set({ [l]: value })} readOnly={readOnly} /> ))}
) } /** * Collects what the core requires (names FR/EN, the kind of a category), then one * `insert`: no element exists with default labels. The fields are a local draft: nothing * is written before « Créer », a close or a move never creates (R2F-3). */ export default function FindingCreateForm(props: FindingCreateFormProps) { const t = useT() const form = useCreateForm(props) const category = props.pending.kind === 'category' return (
{ event.preventDefault() form.create() }} > {props.readOnly && } {category && form.zones.chosen && } {form.error && (

{form.error}

)} props.onClose(props.readOnly)} onKeepTyping={form.guard.keepTyping} onDiscard={() => props.onClose(true)} /> ) } interface ZoneChoice { zones: readonly FindingItem[] zoneId: string setZoneId: (id: string) => void chosen: FindingItem | null } /** The zones to choose from; with exactly one, it is preselected, otherwise nothing is. */ function useZoneChoice(): ZoneChoice { const doc = useSheetDocument() const zones = doc ? buildItems(doc).filter((i) => i.kind === 'zone') : [] const [zoneId, setZoneId] = useState( zones.length === 1 ? zones[0].zoneId : '', ) const chosen = zones.find((zone) => zone.zoneId === zoneId) ?? null return { zones, zoneId, setZoneId, chosen } } function ZoneSelect({ zones, readOnly, }: { zones: ZoneChoice readOnly: boolean }) { const t = useT() const locale = useLocaleStore((s) => s.locale) return ( ({ value: zone.zoneId, label: zone.name[locale], })), ]} onCommit={zones.setZoneId} /> ) } /** A category lands at zone level: the line under the dialog's title names the zone chosen. */ function ZoneTitle({ zone }: { zone: FindingItem }) { const t = useT() const locale = useLocaleStore((s) => s.locale) return (

{t('editor.findings.new.category_in_zone').replace( '{zone}', zone.name[locale], )}

) } const PREFIX: Record = { zone: 'zone', category: 'fcat', node: 'node', } function insertCommand( pending: PendingFinding, id: string, name: { fr: string; en: string }, kind: string, ): EditCommand { const parent = pending.parent?.key if (pending.kind === 'zone') { return { op: 'insert', element: { kind: 'zone', value: { id, name, categories: [] } }, } } if (pending.kind === 'category') { return { op: 'insert', parent: pending.parent?.key, element: { kind: 'finding_category', value: { id, kind: kind as FindingCategoryKind, name, description: {}, reference_ids: [], review_status: 'to_confirm', children: [], }, }, } } const node: FindingNode = { id, name, description: {}, requires_vet_referral: false, reference_ids: [], review_status: 'to_confirm', children: [], } return { op: 'insert', parent, element: { kind: 'finding_node', value: node }, } }