Forms Reference
The details of the form behavior. Start with the recipe on Forms: it covers validation, the submit, pending state, server errors and field arrays.
The slice
Section titled “The slice”state.form holds:
| Field | |
|---|---|
values, initial | The current values, and the ones the form started with (or was last saved or reset with) |
errors | Every current schema error by field name, shown or not |
touched, server, remote, pending | Blurred fields; server errors; check results; checks running |
submitting, submitted, submitCount, queued, validating, validated | Submit state: the request sent and not answered yet; form.DONE arrived (or a submit without a request was dispatched); attempts; a submit waits for a check or an async schema; an async schema runs; the schema has answered since the start or the last reset |
progress, resets | The submit request’s last progress step ({ phase, loaded, total, fraction }, or null); how many times the form started over (form.RESET, resetOnShow), for keying a file input |
added, kept | The dynamic fields on the form now: name → start value ({} without the dynamic option); the ones that went whose values stay: name → true |
fields, valid, dirty, error | Calculated: per-field view data; no errors as of the schema’s last answer (false before the first); values differ from initial; the form-level message |
The options are on Forms.
The actions
Section titled “The actions”Named after the uses key (form.CHANGE for uses = { form: … }):
| Action | Data |
|---|---|
form.CHANGE | { name, value }: from the form element’s input events (field types; a checkbox gives checked, its value as item and its group’s values in document order as order; a file input its File) |
form.SET | { values }: several fields at once, by field name ({ name: 'Dana', 'addresses.7.city': 'Hilo' }), as if the user had typed them: one validation, the fields count as changed, touched as for form.CHANGE (so errors show by the show rule), their server errors and check results cleared. Fields not named keep their values; a name that isn’t a field is skipped (SYG230 in development). For a fill from elsewhere: an AI extraction, a saved draft, an address lookup |
form.BLUR | The field name, from focusout |
form.SUBMIT | From the form element’s submit (default prevented) |
form.ADD / form.REMOVE | { field, value } / { field, id }: field array rows |
form.ERRORS | Server errors: an error reply, a map or a list of issues |
form.DONE | The submit’s request was saved: initial becomes values, submitted turns on (a submit without a request needs none) |
form.RESET | Back to initial, or to the values given |
form.PROGRESS | A progress step of the submit’s request, sent with progress: 'form.PROGRESS': kept as progress until form.DONE or form.ERRORS (file fields) |
form.VALIDATE | Internal: the first validation when the host starts; with resetOnShow, the start over (also each time the form element appears again) |
form.SYNC | Internal: the dynamic fields changed with the host’s state, or a schema function returned another schema; data { fields } |
As for any behavior, a host model entry with the same name runs after the form’s: 'form.DONE': (state) => ({ ...state, done: true }) shows a confirmation. Trigger an action from elsewhere with an intent action of that name, or t.simulateAction('form.RESET') in a test.
File fields
Section titled “File fields”A file input whose name is in values is a field like any other: its value is the File the user picked (an array of them with multiple, null when none), the schema validates it, its error shows on fields.avatar.error, and the submit’s data carries it, so request sends it as multipart:
import { form } from 'sygnal'import { z } from 'zod'
const profileSchema = z.object({ name: z.string().min(1, 'Enter your name'), avatar: z.file('Choose a photo').max(5_000_000, 'At most 5 MB').mime(['image/png', 'image/jpeg'], 'A PNG or JPEG photo'),})
function Profile({ state }) { const f = state.form.fields const percent = Math.round((state.form.progress?.fraction ?? 0) * 100) return ( <form> <label>Name <input name="name" value={f.name.value} /></label> <label>Photo <input type="file" name="avatar" accept="image/*" key={'avatar' + state.form.resets} /></label> <p className="chosen">{f.avatar.value?.name}</p> <p className="error">{f.avatar.error}</p> {state.form.submitting && <progress max="100" value={percent} aria-label="Upload progress" />} <button type="submit" disabled={state.form.submitting}>Save</button> </form> )}
// the data has a File, so the form sends it as multipart, with progress in state.form.progressProfile.uses = { form: form(profileSchema, { values: { name: '', avatar: null }, request: { url: '/api/profile' } }) }- Progress: the form’s
requestasks for progress when it sends a file (progress: 'form.PROGRESS';progress: trueon therequestasks for it on a JSON submit too; asubmitentry’s request can name it), and the form keeps the latest step instate.form.progress({ phase, loaded, total, fraction }) while it is submitting, and clears it onform.DONE,form.ERRORSandform.RESET. - Don’t bind
value: the browser doesn’t let a page set a file input’s file. So a reset can’t clear it through state; instead the form counts its start overs instate.form.resets, andkey={'avatar' + state.form.resets}makes a new, empty input after each one. For the same reason, show the chosen file’s name yourself (f.avatar.value?.name): after a reset to saved values (form.DONEmakes the saved values the start values) the value is still the file while the new input is empty. - Validation uses your schema’s file checks: zod’s
z.file()(.max(),.mime()), valibot’sv.file(), orinstanceof Filein a hand-written schema. Required means rejectingnull. - Tests pick a file with
t.simulateEvent('[name="avatar"]', 'input', { files: [new File(['…'], 'me.png')] }), submit, thent.progress('HTTP', { loaded: 1, total: 2 }, 'form.PROGRESS')andt.respond('HTTP', reply, 'form.DONE'). - A file input whose
nameisn’t invaluesis left alone, as before 6.7, for an app that reads its files in its own intent. - A
Filecan’t be serialized, sopersist()and server-rendered state don’t carry file fields.
Any Standard Schema
Section titled “Any Standard Schema”form() takes any object with ~standard.validate: zod (3.24 and later), valibot (1.0 and later), arktype, or one you write. A schema’s issue paths become field names, and an issue without a path is a form-level message (state.form.error, shown after a submit):
const EMAIL = /^\S+@\S+\.\S+$/
export const signupSchema = { '~standard': { version: 1, vendor: 'my-app', validate(values) { const issues = [] if (!values.name.trim()) issues.push({ message: 'Enter your name', path: ['name'] }) if (!EMAIL.test(values.email)) issues.push({ message: 'Enter a valid email address', path: ['email'] }) return issues.length ? { issues } : { value: { ...values, email: values.email.trim().toLowerCase() } } }, },}An async schema (valibot’s pipeAsync, zod’s async refinements) works too: state.form.validating is true while it runs (also at the start, until its first answer) and a submit waits for it. state.form.valid is false until the first answer; after that it keeps the last answer’s validity while the schema re-validates, so <button disabled={!state.form.valid}> doesn’t flicker on every keystroke (show progress with validating). The schema first runs when the component starts, not when form() is called. Something that isn’t a Standard Schema is SYG231.
Async checks
Section titled “Async checks”Some checks need the server: is this email address taken? check names a field and the request that checks it. The request goes to the HTTP driver (makeFetchDriver) with a reply action the form handles, and latest: true, so a check for a newer value replaces the older one.
In this demo, a stand-in server answers both requests: ada@example.com is already registered, and so is each address that signs up.
const registered = ['ada@example.com']
export default { 'GET /api/email-available': ({ query }) => ({ json: { available: !registered.includes(query.email) } }), 'POST /api/signup': ({ json }) => { if (registered.includes(json.email)) return { status: 422, json: { errors: { email: 'Already registered' } } } registered.push(json.email) return { status: 201, json: { id: registered.length } } },}The schema checks the address’s form, in ./schema.js:
import { z } from 'zod'
export const signupSchema = z.object({ email: z.string().trim().toLowerCase().email('Enter a valid email address'),})The form checks the address with the server when the field loses focus:
import { form } from 'sygnal'import { signupSchema } from './schema.js'
function Signup({ state, uid }) { const f = state.form.fields return ( <form className="signup" noValidate> <label for={uid('email')}>Email</label> <input id={uid('email')} name="email" type="email" value={f.email.value} aria-invalid={f.email.invalid} aria-describedby={uid('email-error')} /> <p id={uid('email-error')}>{f.email.pending ? 'Checking…' : f.email.error}</p> <button type="submit" disabled={state.form.submitting}>Sign up</button> <p role="status">{state.form.submitted ? 'Signed up.' : ''}</p> </form> )}
Signup.uses = { form: form(signupSchema, { values: { email: '' }, submit: 'SIGN_UP', check: { email: { request: (email) => ({ url: '/api/email-available', query: { email } }), error: (body) => !body.available && 'This email is already registered', }, }, }),}
Signup.model = { SIGN_UP: { HTTP: (state, values) => ({ url: '/api/signup', method: 'POST', json: values, ok: 'form.DONE', error: 'form.ERRORS' }) },}The message line keeps its height, so the button doesn’t move when Checking… appears (why):
.signup p { min-height: 1.5em; }- A field is checked when it loses focus, once per value, and only when its schema error is clear and it isn’t empty.
error(body)turns the reply into a message, or a falsy value when the value is fine. - A submit while a check runs (or before a field was ever checked) waits for it:
state.form.queuedistrue, and the submit goes on once every check passed, or stops and focuses the field whose check failed. Checks for several fields run one after the other. - Editing the field drops its check: a late reply for the old value is ignored. Editing any field cancels a queued submit.
- A check that fails (network error, 500) doesn’t block the form: the server validates again on submit.
A test answers the check like any request:
import { renderComponent } from 'sygnal'import { it, expect } from 'vitest'import Signup from './Signup.jsx'
it('validates, checks the email, and posts the cleaned values', async () => { const t = renderComponent(Signup, { strict: true }) await t.ready() t.simulateEvent('[name="email"]', 'input', { value: 'nope' }) t.simulateEvent('[name="email"]', 'focusout') await t.settle() expect(t.state.form.fields.email.error).toBe('Enter a valid email address')
t.simulateEvent('[name="email"]', 'input', { value: 'Ada@Example.com' }) t.simulateEvent('[name="email"]', 'focusout') await t.settle() expect(t.requests('HTTP').at(-1)).toMatchObject({ url: '/api/email-available' }) await t.respond('HTTP', { available: true })
t.simulateEvent('.signup', 'submit') await t.settle() expect(t.requests('HTTP').at(-1)).toMatchObject({ url: '/api/signup', json: { email: 'ada@example.com' } }) await t.fail('HTTP', { status: 422, body: { errors: { email: 'Already registered' } } }) expect(t.state.form.fields.email.error).toBe('Already registered') t.expectNoDiagnostics()})Two forms in one component
Section titled “Two forms in one component”Each form use listens on its form selector inside the component, so two uses left at the default 'form' would both hear every form element: typing in one changes the other, and each submit is handled twice. Give each form element a class and pass it (SYG237 warns otherwise); the first invalid field focused on submit is then also searched in that form only:
import { form } from 'sygnal'import { loginSchema, newsSchema } from './schemas.js'
function Account({ state }) { const login = state.login.fields, news = state.news.fields return ( <div> <form className="login" noValidate> <input name="email" aria-label="Email" value={login.email.value} /> <button type="submit">Sign in</button> </form> <form className="news" noValidate> <input name="email" aria-label="Newsletter email" value={news.email.value} /> <button type="submit">Subscribe</button> </form> </div> )}
Account.uses = { login: form(loginSchema, { values: { email: '' }, submit: 'SIGN_IN', form: '.login' }), news: form(newsSchema, { values: { email: '' }, submit: 'SUBSCRIBE', form: '.news' }),}
Account.model = { SIGN_IN: { HTTP: (state, values) => ({ url: '/api/sign-in', method: 'POST', json: values, ok: 'login.DONE', error: 'login.ERRORS' }) }, SUBSCRIBE: { HTTP: (state, values) => ({ url: '/api/newsletter', method: 'POST', json: values, ok: 'news.DONE', error: 'news.ERRORS' }) },}Rows as components
Section titled “Rows as components”The recipe renders field array rows inline, which needs no child component. When a row is big enough to be a component of its own, render the rows with a Collection, pass fields down, and send the remove up with PARENT:
import { Collection, form } from 'sygnal'import { signupSchema } from './schema.js'
function Address({ state, fields, uid }) { const city = fields[`addresses.${state.id}.city`] return ( <div className="address"> <label for={uid('city')}>City</label> <input id={uid('city')} name={city.name} value={city.value} aria-invalid={city.invalid} aria-describedby={uid('city-error')} /> <p id={uid('city-error')}>{city.error}</p> <button type="button" className="remove">Remove address</button> </div> )}
Address.intent = ({ DOM }) => ({ REMOVE: DOM.click('.remove') })Address.model = { REMOVE: { PARENT: (state) => ({ field: 'addresses', id: state.id }) } }
function Signup({ state, uid }) { const f = state.form.fields return ( <form className="signup" noValidate> <label for={uid('email')}>Email</label> <input id={uid('email')} name="email" type="email" value={f.email.value} aria-invalid={f.email.invalid} aria-describedby={uid('email-error')} /> <p id={uid('email-error')}>{f.email.error}</p> <fieldset aria-describedby={uid('addresses-error')}> <legend>Addresses</legend> <Collection of={Address} from={{ get: (s) => s.form.values.addresses }} fields={f} /> <p id={uid('addresses-error')}>{f.addresses.error}</p> <button type="button" className="add-address">Add address</button> </fieldset> <button type="submit" disabled={state.form.submitting}>Sign up</button> </form> )}
Signup.uses = { form: form(signupSchema, { values: { email: '', addresses: [{ id: 1, city: '' }] }, submit: 'SIGN_UP' }),}
Signup.intent = ({ DOM, CHILD }) => ({ 'form.ADD': DOM.click('.add-address').mapTo({ field: 'addresses', value: { city: '' } }), 'form.REMOVE': CHILD.select(Address),})
Signup.model = { SIGN_UP: { HTTP: (state, values) => ({ url: '/api/signup', method: 'POST', json: values, ok: 'form.DONE', error: 'form.ERRORS' }) },}- The Collection reads the rows through a read-only lens (
from={{ get }}): rows don’t write their own state, the form does, because the row’s inputs are inside the form element. - Fields of child components and Collection items inside the form element count as the form’s fields.
- A failed submit focuses the first invalid field even inside a row.
Fields chosen at run time
Section titled “Fields chosen at run time”Some forms don’t know their fields when they are written: the user adds a line, or a model composes the form from field pieces (composed UI). Two things follow the host’s state then:
-
dynamic: (state) => ({ name: start value })names the fields beyondvaluesthat are on the form now. The start value can be one value or an object of them ({ amount: '', currency: 'USD' }makesline2.amountandline2.currencyfields). When an entry appears, it is added tovalues(and toinitial, so it isn’t dirty) with its start value; while it stays, it keeps what was typed (an object start value that changes shape reshapes it: new keys are added, keys it no longer has are dropped); when it goes, its touched state, server errors and check results go, and its value is kept, as in React Hook Form and TanStack Form (seekeepRemovedbelow). An entry named after a field ofvaluesdoesn’t change that field: the static one owns it, so it stays when the entry goes.form.RESETandresetOnShowstart the dynamic fields over too. A name that is in neithervaluesnordynamicis still ignored (SYG230). -
keepRemoved(defaulttrue) is what happens to the value of an entry that goes. By default it stays invaluesand ininitial(sodirtystill counts what was typed in it), and its name is instate.form.kept; when the entry comes back, the field shows the kept value (reshaped to the start value, as for an entry that stays). It is not on the form meanwhile, so the schema validates the values without it and a submit doesn’t send it, whatever the schema keeps: a removed line’s amount can’t block the submit or reach the server.form.RESETandresetOnShowdrop the kept values. WithkeepRemoved: falsethe value goes with the entry (and a parent object it leaves empty:'trip.amount'takestripalong), for a form where a field that comes back should start empty.Hiding a field is not removing it. A field stays on the form while it is in
valuesor indynamic’s result, rendered or not: a collapsed section or an earlier wizard step is still validated and submitted. Only an entry that leavesdynamicgoes tokept. React Hook Form can’t tell the two apart (its fields register when they mount), so by default a removed field’s value stays in what it submits and in what a schema resolver validates; here a value that should still be sent belongs in a field that stays declared. -
form((state) => schema, options): a schema that depends on the host’s state, for rules that follow what is on the form (a line’s amount is required while the line is there, a note becomes required once there are two lines). It is called whenever the form validates, and the form validates again when it returns another schema. The form caches results per schema object, so return the same schema while the rules don’t change: memoize it on the part of the state it reads, not on the whole state object, which is new after every change (SYG239 when it builds a new one on every call or every state change).
import { form } from 'sygnal'import { z } from 'zod'
const line = z.object({ amount: z.coerce.number().positive('Enter an amount'), currency: z.string() })
// one schema per list of lines (the form caches its results per schema object)const schemas = new WeakMap()function schemaOf(state) { if (!schemas.has(state.lines)) { schemas.set(state.lines, z.object({ note: state.lines.length > 1 ? z.string().min(1, 'Say what the amounts are for') : z.string(), ...Object.fromEntries(state.lines.map((key) => [key, line])), })) } return schemas.get(state.lines)}
export default function Expense({ state }) { const f = state.form.fields return ( <form className="expense" noValidate> {state.lines.map((key) => ( <div className="line"> <label>Amount <input name={`${key}.amount`} type="number" value={f[`${key}.amount`].value} /></label> <select name={`${key}.currency`} aria-label="Currency"> {['USD', 'EUR'].map((c) => <option value={c} selected={f[`${key}.currency`].value === c}>{c}</option>)} </select> <span className="error">{f[`${key}.amount`].error}</span> <button type="button" className="remove-line" data-key={key}>Remove</button> </div> ))} <button type="button" className="add-line">Add an amount</button> <label>Note <input name="note" value={f.note.value} /></label> <span className="error">{f.note.error}</span> <button type="submit">Send</button> </form> )}
Expense.initialState = { lines: ['line1'], next: 2, sent: null }
Expense.uses = { form: form(schemaOf, { values: { note: '' }, dynamic: (state) => Object.fromEntries(state.lines.map((key) => [key, { amount: '', currency: 'USD' }])), form: '.expense', submit: 'SEND', }),}
Expense.intent = ({ DOM }) => ({ ADD_LINE: DOM.click('.add-line'), REMOVE_LINE: DOM.click('.remove-line').data('key'),})
Expense.model = { ADD_LINE: (state) => ({ ...state, lines: [...state.lines, `line${state.next}`], next: state.next + 1 }), REMOVE_LINE: (state, key) => ({ ...state, lines: state.lines.filter((k) => k !== key) }), // the schema's output: { note, line1: { amount: 12, currency: 'USD' }, … }, only the lines on the form SEND: (state, data) => ({ ...state, sent: data }),}- A field is in
state.form.fieldsin the first render that shows it: the form adds it in the same update as the state change that names it. - Name the dynamic fields after something that identifies the piece, not its position (the line’s key here; in a composed form, the
nodekey a part gets as a prop:name={`${node}.amount`}), so a piece can repeat and its values follow it when another is removed. - A submit the schema rejects is blocked like any other: nothing is dispatched,
submittedstaysfalse, the first invalid field is focused. - Dynamic names are object keys, not array rows (rows have
form.ADD/form.REMOVE). Acheckis keyed by a fixed name, so it works on a dynamic field only when its name is known in advance. - The
examples/ai-adaptiveintake lab builds a form from pieces a model picks this way: each catalog part has its start value and its rules, keyed by node.
Saving and resetting
Section titled “Saving and resetting”form.DONE marks the submit saved: submitting turns off, submitted on, and the saved values become initial (so dirty is false again).
Whether a valid submit waits for form.DONE depends on how it is sent:
- With
request: the form sends it on itshttpsink and waits.requestis an object or(data, state) => request, called with the schema’s output and the host’s state (as committed: the outputs’ state since 7.0);ABORTor a falsy result sends nothing and leaves the submit pending, as below. The form addsjson: data(ormultipart: datawhen a top-level value is aFile,Blobor an array of them; a file nested deeper isn’t sent as a file) unless the request setsjson,multipartorbody, addsprogress: 'form.PROGRESS'to a multipart submit (or when the request setsprogress: true; a progress request goes over XMLHttpRequest, so a plain JSON submit stays onfetch), and always setsok: 'form.DONE'anderror: 'form.ERRORS'. Withsubmitas well, that host action is dispatched too (to set state); its entry shouldn’t send another request.
Otherwise it depends on the host’s entry for the submit action, checked when the host starts:
- With the
httpsink (SIGN_UP: { HTTP: … }, or the sink thehttpoption names, such ashttp: 'API'):submittingistrueuntilform.DONEorform.ERRORS, and a submit meanwhile is dropped (SYG232). Even when the entry returnsABORTthis time, the form waits. - Anything else (
STATE,PARENT,EVENTS,EFFECT,ROUTER, a reducer function): no request, so the submit is done at once, as ifform.DONEhad arrived (no hostform.DONEentry runs). AnEFFECTthat callsnext('form.DONE')itself still works; the secondDONEchanges nothing. Work that answers later without thehttpsink (a promise in anEFFECT) gets no pending state: send it through a driver as a request instead. - A host that unmounts keeps its slice in the parent’s state when it has a
stateprop. When it mounts again, the form clearssubmitting,queuedand running checks (their replies went to the old host); the values, errors andsubmittedstay.form.RESETgoes back toinitial, or to the values it is given (t.simulateAction('form.RESET', values), or an intent action'form.RESET': DOM.click('.reset'): data that isn’t a plain object, such as the click event, meansinitial); it clears errors, touched fields and the submit count. - Starting over when shown (
resetOnShow: true): the form goes back to its start values, as a new form (initialtoo; touched fields, errors, server errors, checks and the submit state cleared), when its host starts (mounted again, a Switchable page made again for anotherinstance) and each time its form element appears in the host’s DOM after being absent (a Switchable page shown again: hidden pages stay alive and keep their state; a form rendered conditionally). Re-renders while the form is shown keep what the user typed. With the mock DOM (and in SSR) only the host’s start counts. Avaluesfunction gets the host’s whole state and is called at each start over; withoutresetOnShow, once, when the host starts and the slice is still untouched. Before its first call (the first render of a page that reads its parent’s state) the fields come from calling it with a blank state, every value read from it''.
Without the behavior: the helpers
Section titled “Without the behavior: the helpers”The behavior covers the common form. When a form needs its own state layout or flow, write the actions yourself and use the functions the behavior is built on; each is a pure function for a reducer:
| Helper | |
|---|---|
checkForm(schema, values) | { errors, value }: errors by field name and the schema’s output; a Promise for an async schema |
formErrors(schema, values) | Only the errors ({} when valid) |
setField(values, name, value), getField(values, name), hasField(values, name) | Immutable set and get by field name (rows by id); whether the field exists (also with an undefined value) |
fieldName(values, path), fieldNames(values) | An issue path as a field name; every field name of values |
replyErrors(reply, values?) | Server errors (a reply, a map or a list of issues) as field errors |
focusInvalid(errors, within?) | An ELEMENT command that focuses the first field with an error, children included; with within (the form element’s selector), only a field inside that element; ABORT when there is none |
import { formErrors, setField, focusInvalid, ABORT } from 'sygnal'import { profileSchema } from './schema.js'
function Profile({ state }) { return ( <form className="profile" noValidate> <label>Display name <input name="name" value={state.values.name} /></label> <p>{state.submitted ? state.errors.name : ''}</p> <button type="submit">Save</button> </form> )}
Profile.initialState = { values: { name: '' }, errors: formErrors(profileSchema, { name: '' }), submitted: false }
Profile.intent = ({ DOM }) => ({ CHANGE: DOM.select('.profile').events('input').map((e) => ({ name: e.target.name, value: e.target.value })), SUBMIT: DOM.select('.profile').events('submit', { preventDefault: true }),})
Profile.model = { CHANGE: (state, { name, value }) => { const values = setField(state.values, name, value) return { ...state, values, errors: formErrors(profileSchema, values) } }, SUBMIT: { STATE: (state) => ({ ...state, submitted: true }), ELEMENT: (state) => focusInvalid(state.errors, '.profile'), HTTP: (state) => (Object.keys(state.errors).length ? ABORT : { url: '/api/profile', method: 'PUT', json: state.values }), },}Offer the form to the browser’s agent
Section titled “Offer the form to the browser’s agent”With tool: formTool({ … }), the form becomes a declarative WebMCP tool: the browser’s AI agent sees it, fills its fields and submits it.
import { form } from 'sygnal'import { formTool } from 'sygnal/ai'
Signup.uses = { form: form(signupSchema, { values: { email: '', plan: '' }, submit: 'SIGN_UP', tool: formTool({ name: 'sign_up', description: 'Create an account' }), }),}- The form writes the attributes the browser reads:
toolnameandtooldescriptionon the<form>,toolautosubmitwithautosubmit: true, and atoolparamdescriptionon each named field, from its<label>(wrapping orfor=) and otherwise itsaria-label. The view stays as it is. To write one yourself, use theattrs-prefix (attrs-toolparamdescription="…"), which wins: a baretoolnamein JSX sets a DOM property the browser ignores (SYG153). - An agent’s submit is an ordinary
form.SUBMIT: the same schema, checks andsubmitaction. The agent’s call resolves after the outcome is rendered, with{ ok: true, values }(the schema’s output, whatsubmitgot) or{ ok: false, errors }(the field errors by name;''is form-level). A submit sent as a request answers after its reply:form.DONEgivesok: true,form.ERRORSthe server errors. autosubmitdefaults tofalse: the agent’s call fills the fields and stays pending until the user submits the form, then gets the same answer. Setautosubmit: trueonly for forms that are safe to submit without the user looking.- A user’s own submit is unchanged.
formToolcomes fromsygnal/aiso that an app usingformwithout a tool doesn’t carry the tool code. A plain object astooldoes nothing but report SYG245 in development.
TypeScript
Section titled “TypeScript”With a schema that declares its Standard Schema types (zod, valibot and arktype do), form() types the values from the schema’s input and checks values against it. UsesState<typeof uses> gives the component’s state the slice: state.form.values.email and state.form.fields.email.value are strings, and a top-level field name that isn’t in the values is a type error (nested paths such as f[`addresses.${id}.city`] stay open). FormOutput<typeof uses.form> (or SchemaOutput<typeof signupSchema>) is the schema’s output, the data of the host’s submit action:
import { form } from 'sygnal'import type { Component, UsesState, UsesActions, FormOutput } from 'sygnal'import { z } from 'zod'
const signupSchema = z.object({ email: z.string().trim().email('Enter a valid email address'), age: z.coerce.number().int().min(18, 'You must be 18 or older'),})
const uses = { form: form(signupSchema, { values: { email: '', age: '' }, submit: 'SIGN_UP' }),}
type State = UsesState<typeof uses>type Actions = UsesActions<typeof uses> & { SIGN_UP: FormOutput<typeof uses.form> }
const Signup: Component<State, {}, {}, Actions> = ({ state }) => { const f = state.form.fields return ( <form noValidate> <label>Email <input name="email" value={f.email.value} aria-invalid={f.email.invalid} /></label> <label>Age <input name="age" inputMode="numeric" value={f.age.value} aria-invalid={f.age.invalid} /></label> <button type="submit" disabled={state.form.submitting}>Sign up</button> </form> )}
Signup.uses = usesSignup.model = { // values: { email: string; age: number }, the schema's output SIGN_UP: { HTTP: (state, values) => ({ url: '/api/signup', method: 'POST', json: values, ok: 'form.DONE', error: 'form.ERRORS' }) },}A schema without types (a hand-written one) types the values from values and the output as any. The reply actions are typed too: form.ERRORS takes an error reply, a map { name: message } or a list of issues (FormServerErrors), and form.RESET the whole values (or nothing, for initial).
Diagnostics
Section titled “Diagnostics”With the dev checks on (the Vite plugin in dev, renderComponent in tests): SYG230 a field inside the form whose name isn’t in values, SYG231 a schema that isn’t a Standard Schema, SYG232 a submit dropped while one is in progress (info), SYG233 a value the schema strips from its output, SYG234 a submit action the model doesn’t have, SYG235 a check for an unknown field, or a check request that sets ok/error/latest, SYG236 array rows without an id, SYG237 two forms in one component on the same selector, and SYG239 a schema function that builds a new schema on every call. sygnal-check knows form: an option typo is SYG127, and fields inside the form element are not reported as uncontrolled (SYG111).
processForm()
Section titled “processForm()”For a form without validation, processForm() reads every named field of a form element on its events:
import { processForm } from 'sygnal'
function ContactForm({ state }) { return ( <form className="contact-form"> <input name="name" aria-label="Name" value={state.name} /> <input name="email" aria-label="Email" value={state.email} /> <textarea name="message" aria-label="Message">{state.message}</textarea> <button type="submit">Send</button> </form> )}
ContactForm.initialState = { name: '', email: '', message: '' }
ContactForm.intent = ({ DOM }) => ({ // Listen only to submit events SUBMIT: processForm(DOM.select('.contact-form'), { events: 'submit' }),
// Listen to all input changes (default: both 'input' and 'submit') FIELD_CHANGE: processForm(DOM.select('.contact-form'))})
ContactForm.model = { FIELD_CHANGE: (state, data) => ({ ...state, name: data.name, email: data.email, message: data.message }), SUBMIT: { STATE: (state) => ({ ...state, submitted: true }), LOG: (state, data) => data // { name: '...', email: '...', message: '...', eventType: 'submit', event } }}processForm() Options
Section titled “processForm() Options”processForm(DOM.select('.my-form'), { events: 'submit', preventDefault: true })| Option | Type | Default | Description |
|---|---|---|---|
events | String or Array | ['input', 'submit'] | Which form events to listen for |
preventDefault | Boolean | true | Whether to call preventDefault() on events |
Return Value
Section titled “Return Value”The stream emits an object with:
- All form field values keyed by their
nameattribute: a string (a file input: itsFile); a<select multiple>an array of its selected values ([]when none), and so does amultipleSelect or Combobox. Checkboxes that share a name (more than one in the form, disabled ones included) give an array of the checked, enabled boxes’ values in document order ([]when none is checked), likeFormData.getAll(); a lone checkbox gives itsvalue("on"without one), no entry when unchecked. Since 7.2; before, both gave the last selected or checked value (none: no entry), sodata.tags.at(-1)is the old value. A group that can render a single box (a filtered list of options) then gives a string: read it as[].concat(data.tags ?? []), or use theformbehavior, whose array fields are arrays however many boxes render event— The raw DOM eventeventType— The event type string (e.g.,'submit','input')