feat: implement immutable form definitions

This commit is contained in:
2026-08-01 17:48:34 +02:00
parent 5825c2c8e4
commit 343a208894
25 changed files with 2072 additions and 20 deletions
@@ -0,0 +1,330 @@
import { ArrowDown, ArrowUp, Plus, Trash2 } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import {
Button,
Dialog,
DismissibleAlert,
FormField as Field,
IconButton,
ToggleSwitch,
type ApiSettings
} from "@govoplan/core-webui";
import {
saveFormDefinition,
type FormDefinition,
type FormFieldDefinition,
type FormValueType
} from "../../api/forms";
const VALUE_TYPES: Array<{ value: FormValueType; label: string }> = [
{ value: "text", label: "Text" },
{ value: "multiline_text", label: "Long text" },
{ value: "email", label: "Email" },
{ value: "integer", label: "Integer" },
{ value: "number", label: "Number" },
{ value: "boolean", label: "Yes / no" },
{ value: "date", label: "Date" },
{ value: "datetime", label: "Date and time" },
{ value: "choice", label: "Single choice" },
{ value: "multi_choice", label: "Multiple choice" },
{ value: "object", label: "Structured object" },
{ value: "list", label: "Structured list" }
];
export default function FormDefinitionDialog({
open,
settings,
tenantId,
definition,
canPublish,
onClose,
onSaved
}: {
open: boolean;
settings: ApiSettings;
tenantId: string;
definition: FormDefinition | null;
canPublish: boolean;
onClose: () => void;
onSaved: (definition: FormDefinition) => void;
}) {
const [draft, setDraft] = useState<FormDefinition>(() => initialDraft(tenantId, definition));
const [changeReason, setChangeReason] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
useEffect(() => {
if (!open) return;
setDraft(initialDraft(tenantId, definition));
setChangeReason("");
setBusy(false);
setError("");
}, [definition, open, tenantId]);
const valid = useMemo(() => Boolean(
draft.title.trim()
&& draft.key.trim()
&& draft.fields.length > 0
&& draft.fields.every((field) => field.key.trim() && field.label.trim())
&& changeReason.trim()
), [changeReason, draft]);
async function save() {
if (!valid) return;
setBusy(true);
setError("");
const revision = crypto.randomUUID();
const recordedAt = new Date().toISOString();
const payload: FormDefinition = {
...draft,
reference: {
...draft.reference,
version: revision
},
temporal: {
...draft.temporal,
revision,
recorded_at: recordedAt,
superseded_at: null,
change_reason: changeReason.trim()
},
title: draft.title.trim(),
key: draft.key.trim(),
description: draft.description?.trim() || null,
fields: draft.fields.map(normalizeField),
policy_refs: draft.policy_refs.map((item) => item.trim()).filter(Boolean),
metadata: { ...draft.metadata }
};
try {
const saved = await saveFormDefinition(
settings,
payload,
definition?.reference.version
);
onSaved(saved);
} catch (reason) {
setError(reason instanceof Error ? reason.message : "The Form definition could not be saved.");
} finally {
setBusy(false);
}
}
function patchField(index: number, patch: Partial<FormFieldDefinition>) {
setDraft((current) => ({
...current,
fields: current.fields.map((field, fieldIndex) => fieldIndex === index ? { ...field, ...patch } : field)
}));
}
function moveField(index: number, delta: -1 | 1) {
setDraft((current) => {
const target = index + delta;
if (target < 0 || target >= current.fields.length) return current;
const fields = [...current.fields];
[fields[index], fields[target]] = [fields[target], fields[index]];
return { ...current, fields };
});
}
return (
<Dialog
open={open}
title={definition ? `Revise ${definition.title}` : "New Form definition"}
onClose={onClose}
closeDisabled={busy}
portal
className="form-definition-dialog"
footer={
<>
<Button onClick={onClose} disabled={busy}>Cancel</Button>
<Button variant="primary" onClick={() => void save()} disabled={busy || !valid}>
{busy ? "Saving" : "Save revision"}
</Button>
</>
}>
<div className="form-definition-editor">
{error && <DismissibleAlert tone="danger" resetKey={error}>{error}</DismissibleAlert>}
<div className="form-definition-grid">
<Field label="Title">
<input value={draft.title} disabled={busy} onChange={(event) => setDraft({ ...draft, title: event.target.value })} />
</Field>
<Field label="Key">
<input value={draft.key} disabled={busy || Boolean(definition)} onChange={(event) => setDraft({ ...draft, key: event.target.value })} />
</Field>
<Field label="Description" className="form-definition-wide">
<textarea rows={3} value={draft.description ?? ""} disabled={busy} onChange={(event) => setDraft({ ...draft, description: event.target.value })} />
</Field>
<Field label="Publication state">
<select value={draft.publication_state} disabled={busy} onChange={(event) => setDraft({ ...draft, publication_state: event.target.value as FormDefinition["publication_state"] })}>
{definition?.publication_state !== "published" && <option value="draft">Draft</option>}
{canPublish && <option value="published">Published</option>}
{canPublish && <option value="retired">Retired</option>}
</select>
</Field>
<Field label="Signature">
<select value={draft.signature_requirement} disabled={busy} onChange={(event) => setDraft({ ...draft, signature_requirement: event.target.value as FormDefinition["signature_requirement"] })}>
<option value="none">Not used</option>
<option value="optional">Optional</option>
<option value="required">Required</option>
</select>
</Field>
<Field label="Maximum attachments">
<input type="number" min={0} max={1000} value={draft.max_attachments} disabled={busy} onChange={(event) => setDraft({ ...draft, max_attachments: Number(event.target.value) })} />
</Field>
<div className="form-definition-toggle">
<ToggleSwitch label="Draft saving" checked={draft.allow_drafts} disabled={busy} onChange={(allow_drafts) => setDraft({ ...draft, allow_drafts })} />
</div>
<Field label="Policy references" className="form-definition-wide">
<input value={draft.policy_refs.join(", ")} disabled={busy} placeholder="policy:permit-intake" onChange={(event) => setDraft({ ...draft, policy_refs: splitValues(event.target.value) })} />
</Field>
<div className="form-definition-handoffs form-definition-wide">
<span>Permitted handoffs</span>
{(["case", "workflow", "record"] as const).map((kind) =>
<ToggleSwitch
key={kind}
label={humanize(kind)}
checked={draft.handoff_kinds.includes(kind)}
disabled={busy}
onChange={(checked) => setDraft({
...draft,
handoff_kinds: checked
? [...draft.handoff_kinds, kind]
: draft.handoff_kinds.filter((item) => item !== kind)
})}
/>
)}
</div>
</div>
<div className="form-field-editor-heading">
<h3>Fields</h3>
<Button onClick={() => setDraft({ ...draft, fields: [...draft.fields, emptyField(draft.fields.length + 1)] })} disabled={busy}>
<Plus size={16} aria-hidden="true" />Add field
</Button>
</div>
<div className="form-field-editor-list">
{draft.fields.map((field, index) =>
<div className="form-field-editor-row" key={`${index}:${field.key}`}>
<div className="form-field-order">
<IconButton label={`Move ${field.label || "field"} up`} icon={<ArrowUp size={15} />} disabled={busy || index === 0} onClick={() => moveField(index, -1)} />
<IconButton label={`Move ${field.label || "field"} down`} icon={<ArrowDown size={15} />} disabled={busy || index === draft.fields.length - 1} onClick={() => moveField(index, 1)} />
</div>
<Field label="Key"><input value={field.key} disabled={busy} onChange={(event) => patchField(index, { key: event.target.value })} /></Field>
<Field label="Label"><input value={field.label} disabled={busy} onChange={(event) => patchField(index, { label: event.target.value })} /></Field>
<Field label="Type">
<select value={field.value_type} disabled={busy} onChange={(event) => patchField(index, { value_type: event.target.value as FormValueType, options: isChoice(event.target.value) ? field.options : [] })}>
{VALUE_TYPES.map((type) => <option key={type.value} value={type.value}>{type.label}</option>)}
</select>
</Field>
<div className="form-field-required"><ToggleSwitch label="Required" checked={field.required} disabled={busy} onChange={(required) => patchField(index, { required })} /></div>
<Field label="Help text" className="form-field-help"><input value={field.help_text ?? ""} disabled={busy} onChange={(event) => patchField(index, { help_text: event.target.value })} /></Field>
{isChoice(field.value_type) &&
<Field label="Options" className="form-field-options"><input value={field.options.join(", ")} disabled={busy} onChange={(event) => patchField(index, { options: splitValues(event.target.value) })} /></Field>
}
<ConstraintFields field={field} disabled={busy} onChange={(constraints) => patchField(index, { constraints })} />
<IconButton
label={`Remove ${field.label || "field"}`}
icon={<Trash2 size={16} />}
variant="danger"
disabled={busy || draft.fields.length === 1}
onClick={() => setDraft({ ...draft, fields: draft.fields.filter((_, fieldIndex) => fieldIndex !== index) })}
/>
</div>
)}
</div>
<Field label="Change reason">
<input value={changeReason} disabled={busy} maxLength={1000} onChange={(event) => setChangeReason(event.target.value)} placeholder="Why is this revision needed?" />
</Field>
</div>
</Dialog>
);
}
function ConstraintFields({ field, disabled, onChange }: { field: FormFieldDefinition; disabled: boolean; onChange: (value: Record<string, unknown>) => void }) {
if (["text", "multiline_text", "email"].includes(field.value_type)) {
return (
<div className="form-field-constraints">
<Field label="Minimum length"><input type="number" min={0} value={constraintValue(field.constraints.min_length)} disabled={disabled} onChange={(event) => onChange(patchConstraint(field.constraints, "min_length", event.target.value))} /></Field>
<Field label="Maximum length"><input type="number" min={0} value={constraintValue(field.constraints.max_length)} disabled={disabled} onChange={(event) => onChange(patchConstraint(field.constraints, "max_length", event.target.value))} /></Field>
<Field label="Pattern"><input value={String(field.constraints.pattern ?? "")} disabled={disabled} onChange={(event) => onChange(patchTextConstraint(field.constraints, "pattern", event.target.value))} /></Field>
</div>
);
}
if (["integer", "number"].includes(field.value_type)) {
return (
<div className="form-field-constraints">
<Field label="Minimum"><input type="number" value={constraintValue(field.constraints.minimum)} disabled={disabled} onChange={(event) => onChange(patchConstraint(field.constraints, "minimum", event.target.value))} /></Field>
<Field label="Maximum"><input type="number" value={constraintValue(field.constraints.maximum)} disabled={disabled} onChange={(event) => onChange(patchConstraint(field.constraints, "maximum", event.target.value))} /></Field>
</div>
);
}
return null;
}
function initialDraft(tenantId: string, definition: FormDefinition | null): FormDefinition {
if (definition) return structuredClone(definition);
const id = crypto.randomUUID();
const revision = crypto.randomUUID();
const now = new Date().toISOString();
return {
reference: { kind: "form", owner_module: "forms", object_id: id, tenant_id: tenantId, version: revision },
key: "",
temporal: { revision, recorded_at: now, change_reason: "" },
title: "",
description: "",
fields: [emptyField(1)],
publication_state: "draft",
allow_drafts: true,
max_attachments: 0,
signature_requirement: "none",
policy_refs: [],
handoff_kinds: [],
metadata: {}
};
}
function emptyField(index: number): FormFieldDefinition {
return { key: `field-${index}`, label: "", value_type: "text", required: false, help_text: "", options: [], constraints: {} };
}
function normalizeField(field: FormFieldDefinition): FormFieldDefinition {
return {
...field,
key: field.key.trim(),
label: field.label.trim(),
help_text: field.help_text?.trim() || null,
options: isChoice(field.value_type) ? field.options.map((item) => item.trim()).filter(Boolean) : [],
constraints: Object.fromEntries(Object.entries(field.constraints).filter(([, value]) => value !== "" && value !== null && value !== undefined))
};
}
function splitValues(value: string): string[] {
return value.split(",").map((item) => item.trim()).filter(Boolean);
}
function isChoice(value: string): boolean {
return value === "choice" || value === "multi_choice";
}
function patchConstraint(current: Record<string, unknown>, key: string, value: string): Record<string, unknown> {
const next = { ...current };
if (!value.trim()) delete next[key];
else next[key] = Number(value);
return next;
}
function patchTextConstraint(current: Record<string, unknown>, key: string, value: string): Record<string, unknown> {
const next = { ...current };
if (!value) delete next[key];
else next[key] = value;
return next;
}
function constraintValue(value: unknown): number | "" {
return typeof value === "number" ? value : "";
}
function humanize(value: string): string {
return value.replace(/[_:.-]+/g, " ").replace(/\b\w/g, (letter) => letter.toUpperCase());
}
+126
View File
@@ -0,0 +1,126 @@
import { Pencil, Plus, RefreshCw, Search } from "lucide-react";
import { useCallback, useEffect, useState, type FormEvent } from "react";
import {
Button,
DismissibleAlert,
IconButton,
LoadingIndicator,
PageScrollViewport,
StatusBadge,
hasScope,
type PlatformRouteContext
} from "@govoplan/core-webui";
import { listFormDefinitions, type FormDefinition } from "../../api/forms";
import FormDefinitionDialog from "./FormDefinitionDialog";
export default function FormsPage({ settings, auth }: PlatformRouteContext) {
const [query, setQuery] = useState("");
const [submittedQuery, setSubmittedQuery] = useState("");
const [state, setState] = useState("");
const [items, setItems] = useState<FormDefinition[]>([]);
const [total, setTotal] = useState(0);
const [editing, setEditing] = useState<FormDefinition | "new" | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const canWrite = hasScope(auth, "forms:definition:write");
const canAdmin = hasScope(auth, "forms:definition:admin");
const tenantId = auth.active_tenant?.id ?? auth.tenant.id;
const load = useCallback((signal?: AbortSignal) => {
setLoading(true);
setError("");
return listFormDefinitions(settings, {
query: submittedQuery,
states: state ? [state] : undefined,
limit: 200
}, signal).
then((result) => {
setItems(result.definitions);
setTotal(result.total);
}).
finally(() => setLoading(false));
}, [settings, state, submittedQuery]);
useEffect(() => {
const controller = new AbortController();
load(controller.signal).catch((reason) => {
if ((reason as Error).name !== "AbortError") {
setError(reason instanceof Error ? reason.message : "Form definitions could not be loaded.");
}
});
return () => controller.abort();
}, [load]);
function search(event: FormEvent) {
event.preventDefault();
setSubmittedQuery(query.trim());
}
return (
<main className="forms-page">
<div className="forms-shell">
<div className="forms-toolbar">
<form onSubmit={search} className="forms-search">
<Search size={17} aria-hidden="true" />
<input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Search definitions" aria-label="Search Form definitions" />
<Button type="submit">Search</Button>
</form>
<label>
<span>State</span>
<select value={state} onChange={(event) => setState(event.target.value)}>
<option value="">All</option>
<option value="draft">Draft</option>
<option value="published">Published</option>
<option value="retired">Retired</option>
</select>
</label>
<IconButton label="Refresh definitions" icon={<RefreshCw size={16} />} onClick={() => void load()} disabled={loading} />
{canWrite && <Button variant="primary" onClick={() => setEditing("new")}><Plus size={16} aria-hidden="true" />New definition</Button>}
<span className="forms-count">{total}</span>
</div>
<PageScrollViewport className="forms-list-viewport">
{error && <DismissibleAlert tone="danger" resetKey={error}>{error}</DismissibleAlert>}
{loading && <LoadingIndicator label="Loading Form definitions" />}
{!loading && !error && items.length === 0 && <div className="forms-empty">No matching definitions.</div>}
{!loading && items.length > 0 &&
<div className="forms-list" role="list">
{items.map((item) => {
const mayRevise = canWrite && (item.publication_state === "draft" || canAdmin) && item.publication_state !== "retired";
return (
<div className="forms-row" role="listitem" key={item.reference.object_id}>
<span><strong>{item.title}</strong><small>{item.key}</small></span>
<span>{item.fields.length} fields</span>
<span>Revision {item.reference.version}</span>
<StatusBadge status={item.publication_state === "published" ? "active" : "inactive"} label={humanize(item.publication_state)} />
{mayRevise
? <IconButton label={`Revise ${item.title}`} icon={<Pencil size={16} />} onClick={() => setEditing(item)} />
: <span className="forms-row-action-spacer" />}
</div>
);
})}
</div>
}
</PageScrollViewport>
</div>
{editing &&
<FormDefinitionDialog
open
settings={settings}
tenantId={tenantId}
definition={editing === "new" ? null : editing}
canPublish={canAdmin}
onClose={() => setEditing(null)}
onSaved={() => {
setEditing(null);
void load().catch((reason) => setError(reason instanceof Error ? reason.message : "Definitions could not be reloaded."));
}}
/>
}
</main>
);
}
function humanize(value: string): string {
return value.replace(/[_:.-]+/g, " ").replace(/\b\w/g, (letter) => letter.toUpperCase());
}