# API

> The public exports of each package, by entry point.

Source: https://forms.lunarhue.dev/react/reference/api

Each entry point and what it exports. Signatures leave out type parameters.
Your editor shows the full types, and each export has a doc comment.

The adapter re-exports core, and its `plugins` entry re-exports core's
plugins, so you import everything from the adapter you installed.

## Adapter

`@lunarhue/forms-react`, for React 16.8 and later.

### createForms

Call it once at module scope. Every form defined from it shares these settings.

```ts
createForms(options?: {
  plugins?: Plugin[];        // every form gets these, in this order
  fields?: { TextField, … }; // field components or field types, bound on every form
  mapError?: MapError;       // turns issues and thrown errors into your error type
  validate?: ValidateTiming; // when validators first run, "blur" by default
  show?: Show;               // when errors show, "touched-or-submitted" by default
  equals?: Equals;           // the dirty comparison, needs dirty()
  focusOnInvalid?: FocusOnInvalid; // what an invalid submit focuses, true by default
  onPluginError?: PluginErrorHandler;
}): Forms
```

A plugin list can hold `false`, `null` or `undefined` in place of a plugin,
so `plugins: [mask(), dev && devtools()]` works and a bundler can drop the
plugin it never uses. The types count a plugin that may be missing as not
installed: with `dev && dirty()` in the list, `equals` is still a type error.

| | |
| --- | --- |
| `forms.define(config, ...parts)` | Defines a form. Returns the definition you pass to the form hook and to `useFormContext`. `parts` attach at the root when the store is made. |
| `forms.scope(handle)` | The scope at an object handle: `root`, `Field` and the field components. Cached per handle. |
| `forms.fieldset(schema, ...parts)` | A reusable shape for a group of fields, typed from a schema that never runs. `parts` attach at each field the fieldset is used on. |
| `forms.fieldset<V>(...parts)` | The same shape from a type. |
| `fieldset.at(name)` | The fieldset's parts pinned at `name`, for `define`. |

### defineField

```ts
defineField(component, ...parts): FieldType
```

A field type: `component` with `parts` that attach at each field it renders.
Register it in `fields`. Each part must fit the component's value, and the
form must have the plugins the parts need, or using it is a type error.
`PhoneField.at(name)` pins the parts at one field, for `define`.

### define

```ts
forms.define({
  defaultValues?,  // required unless a schema plugin accepts the schema
  schema?,         // needs the schema plugin for its library
  plugins?,        // this form's plugins, after the shared ones
  validate?: { on?, form?, fields? },
  show?,
  equals?,         // needs dirty()
  disabled?,       // fields that start disabled
  readOnly?,       // fields that start read-only
  onSubmit?: (value, ctx) => result,
})
```

`define` also takes a function of per-form options that returns the config.
The form hook then needs those options as its second argument.

### useForm

```ts
useForm(definition, instance?: { id?, focusOnInvalid?, plugins? }): FormInstance
useForm(definition, options, instance?) // when define took a function
```

