Use cases
Rendering forms
Render a form from a schema in your Featurevisor project, so a new field, a new title or a retired choice ships in a pull request rather than a release. This guide describes a sign up form once, then renders it with plain React, with React Hook Form and with TanStack Form.
Experimental
@featurevisor/schemas is experimental, so its API may change in a minor release.
How it works#
- A schema holds the form's rules, and its annotations hold what people read: titles, placeholders, help, the order of fields and labels for choices.
- A component renders each field from the schema's handle, so the form follows each new datafile, whichever way you render it.
- The same handle validates in the browser, in a form library and on the server, from one definition.
- Read Describe the form, then the section for the way you render. The sections from Render nested fields and lists on apply to all three.
Describe the form#
Define the vocabulary#
Your forms share a vocabulary of annotations: the names a field's annotations may use, such as a placeholder or help text, beside the built in title. Define it first, as a schema of its own:
description: What our forms say about a form and its fieldstype: objectproperties: placeholder: type: string help: type: string input: type: string enum: [text, email, password, select, checkbox, combobox] autocomplete: type: string hidden: type: boolean submitLabel: type: stringWrite the form#
The sign up form names that vocabulary in annotationsSchema, so lint checks every annotation in the file against it, and lists its fields in the order people fill them in:
description: A sign up formtags: - webannotationsSchema: schema: formAnnotationstype: objectproperties: email: type: string pattern: ^[^@\s]+@[^@\s]+$ annotations: title: Email address input: email autocomplete: email displayName: type: string minLength: 2 maxLength: 40 annotations: title: Display name help: Shown beside your reviews country: type: string enum: [nl, de] annotations: title: Country options: nl: title: Netherlands de: title: Germanyrequired: [email, displayName, country]annotations: title: Create your account submitLabel: Sign up order: [displayName, email, country]The web app's target delivers it by its tag, as Schemas shows.
Share a list of choices#
Countries appear in more than one form, with more than a title each. Make the list a schema of its own, with what each choice carries in its optionSchema:
description: What a country choice carriestype: objectproperties: flag: type: string hidden: type: booleandescription: Countries we sell tooptionSchema: schema: countryOptiontype: stringenum: [nl, de, be]annotations: options: nl: title: Netherlands flag: nl de: title: Germany flag: de be: title: Belgium flag: be hidden: trueThe form references it, with its own title beside the reference:
# ...properties: # ... country: schema: country annotations: title: CountryEvery form's select lists Netherlands and Germany, from the shared list. Belgium is accepted ahead of its launch, and hidden leaves it out of the list until then. A custom select can show option.flag beside each title. Adding a country to every form is now one pull request.
hidden changes only what a form shows. The web app's datafile lists Belgium for anyone who reads it, and its sign up accepts be from anyone who sends it. Remove be from the enum to stop accepting it before launch.
Reveal a field for businesses#
A business account gives a VAT number, and a personal one never sees the field. Add the two fields, with the VAT number hidden, and a mutation that requires and shows it for businesses:
# ...properties: # ... accountType: type: string enum: [personal, business] annotations: title: Account options: personal: title: Personal business: title: Business taxId: type: string annotations: title: VAT number hidden: truerequired: [email, displayName, country, accountType]annotations: title: Create your account submitLabel: Sign up order: [displayName, email, country, accountType, taxId]mutations: - key: business conditions: - input: accountType operator: equals value: business mutate: required:appendUnique: taxId properties.taxId.annotations.hidden: false# ...properties: # ... accountType: type: string enum: [personal, business] annotations: title: Account options: personal: title: Personal business: title: Business taxId: type: string annotations: title: VAT number hidden: truerequired: [email, displayName, country, accountType]annotations: title: Create your account submitLabel: Sign up order: [displayName, email, country, accountType, taxId]mutations: - key: business conditions: input('accountType') == 'business' mutate: required:appendUnique: taxId properties.taxId.annotations.hidden: falseA handle's withInput applies the mutations that match what was typed so far, to rules and annotations alike, so once Business is chosen the VAT number appears, with required on its input, before anything is sent. Each way of rendering below passes it the form's values, and none of them names the field.
Start with a choice made#
Most people sign up from the Netherlands, for themselves. Give those fields a default, the value a form starts with:
# ...properties: # ... country: schema: country annotations: title: Country default: nl accountType: type: string enum: [personal, business] annotations: title: Account default: personal options: personal: title: Personal business: title: BusinessEvery way of rendering below starts from them, through one helper that collects each field's default:
export function defaultsOf(schema) { const defaults = {} for (const field of schema.fields) { if (field.annotations.default !== undefined) { defaults[field.name] = field.annotations.default } else if (field.renderAs === 'object') { const nested = defaultsOf(field) if (Object.keys(nested).length > 0) defaults[field.name] = nested } } return defaults}defaultsOf(signUp) gives { country: 'nl', accountType: 'personal' }. An object without a default of its own starts from its fields' defaults, as nested fields do. Validation never fills a default in, so a request that leaves out the country still fails.
Render with plain React#
Render each field#
One component renders any field: a select for choices, a checkbox for a boolean and an input for the rest. It takes the title, placeholder and help from the field's annotations, and the HTML attributes from its rules:
export function Field({ field, value, errors }) { const { title, placeholder, help, input, autocomplete } = field.annotations const renderAs = input ?? field.renderAs return ( <label> {title ?? field.name} {renderAs === 'select' ? ( <select name={field.path} defaultValue={value} {...field.constraints}> {field.options .filter((option) => !option.hidden) .map((option) => ( <option key={option.value} value={option.value}> {option.title ?? option.value} </option> ))} </select> ) : renderAs === 'boolean' ? ( <input type="checkbox" name={field.path} defaultChecked={value} /> ) : ( <input name={field.path} type={renderAs === 'number' ? 'number' : input ?? 'text'} defaultValue={value} placeholder={placeholder} autoComplete={autocomplete} {...field.constraints} /> )} {help && <small>{help}</small>} {errors?.map((error) => ( <p key={error} role="alert"> {error} </p> ))} </label> )}Render the form#
The form reads its values with fromFormData whenever they change, and renders the schema's fields, in their order, from withInput. It sits under a FeaturevisorProvider:
'use client'import { useActionState, useState } from 'react'import { initialFormState } from '@featurevisor/schemas'import { useSchema } from '@featurevisor/schemas/react'import { signUpAction } from '../actions'import { defaultsOf } from '../defaults'import { Field } from './Field'export function SignUpForm() { const [state, action] = useActionState(signUpAction, initialFormState) const schema = useSchema('signUp') const [values, setValues] = useState(state.values ?? defaultsOf(schema)) const signUp = schema.withInput(values) return ( <form action={action} onChange={(event) => setValues(signUp.fromFormData(new FormData(event.currentTarget))) } > <h1>{signUp.annotations.title}</h1> {signUp.fields .filter((field) => !field.annotations.hidden) .map((field) => ( <Field key={field.path} field={field} value={values[field.path]} errors={state.errors.fieldErrors[field.path]} /> ))} <button>{signUp.annotations.submitLabel ?? 'Continue'}</button> </form> )}It renders Create your account over a display name of 2 to 40 characters with its help text, an email input with its placeholder, a required select of Netherlands and Germany on the Netherlands, the account select on Personal and a Sign up button. Choosing Business adds the VAT number. values starts from the schema's defaults, or from what the server sent back, and signUp is the form as typed so far, so every member, from fields to annotations, follows the values.
Check a name while typing#
Whether a display name is taken needs your API. A check in code asks it, and useValidation shows the answer as the user types, waiting until they pause:
import { useSchema, useValidation } from '@featurevisor/schemas/react'const checks = { refine: [ { key: 'nameAvailable', path: 'displayName', check: async (displayName, { signal }) => { const name = encodeURIComponent(displayName) const response = await fetch(`/api/names/${name}`, { signal }) const { available } = await response.json() return available }, message: 'That display name is taken', }, ],}export function NameCheck({ displayName = '' }) { const signUp = useSchema('signUp', checks) const result = useValidation(signUp.field('displayName'), displayName, { debounce: 400, }) if (result.validating) return <small>Checking…</small> return result.issues ? <small>{result.issues[0].message}</small> : null}Render <NameCheck displayName={values.displayName} /> in the form, after the fields. It works the same beside a form library. The schema's own rules answer at once, so a one letter name says so without asking the API, and the hook keeps each answer, so the same name is never asked twice.
Submit to a server action#
The form posts to a server action, which validates with the same schema. formAction reads the form data by the schema's types, validates it and answers with the issues by field, or runs your function:
'use server'import { formAction } from '@featurevisor/schemas'import { s } from './featurevisor'const signUp = formAction(s.get('signUp'), async (value) => { const account = await createAccount(value) return { accountId: account.id }})export async function signUpAction(previous, formData) { return signUp(previous, formData)}s is the server's schemas instance, created beside its own SDK instance, as Validating data does. A business without a VAT number gets the form back with Value at "taxId" is required. under the field, and what it typed in place, since the answer carries the values it read. The form works before its JavaScript loads. The browser and the server read the same rules, though while one has a new datafile and the other does not yet, their revisions differ for a moment. Rules that read the context or flags differ too, unless the action gets the request's context, through formAction's context option.
Give the server's handle the same check under the same key, with a database lookup in place of the API call, so its issue matches the browser's.
Render with React Hook Form#
Connect the schema#
A handle is a Standard Schema, so React Hook Form takes it through its Standard Schema resolver. Give the resolver the handle useSchema returns, which stays the same object from render to render:
'use client'import { useForm, useWatch } from 'react-hook-form'import { standardSchemaResolver } from '@hookform/resolvers/standard-schema'import { useSchema } from '@featurevisor/schemas/react'import { defaultsOf } from '../defaults'import { HookField } from './HookField'export function SignUpHookForm({ onSubmit }) { const schema = useSchema('signUp') const form = useForm({ resolver: standardSchemaResolver(schema), defaultValues: defaultsOf(schema), }) useWatch({ control: form.control, name: schema.reads }) const current = schema.withInput(form.getValues()) const paths = current.fields.map((field) => field.path) return ( <form noValidate onSubmit={form.handleSubmit(onSubmit)}> <h1>{current.annotations.title}</h1> {current.fields .filter((field) => !field.annotations.hidden) .map((field) => ( <HookField key={field.path} field={field} form={form} deps={schema.reads.includes(field.path) ? paths : undefined} /> ))} <button>{current.annotations.submitLabel ?? 'Continue'}</button> </form> )}schema is the handle the resolver validates with, and current the same schema with the values typed so far, which the form renders. A handle from withInput is a new object each time, so it never goes to the resolver. defaultValues starts the form from the schema's defaults, and deps is for validating again.
Watch what the rules read#
schema.reads lists the fields the schema's conditions read, here accountType. useWatch renders the form again only when one of them changes, rather than on every keystroke, and current then follows the new values. form.watch() in its place works too, at the cost of a render per keystroke.
Render the fields#
Each field registers with the form, and shows its error from the form's state:
export function HookField({ field, form, deps }) { const { title, placeholder, help, input, autocomplete } = field.annotations const renderAs = input ?? field.renderAs const { error } = form.getFieldState(field.path, form.formState) const control = form.register(field.path, { setValueAs: (value) => (value === '' ? undefined : value), deps, }) return ( <label> {title ?? field.name} {renderAs === 'select' ? ( <select {...control} {...field.constraints}> {field.options .filter((option) => !option.hidden) .map((option) => ( <option key={option.value} value={option.value}> {option.title ?? option.value} </option> ))} </select> ) : renderAs === 'boolean' ? ( <input type="checkbox" {...control} /> ) : ( <input {...control} {...field.constraints} type={input ?? 'text'} placeholder={placeholder} autoComplete={autocomplete} /> )} {help && <small>{help}</small>} {error && <p role="alert">{error.message}</p>} </label> )}React Hook Form keeps an empty input as '', which is a value, so an empty display name would report minLength rather than required. setValueAs turns '' into undefined, which validation counts as missing, so an empty email reports Value at "email" is required., as it does in a form that posts.
Validate again when a choice changes#
After the first submit, React Hook Form validates a field again each time it changes, but only that field. Choosing Business makes the VAT number required, which would show only at the next submit. deps names the fields to validate with it, so a field the rules read, here accountType, validates every field.
Choosing Business after a submit now shows Value at "taxId" is required. at once. Before the first submit nothing shows early, since React Hook Form validates on submit first.
Validate as people leave a field#
To show a field's issue as soon as someone leaves it, rather than at the first submit, give useForm a mode:
const form = useForm({ resolver: standardSchemaResolver(schema), defaultValues: defaultsOf(schema), mode: 'onTouched',})Typing nope in the email and moving on says Value at "email" does not match the expected pattern. before anything is sent, while fields nobody has touched stay quiet. A touched field then validates again on every change.
Keep each issue's code#
React Hook Form's Standard Schema resolver keeps each issue's message but sets its type to '', so a form that styles or words errors by code loses it. A resolver of your own keeps it:
import { toNestErrors } from '@hookform/resolvers'export function featurevisorResolver(schema) { return async (values, context, options) => { const result = await schema.validate(values, { context }) if (!result.issues) return { values, errors: {} } const errors = {} for (const issue of result.issues) { const name = issue.path.join('.') errors[name] ??= { type: issue.code, message: issue.message } } return { values: {}, errors: toNestErrors(errors, options) } }}Give useForm featurevisorResolver(schema) in place of standardSchemaResolver(schema). An empty email's error then has type: 'required', and an invite's email that does not match has type: 'pattern', each under its field. It also hands useForm's context to the schema, so a rule a mutation sets for German users applies to a form given context: { country: 'de' }.
Leave hidden fields out#
A field that becomes hidden keeps its value. Choose Business, type a VAT number, go back to Personal, and the form still sends taxId. shouldUnregister drops a field's value when its input goes away:
const form = useForm({ resolver: standardSchemaResolver(schema), defaultValues: defaultsOf(schema), shouldUnregister: true,})The same steps now submit no taxId.
Submit#
handleSubmit runs the resolver first, and calls onSubmit only with a value that passed every rule:
<SignUpHookForm onSubmit={(value) => fetch('/api/sign-up', { method: 'POST', body: JSON.stringify(value) }) }/>The server validates it again with the same schema, through s.parse, as Validating data shows.
Give useSchema the name check too, and the resolver runs it before submitting. After the first submit, React Hook Form validates again on every change, so the check asks your API at each keystroke. reValidateMode: 'onBlur' in useForm waits until the field loses focus, or leave the check out of the resolver and show it with NameCheck, which waits for a pause.
Render with TanStack Form#
Connect the schema#
TanStack Form takes a Standard Schema as a validator directly. Give it the handle useSchema returns:
'use client'import { revalidateLogic, useForm, useSelector } from '@tanstack/react-form'import { useSchema } from '@featurevisor/schemas/react'import { defaultsOf } from '../defaults'import { TanStackField } from './TanStackField'export function SignUpTanStackForm({ onSubmit }) { const schema = useSchema('signUp') const form = useForm({ defaultValues: defaultsOf(schema), validationLogic: revalidateLogic(), validators: { onDynamic: schema }, onSubmit: ({ value }) => onSubmit(value), }) const values = useSelector(form.store, (state) => state.values) const current = schema.withInput(values) return ( <form noValidate onSubmit={(event) => { event.preventDefault() form.handleSubmit() }} > <h1>{current.annotations.title}</h1> {current.fields .filter((field) => !field.annotations.hidden) .map((field) => ( <form.Field key={field.path} name={field.path}> {(control) => <TanStackField field={field} control={control} />} </form.Field> ))} <button>{current.annotations.submitLabel ?? 'Continue'}</button> </form> )}revalidateLogic() validates the whole form when it is submitted, then again on every change, as React Hook Form does, and onDynamic is the validator it runs. Each issue goes on its field, so choosing Business after a submit shows Value at "taxId" is required. at once. defaultValues starts the form from the schema's defaults.
Follow the values typed so far#
useSelector reads the form's values, and renders the form again when they change. current is the schema with those values, so choosing Business adds the VAT number.
Render the fields#
TanStack Form's inputs are controlled, so each field reads its value from the form and writes every change back. Its errors are the schema's issues, each with its message:
export function TanStackField({ field, control }) { const { title, placeholder, help, input, autocomplete } = field.annotations const renderAs = input ?? field.renderAs const { value } = control.state const change = (next) => control.handleChange(next === '' ? undefined : next) return ( <label> {title ?? field.name} {renderAs === 'select' ? ( <select name={field.path} value={value ?? ''} onChange={(event) => change(event.target.value)} onBlur={control.handleBlur} {...field.constraints} > {field.options .filter((option) => !option.hidden) .map((option) => ( <option key={option.value} value={option.value}> {option.title ?? option.value} </option> ))} </select> ) : renderAs === 'boolean' ? ( <input type="checkbox" name={field.path} checked={value ?? false} onChange={(event) => control.handleChange(event.target.checked)} /> ) : ( <input name={field.path} value={value ?? ''} onChange={(event) => change(event.target.value)} onBlur={control.handleBlur} {...field.constraints} type={input ?? 'text'} placeholder={placeholder} autoComplete={autocomplete} /> )} {help && <small>{help}</small>} {control.state.meta.errors.map((error) => ( <p key={error.message} role="alert"> {error.message} </p> ))} </label> )}change writes an empty input as undefined, which validation counts as missing, so an empty display name reports required, as it does in a form that posts.
Validate as people leave a field#
revalidateLogic takes a mode for before the first submit. With blur, the whole form validates each time someone leaves a field:
validationLogic: revalidateLogic({ mode: 'blur' }),Every field then has its issues from the first blur, so in TanStackField show a field's issues only once it has been touched, or once the server reports one:
const { value, meta } = control.stateconst shown = meta.isTouched || meta.errorMap.onServer ? meta.errors : []Render shown in place of control.state.meta.errors. Typing nope in the email and leaving it shows Value at "email" does not match the expected pattern. alone. A submit touches every field, so every issue shows then.
Leave hidden fields out#
TanStack Form keeps a hidden field's value too. Leave it out when submitting, through the schema's view of the values:
export function visibleValues(schema, values) { const hidden = schema .withInput(values) .fields.filter((field) => field.annotations.hidden) .map((field) => field.name) return Object.fromEntries( Object.entries(values).filter(([name]) => !hidden.includes(name)), )}onSubmit: ({ value }) => onSubmit(visibleValues(schema, value)),Choosing Business, typing a VAT number and going back to Personal then submits no taxId.
Submit#
onSubmit gets the form's value once it passes every rule:
<SignUpTanStackForm onSubmit={(value) => fetch('/api/sign-up', { method: 'POST', body: JSON.stringify(value) }) }/>The server validates it again with s.parse, as Validating data shows.
Give useSchema the name check too, and the handle can answer later, which TanStack Form's synchronous validators refuse with async function passed to sync validator, submitting nothing. Give it as onDynamicAsync instead, with a pause before each check:
validators: { onDynamicAsync: schema, onDynamicAsyncDebounceMs: 400,},After the first submit it asks your API once the user pauses, rather than at every keystroke.
Validate on the server#
In Next.js, TanStack Form's createServerValidate reads form data with decode-formdata, which keeps an empty input as ''. A schema counts '' as given, so a business with an empty VAT number passes. Read the form with fromFormData instead, and answer in TanStack Form's server state:
'use server'import { initialFormState, standardSchemaValidators,} from '@tanstack/react-form-nextjs'import { s } from './featurevisor'export async function signUpAction(previous, formData) { const signUp = s.get('signUp') const values = signUp.fromFormData(formData) const errors = await standardSchemaValidators.validateAsync( { value: values, validationSource: 'form' }, signUp, ) if (errors) { return { errorMap: { onServer: errors }, values, errors: [errors.form] } } await createAccount(values) return initialFormState}The form merges what the action answers, as TanStack Form's Next.js guide shows:
const [state, action] = useActionState(signUpAction, initialFormState)const form = useForm({ defaultValues: defaultsOf(schema), validationLogic: revalidateLogic(), validators: { onDynamic: schema }, transform: useTransform((base) => mergeForm(base, state), [state]),})Give the form action={action} and onSubmit={() => form.handleSubmit()}. A business without a VAT number gets the form back with Value at "taxId" is required. under the field. The server validates with its own datafile and its instance's context, so rules that read the context or flags can differ from the browser's unless it validates with the request's context, as Validating data does.
Render nested fields and lists#
Describe them#
A group of settings is an object, and a list of rows is an array of objects. Each invite needs an email address, and an invite to an admin needs a name too:
# ...properties: # ... notifications: type: object properties: email: type: boolean annotations: title: By email default: true sms: type: boolean annotations: title: By text message default: false annotations: title: Notify me order: [email, sms] invites: type: array maxItems: 3 items: type: object properties: email: type: string pattern: ^[^@\s]+@[^@\s]+$ annotations: title: Email address name: type: string annotations: title: Name admin: type: boolean annotations: title: Admin required: [email] annotations: order: [email, name, admin] mutations: - key: adminInvite conditions: - input: admin operator: equals value: true mutate: required:appendUnique: name annotations: title: Invite your team default: []annotations: # ... order: - displayName - email - country - accountType - taxId - notifications - invites# ...properties: # ... notifications: type: object properties: email: type: boolean annotations: title: By email default: true sms: type: boolean annotations: title: By text message default: false annotations: title: Notify me order: [email, sms] invites: type: array maxItems: 3 items: type: object properties: email: type: string pattern: ^[^@\s]+@[^@\s]+$ annotations: title: Email address name: type: string annotations: title: Name admin: type: boolean annotations: title: Admin required: [email] annotations: order: [email, name, admin] mutations: - key: adminInvite conditions: input('admin') == true mutate: required:appendUnique: name annotations: title: Invite your team default: []annotations: # ... order: - displayName - email - country - accountType - taxId - notifications - invitesdefaultsOf(signUp) now also gives notifications: { email: true, sms: false } and invites: [], so both boxes start as the schema says and the list starts empty, as React Hook Form's useFieldArray and TanStack Form's array fields expect.
adminInvite sits in items, so it checks each row on its own, as Change each row of a list explains. An admin invite without a name reports Value at "invites.1.name" is required., and the other rows stay valid.
Render them with React Hook Form#
A component of its own renders an object's fields in a fieldset, a list's rows with useFieldArray, and any other field with HookField:
import { useFieldArray } from 'react-hook-form'import { HookField } from './HookField'export function HookFields({ fields, form, deps }) { return fields .filter((field) => !field.annotations.hidden) .map((field) => field.renderAs === 'object' ? ( <fieldset key={field.path}> <legend>{field.annotations.title ?? field.name}</legend> <HookFields fields={field.fields} form={form} deps={deps} /> </fieldset> ) : field.renderAs === 'list' ? ( <HookList key={field.path} handle={field} form={form} deps={deps} /> ) : ( <HookField key={field.path} field={field} form={form} deps={deps?.(field)} /> ), )}function HookList({ handle, form, deps }) { const rows = useFieldArray({ control: form.control, name: handle.path }) return ( <fieldset> <legend>{handle.annotations.title ?? handle.name}</legend> {rows.fields.map((row, index) => ( <div key={row.id}> <HookFields fields={handle.field(String(index)).fields} form={form} deps={deps} /> <button type="button" onClick={() => rows.remove(index)}> Remove </button> </div> ))} <button type="button" onClick={() => rows.append({})}> Add </button> </fieldset> )}Each row is the list's handle at its index, such as invites.0, whose fields have paths such as invites.0.email, which React Hook Form registers as they are. A row's handle comes from current, so ticking Admin makes that row's name required.
schema.reads is now ['accountType', 'invites[].admin'], where [] stands for every row. React Hook Form names each row by its index, so watch the whole list, and match a row's field with its index read as []:
// ...// `invites.0.admin` is `invites[].admin` in `reads`.const everyRow = (path) => path.replace(/\.\d+(?=\.|$)/g, '[]')export function SignUpHookForm({ onSubmit }) { // ... useWatch({ control: form.control, name: schema.reads.map((path) => path.split('[]')[0]), }) const current = schema.withInput(form.getValues()) const paths = current.fields.map((field) => field.path) return ( <form noValidate onSubmit={form.handleSubmit(onSubmit)}> <h1>{current.annotations.title}</h1> <HookFields fields={current.fields} form={form} deps={(field) => schema.reads.includes(everyRow(field.path)) ? paths : undefined } /> <button>{current.annotations.submitLabel ?? 'Continue'}</button> </form> )}The form now renders again as a row changes, and ticking Admin after a submit shows Value at "invites.0.name" is required. at once. An invite of nope reports Value at "invites.0.email" does not match the expected pattern. under its row, and the form submits notifications and invites as the schema describes them.
Render them with TanStack Form#
TanStack Form's array fields take the list, and a field of its own for each row's fields:
import { TanStackField } from './TanStackField'// TanStack Form names a row's field `invites[0].email`.const nameOf = (path) => path.replace(/\.(\d+)(?=\.|$)/g, '[$1]')export function TanStackFields({ fields, form }) { return fields .filter((field) => !field.annotations.hidden) .map((field) => field.renderAs === 'object' ? ( <fieldset key={field.path}> <legend>{field.annotations.title ?? field.name}</legend> <TanStackFields fields={field.fields} form={form} /> </fieldset> ) : field.renderAs === 'list' ? ( <TanStackList key={field.path} handle={field} form={form} /> ) : ( <form.Field key={field.path} name={nameOf(field.path)}> {(control) => <TanStackField field={field} control={control} />} </form.Field> ), )}function TanStackList({ handle, form }) { return ( <form.Field name={handle.path} mode="array"> {(list) => ( <fieldset> <legend>{handle.annotations.title ?? handle.name}</legend> {(list.state.value ?? []).map((_, index) => ( <div key={index}> <TanStackFields fields={handle.field(String(index)).fields} form={form} /> <button type="button" onClick={() => list.removeValue(index)}> Remove </button> </div> ))} <button type="button" onClick={() => list.pushValue({})}> Add </button> </fieldset> )} </form.Field> )}In SignUpTanStackForm, render TanStackFields with current.fields in place of mapping them. A handle's path is invites.0.email, so nameOf gives TanStack Form its own name for the field, without which an invite's issue would never reach it. The form already renders again as any value changes, and validates every field after a submit, so ticking Admin needs nothing more.
Word the messages#
Start in English#
A schema words its own issues in messages, field by field, in English to begin with:
# ...messages: email: required: Tell us your email address displayName: minLength: Use at least {minLength} charactersA one letter name now says Use at least 2 characters, in the browser and from the server action alike.
Use translation keys#
Text in a schema suits one language. In a real application, keep the text where your translations already live, and let the schema hold keys. A title, a choice's title and a message can each be a key:
# ...properties: displayName: # ... annotations: title: signUp.displayName.title help: signUp.displayName.helpmessages: displayName: minLength: signUp.displayName.tooShortSchemasProvider gives a key to each issue code you list, for the issues a schema does not word itself, and its message turns each issue's key into text with your translation function, here called t:
import { SchemasProvider } from '@featurevisor/schemas/react'import { t } from './i18n'import { SignUpForm } from './components/SignUpForm'const messages = { required: 'errors.required', pattern: 'errors.pattern', maxLength: 'errors.maxLength',}export default function App() { return ( <SchemasProvider messages={messages} message={(issue) => t(issue.message, issue.params)} > <SignUpForm /> </SchemasProvider> )}In Field, render t(title), t(help) and t(option.title) in place of the text. A key changes on the product's schedule, like any rule, and its text changes in your translation system on its own. Issues carry the field's title, a key here, in params.title, so a translation can name the field.
Ship a field without a deploy#
Marketing wants a newsletter box at sign up. Add the field and its title, and its place in the order:
# ...properties: # ... newsletter: type: boolean annotations: title: Send me product newsannotations: title: Create your account submitLabel: Sign up order: - displayName - email - country - accountType - taxId - newsletter - notifications - invitesOnce it merges and the datafile is deployed, every form shows the checkbox after the account fields, plain React, React Hook Form and TanStack Form alike, with no change to a component and no release. An unchecked box reads as false. Retiring a choice, rewording a title or reordering the form ships the same way.
A form already open shows the change as soon as its datafile arrives, since useSchema renders again when a new datafile changes the schema, or a segment, flag or global variable its conditions read. What it validated before followed the old rules, so validate again when the schema changes. In SignUpHookForm, once the form has been submitted:
useEffect( () => schema.subscribe(() => { if (form.formState.isSubmitted) form.trigger() }), [schema, form],)TanStack Form's revalidateLogic validates with the new rules at the next change.
Suggest choices from your API#
Countries are a short list that changes rarely, so they live in the schema. Cities are far too many for one, so your API suggests them as people type and checks the one they send, while the schema keeps the field's own rules.
Add the field#
Add the city after the country it belongs to, as text with the vocabulary's combobox input:
# ...properties: # ... city: type: string maxLength: 80 annotations: title: City input: combobox placeholder: Start typing your cityannotations: title: Create your account submitLabel: Sign up order: - displayName - email - country - city - accountType - taxId - newsletter - notifications - invitesThe city is optional, and an empty input reads as no city.
Describe where cities come from#
Cities come from your API, so describe them as an option source, whose search asks the API for what was typed in the chosen country:
export const cities = { key: 'cities', path: 'city', reads: ['country'], search: async (query, { input, signal }) => { if (!input?.country) return [] const q = encodeURIComponent(query) const response = await fetch(`/api/cities/${input.country}?q=${q}`, { signal, }) return response.json() },}The API answers with city names, such as ["Amsterdam", "Rotterdam", "The Hague", "Utrecht"], and choices can be values alone.
Suggest cities as people type#
useSearch asks the source once the user pauses, cancels a search the next keystroke makes stale, and keeps the last suggestions while the next ones load. A native datalist offers them, which browsers and screen readers already know:
import { useState } from 'react'import { useSchema, useSearch } from '@featurevisor/schemas/react'import { cities } from '../optionSources'export function CityField({ values, errors }) { const [city, setCity] = useState(values.city ?? '') const field = useSchema('signUp', { optionSources: [cities] }) .withInput(values) .field('city') const { options } = useSearch(field, city, { debounce: 300, minLength: 2, }) const { title, placeholder } = field.annotations const list = `${field.path}-suggestions` return ( <label> {title} <input name={field.path} value={city} onChange={(event) => setCity(event.target.value)} list={list} placeholder={placeholder} autoComplete="off" {...field.constraints} /> <datalist id={list}> {options.map((option) => ( <option key={option.value} value={option.value} /> ))} </datalist> {errors?.map((error) => ( <p key={error} role="alert"> {error} </p> ))} </label> )}In SignUpForm, render it in place of Field for a field whose input is combobox, with the form's values and the field's errors. withInput(values) gives the source the country chosen so far, and a new country searches again, since the source reads it. Nothing asks the API until two letters are typed, and maxLength from the schema applies as it does to any other input.
Check the city on the server#
Which cities exist is your data, so the server's handle gets the same source with a lookup against your database:
'use server'import { formAction } from '@featurevisor/schemas'import { s } from './featurevisor'const cities = { key: 'cities', path: 'city', reads: ['country'], lookup: (city, { input }) => findCity(input.country, city), message: 'Choose a city from the list',}const signUp = formAction( s.get('signUp', { optionSources: [cities] }), async (value) => { const account = await createAccount(value) return { accountId: account.id } },)export async function signUpAction(previous, formData) { return signUp(previous, formData)}findCity is your own lookup, as createAccount is, and returns the city or nothing. A city it cannot find comes back as Choose a city from the list under the field, with what was typed in place. reads: ['country'] holds the lookup back while the country has an issue of its own, so it always gets a country the schema accepts, and a form without a city never reaches it.
Type it#
Code generation types each schema's fields and its vocabularies:
npx featurevisor generate-code \ --language typescript \ --out-dir ./src/generated \ --target=web \ --schemas \ --reactImport useSchema from ./generated in place of the package. A field's annotations.placeholder is then a string, annotations.placholder fails to compile, and so does a field path the schema does not have.
SignUpSchema from ./generated is the schema's type, and a typed defaultsOf keeps it:
import type { SchemaHandle } from '@featurevisor/schemas'export function defaultsOf<T>( schema: SchemaHandle<T, boolean, any>,): Partial<T> { const defaults: Record<string, unknown> = {} for (const field of schema.fields) { if (field.annotations.default !== undefined) { defaults[field.name] = field.annotations.default } else if (field.renderAs === 'object') { const nested = defaultsOf(field) if (Object.keys(nested).length > 0) defaults[field.name] = nested } } return defaults as Partial<T>}React Hook Form takes the type it validates, as useForm<SignUpSchema>, and the defaults fit it. TanStack Form takes its type from defaultValues, so a Partial<SignUpSchema> there would reach onSubmit too. onSubmit only gets a value that passed the schema, so give the defaults as the schema's type, defaultsOf(schema) as SignUpSchema.
Test it#
With every step, schemas/signUp.yml reads:
description: A sign up formtags: - webannotationsSchema: schema: formAnnotationstype: objectproperties: email: type: string pattern: ^[^@\s]+@[^@\s]+$ annotations: title: Email address input: email autocomplete: email displayName: type: string minLength: 2 maxLength: 40 annotations: title: Display name help: Shown beside your reviews country: schema: country annotations: title: Country default: nl city: type: string maxLength: 80 annotations: title: City input: combobox placeholder: Start typing your city accountType: type: string enum: [personal, business] annotations: title: Account default: personal options: personal: title: Personal business: title: Business taxId: type: string annotations: title: VAT number hidden: true newsletter: type: boolean annotations: title: Send me product news notifications: type: object properties: email: type: boolean annotations: title: By email default: true sms: type: boolean annotations: title: By text message default: false annotations: title: Notify me order: [email, sms] invites: type: array maxItems: 3 items: type: object properties: email: type: string pattern: ^[^@\s]+@[^@\s]+$ annotations: title: Email address name: type: string annotations: title: Name admin: type: boolean annotations: title: Admin required: [email] annotations: order: [email, name, admin] mutations: - key: adminInvite conditions: - input: admin operator: equals value: true mutate: required:appendUnique: name annotations: title: Invite your team default: []required: [email, displayName, country, accountType]messages: email: required: Tell us your email address displayName: minLength: Use at least {minLength} charactersannotations: title: Create your account submitLabel: Sign up order: - displayName - email - country - city - accountType - taxId - newsletter - notifications - invitesmutations: - key: business conditions: - input: accountType operator: equals value: business mutate: required:appendUnique: taxId properties.taxId.annotations.hidden: falsedescription: A sign up formtags: - webannotationsSchema: schema: formAnnotationstype: objectproperties: email: type: string pattern: ^[^@\s]+@[^@\s]+$ annotations: title: Email address input: email autocomplete: email displayName: type: string minLength: 2 maxLength: 40 annotations: title: Display name help: Shown beside your reviews country: schema: country annotations: title: Country default: nl city: type: string maxLength: 80 annotations: title: City input: combobox placeholder: Start typing your city accountType: type: string enum: [personal, business] annotations: title: Account default: personal options: personal: title: Personal business: title: Business taxId: type: string annotations: title: VAT number hidden: true newsletter: type: boolean annotations: title: Send me product news notifications: type: object properties: email: type: boolean annotations: title: By email default: true sms: type: boolean annotations: title: By text message default: false annotations: title: Notify me order: [email, sms] invites: type: array maxItems: 3 items: type: object properties: email: type: string pattern: ^[^@\s]+@[^@\s]+$ annotations: title: Email address name: type: string annotations: title: Name admin: type: boolean annotations: title: Admin required: [email] annotations: order: [email, name, admin] mutations: - key: adminInvite conditions: input('admin') == true mutate: required:appendUnique: name annotations: title: Invite your team default: []required: [email, displayName, country, accountType]messages: email: required: Tell us your email address displayName: minLength: Use at least {minLength} charactersannotations: title: Create your account submitLabel: Sign up order: - displayName - email - country - city - accountType - taxId - newsletter - notifications - invitesmutations: - key: business conditions: input('accountType') == 'business' mutate: required:appendUnique: taxId properties.taxId.annotations.hidden: falseA spec keeps the rules people meet in the form, since annotations change nothing a spec checks:
schema: signUpassertions: - description: A personal account signs up value: displayName: Ada country: nl accountType: personal expectedToBeValid: true - description: A business gives a VAT number value: displayName: Ada country: nl accountType: business expectedIssues: - path: [taxId] code: required mutation: business - description: An admin invite needs a name value: displayName: Ada country: nl accountType: personal invites: admin: true expectedIssues: - path: [invites, 1, name] code: required mutation: adminInvite
