State container
Every rendered form has one form state container. It holds the nested values, the errors and warnings of each field, the touched, dirty and pending marks, the row ids of field arrays and what the browser reports about each control. React and Radiant both bind to it, so a form validates, resets and submits the same way in either. Nothing else keeps form state: there is no form library underneath.
A form runtime creates the container of the form it runs. Create one yourself to test a form without a DOM, to render on a server or to write a binding for another framework. What an app reads of it is in Form state.
The interface is FormStateContainer, the factory createFormStateContainer and the snapshot FormStateSnapshot, all from @schema-engine/forms/state-container. The examples use the placeholder engine of Write a renderer.
Create a container
A container is made from the normalized form config, the engine's validation registry and the defaults. The config carries the validation timing (validationMode, reValidateMode) and the payload, so no renderer can differ.
import { createFormStateContainer, selectFieldState } from '@schema-engine/forms/state-container';
import { engine } from './engine';
const config = engine.defineForm({
id: 'signup',
steps: [
{
id: 'account',
title: 'Account',
elements: [
{ $type: 'input', id: 'email', name: 'email', rules: [{ $type: 'required', id: 'email-required' }] },
{
$type: 'input',
id: 'password',
name: 'password',
rules: [{ $type: 'minLength', id: 'password-min', value: 8 }],
},
],
},
],
});
export const container = createFormStateContainer({
config,
registry: engine.getValidationRegistry(),
defaults: { email: '[email protected]', password: '' },
});
export async function fillIn() {
container.setValue('password', 'short');
const recordedBefore = container.getSnapshot().isValid;
const checked = await container.checkValidity();
const recordedAfterCheck = container.getSnapshot().isValid;
const validated = await container.validate();
const snapshot = container.getSnapshot();
return {
recordedBefore,
checked,
recordedAfterCheck,
validated,
isValid: snapshot.isValid,
error: snapshot.errors['password'],
field: selectFieldState(snapshot, 'password'),
};
}| Option | Meaning |
|---|---|
config | A form from engine.defineForm or engine.validateForm: its elements, validationMode, reValidateMode and payload. |
registry | The engine's validation registry, engine.getValidationRegistry(). |
defaults | The values the form starts from and reset() restores. They are copied, never shared with the live values. |
snapshot | The values and rowIds of a container that rendered the form on a server. See Server rendering. |
fillIn() makes the three reads of Validity differ: after setValue('password', 'short') the recorded state is still valid, checkValidity() is false and leaves it so, and validate() resolves { outcome: 'invalid' } and records the minLength error.
Read state
container.getSnapshot() returns an immutable snapshot. It is the same object until something changes, and a branch that did not change keeps its reference, so it is safe to compare by identity and to hand to useSyncExternalStore.
| Member | Holds |
|---|---|
values | The nested value tree. |
errors | The error of each path, flat by dotted path (contacts.0.email). The form itself is FORM_ROOT ('__root__'). |
warnings | Advice from rules declared severity: 'warning', shaped and timed like errors. A warning never blocks. |
touched | The paths the user has blurred. A mark on a container covers the fields below it. |
dirty | The paths whose value differs from the defaults. |
validating | The paths a check is still running for. |
rowIds | The ids of each array's rows, by array path. A field array renders by these ids. |
isValid | Whether no error is recorded for a path that takes part. See Validity. |
generation | How many times the form was reset. |
participation | The ids of the skipped steps and the state of each field a constraint or authoring hides, disables or requires. |
An error is never inherited: errors['contacts'] is the array's own error and errors['contacts.0.email'] the row's, and both can be present. An error is an issue with every issue of its path in all, ordered as what the server said, then each rule the value fails in authored order, then what the browser reported. Its type, ruleId and params say what is wrong; Issue text says how to word it.
Read one field with the selectors, which are pure functions of the snapshot and memoized per snapshot and path:
| Selector | Returns |
|---|---|
selectFieldState(snapshot, path) | error (exactly that path's, never one inherited), warning, invalid, isTouched, isDirty, isValidating, hidden, disabled and required |
selectValue(snapshot, path) | The value at the path |
toFieldArrayValue(rowIds, commands) | fields with stable ids and the array operations, as a widget takes them |
A field state is the same object in every snapshot while it is unchanged. A binding renders from these selectors: React's useFormField, useWatch, useFieldArray and useFormContext().formState read them through useSyncExternalStore, and Radiant's FormController.select(selector) makes a signal over one.
Write state
| Command | Does |
|---|---|
setValue(path, value) | Replaces the whole branch at the path. It is a change: it validates when the mode says so and drops what described the old value. |
blur(path) | Marks the path touched and validates it when the mode says so. |
reportNative(facts) | Reports what the browser says about each control. See Native validity. |
fieldArray(path) | The array's commands: append, prepend, insert, swap, move, update, replace and remove. Each is one update, and a row's state moves with it. |
reset(values?) | Restores the defaults, or replaces them with values first, and clears errors, marks and native facts. Every row gets a new id. |
Every command is one atomic update and notifies subscribers once. A path with a segment that starts with __, or is constructor or prototype, is rejected, and so is a write to a row the array does not have: make rows with fieldArray.
Submit
container.submit() clears the server's answer to the last submission, validates the whole form as validate() does and says how that ended:
| Outcome | Meaning |
|---|---|
'passed' | Nothing blocks. values are exactly the values that passed, frozen, without the paths that took no part, plus the config's payload. setServerErrors hands back the server's answer. |
'invalid' | An error blocks. Show the errors and focus the first control. |
'overtaken' | An edit, a row move, a reset or a later submission outran the check. There is no verdict: ask again and show nothing the user did not cause. |
A rendered form wraps this in its runtime, which adds the submission state, the actions and your onSubmit.
Server rendering
A server builds a container, renders its state and sends the part a client needs. The client passes it back as snapshot, with the same defaults, so the fields that differ from them are dirty and reset restores them:
import { createFormStateContainer, toHydration } from '@schema-engine/forms/state-container';
import { engine } from './engine';
const config = engine.defineForm({
id: 'profile',
steps: [{ id: 'main', title: 'Profile', elements: [{ $type: 'input', id: 'name', name: 'name' }] }],
});
const registry = engine.getValidationRegistry();
const defaults = { name: 'Ada' };
/** On the server: render the form from its container, and send the part a client needs next to the markup. */
export function renderOnServer() {
const server = createFormStateContainer({ config, registry, defaults });
return JSON.stringify(toHydration(server.getServerSnapshot()));
}
/** In the browser: start from what the server rendered, with the same defaults. */
export function hydrateOnClient(payload: string) {
return createFormStateContainer({ config, registry, defaults, snapshot: JSON.parse(payload) });
}toHydration returns the values and rowIds, which are plain and serializable. The client starts from those values and adopts those row ids, so a row the server rendered keeps its identity. A hydration whose ids do not match its own values throws an Error: it cannot come from a real snapshot, so there is nothing to catch. The row ids a container makes are deterministic, so a client built from the same defaults matches the server without a snapshot.
Write a binding
The contract is public, so a renderer for another framework, a native client or a test harness binds the same container. A binding:
- reads
getSnapshot()andsubscribe(), and renders from the selectors; - sends each control's value with
setValue(path, value), its blur withblur(path)and its browser verdict withreportNative(facts); - keeps focus, the native controls and the native submit, which are the host's;
- submits with
submit(), or through the runtime, and shows the server's answer throughsetServerErrors.
Test a container
formStateContainerConformance from @schema-engine/forms/testing is the suite that proves a container keeps the contract: validation timing, row identity, native facts, freshness, participation and server errors. Run it against any implementation of FormStateContainerFactory, and pass the describe and test of your test runner:
import { describe, test } from 'vitest';
import { formStateContainerConformance } from '@schema-engine/forms/testing';
import { createFormStateContainer } from '@schema-engine/forms/state-container';
formStateContainerConformance(createFormStateContainer, { describe, test });The suite depends on no test runner, so any runner with describe and test works, such as Jest, Bun or node:test.