/** * vapor-chamber - Form Bus * * Reactive form state management built on the command bus. * * createFormBus wraps a command bus around a typed form, giving you: * - Reactive values, errors, dirty, valid, and submitting state * - Per-field validation rules * - Full plugin pipeline on every form command (logger, authGuard, etc.) * * `history()` records form commands, but its undo restores no field: the * form registers no inverse (an undo without one only moves the stacks). * * @example * const form = createFormBus({ * fields: { email: '', password: '' }, * rules: { * email: (v) => v.includes('@') ? null : 'Invalid email', * password: (v) => v.length >= 8 ? null : 'Too short', * }, * onSubmit: async (values) => await api.login(values), * }); * * form.set('email', 'user@example.com'); * await form.submit(); // runs validation, then onSubmit * form.reset(); // restores initial field values */ import type { Signal } from './signal'; import type { CommandBus, PluginParts } from './command-bus'; export type FormRules> = { [K in keyof T]?: (value: T[K], values: T) => string | null | Promise; }; export type FormBusOptions> = { /** Initial field values - also used as the reset target. */ fields: T; /** Per-field validation rules. Return a string on error, null on pass. */ rules?: FormRules; /** Called after successful validation on submit(). May be async. */ onSubmit?: (values: T) => void | Promise; /** * Create reactive signals for all form state (values, errors, isDirty, etc.). * Default: true. Set to false for headless / server-side / batch use cases * where reactivity is not needed - avoids eight signal allocations per form. * When false, all Signal fields still work as plain get/set wrappers. */ reactive?: boolean; /** * Inject an external command bus instead of creating an isolated one. * When provided, form commands (formSet, formTouch, formReset, formValidate, * formErrors) flow through this bus - making them visible to DevTools, metrics, logger, * and global listeners. * * @example * const bus = getCommandBus(); * const form = createFormBus({ fields: { email: '' }, bus }); * // formSet, formTouch, etc. now visible in setupDevtools() */ bus?: CommandBus; /** * Action-name prefix, so two forms can share one bus. Default: `'form'` * (`formSet`, `formTouch`, ...). * * REQUIRED FOR THE SECOND FORM ON A SHARED BUS, and the reason is not * tidiness. The five action names derive from it, so two forms with one id * would register over each other: measured with a login and a signup form * on one bus, `login.set('email', 'a@b.c')` left `login.values` empty and * put the email in `signup.values`. So a second form whose id is already on * the bus throws (tests/store-form-sharing.test.ts). * * const login = createFormBus({ fields: {...}, bus, id: 'login' }); * const signup = createFormBus({ fields: {...}, bus, id: 'signup' }); * // loginSet / signupSet - distinct in devtools, and no cross-writing */ id?: string; }; /** * Errors from outside the form's rules, in the wire contract's one shape * (docs/contract.md 4): a problem's `errors`, each a * pointer into the envelope the client sent (`/payload/`, RFC 6901) * and its sentence. */ export type FormErrorsInput = ReadonlyArray<{ pointer: string; detail: string; }>; /** What an element needs to make a field's error accessible (WCAG 3.3.1, 4.1.2). */ export type FieldAria = { 'aria-invalid': 'true' | undefined; 'aria-describedby': string | undefined; }; export type FormBus> = { /** Reactive current field values. Read-only: `set()` writes them. */ readonly values: { readonly value: T; }; /** Reactive per-field error messages. Empty when all fields pass. */ readonly errors: { readonly value: Partial>; }; /** Reactive set of fields the user has interacted with. */ readonly touched: { readonly value: Partial>; }; /** True when any field differs from its initial value. */ readonly isDirty: { readonly value: boolean; }; /** True when no validation errors exist. */ readonly isValid: { readonly value: boolean; }; /** True while onSubmit is in flight. */ isSubmitting: Signal; /** True while async validation is running. */ isValidating: Signal; /** True when either validating or submitting - use for disabling submit buttons. */ isBusy: Signal; /** Set a single field value and re-run validation. */ set(field: K, value: T[K]): void; /** Mark a field as touched (shows errors for that field). */ touch(field: K): void; /** Validate and call onSubmit. Returns true on success; false on validation failure, a reset during validation, or a submit already in flight. */ submit(): Promise; /** Reset all fields to their initial values and clear errors/touched state. */ reset(): void; /** * Show errors from outside the rules (a server's answer), replacing earlier * ones. Each marks its field touched, so it shows at once, and clears when * that field changes; `submit()` clears them all, since the server decides * again. `submit()` calls this itself when `onSubmit` throws an error whose * problem carries `errors`. */ setErrors(errors: FormErrorsInput): void; /** * `aria-invalid` / `aria-describedby` for a field: invalid only while its * error is shown. `describedBy`, the input's own ids (a hint), stays named, * and the error's id follows it while shown, since `aria-describedby` is an * ID reference list (WAI-ARIA 1.2). Spread it in place of a static * `aria-describedby`: the spread's value overrides the attribute. * tests/form-aria-render.test.ts. */ aria(field: K, describedBy?: string): FieldAria; /** The id for the element holding a field's message: stable, unique per form, a valid id. */ errorId(field: K): string; /** The first field, in declaration order, whose error is shown - the one to focus after a failed submit. */ firstInvalid(): keyof T | undefined; /** Attach a plugin to the form's internal command bus. */ use(plugin: PluginParts): void; /** The underlying command bus - for advanced use (DevTools, testing). */ bus: CommandBus; /** * Unregister this form's handlers from the bus and release its prefix. * * Only meaningful with an INJECTED bus: an isolated one is garbage with the * form. It is how a short-lived form (a modal) leaves a shared bus. */ dispose(): void; }; /** * createFormBus - reactive form state manager built on the command bus. * * All form mutations go through the internal bus, so plugins (logger, * authGuard, etc.) intercept them like any other command. */ export declare function createFormBus>(options: FormBusOptions): FormBus; //# sourceMappingURL=form.d.ts.map