Files
govoplan-forms/webui/src/features/forms/FormDefinitionDialog.tsx
T

703 lines
32 KiB
TypeScript

import { ArrowDown, ArrowUp, Eye, Languages, Plus, Trash2 } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import {
Button,
ConfirmDialog,
Dialog,
DocumentationHelpLink,
DismissibleAlert,
FormField as Field,
IconButton,
ToggleSwitch,
i18nMessage,
usePlatformLanguage,
useUnsavedChanges,
useUnsavedDraftGuard,
type ApiSettings
} from "@govoplan/core-webui";
import {
saveFormDefinition,
type FormDefinition,
type FormCondition,
type FormFieldDefinition,
type FormLocalization,
type FormPageDefinition,
type FormValueType
} from "../../api/forms";
import { FORMS_FIELD_DOCUMENTATION, FORMS_I18N } from "./interfacePatterns";
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 { translateText } = usePlatformLanguage();
const [baseline, setBaseline] = useState<FormDefinition>(() => initialDraft(tenantId, definition));
const [draft, setDraft] = useState<FormDefinition>(baseline);
const [changeReason, setChangeReason] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [confirmLifecycle, setConfirmLifecycle] = useState(false);
const { requestDiscard } = useUnsavedChanges();
useEffect(() => {
if (!open) return;
const next = initialDraft(tenantId, definition);
setDraft(next);
setBaseline(next);
setChangeReason("");
setBusy(false);
setError("");
setConfirmLifecycle(false);
}, [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]);
const dirty = useMemo(
() => Boolean(changeReason || JSON.stringify(draft) !== JSON.stringify(baseline)),
[baseline, changeReason, draft]
);
async function save(): Promise<boolean> {
if (!valid) return false;
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);
return true;
} catch (reason) {
setError(reason instanceof Error ? reason.message : "The Form definition could not be saved.");
return false;
} finally {
setBusy(false);
}
}
useUnsavedDraftGuard({
dirty: open && dirty,
onSave: save,
onDiscard: () => {
setDraft(baseline);
setChangeReason("");
},
title: "i18n:govoplan-forms.unsaved_title",
message: "i18n:govoplan-forms.unsaved_message"
});
function requestClose() {
if (busy) return;
if (dirty) requestDiscard(onClose);
else onClose();
}
function requestSave() {
const previousState = definition?.publication_state ?? "draft";
if (draft.publication_state !== "draft" && draft.publication_state !== previousState) {
setConfirmLifecycle(true);
return;
}
void save();
}
function patchField(index: number, patch: Partial<FormFieldDefinition>) {
setDraft((current) => ({
...current,
fields: current.fields.map((field, fieldIndex) => fieldIndex === index ? { ...field, ...patch } : field),
pages: patch.key && patch.key !== current.fields[index].key
? remapPageField(current.pages ?? [], current.fields[index].key, patch.key)
: current.pages
}));
}
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={requestClose}
closeDisabled={busy}
portal
className="form-definition-dialog"
footer={
<>
<Button onClick={requestClose} disabled={busy} disabledReason={busy ? FORMS_I18N.busy : undefined}>Cancel</Button>
<Button variant="primary" onClick={requestSave} disabled={busy || !valid} disabledReason={busy ? FORMS_I18N.busy : !valid ? FORMS_I18N.incomplete : undefined}>
{busy ? "Saving" : "Save revision"}
</Button>
</>
}>
<div className="form-definition-editor">
<div className="form-definition-help"><DocumentationHelpLink reference={FORMS_FIELD_DOCUMENTATION} /></div>
{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" help={!canPublish ? FORMS_I18N.adminReason : undefined} documentation={FORMS_FIELD_DOCUMENTATION}>
<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" documentation={FORMS_FIELD_DOCUMENTATION}>
<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" documentation={FORMS_FIELD_DOCUMENTATION}>
<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>
<Field label="Accessibility instructions" className="form-definition-wide" documentation={FORMS_FIELD_DOCUMENTATION}>
<textarea
rows={2}
value={String(draft.accessibility?.instructions ?? "")}
disabled={busy}
onChange={(event) => setDraft({
...draft,
accessibility: patchOptionalText(draft.accessibility ?? {}, "instructions", event.target.value)
})}
placeholder="Optional instructions announced before the Form"
/>
</Field>
</div>
<div className="form-field-editor-heading">
<h3>Fields</h3>
<Button onClick={() => setDraft(addField(draft))} 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>
}
<ConditionFields
condition={field.visibility_condition ?? null}
fields={draft.fields}
currentKey={field.key}
disabled={busy}
onChange={(visibility_condition) => patchField(index, { visibility_condition })}
/>
<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}
disabledReason={busy ? FORMS_I18N.busy : draft.fields.length === 1 ? FORMS_I18N.oneField : undefined}
onClick={() => setDraft(removeField(draft, index))}
/>
</div>
)}
</div>
<PageEditor draft={draft} disabled={busy} onChange={setDraft} />
<LocalizationEditor draft={draft} disabled={busy} onChange={setDraft} />
<DefinitionPreview definition={draft} previous={definition} />
<Field label="Change reason" documentation={FORMS_FIELD_DOCUMENTATION}>
<input value={changeReason} disabled={busy} maxLength={1000} onChange={(event) => setChangeReason(event.target.value)} placeholder="Why is this revision needed?" />
</Field>
</div>
<ConfirmDialog
open={confirmLifecycle}
title="i18n:govoplan-forms.lifecycle_title"
message={i18nMessage("i18n:govoplan-forms.lifecycle_message", { state: translateText(humanize(draft.publication_state)) })}
confirmLabel="Save revision"
tone={draft.publication_state === "retired" ? "danger" : "default"}
busy={busy}
onCancel={() => setConfirmLifecycle(false)}
onConfirm={() => {
setConfirmLifecycle(false);
void save();
}}
/>
</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 ConditionFields({
condition,
fields,
currentKey,
disabled,
onChange
}: {
condition: FormCondition | null;
fields: FormFieldDefinition[];
currentKey: string;
disabled: boolean;
onChange: (value: FormCondition | null) => void;
}) {
const predicate = condition?.kind === "predicate" ? condition : null;
const candidates = fields.filter((item) => item.key !== currentKey && item.key.trim());
return (
<div className="form-field-condition">
<Field label="Visible when">
<select
value={predicate?.field_key ?? ""}
disabled={disabled || candidates.length === 0}
onChange={(event) => onChange(event.target.value
? { kind: "predicate", field_key: event.target.value, operator: "eq", value: true }
: null)}>
<option value="">Always visible</option>
{candidates.map((item) => <option key={item.key} value={item.key}>{item.label || item.key}</option>)}
</select>
</Field>
{predicate && <>
<Field label="Condition">
<select
value={predicate.operator}
disabled={disabled}
onChange={(event) => onChange({
...predicate,
operator: event.target.value as Extract<FormCondition, { kind: "predicate" }>["operator"],
...(event.target.value === "is_empty" || event.target.value === "is_not_empty" ? { value: undefined } : {})
})}>
<option value="eq">Equals</option>
<option value="neq">Does not equal</option>
<option value="is_empty">Is empty</option>
<option value="is_not_empty">Is not empty</option>
<option value="contains">Contains</option>
</select>
</Field>
{!(["is_empty", "is_not_empty"] as string[]).includes(predicate.operator) &&
<Field label="Value">
<input
value={conditionInputValue(predicate.value)}
disabled={disabled}
onChange={(event) => onChange({ ...predicate, value: parseConditionValue(event.target.value, fields.find((item) => item.key === predicate.field_key)?.value_type) })}
/>
</Field>
}
</>}
</div>
);
}
function PageEditor({ draft, disabled, onChange }: { draft: FormDefinition; disabled: boolean; onChange: (value: FormDefinition) => void }) {
const pages = draft.pages ?? [];
function updatePages(next: FormPageDefinition[]) {
onChange({ ...draft, pages: next });
}
return (
<section className="form-composition-section">
<div className="form-field-editor-heading">
<h3>Pages and sections</h3>
{pages.length === 0
? <Button disabled={disabled} onClick={() => updatePages([defaultPage(draft.fields)])}><Plus size={16} aria-hidden="true" />Enable pages</Button>
: <Button disabled={disabled} onClick={() => updatePages([...pages, emptyPage(pages.length + 1)])}><Plus size={16} aria-hidden="true" />Add page</Button>}
</div>
{pages.length === 0 && <p className="form-section-note">Fields render in their declared order on one page.</p>}
{pages.map((page, pageIndex) =>
<div className="form-page-editor" key={`${pageIndex}:${page.key}`}>
<div className="form-page-editor-heading">
<Field label="Page key"><input value={page.key} disabled={disabled} onChange={(event) => updatePages(replaceAt(pages, pageIndex, { ...page, key: event.target.value }))} /></Field>
<Field label="Page title"><input value={page.title} disabled={disabled} onChange={(event) => updatePages(replaceAt(pages, pageIndex, { ...page, title: event.target.value }))} /></Field>
<IconButton label={`Remove page ${page.title || page.key}`} icon={<Trash2 size={16} />} variant="danger" disabled={disabled} onClick={() => updatePages(pages.filter((_, index) => index !== pageIndex))} />
</div>
{page.sections.map((section, sectionIndex) =>
<div className="form-section-editor" key={`${sectionIndex}:${section.key}`}>
<Field label="Section key"><input value={section.key} disabled={disabled} onChange={(event) => updatePages(replaceAt(pages, pageIndex, { ...page, sections: replaceAt(page.sections, sectionIndex, { ...section, key: event.target.value }) }))} /></Field>
<Field label="Section title"><input value={section.title} disabled={disabled} onChange={(event) => updatePages(replaceAt(pages, pageIndex, { ...page, sections: replaceAt(page.sections, sectionIndex, { ...section, title: event.target.value }) }))} /></Field>
<Field label="Fields">
<select
multiple
value={section.field_keys}
disabled={disabled}
onChange={(event) => updatePages(replaceAt(pages, pageIndex, {
...page,
sections: replaceAt(page.sections, sectionIndex, {
...section,
field_keys: Array.from(event.currentTarget.selectedOptions, (option) => option.value)
})
}))}>
{draft.fields.map((field) => <option key={field.key} value={field.key}>{field.label || field.key}</option>)}
</select>
</Field>
<IconButton label={`Remove section ${section.title || section.key}`} icon={<Trash2 size={16} />} variant="danger" disabled={disabled || page.sections.length === 1} onClick={() => updatePages(replaceAt(pages, pageIndex, { ...page, sections: page.sections.filter((_, index) => index !== sectionIndex) }))} />
</div>
)}
<Button disabled={disabled} onClick={() => updatePages(replaceAt(pages, pageIndex, { ...page, sections: [...page.sections, emptySection(page.sections.length + 1)] }))}><Plus size={15} aria-hidden="true" />Add section</Button>
</div>
)}
</section>
);
}
function LocalizationEditor({ draft, disabled, onChange }: { draft: FormDefinition; disabled: boolean; onChange: (value: FormDefinition) => void }) {
const localizations = draft.localizations ?? [];
function update(items: FormLocalization[]) {
const fallback = items.some((item) => item.locale === draft.fallback_locale)
? draft.fallback_locale
: items[0]?.locale ?? null;
onChange({ ...draft, localizations: items, fallback_locale: fallback });
}
return (
<section className="form-composition-section">
<div className="form-field-editor-heading">
<h3><Languages size={17} aria-hidden="true" />Localizations</h3>
<Button disabled={disabled} onClick={() => update([...localizations, emptyLocalization()])}><Plus size={16} aria-hidden="true" />Add locale</Button>
</div>
{localizations.length === 0 && <p className="form-section-note">The canonical labels are used for every locale.</p>}
{localizations.map((localization, index) =>
<div className="form-localization-editor" key={`${index}:${localization.locale}`}>
<Field label="Locale"><input value={localization.locale} disabled={disabled} placeholder="de" onChange={(event) => update(replaceAt(localizations, index, { ...localization, locale: event.target.value }))} /></Field>
<Field label="Localized title"><input value={localization.title ?? ""} disabled={disabled} onChange={(event) => update(replaceAt(localizations, index, { ...localization, title: event.target.value }))} /></Field>
<label className="form-localization-fallback"><input type="radio" checked={draft.fallback_locale === localization.locale} disabled={disabled || !localization.locale} onChange={() => onChange({ ...draft, fallback_locale: localization.locale })} />Fallback</label>
<IconButton label={`Remove locale ${localization.locale || index + 1}`} icon={<Trash2 size={16} />} variant="danger" disabled={disabled} onClick={() => update(localizations.filter((_, itemIndex) => itemIndex !== index))} />
<div className="form-localization-fields">
{draft.fields.map((field) =>
<Field key={field.key} label={`${field.label || field.key} label`}>
<input
value={localization.field_labels[field.key] ?? ""}
disabled={disabled}
onChange={(event) => update(replaceAt(localizations, index, {
...localization,
field_labels: patchOptionalText(localization.field_labels, field.key, event.target.value)
}))}
/>
</Field>
)}
</div>
</div>
)}
</section>
);
}
function DefinitionPreview({ definition, previous }: { definition: FormDefinition; previous: FormDefinition | null }) {
const changed = previous ? definitionChanges(previous, definition) : ["New definition"];
return (
<section className="form-composition-section form-definition-preview">
<div className="form-field-editor-heading"><h3><Eye size={17} aria-hidden="true" />Preview and revision changes</h3></div>
<div className="form-preview-grid">
<div>
<strong>{definition.title || "Untitled Form"}</strong>
{(definition.pages?.length ? definition.pages : [defaultPage(definition.fields)]).map((page) =>
<div key={page.key} className="form-preview-page">
<span>{page.title}</span>
{page.sections.map((section) => <small key={section.key}>{section.title}: {section.field_keys.join(", ") || "No fields"}</small>)}
</div>
)}
</div>
<div><strong>Changes</strong><ul>{changed.map((item) => <li key={item}>{item}</li>)}</ul></div>
</div>
</section>
);
}
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: [],
pages: [],
fallback_locale: null,
localizations: [],
accessibility: {},
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 addField(definition: FormDefinition): FormDefinition {
const field = emptyField(definition.fields.length + 1);
const pages = definition.pages ?? [];
if (pages.length === 0) return { ...definition, fields: [...definition.fields, field] };
const firstPage = pages[0];
const firstSection = firstPage.sections[0];
return {
...definition,
fields: [...definition.fields, field],
pages: replaceAt(pages, 0, {
...firstPage,
sections: replaceAt(firstPage.sections, 0, {
...firstSection,
field_keys: [...firstSection.field_keys, field.key]
})
})
};
}
function removeField(definition: FormDefinition, index: number): FormDefinition {
const key = definition.fields[index].key;
return {
...definition,
fields: definition.fields.filter((_, fieldIndex) => fieldIndex !== index),
pages: (definition.pages ?? []).map((page) => ({
...page,
sections: page.sections.map((section) => ({
...section,
field_keys: section.field_keys.filter((fieldKey) => fieldKey !== key)
}))
}))
};
}
function remapPageField(pages: FormPageDefinition[], previous: string, next: string): FormPageDefinition[] {
return pages.map((page) => ({
...page,
sections: page.sections.map((section) => ({
...section,
field_keys: section.field_keys.map((key) => key === previous ? next : key)
}))
}));
}
function defaultPage(fields: FormFieldDefinition[]): FormPageDefinition {
return {
key: "page-1",
title: "Form",
sections: [{ key: "section-1", title: "Details", field_keys: fields.map((item) => item.key) }]
};
}
function emptyPage(index: number): FormPageDefinition {
return { key: `page-${index}`, title: `Page ${index}`, sections: [emptySection(1)] };
}
function emptySection(index: number) {
return { key: `section-${index}`, title: `Section ${index}`, field_keys: [] as string[] };
}
function emptyLocalization(): FormLocalization {
return {
locale: "",
title: "",
description: "",
field_labels: {},
field_help_texts: {},
option_labels: {},
page_titles: {},
section_titles: {}
};
}
function replaceAt<T>(items: T[], index: number, value: T): T[] {
return items.map((item, itemIndex) => itemIndex === index ? value : item);
}
function patchOptionalText<T extends Record<string, unknown>>(current: T, key: string, value: string): T {
const next = { ...current };
if (value.trim()) next[key as keyof T] = value as T[keyof T];
else delete next[key as keyof T];
return next;
}
function conditionInputValue(value: unknown): string {
if (typeof value === "string") return value;
if (value === undefined || value === null) return "";
return JSON.stringify(value);
}
function parseConditionValue(value: string, type?: FormValueType): unknown {
if (type === "boolean") return value.trim().toLowerCase() === "true";
if (type === "integer") return Number.parseInt(value, 10);
if (type === "number") return Number(value);
return value;
}
function definitionChanges(previous: FormDefinition, current: FormDefinition): string[] {
const changes: string[] = [];
if (previous.title !== current.title) changes.push("Title changed");
if (previous.publication_state !== current.publication_state) changes.push(`State: ${previous.publication_state} -> ${current.publication_state}`);
if (previous.fields.length !== current.fields.length) changes.push(`Fields: ${previous.fields.length} -> ${current.fields.length}`);
if ((previous.pages?.length ?? 0) !== (current.pages?.length ?? 0)) changes.push(`Pages: ${previous.pages?.length ?? 0} -> ${current.pages?.length ?? 0}`);
if ((previous.localizations?.length ?? 0) !== (current.localizations?.length ?? 0)) changes.push(`Locales: ${previous.localizations?.length ?? 0} -> ${current.localizations?.length ?? 0}`);
if (changes.length === 0 && JSON.stringify(previous) !== JSON.stringify(current)) changes.push("Definition details changed");
return changes.length ? changes : ["No unsaved changes"];
}
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());
}