import { Field, FormApi, type AnyFormApi } from "@tanstack/vue-form"; import { defineComponent, h, shallowRef, type Component, type ShallowRef } from "vue"; import type { DraftValidator } from "./validation.ts"; /** * The edit form for one control-plane resource kind. * * The settings store owns these, not the pages: an edit survives in-app * navigation and the save bar reviews every section at once, so a form cannot * live and die with the page that renders it. Pages bind fields through * `Field`, the same slot component useForm returns. */ export interface SettingsForm { api: AnyFormApi; /** form.Field, bound to this form. */ Field: ReturnType; /** The current values, mirrored into Vue so diffs and pages react to edits. */ values: ShallowRef; /** Validates and saves. False when validation blocked it or the save failed. */ submit: () => Promise; /** Replaces the values; keepDefaultValues leaves the edit dirty against them. */ reset: (value: unknown, opts?: { keepDefaultValues?: boolean }) => void; dispose: () => void; } /** createSettingsForm builds the form for one kind. `validate` is the kind's * draft rule; its issues land on the fields they name, so a field's own error * and the save bar's list come from one function. `submit` performs the save * and reports whether it landed. */ export function createSettingsForm( initial: unknown, validate: DraftValidator | undefined, submit: (value: unknown) => Promise, ): SettingsForm { let saved = false; // TanStack turns a null document into {}. An unset resource is stored as // null, so while the form is still empty it reports, diffs and saves null; // otherwise opening an unset section would read as an edit, and saving it // would store {} where nothing was set, even for a list-shaped kind. let unset = initial === null; const current = (value: unknown) => (unset && isEmptyObject(value) ? null : value); const api = new FormApi({ defaultValues: initial ?? {}, validators: validate ? { onChange: ({ value }: { value: unknown }) => { const issues = validate(value); if (!issues.length) return undefined; return { fields: Object.fromEntries(issues.map((issue) => [issue.path, issue.message])) }; }, } : undefined, onSubmit: async ({ value }: { value: unknown }) => { saved = await submit(current(value)); }, }) as AnyFormApi; const unmount = api.mount(); const values = shallowRef(current(api.state.values)); const { unsubscribe } = api.store.subscribe(() => { const next = current(api.state.values); if (values.value !== next) values.value = next; }); const BoundField = defineComponent( // Field is typed generically over the form; bound here, it is any field of it. (_props, context) => () => h(Field as Component, { ...context.attrs, form: api }, context.slots), { name: "SettingsField", inheritAttrs: false }, ); return { api, Field: BoundField, values, reset: (value, opts) => { unset = value === null; api.reset(value ?? {}, opts); }, submit: async () => { saved = false; await api.handleSubmit(); return saved; }, dispose: () => { unsubscribe(); unmount(); }, }; } function isEmptyObject(value: unknown): boolean { return typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length === 0; } interface FieldMetaLike { state: { meta: { isValid: boolean; isTouched: boolean; isDirty: boolean } }; } /** fieldInvalid is the shadcn-vue isInvalid check: show an error once the * operator has touched or changed the field, not on a value they never edited. */ export function fieldInvalid(field: FieldMetaLike): boolean { const { isValid, isTouched, isDirty } = field.state.meta; return !isValid && (isTouched || isDirty); }