'use client'; import { cn } from 'cn'; import { CheckIcon, PlusIcon, TriangleAlertIcon, XIcon } from 'lucide-react'; import { AuthoredPlugin } from 'platejs/authored'; import { FIELD_TESTS, fitsField, type FieldKind, type FieldOption, type FieldPatch, type FieldProblem, type FieldSettings, type FieldTest, type FieldValue, } from 'platejs/field'; import { FieldPlugin, useFieldRead } from 'platejs/field/react'; import { type EditorElementProps, EditorElement, useEditor, useEditorReadOnly, useEditorSelector, usePluginStore, } from 'platejs/react'; import * as React from 'react'; import { Button } from '@/components/ui/button'; import { Checkbox } from '@/components/ui/checkbox'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { NativeSelect, NativeSelectOption, } from '@/components/ui/native-select'; import { Popover, PopoverContent, PopoverTrigger, } from '@/components/ui/popover'; import { inlineSuggestionVariants } from '@/registry/lib/inline-suggestion'; const KINDS: Record = { checkbox: 'Checkbox', choice: 'Choice', date: 'Date', number: 'Number', signature: 'Signature', text: 'Text', }; const TEST_LABELS: Record = { above: 'is above', below: 'is below', blank: 'is blank', equals: 'is', filled: 'is filled', 'not-equals': 'is not', }; const PROBLEMS: Record = { 'answer-conflict': 'The fields of its name hold different answers.', 'condition-loop': 'Its condition leads back to this field.', 'invalid-value': 'A value does not fit this kind of field.', 'missing-target': 'The field its condition names is gone.', 'name-conflict': 'The fields of its name differ in kind, options or condition.', 'unsupported-test': 'Its condition does not fit the field it names.', }; const isKind = (value: string): value is FieldKind => value in KINDS; const isTest = (value: string): value is FieldTest => value in TEST_LABELS; const needsValue = (test: FieldTest) => test !== 'filled' && test !== 'blank'; const firstValue = ({ kind, options }: FieldSettings) => ({ checkbox: true, choice: options?.[0]?.value, date: new Date().toISOString().slice(0, 10), number: 0, signature: undefined, text: '', })[kind]; const fillableTests = (target: FieldSettings) => FIELD_TESTS[target.kind].filter( (test) => !needsValue(test) || firstValue(target) !== undefined ); const conditionOn = ( ref: string, target: FieldSettings, test: FieldTest, value?: FieldValue ) => ({ ref, test, ...(needsValue(test) ? { value: value ?? firstValue(target) } : {}), }); type FieldNode = EditorElementProps['element']; const saveAnswer = ( editor: ReturnType, fieldId: string, value?: FieldValue ) => { editor.update((tx) => tx.plugin(FieldPlugin).update(fieldId, { value })); return Object.is( editor.plugin(FieldPlugin).read.field(fieldId)?.node.value, value ); }; const useWaitsForReview = (element: FieldNode, watches: boolean) => { const editor = useEditor(); const subscribe = React.useCallback( (wake: () => void) => (watches ? editor.subscribeCommit(wake) : () => {}), [editor, watches] ); const waits = () => watches && editor .plugin(AuthoredPlugin) .read.reviewOf(element) .marks.some((mark) => mark.kind === 'format' && mark.key === 'value'); return React.useSyncExternalStore(subscribe, waits, waits); }; export function FieldElement(props: EditorElementProps) { const { element } = props; const editor = useEditor(); const readOnly = useEditorReadOnly(); const fillRole = usePluginStore(FieldPlugin, 'fillRole') ?? null; const field = useFieldRead(element.fieldId); const problems = field?.problems ?? []; const skipped = field?.applies === false; const warning = problems.map((problem) => PROBLEMS[problem]).join(' '); const filling = fillRole !== null; const ownField = element.role === fillRole; const waitsForReview = useWaitsForReview( element, ownField && editor.plugin(AuthoredPlugin).installed ); const fills = ownField && !readOnly && !waitsForReview; const toggles = fills && element.kind === 'checkbox'; const ticked = element.value === true; const [refusedToggle, setRefusedToggle] = React.useState<{ role: string | null; stored?: FieldValue; } | null>(null); if ( refusedToggle && (refusedToggle.role !== fillRole || !Object.is(refusedToggle.stored, element.value)) ) { setRefusedToggle(null); } const answer = String( element.options?.find((option) => option.value === element.value)?.label ?? element.value ?? '' ); let form: React.ReactNode = null; if (!filling && !readOnly) form = ; if (fills && !toggles) form = ; const openAtPointerDownRef = React.useRef(false); const [openAs, setOpenAs] = React.useState<{ role: string | null } | null>( null ); const open = form !== null && openAs?.role === fillRole; if (openAs && !open) setOpenAs(null); const chip = { className: cn( 'inline-flex w-fit items-baseline gap-1 rounded-sm bg-muted px-1 text-muted-foreground', (form || toggles) && 'cursor-pointer', skipped && 'opacity-50', inlineSuggestionVariants({ on: 'parent' }) ), contentEditable: false, draggable: !filling, onClick: (event: React.MouseEvent) => { if (toggles) { setRefusedToggle( saveAnswer(editor, element.fieldId, !ticked) ? null : { role: fillRole, stored: element.value } ); return; } const beganOpen = event.detail === 0 ? open : openAtPointerDownRef.current; if (!form || beganOpen) return; event.preventDefault(); setOpenAs({ role: fillRole }); }, onPointerDown: () => { openAtPointerDownRef.current = open; }, }; const chipContent = ( <> {filling && element.kind === 'checkbox' && ( {ticked && } )} {filling && element.kind !== 'checkbox' ? answer || element.label : element.label} {element.required && *} {element.role} {skipped && skipped} {waitsForReview && ( waits for review )} {warning && ( )} ); return ( {form ? ( setOpenAs(nextOpen ? { role: fillRole } : null) } > {form} ) : ( )} {ownField && element.kind === 'checkbox' && ( {refusedToggle && ' Not saved.'} )} {props.children} ); } function FieldAnswerForm({ element }: { element: FieldNode }) { const editor = useEditor(); const { fieldId, kind, label, options, value } = element; const [refusal, setRefusal] = React.useState<{ stored?: FieldValue; } | null>(null); if (refusal && !Object.is(refusal.stored, value)) setRefusal(null); const setValue = (next?: FieldValue) => setRefusal(saveAnswer(editor, fieldId, next) ? null : { stored: value }); return (

{refusal && 'Not saved.'}

); } function FieldSettingsForm({ element }: { element: FieldNode }) { const editor = useEditor(); const { condition, fieldId, kind, options = [] } = element; const update = (patch: FieldPatch) => editor.update((tx) => tx.plugin(FieldPlugin).update(fieldId, patch)); const fields = useEditorSelector( (innerEditor) => innerEditor.plugin(FieldPlugin).read.fields(), { shouldUpdate: (commit) => !commit || commit.changed.hasAny('properties') || commit.changed.hasAny('structure'), } ); const targets = fields.filter((entry) => entry.fieldId !== fieldId); const target = fields.find((entry) => entry.fieldId === condition?.ref)?.node; const namers = new Map(); for (const { fieldId: namer, node } of fields) { if (!node.condition) continue; const named = namers.get(node.condition.ref) ?? []; named.push(namer); namers.set(node.condition.ref, named); } const leadsHere = new Set([fieldId]); for (const id of leadsHere) { for (const namer of namers.get(id) ?? []) leadsHere.add(namer); } const choices = fields.filter( (entry) => entry.fieldId === condition?.ref || !leadsHere.has(entry.fieldId) ); const tests = target ? fillableTests(target) : []; return (
update({ label: event.target.value })} /> { if (isKind(event.target.value)) update({ kind: event.target.value }); }} > {Object.entries(KINDS).map(([value, label]) => ( {label} ))} update({ role: event.target.value })} /> {[...new Set(targets.map((entry) => entry.node.role))].map((role) => ( ))} update({ required: checked === true || undefined }) } /> {kind === 'choice' && ( <>
{options.map((option, index) => (
update({ options: options.map((entry) => entry === option ? { ...entry, label: event.target.value } : entry ), }) } />
))}
)} {kind !== 'signature' && ( <> update({ defaultValue })} /> )} { const next = choices.find( (entry) => `#${entry.fieldId}` === event.target.value ); update({ condition: next && conditionOn(next.fieldId, next.node, fillableTests(next.node)[0]), }); }} > Always {condition && !target && ( Missing field )} {choices.map((entry) => ( {entry.node.label} ))} {condition && target && (
{ if (!isTest(event.target.value)) return; update({ condition: conditionOn( condition.ref, target, event.target.value, fitsField(target, condition.value) ? condition.value : undefined ), }); }} > {[...new Set([...tests, condition.test])].map((test) => ( {TEST_LABELS[test]} ))} {needsValue(condition.test) && tests.includes(condition.test) && ( update({ condition: conditionOn( condition.ref, target, condition.test, value ), }) } /> )}
)}
); } const NO_OPTION = ''; const optionToken = (option: FieldOption) => `option:${option.value}`; const entryOf = ( kind: FieldKind, input: HTMLInputElement, clearable: boolean ): { value?: FieldValue } | null => { // The browser reports a number or date typed in part as bad input. if (input.validity.badInput) return null; if (input.value === '') { if (clearable) return { value: undefined }; return kind === 'text' ? { value: '' } : null; } const value = kind === 'number' ? input.valueAsNumber : input.value; return fitsField({ kind }, value) ? { value } : null; }; function FieldValueInput({ clearable = true, kind, label, onChange, options, value, }: { clearable?: boolean; kind: FieldKind; label: string; onChange: (value: FieldValue | undefined) => void; options?: readonly FieldOption[]; value?: FieldValue; }) { const [draft, setDraft] = React.useState<{ kind: FieldKind; stored?: FieldValue; text: string; } | null>(null); const [resets, setResets] = React.useState(0); if (draft && (draft.kind !== kind || !Object.is(draft.stored, value))) { setDraft(null); } if (kind === 'checkbox') { return ( onChange(checked === true)} /> ); } if (kind === 'choice') { const picked = options?.find((option) => option.value === value); return ( { const option = options?.find( (entry) => optionToken(entry) === event.target.value ); if (option) onChange(option.value); else if (event.target.value === NO_OPTION && clearable) { onChange(undefined); } }} > {(clearable || !picked) && ( None )} {options?.map((option) => ( {option.label} ))} ); } return ( { // A partial number or date reads as an empty value, so React never // clears it from an input whose stored answer is empty, and WebKit // keeps a partial date through an empty value write. if (event.currentTarget.validity.badInput) { setResets((count) => count + 1); } setDraft(null); }} onInput={(event) => { const entry = entryOf(kind, event.currentTarget, clearable); if (entry) onChange(entry.value); setDraft({ kind, stored: entry ? entry.value : value, text: event.currentTarget.value, }); }} /> ); } export const FieldKit = [FieldPlugin.configure({ component: FieldElement })];