API
The public exports of each package, by entry point.
A quick reference of every public export, grouped by entry point. Type parameters are omitted here for readability; hover any symbol in your editor for full generics and doc comments.
Your framework adapter re-exports everything from @lunarhue/forms-core, and its /plugins entry re-exports core’s plugins, so you only need to import from the adapter you installed.
Adapter
@lunarhue/forms-solid targets Solid 2. On Solid 1.8+, import from @lunarhue/forms-solid/v1. It exposes the exact same API and types, so moving to Solid 2 is a one-line import change.
createForms
Call once at module scope. Every form defined from the returned forms object inherits these shared settings.
createForms(options?: {
plugins?: Plugin[]; // installed on every form, in order
fields?: { TextField, … }; // field components or field types, bound on every form
mapError?: MapError; // transforms schema issues and thrown errors into your error type
validate?: ValidateTiming; // when validators first run ("blur" by default)
show?: Show; // when errors become visible ("touched-or-submitted" by default)
equals?: Equals; // custom dirty comparison (requires dirty())
focusOnInvalid?: FocusOnInvalid; // focus behavior on invalid submit (true by default)
subscribe?: Subscribe; // e.g. perField() (matches /mini; ignored on full entry)
onPluginError?: PluginErrorHandler;
}): FormsPlugin arrays accept false, null, or undefined entries so conditional plugins like plugins: [dirty(), dev && devtools()] tree-shake cleanly. TypeScript treats conditional plugins as not guaranteed to be installed.
| Method | What it does |
|---|---|
forms.define(config, ...parts) |
Defines a form (returns the definition passed to the form hook and useFormContext). Trailing parts attach at the root when the store is created. |
forms.scope(handle) |
Returns a cached scope (root, Field, and registered field components) relative to an object handle. |
forms.fieldset(schema, ...parts) |
Defines a reusable field-group shape typed from a schema (validation still comes from the form). parts attach wherever the fieldset is used. |
forms.fieldset<V, P>(...parts) |
Same as above using a TypeScript type instead of a schema. P lists required plugin factories (e.g. typeof rules), or omit both when inferred from a typed part like ruled<Billing>(...). |
fieldset.at(name) |
Pins the fieldset’s parts at name on a form definition. |
defineField
defineField(component, ...parts): FieldTypeCreates a reusable field type combining component with parts that attach wherever it renders. Register it in createForms({ fields }). TypeScript verifies both value compatibility and required plugins. Call PhoneField.at(name) to pin its parts on forms.define(...).
define
forms.define({
defaultValues?, // required unless a schema plugin handles `schema`
schema?, // any Standard Schema; schema plugin makes defaultValues optional
plugins?, // form-specific plugins (run after shared plugins)
validate?: {
form?: formValidator(check),
fields?: fieldValidators({ ... }),
},
show?,
equals?, // requires dirty()
disabled?, // fields that start disabled
readOnly?, // fields that start read-only
onSubmit?: (value, ctx) => result,
})define also accepts a factory function (options) => config for per-instance options. Passing those options becomes the second argument to the form hook.
Validators
| Helper | What it does |
|---|---|
fieldValidators(tree) |
Per-field validator map matching your value shape, for validate.fields. A one-element tuple at an array applies to every row. |
formValidator(check) |
Whole-form validator for validate.form. Returns errors keyed by dotted field name plus optional form errors. |
validateOn(check, timing) |
Overrides when check first runs: "input", "blur", or "submit". |
debounced(check, ms) |
Waits for a ms pause in typing before calling check (bypassed on submit). |
recheckOnSubmit(check) |
Forces check to run on every submit even when its previous result is still current. |
pipe(...checks) |
Runs checks sequentially and stops at the first error. Stays synchronous while checks are sync, preventing downstream debounced checks from starting early. |
Every wrapper accepts a validator function or Standard Schema, composes in any order, and works in fieldValidators, formValidator, validate props, and registerValidator. See Validation.
createForm
createForm(definition, settings?: { id?, focusOnInvalid?, plugins? }): SolidForm
createForm(definition, options, settings?) // when define took a functionCreates the form tied to the current reactive owner. id prefixes DOM IDs (defaults to createUniqueId()). plugins installs instance-only plugins like a signal binding.
Members on the returned form object:
| Member | What it is |
|---|---|
form.Form |
Context provider wrapper; its child function receives formProps. |
form.state |
Form snapshot exposed as fine-grained reactive getters (e.g. form.state.submitting). |
form.root |
Handle for the whole form value. |
form.Field |
Renders one field by name or handle; children receive the field object. |
form.TextField |
Bound version of each registered field component. |
form.submit(intent?) |
Programmatically submits and resolves to the Submission, applying focusOnInvalid. |
form.handleSubmit(event?) |
Calls preventDefault() and submits. |
form.formProps |
Props to spread directly onto <form>. |
form.store |
Underlying framework-agnostic store (see Store). |
form.plugins |
Installed plugin APIs keyed by plugin name (e.g. form.plugins.history.undo()). |
form.id |
The store’s DOM ID prefix. |
useFormContext
| Call | Returns |
|---|---|
useFormContext() |
Nearest form.Form above, with unknown value types (enough for a submit button). |
useFormContext(definition) |
Nearest form created from definition, fully typed. |
useFormContext(forms) |
Nearest form from that createForms call, typed with its shared plugins and fields. |
Throws if no matching <form.Form> ancestor is found.
Reading state
| Primitive / Component | What it does |
|---|---|
createField(handle) |
Returns a reactive FieldApi tied to the current owner. |
createItems(handle) |
Returns an accessor of ordered row handles, updating only when keys change. Requires arrays(). |
<Items handle fallback?> |
Renders keyed rows via For with (item, index) children. Requires arrays(). |
createValidator(handle, validator) |
Registers a validator for the lifetime of the current owner. |
createDisabledErrors(form) |
Accessor of disabled fields whose errors blocked the last submit. |
createInvalidFields(form) |
Accessor of all errored fields in form order as { field, name, errors }. |
Inputs
| Helper | What it does |
|---|---|
inputProps(field, { type }?) |
Props for text-like <input> on string fields. |
textareaProps(field) |
Props for <textarea> on string fields. |
selectProps(field, { empty }?) |
Props for <select> on string fields. |
numberProps(field, { empty }?) |
Props for <input type="number"> on number fields; preserves in-progress 1. and -. |
rangeProps(field) |
Props for <input type="range"> on number fields. |
checkboxProps(field) |
Props for <input type="checkbox"> on boolean fields. |
checkboxGroupProps(field, value) |
Props for one checkbox in a string/number array group. |
radioProps(field, value) |
Props for one radio button writing value. |
numberPieces(field, { empty }?) |
{ text, setText, handleBlur } for custom numeric inputs. |
errorId(handle) |
Returns the error element ID for handle. |
elementsOf(handle) |
Returns connected DOM elements registered for handle, in document order. |
isFocused(handle) |
true while focus is on or inside any of handle’s elements (works in production with no extra setup). |
fieldOf(element) |
Returns the handle whose ref registered element (requires trackElements() in production). |
trackElements(listener?) |
Enables fieldOf in production and optionally notifies on every element registration/cleanup. |
| Helper | What it does |
|---|---|
fieldRef(handle) |
Returns a ref callback registering a custom input as the field’s focus target. |
Every props helper type-checks against its expected field value type, requires empty when undefined isn’t allowed, and wires aria-invalid and aria-describedby automatically while errors are shown.
Every props helper (except numberPieces) also accepts a describedBy option to prepend extra hint IDs to aria-describedby (passed last, e.g. radioProps(field, value, { describedBy })). Returned attributes are reactive getters.
Field object (FieldApi)
Passed to registered components as field, to form.Field children, and returned by createField(handle):
| Member | What it is |
|---|---|
value |
Current field value. |
name |
Dotted path name (e.g. "address.city"). |
errors, shownErrors |
All errors, and errors currently visible per show. |
userErrors |
Errors set via setErrors (also at the end of errors). |
invalid |
true when the field has any validation or user error. |
touched, edited |
Blurred once; modified by the user. |
dirty |
Differs from baseline (requires dirty()). |
validating |
true while an async validator is running. |
disabled, readOnly |
Active on this field or inherited from an ancestor. |
meta |
Plugin meta slots (read via each plugin’s .meta(field)). |
keys |
Array fields only: ordered stable item keys. |
text, setText(text, from?) |
Display text and text-writing helper (preserves caret with masks). |
ref |
Ref callback registering the DOM element for focus on invalid submit. |
handle |
The stable field handle. |
id, path, errorId |
Stable DOM ID, internal path array, and error container ID. |
Also includes all of the field handle’s commands, pre-bound.
Handles
Returned by form.root, handle.at(key), and handle.item(key):
| Member | What it does |
|---|---|
id, path, store |
DOM ID, stable path, and parent store. |
peek() |
Non-reactive snapshot read for event handlers. |
setTouched(touched?) |
Sets the touched flag. |
handleBlur() |
Marks touched, runs blur validation, and fires plugin onBlur. |
setErrors(errors) |
Replaces user errors (cleared on the next user edit). |
validate() |
Runs validators now; resolves true if valid. |
registerValidator(validator) |
Attaches a validator and returns its cleanup function. |
reset(options?) |
Resets to baseline (or { to: "initial" } for starting values). |
setDisabled(on), setReadOnly(on) |
Sets the flag for this field and its subtree. |
Kind-specific handle methods:
| Method | Kind |
|---|---|
setValue(value, options?) |
Leaves: writes a value or updater (prev) => next. |
setValue(patch) / setValue(value, { replace: true }) |
Objects: shallow-merges a patch or replaces wholesale. |
at(key) |
Objects: returns child handle. |
push(item?), insert(index, item?) |
Arrays: appends or inserts a row (requires arrays()). |
remove(index), move(from, to) |
Arrays: removes or moves a row while keeping keys and state (requires arrays()). |
item(key) |
Arrays: returns the handle for a row’s stable key. |
key |
Array items: the row’s stable key. |
Value writes accept { edited: false } for programmatic updates that shouldn’t count as user edits.
Store
form.store is the framework-agnostic core store, useful in plugins, utilities, and tests:
| Method | What it does |
|---|---|
getFormSnapshot(), subscribeForm(listener) |
Reads and subscribes to form-level state. |
getSnapshot(path), subscribe(path, listener) |
Reads and subscribes to a single field by stable path. |
peek() |
Current form snapshot for event handlers. |
batch(fn) |
Groups multiple writes into a single notification pass. |
submit(intent?), handleSubmit(event?) |
Submits without adapter focus management. |
setErrors(errorMap) |
Replaces user errors across the form (unknown names fall back to root). |
validate() |
Runs all validators now. |
reset(options?) |
Resets to baseline, { to: "initial" }, or { values } (writes new values and makes them the new baseline). |
fieldAt(path) |
Returns the handle at a stable path, or undefined. |
pathOf(name) |
Resolves a dotted name like "rows.0.title" to its stable path, or undefined. |
changes(path?) |
Lists dirty leaves under path (requires dirty()). |
firstInvalid(), disabledInvalid() |
Finds the first invalid enabled field, or all invalid disabled fields. |
Types
| Type | Description |
|---|---|
FieldApi<T, P, E> |
Field prop type for components (P = required plugin factories like typeof dirty, E = error type). |
ExactFieldApi<V> |
Field object preserving the exact value type V. |
HandleOf<typeof fieldset, A> |
Handle prop type for fieldset components (pass generic A to allow extra keys). |
FieldType<C, N> |
Return type of defineField. |
Part<P, V> |
Part type (P = plugin factory or never for standalone, V = accepted field value). |
FormOf<typeof definition> |
Form instance type for a definition or forms object. |
FieldHandle<V, P, E> |
Leaf, object, or array handle matching V (also LeafHandle, ObjectHandle, ArrayHandle, ItemHandle, AnyFieldHandle<P, E>). |
FieldPath<V>, ValueAt<V, P> |
Valid dotted paths of V and the value type at path P. |
ValueOf<H>, ErrorOf<H> |
Extracts value and error types from a handle. |
FieldSnapshot<V>, FormSnapshot |
Snapshot types for fields and the form. |
FormResetOptions<V>, ResetOptions, ResetValues<V> |
Options accepted by store.reset(...) and handle.reset(...). |
ErrorsByKind<E>, ValidatorKind |
Return type and keys of errorsByKind(handle). |
InvalidField<E>, DisabledInvalid<E> |
Entry shape { field, name, errors } returned by invalidFields and disabledInvalid. |
Subscribe, WrappedSchema<Input> |
Subscription mode type for perField(), and return type of wrapped Standard Schemas. |
Submission, FormError, Choice, Draft<T>, StandardSchemaV1 |
Supporting form, error, choice, draft, and schema types. |
Internal helper types that show up in editor hovers aren’t part of the public contract and may change between releases; stick to the exported types above.
Core helpers
| Helper | What it does |
|---|---|
createFormsCore(config?) |
Framework-agnostic core entry point wrapped by adapters. |
branch(handle, snapshot, key, value) |
Narrows an object handle to one variant of a discriminated union. |
invalidFields(store), subscribeInvalid(store, listener) |
Imperative helpers backing useInvalidFields and createInvalidFields. |
errorsByKind(handle) |
One-time read returning { schema, form, field } validation errors (excludes userErrors). |
splitPath(path) |
Splits "items.0.name" into ["items", 0, "name"]. |
fieldId(formId, path), optionId(id, option) |
Generates the same DOM IDs used by adapters. |
Plugins
All built-in plugins live in one side-effect-free entry, so your bundler drops anything you don’t import.
Import from @lunarhue/forms-solid/plugins.
Writing plugins
| Export | What it does |
|---|---|
definePlugin(definition) |
Creates a plugin factory supporting setup, part, requires, initialValue, schema, and meta (initialMeta / initialFormMeta). Hooks: beforeWrite, onWrite, onReset, onBlur, beforeSubmit, onSubmitted, onActive. |
part(plugin, config) |
Creates a typed part for a plugin’s part hook. |
part<V>(hooks) |
Creates a standalone part with custom hooks (no plugin needed). |
transform<V>(fn) |
Standalone part that transforms or refuses writes at its path. |
text<V>(display, afterInput?) |
Standalone part controlling text input display formatting. |
observe<V>(fn) |
Standalone part reacting to writes at its path. |
refuse |
Sentinel returned from beforeWrite or beforeSubmit to cancel the operation. |
flushPlugins(store) |
Synchronously flushes pending deferred and idle plugin deliveries (for tests). |
Built-in plugins
| Plugin | What it adds |
|---|---|
arrays() |
Dynamic array rows (Items, useItems/createItems, push, insert, remove, move) with stable keys. See Arrays. |
dirty() |
dirty flags, equals, and store.changes(). See Dirty. |
baselineOnSubmit() |
Advances the baseline on "succeeded" submits (leaves refused/failed submits dirty). See Dirty. |
history(limit = 100) |
Undo/redo via form.plugins.history.undo() / .redo() and history.formMeta(state). See History. |
persist(key | { key, storage }) |
Idle-time JSON draft persistence and restore on mount. See Persist. |
rebase() |
form.plugins.rebase(handle, incoming, resolve) returning { taken }. See Rebase. |
rules() + ruled(fields) |
Computed disabled and hidden flags (rules.meta(field)). See Rules. |
bind(options) |
Generic two-way external store binding (get, set, subscribe, initial, incoming). |
Text & masks (/text)
Import from @lunarhue/forms-react/text, @lunarhue/forms-solid/text, or @lunarhue/forms-core/text. Standalone parts, no plugin needed.
| Export | What it does |
|---|---|
masked({ clean, display? }) |
Cleans stored string values and optionally formats displayed text with caret tracking. |
cleaned(clean), displayed(display, clean?) |
Cleaning-only or display-only halves of masked. |
digits, upper |
Built-in string cleaners. |
replaceText(input, text, clean, event) |
Caret-preserving helper for custom afterInput hooks. |
See Masks.
Testing
Import from @lunarhue/forms-core/plugins/testing (core-only entry):
| Export | What it does |
|---|---|
testStore(config, ...parts) |
Framework-free test harness returning { store, records, errors, flush, listen, server }. |
Schema (@lunarhue/forms-schema)
| Export | Entry |
|---|---|
zod() |
@lunarhue/forms-schema/zod: Zod 4 (zod and zod/mini) default value inference. |
valibot() |
@lunarhue/forms-schema/valibot: Valibot sync/async default value inference. |
Bindings (@lunarhue/forms-bind)
| Export | Entry |
|---|---|
zustand(store, options?) |
@lunarhue/forms-bind/zustand: binds a Zustand 5 store or slice (select, update, isEqual). |
signal(get, set, options?) |
@lunarhue/forms-bind/solid: binds a Solid 2 signal. |
See Solid signals.
Devtools (@lunarhue/forms-devtools)
| Export | What it does |
|---|---|
devtools(options?) |
Plugin that registers mounted forms with the on-page devtools panel (enabled?: boolean | (() => boolean), onDisable?: () => void). Gate with dev && devtools() to omit it from production bundles. |
syncDevtools() |
Re-checks every registered form’s enabled() callback so the panel mounts or unmounts immediately when your toggle changes. |
See Devtools.
Last updated