---
title: Write a form state store
description: "How to give a form a store you own: the contract, a minimal working store, and the rules a store keeps when RuiForm drives it."
order: 4
---

import { meta as FormMeta, injectedMeta, Injected } from '@/content/stories/form';
import Canvas from '@/components/component-docs/canvas';

export const config = {
	dependencies: {
		components: [Canvas],
	},
};

# Write a form state store

<p class="docs-lede">
	`RuiForm` keeps your controls, their native validity and the presentation. A store you write keeps the values, when
	validation runs and which errors show.
</p>

## When to write one

Use the form's own store (`FormStore`) when rules on `RuiField` are enough. Write a store when something else already owns form state, such as a schema-driven forms layer, and the form should only bridge controls to it. You hand the store to the form with `form.connect(store, handlers)`.

<Canvas of={Injected} meta={injectedMeta} />

## The contract

`FormStateStore` has ten members. `RuiForm` calls each for one reason:

| Member | Why the form calls it |
| --- | --- |
| `getValue(path)` | Seed a control when it registers, and compare controls with the store on every notification. |
| `setValue(path, value)` | A control changed. |
| `focus(path, { source })` | The user entered a field. Called once per visit, after the `blur` of the field they left. `source` is `'program'` when Radiant moved focus itself, as `rui-form.focusField(paths)` does for the first invalid field after a failed submit, and `'user'` otherwise. |
| `blur(path)` | The user left a field. Called once per visit, and only while `getFocusedPath()` still returns `path`. |
| `getFocusedPath()` | The path of the visit your store has open, or `undefined`. A reset, or a row removal in a store that has rows, can end the visit while the field still holds focus in the DOM; the field then reports no `blur`. |
| `getSnapshot()` | The values, `errors` and `warnings` to show. The same object until state changes. |
| `subscribe(listener)` | Notify the form when state changed. |
| `reset()` | A native reset, unless you pass a `resetHandler`. Clear values, errors, field state and every native fact. |
| `validate()` | Submit. Resolve `{ outcome }`: `'passed'` emits `rui-submit`, `'invalid'` while the store holds any error emits `rui-invalid` with the snapshot's errors, and `'overtaken'` (a newer write superseded the check) ends the submission without an event, so the user submits again. |
| `reportNative(facts)` | The validity of controls, keyed by path, whenever a control's value or presence changes. |

Paths are the dotted `name` of each field's control, so `profile.name` is `values.profile.name` and `rows.0.title` is `values.rows[0].title`.

Form controls dispatch the platform's `input` and `change` events, which is how the form learns a value changed and calls `setValue`; `rui-change` remains only for non-form components (tabs, tree, menus, table, calendar, cycle-toggle).

## A minimal store

This is the store the examples use. It keeps nested values by path, holds the native facts, shows an error only for a path the user changed or left (or after a validate), and shows warnings always.

