UNPKG

@mitcsutt/kiln-forms

Version:

Kiln forms: typed React forms on TanStack Form, in component or JSON schema mode, rendered through kiln-ui

148 lines (147 loc) • 7.37 kB
import type { AnyFormApi } from '@tanstack/react-form'; import type { AnyKitForm, FieldRegistry } from '../kit/types.js'; import type { NormalisedError } from './errors.js'; import type { ErrorVisibility } from './visibility.js'; import { type FormMessages } from './messages.js'; import type { ScopeHandle } from '../components/layouts/FieldScope/index.js'; import type { FormDragAndDrop } from '../components/layouts/Repeater/dragAndDrop.js'; export type { AnyKitForm }; export type ValidateOn = 'blur' | 'change' | 'submit'; export type FocusOnInvalid = 'auto' | 'first-field' | 'summary' | false; export type AfterSubmit = 'rebaseline' | 'reset' | 'keep' | 'lock'; export type InactiveReason = 'disabled' | 'readOnly' | 'excluded' | 'hidden'; export type InactiveSubmit = 'keep' | 'prune'; export type AutosaveStatus = 'idle' | 'saving' | 'saved' | 'error'; export interface FormRuntimeOptions { errorVisibility: ErrorVisibility; validateOn: ValidateOn; focusOnInvalid: FocusOnInvalid; afterSubmit: AfterSubmit; /** Display text for a normalised error (after `$key` resolution). */ formatError: (error: NormalisedError) => string; messages: FormMessages; } export interface FieldRegistration { id: string; focus(): void; getLabel(): string; scopes: readonly ScopeHandle[]; element(): HTMLElement | null; /** * The field's own check of its value (`useFieldBinding({ check })`), run with its `onDynamic` * validator by the kit's validation logic. Only set when the field has one. */ check?: (value: unknown) => string | undefined; } export interface InactiveEntry { reason: InactiveReason; submit: InactiveSubmit; } /** A derived-field rule as the runtime stores it (component-mode `derive`, schema `compute`). */ export interface RuntimeDeriveRule { field: string; from: readonly string[]; compute: (values: unknown) => unknown; } /** Per-form state that is not form values (§5.1). Not React state: read it with `useRuntimeValue`. */ export interface FormRuntime { options: FormRuntimeOptions; fields: Map<string, FieldRegistration>; inactive: Map<string, InactiveEntry>; summary: { mounted: boolean; focus(): void; } | null; formElement: HTMLFormElement | null; locked: boolean; /** Autosave status for `FormStatus` (set by `useAutosave`). */ autosave: AutosaveStatus; /** Field-level `defaultValue`s seen by bindings (prune uses them before form defaults). */ fieldDefaults: Map<string, unknown>; /** * The current baseline (new defaults after `rebaseline` / `useServerValues` / autosave), and the * user's `defaultValues` it replaced — dropped when the user passes different defaults. */ baseline: { values: unknown; source: unknown; } | null; /** The `defaultValues` the app passed on the latest render. */ userDefaults: unknown; /** * TanStack's core `FormApi` (set on mount). The React form is a spread copy whose `options` * goes stale after `update()`, so anything reading options goes through `coreApi()`. */ core: AnyFormApi | null; /** Name of the field whose change is being validated right now (set by the kit's change listener). */ changing: string | null; /** * While true, a `change` validation runs `onDynamic` even before the field's first blur — set * only for the duration of `useAutosave`'s pre-save validation pass. */ forceDynamic: boolean; /** * The kit's field registry (set by `useAppForm`), so layouts can bind typed shorthand fields * (`bindFields(form, registry, prefix)`). `null` for a form not created by a kit. */ registry: FieldRegistry | null; /** * The kit's `dragAndDrop` (set by `useAppForm`), which a Repeater with `reorderable="drag"` * renders its handles with. `null` when the kit has none. */ dragAndDrop: FormDragAndDrop | null; /** * Derive rules registered at runtime (schema `compute`, §10.6), by owner (a schema object), * ref-counted. Read by the same form `onChange` listener as the `derive` option (§6.9): they * run when a `from` path changes, never on mount, whether or not the derived field is rendered. */ derive: Map<object, { rules: readonly RuntimeDeriveRule[]; refs: number; }>; /** * Each mounted `Repeater`'s new-item value, by array path: pruning a field inside * a row uses the row's `newItem` value for it, as a top-level field uses the form defaults. */ itemTemplates: Map<string, () => unknown>; /** Calls every listener; components re-render only if the slice they read changed. */ subscribe: (listener: () => void) => () => void; notify(): void; } export declare function defaultRuntimeOptions(): FormRuntimeOptions; export declare function createFormRuntime(): FormRuntime; /** The TanStack API of a form the package was given. */ export declare function toFormApi(form: AnyKitForm): AnyFormApi; /** The live core `FormApi` of a form (falls back to the object itself before mount). */ export declare function coreApi(form: AnyKitForm): AnyFormApi; /** The runtime of a form (created lazily with defaults for a raw TanStack form). */ export declare function getFormRuntime(form: AnyKitForm): FormRuntime; /** Associates a runtime created before the form (by `useAppForm`) with the form. */ export declare function attachFormRuntime(form: AnyKitForm, runtime: FormRuntime): void; /** The runtime of `form`, or of the form in context. */ export declare function useFormRuntime(form?: AnyKitForm): FormRuntime; /** `form` if given, else the form from `<Form>` / `<form.AppForm>` context. */ export declare function useResolvedForm(form?: AnyKitForm): AnyFormApi; /** * One slice of the runtime (the lock, the autosave status), re-rendering only when it changes. * `select` must return a primitive (or a value that is stable while the slice is unchanged). */ export declare function useRuntimeValue<T>(runtime: FormRuntime, select: (runtime: FormRuntime) => T): T; /** * Marks paths inactive (§5.4): their validators stop, their errors are cleared, and with * `submit: 'prune'` their submitted value becomes the default. Returns an undo function. */ export declare function markInactive(form: AnyKitForm, names: readonly string[], reason: InactiveReason, submit: InactiveSubmit): () => void; /** Clears every error slot of the given paths (and anything nested under them). */ export declare function clearErrors(form: AnyFormApi, names: readonly string[]): void; /** Whether `path` (or one of its ancestors) is inactive. */ export declare function isInactive(runtime: FormRuntime, path: string): boolean; /** Display text for a normalised error: `$key` messages resolved, then the form's `formatError`. */ export declare function formatErrorText(runtime: FormRuntime, error: NormalisedError): string; /** * Registers derive rules for `owner` (ref-counted: several renderers of one schema register once). * Returns the unregister function. */ export declare function registerDerive(form: AnyKitForm, owner: object, rules: readonly RuntimeDeriveRule[]): () => void; /** Every derive rule registered at runtime. */ export declare function runtimeDeriveRules(runtime: FormRuntime): RuntimeDeriveRule[];