Makes the form on the first render and returns the same object after. `id`
prefixes every DOM id and defaults to `useId()`. `plugins` are this form's
only, such as a [Zustand binding](https://forms.lunarhue.dev/react/integrations/zustand.md).

The form it returns:

| | |
| --- | --- |
| `form.Form` | Provides the form to the tree below. Its child is a function of the form element props. |
| `form.State` | Renders a selection of the form snapshot: `select`, `isEqual`, and children `(selected, form)`. |
| `form.root` | The handle for the whole value. |
| `form.Field` | Renders one field by `name` or `handle`. Children get the field object, or `select`'s result. |
| `form.TextField` | Each registered field component, bound by `name`. |
| `form.submit(intent?)` | Submits and resolves to the `Submission`. Focuses per `focusOnInvalid`. |
| `form.handleSubmit(event?)` | Calls `preventDefault`, then submits. |
| `form.formProps` | Props for the `<form>` element. |
| `form.store` | The core store. See [Store](#store). |
| `form.plugins` | Each plugin's API by name, as `form.plugins.history.undo()`. |
| `form.id` | The store id. |

### useFormContext

| | |
| --- | --- |
| `useFormContext()` | The form of the nearest `form.Form`, with unknown types. Enough for a submit button. |
| `useFormContext(definition)` | The nearest form made from `definition`, fully typed. Skips forms of other definitions. |
| `useFormContext(forms)` | The nearest form from that `createForms` call, typed with its plugins and fields. |

Each throws when no matching `form.Form` is above.

### Reading state

| | |
| --- | --- |
| `useField(handle, select?, isEqual?)` | The field snapshot, or a selection of it. Re-renders when it changes by `isEqual`. |
| `useFormState(form, select?, isEqual?)` | The form snapshot, or a selection of it. |
| `useItems(handle)` | An array's item handles. Re-renders only when an item is added, removed or moved. Needs `arrays()`. |
| `<Items handle>` | Renders one child per item, keyed by the item's key. Children `(item, index)`. Needs `arrays()`. |
| `useValidator(handle, validator)` | Adds a validator while the component is mounted. |
| `useDisabledErrors(form)` | The disabled fields whose errors blocked the last submit. |
| `useInvalidFields(form)` | Every field with errors, in form order, as `{ field, name, errors }`. Re-renders when the list changes. |

### Inputs

| | |
| --- | --- |
| `inputProps(field, options?)` | Props that bind one plain HTML element to a field object. |
| `useInputProps(handle, options?)` | The same props for a handle. |
| `useFieldRef(handle)` | A ref callback that records a custom input as the field's focus target. |
| `errorId(handle)` | The id of the element that shows the field's errors. |
| `elementsOf(handle)` | The field's elements in the document, in document order. |
| `fieldOf(element)` | The handle of the field whose ref got `element`. In production it returns `undefined` unless `trackElements()` ran before the form rendered. |
| `trackElements(listener?)` | Records each field element for `fieldOf` in production. `listener` gets every element a ref records or forgets, `<form>` elements included. |

The options pick the element by `kind`: `"text"` (the default), `"textarea"`,
`"number"`, `"range"`, `"checkbox"`, `"radio"` or `"select"`. The compiler
checks the kind against the field's value type. Input props set
`aria-invalid` and point `aria-describedby` at the error id while the field
shows errors.

### Field object

What a registered component gets as `field`, and what `Field` passes its
children.

| | |
| --- | --- |
| `value` | The field's value. |
| `name` | The dotted name, as `"address.city"`. |
| `errors` | Every error on the field. |
| `shownErrors` | The errors to show now, per `show`. |
| `userErrors` | The errors set with `setErrors`, the tail of `errors`. |
| `invalid` | True when it has any error, from validation or `setErrors`. |
| `touched` | True after a blur. |
| `edited` | True after a user edit. |
| `dirty` | True when the value differs from the baseline. Needs `dirty()`. |
| `validating` | True while an async validator runs. |
| `disabled` | True when it or a field above it is disabled. |
| `readOnly` | True when it or a field above it is read-only. |
| `meta` | Plugin state by plugin name, read with the plugin's reader. |
| `keys` | Array fields only: the item keys, in order. |
| `text` | The text an element shows: typed number text, else a plugin's display text, else the value. |
| `setText(text, from?)` | Writes typed text. With a mask, puts the formatted text in the element `from` names and places the caret. |
| `setNumberText(text, empty?)` | Writes typed number text. Text that isn't a number yet writes nothing. |
| `ref` | Records the element for focus after an invalid submit. |
| `handle` | The field's handle. |
| `id`, `path`, `errorId` | The handle's id, its stable path, and the error element id. |

It also has every command of its handle, bound. Its `handleBlur` also drops
typed number text.

### Handles

`form.root`, `handle.at(key)` and `handle.item(key)` return handles. Every
handle has:

| | |
| --- | --- |
| `id`, `path`, `store` | The DOM id, the stable path, the store. |
| `peek()` | The snapshot now, for event handlers. |
| `setTouched(touched?)` | Marks the field touched. |
| `handleBlur()` | Marks it touched and runs blur validation. |
| `setErrors(errors)` | Replaces its user errors. The next user edit clears them. |
| `validate()` | Runs its validators now. Resolves true when valid. |
| `registerValidator(validator)` | Adds a validator. Returns the function that removes it. |
| `reset(options?)` | Back to the baseline, or to the starting value with `{ to: "initial" }`. |
| `setDisabled(on)`, `setReadOnly(on)` | Sets the flag for it and every field below. |

And by kind:

| | |
| --- | --- |
| `setValue(value, options?)` | Leaves: writes a value or `(previous) => next`. |
| `setValue(patch)` | Objects: merges the keys given. |
| `setValue(value, { replace: true })` | Objects: replaces the whole object. |
| `at(key)` | Objects: the child handle. |
| `push(item?)`, `insert(index, item?)` | Arrays: adds an item. Needs `arrays()`. |
| `remove(index)`, `move(from, to)` | Arrays: removes or moves one. Items keep their keys and state. Needs `arrays()`. |
| `item(key)` | Arrays: the handle of the item with that stable key. |
| `key` | Item handles: the item's stable key. |

Writes take `{ edited: false }` for a write that isn't a user edit, such as
loading data.

### Store

`form.store`, the framework-free core store. You need it mostly in plugins and
tests.

| | |
| --- | --- |
| `getFormSnapshot()` | The form snapshot. The same object until something in it changes. |
| `subscribeForm(listener)` | Calls `listener` after a write that changes the form snapshot. |
| `getSnapshot(path)` | The snapshot of the field at a stable path. |
| `subscribe(path, listener)` | Calls `listener` after a write that changes that field. |
| `peek()` | The form snapshot, for event handlers. |
| `batch(fn)` | Runs `fn`, notifying listeners once at the end. |
| `submit(intent?)` | Submits without the adapter's focus handling. |
| `handleSubmit(event?)` | The same, for a submit event. |
| `setErrors(errorMap)` | Replaces user errors across the form. A name no field has goes to the root. |
| `validate()` | Runs every validator now. |
| `reset(options?)` | Resets the whole form. |
| `fieldAt(path)` | The handle at a stable path, or `undefined` when no field is there. |
| `pathOf(name)` | The stable path of a dotted name such as `rows.0.title`, or `undefined` when no field has it. |
| `changes(path?)` | Every dirty leaf below `path`. Needs `dirty()`. |
| `firstInvalid()` | The first enabled field with an error. |
| `disabledInvalid()` | Every disabled field with an error. |

### Types

| | |
| --- | --- |
| `FieldApi<T, E, N>` | The `field` prop of a registered component. `FieldApi<number>` holds `number` or `undefined`. `FieldApi<string \| undefined>` takes required and optional string fields. `N` names plugins the form must have, as `"dirty"` for a component that reads `dirty`. |
| `ExactFieldApi<V>` | The field object with the exact value type. |
| `HandleOf<typeof fieldset, A>` | The handle prop a fieldset component takes. It takes only the fieldset's exact value. For values with more keys, make the component generic, `<A extends Address>`, and pass `A`. |
| `FieldType<C, N>` | What `defineField` returns. `N` names the plugins its parts need. |
| `Part<N, V>` | A plugin's config for one place. `N` is the plugin and `V` the values it fits. |
| `FormOf<typeof definition>` | The form a definition makes. |
| `FieldHandle<V>` | A handle for a `V`: leaf, object or array by its type. Handles are strict in `V`: a `FieldHandle<Address>` takes no handle of an object with more keys. For a generic `V`, the children its constraint names read as the constraint's types. |
| `FieldPath<V>`, `ValueAt<V, P>` | The dotted names of `V`, and the type at one. |
| `ValueOf<H>`, `ErrorOf<H>` | A handle's value and error types. |
| `FieldSnapshot<V>`, `FormSnapshot` | What the field and form reads return. |
| `Submission` | A submit's state: `idle`, `submitting`, `invalid`, `failed` or `succeeded`. |
| `FormError` | The default error type, `{ message: string }`. |
| `Choice` | The value type for select, radio and checkbox group components. |
| `Draft<T>` | `T` as a schema form holds it, with leaves that may be `undefined`. |
| `StandardSchemaV1` | The Standard Schema interface any schema library implements. |

A function has no type of its own name. Write `typeof createForms` for its
signature, or `ReturnType<typeof createForms>` for what it returns.

Hovers in your editor also show types the adapter doesn't export, such as
the ones that work out which names fit a field component. They can change in
any release, so don't copy them into your own code.

### Core helpers

| | |
| --- | --- |
| `createFormsCore(config?)` | Core's entry point, which the adapters wrap. Returns `define`. |
| `branch(handle, snapshot, key, value)` | Narrows a handle to one member of a discriminated union. |
| `invalidFields(store)` | Every field with an error, in form order, as `{ field, name, errors }`. The adapter hooks above wrap it. |
| `subscribeInvalid(store, listener)` | Calls `listener` after a write that may change `invalidFields(store)`. Returns the function that unsubscribes. |
| `errorsByKind(handle)` | The field's validation errors as `{ schema, form, field }` (an `ErrorsByKind<E>`), by the kind of validator that set them. Errors from `setErrors` aren't included. A read, not a subscription. |
| `splitPath(path)` | `"items.0.name"` to `["items", 0, "name"]`. |
| `fieldId(formId, path)` | The DOM id the adapters give a field. |
| `optionId(id, option)` | The DOM id of one radio or checkbox in a group. |

## Plugins

Every plugin comes from one entry. A plugin you don't import isn't in your
bundle, since the package has no side effects and your bundler drops it.

Import from `@lunarhue/forms-react/plugins`.

### plugins

| | |
| --- | --- |
| `definePlugin(definition)` | Makes a plugin from a `setup`, an `attach` for its parts, or a schema plugin from a `schema` adapter. See [Writing a plugin](https://forms.lunarhue.dev/react/writing-plugins/first-plugin.md) and [Schema adapters](https://forms.lunarhue.dev/react/writing-plugins/schema-adapters.md). |
| `refuse` | Returned from `beforeWrite` to stop a write, or from `onSubmit` to stop the submit. |
| `flushPlugins(store)` | Delivers the waiting deferred and idle records now. For tests. |

### plugins/arrays

| | |
| --- | --- |
| `arrays()` | Turns on `Items`, `useItems`, `createItems` and `push`, `insert`, `remove` and `move`, with keys that follow the items. See [Arrays](https://forms.lunarhue.dev/react/plugins/arrays.md). |

### plugins/history

| | |
| --- | --- |
| `history(limit = 100)` | Undo and redo. API `form.plugins.history.undo()` and `.redo()`. |

`canUndo` and `canRedo` are form meta: `plugin.formMeta(snapshot).canUndo`.
See [History](https://forms.lunarhue.dev/react/plugins/history.md).

### plugins/mask

| | |
| --- | --- |
| `mask()` | The mask plugin, for the form's plugins. |
| `masked({ clean, display? })` | A part that cleans a string field's value before the store takes it. |
| `digits`, `upper` | Cleaners: keep the digits, upper-case. |
| `replaceText(input, text, clean, event)` | Writes masked text into an input and keeps the caret. |

Put `masked(...)` on a field type. See [Masks](https://forms.lunarhue.dev/react/plugins/masks.md).

### plugins/rules

| | |
| --- | --- |
| `rules()` | The rules plugin, for the form's plugins. |
| `ruled(fields)` | A part that works out `disabled` and `hidden` per field from the value where it attaches. |
| `rules.meta(field)` | Reads a field's `hidden` flag. |

Each rule takes the value and returns `{ disabled?, hidden? }`. Put `ruled`
after `define`'s config or on a fieldset. See [Rules](https://forms.lunarhue.dev/react/plugins/rules.md).

### plugins/persist

| | |
| --- | --- |
| `persist(key, storage?)` | Saves the value as JSON once the page is idle, and restores it on mount. `localStorage` by default. |

### plugins/rebase

| | |
| --- | --- |
| `rebase()` | API `form.plugins.rebase(handle, incoming, resolve)`, which returns `{ taken }`. |

`resolve` gets each differing leaf (`path`, `value`, `baseline`, `incoming`,
`edited`) and returns `"keep"`, `"take"` or `{ value }`.

### plugins/dirty

| | |
| --- | --- |
| `dirty()` | Turns on `dirty`, `equals` and `store.changes()`. |
| `baselineOnSubmit()` | Moves the baseline to what a successful submit sent. |

### plugins/bind

| | |
| --- | --- |
| `bind(options)` | Copies the form value to a store you own and back. Takes `get`, `set`, `subscribe`, `incoming` and `initial`. |

### Testing

`@lunarhue/forms-core/plugins/testing`, from core only.

| | |
| --- | --- |
| `testStore(config)` | A store for testing a plugin with no framework. Returns `store`, `records`, `errors`, `flush`, `listen` and `server`. |

## Schema

`@lunarhue/forms-schema`. Each plugin lets `schema` take its library's
schemas and fills `defaultValues` from them. Validation needs no plugin.

| | |
| --- | --- |
| `zod()` | From `@lunarhue/forms-schema/zod`. Zod 4, `zod` and `zod/mini`. |
| `valibot()` | From `@lunarhue/forms-schema/valibot`. Sync and async schemas. |

## Bindings

`@lunarhue/forms-bind`. Both take `bind`'s `incoming` and `initial`.

| | |
| --- | --- |
| `zustand(store, options?)` | From `@lunarhue/forms-bind/zustand`. Binds the whole state, or a slice with `select` and `update`. |
| `signal(get, set, options?)` | From `@lunarhue/forms-bind/solid`. Binds a Solid 2 signal. |

See [Zustand](https://forms.lunarhue.dev/react/integrations/zustand.md).