```ts
import type { FieldError, FormStateStore, NativeValidity } from '@ecopages/radiant-ui/form';
type Tree = Record<string, unknown>;

function getPath(tree: unknown, path: string): unknown {
	return path.split('.').reduce<unknown>((node, key) => (node && typeof node === 'object' ? Reflect.get(node, key) : undefined), tree);
}

function setPath(tree: Tree, path: string, value: unknown): Tree {
	const [head = '', ...rest] = path.split('.');
	const child = tree[head];
	const next = rest.length === 0 ? value : setPath(child && typeof child === 'object' ? { ...child } : {}, rest.join('.'), value);
	return { ...tree, [head]: next };
}

export type DemoStoreOptions = {
	initial: Tree;
	/** A rule per path: the message to show while the value is wrong, or nothing. */
	rules?: Record<string, (value: unknown) => string | undefined>;
	/** Advice per path; it shows but never blocks. */
	warnings?: Record<string, (value: unknown) => string | undefined>;
};

/**
 * A minimal `FormStateStore` for the docs. It shows an error only for a path the user
 * has changed or left, or after a validate; native validity is evidence it folds in.
 */
export function createDemoStore({ initial, rules = {}, warnings = {} }: DemoStoreOptions): FormStateStore {
	let values: Tree = initial;
	let facts: Record<string, NativeValidity> = {};
	let focused: string | undefined;
	const checked = new Set<string>();
	const listeners = new Set<() => void>();
	const problems = (path: string): FieldError | undefined => {
		const message = rules[path]?.(getPath(values, path));
		if (message) return { type: 'rule', message };
		const fact = facts[path];
		return fact ? { type: fact.type, params: fact.params, message: fact.message } : undefined;
	};
	const build = () => {
		const errors: Record<string, FieldError> = {};
		for (const path of checked) {
			const error = problems(path);
			if (error) errors[path] = error;
		}
		const advice: Record<string, FieldError> = {};
		for (const [path, check] of Object.entries(warnings)) {
			const message = check(getPath(values, path));
			if (message) advice[path] = { type: 'warning', message };
		}
		return { values, errors, warnings: advice };
	};
	let snapshot = build();
	const publish = () => {
		snapshot = build();
		for (const listener of [...listeners]) listener();
	};
	const holds = (path: string) => {
		const parent = path.split('.').slice(0, -1).join('.');
		const branch = getPath(values, parent);
		return getPath(values, path) !== undefined || parent === '' || (typeof branch === 'object' && branch !== null);
	};
	const keep = (path: string, fact: NativeValidity | null) => {
		const { [path]: _old, ...rest } = facts;
		facts = fact ? { ...rest, [path]: fact } : rest;
	};
	return {
		getValue: (path) => getPath(values, path),
		setValue(path, value) {
			values = setPath(values, path, value);
			checked.add(path);
			publish();
		},
		focus(path) {
			focused = path;
		},
		getFocusedPath: () => focused,
		blur(path) {
			if (focused === path) focused = undefined;
			checked.add(path);
			publish();
		},
		getSnapshot: () => snapshot,
		subscribe(listener) {
			listeners.add(listener);
			return () => listeners.delete(listener);
		},
		reset() {
			values = initial;
			facts = {};
			focused = undefined;
			checked.clear();
			publish();
		},
		async validate() {
			const scope = [...new Set([...Object.keys(rules), ...Object.keys(facts)])];
			for (const path of scope) checked.add(path);
			publish();
			return { outcome: scope.every((path) => !problems(path)) ? 'passed' : 'invalid' };
		},
		reportNative(reported) {
			let shown = false;
			for (const [path, fact] of Object.entries(reported)) {
				if (fact !== null && !holds(path)) continue;
				keep(path, fact);
				shown ||= checked.has(path);
			}
			if (shown) publish();
		},
	};
}
```

## The rules a store keeps

- **Nested values by path.** `setValue('profile.name', 'Ada')` replaces that branch and creates its parents. Return a new snapshot object only when something changed.
- **Facts are pushed.** `reportNative(facts)` maps a path to a `NativeValidity` (`{ type, params?, message? }`, `type` being the failing `ValidityState` flag), or to `null` for a valid control or one that left the form. The form calls it whenever a control's value or presence changes, from either side: right after `setValue` for a user change (before `blur`), and after a store write, a reset, a rename, a connect or a disconnect. Keep a fact until its path is reported again, and count a native problem like any other error.
- **`reportNative` never counts as a change.** Bind the fact to the value you hold, show it only if the path was already validated, and ignore a non-`null` fact for a path you do not hold: one with no value whose parent object is missing too, such as a row that was removed. A required field missing from your initial values is still held, because its parent exists. A `null` always clears.
- **`reset` clears the facts.** The form reports each control's fact again afterwards.
- **Native validity is evidence, not an error.** You decide when it shows, with the same timing as your own rules. See [Native validity](/docs/forms/form#native-validity).
- **`errors` are what you show.** An entry makes its field invalid even without a message. Keys with no control, such as a form-level `__root__`, are ignored by the form. Entries may carry more than `type` and `message`, and `formatError` receives the whole entry.
- **`warnings` never block.** They show beside the control through `RuiFieldWarning` and are not counted by `validate`.

## Handlers

`connect(store, { formatError, submitHandler, resetHandler })` types `formatError` by your store's own entry type, and returns a disposer that returns the form to its own store. A `submitHandler` takes over submit (the form writes the changed controls and reports their facts, then calls it with `{ submitNatively }`; you hold the store, so validate it and move focus with `form.focusField(paths)`), and a `resetHandler` takes over the native reset; it takes no argument. See [Inject a form state store](/docs/forms/form#inject-a-form-state-store).
