Birch UI v0.1
Pricing

Forms overviewMIT

Render accessible, multi-page forms from a JSON schema with conditional logic, computed values, repeatable sections and validation, free under the MIT license.

Open .md

Birch UI Forms turns a JSON schema into a complete, accessible form: labels, help text, validation messages, conditional questions, calculated totals, repeatable sections and multi-page navigation. You describe the form as data, so it can be stored in a database, edited in the Form Builder or generated on a server, and the same schema renders identically in every framework.

The package has two parts:

Part Import License
Form renderer, schema engine, expressions, validation, JSON Schema converters, i18n @birchui/forms MIT, free for any use
Visual Form Builder @birchui/forms/builder Commercial, one-time purchase per developer
Service request form

Loading demo…

View source

Sample data and small UI helpers are imported from the docs' demos/_shared.ts and demos/_scheduler-data.ts files.

demos/form-renderer.ts
import { createForm } from '@birchui/forms';
import { docsTheme, layout, onDocsThemeChange } from './_shared';
import { serviceRequest } from './_forms-data';

export const meta = { title: 'Service request form', height: 600 };

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  body.style.overflow = 'auto';
  body.style.padding = '16px';
  toolbar.append('Choose "Emergency" to reveal a conditional field. Add units on the second page.');

  const form = createForm(body, {
    schema: serviceRequest,
    data: { company: 'Kestrel Logistics', region: 'Europe' },
    theme: docsTheme(),
  });

  const offs = [
    form.on('valueChange', ({ name, value }) => {
      status.textContent = `${name} = ${JSON.stringify(value)}`;
    }),
    form.on('validate', ({ valid, errors }) => {
      status.textContent = valid
        ? 'All fields are valid.'
        : `${errors.length} field(s) need attention: ${errors.map((e) => e.label).join(', ')}`;
    }),
    form.on('formSubmit', ({ data }) => {
      status.textContent = `Submitted: ${JSON.stringify(data)}`;
    }),
  ];
  status.textContent = 'Values appear here as you type.';
  const stopTheme = onDocsThemeChange((theme) => form.update({ theme }));
  return () => {
    for (const off of offs) off();
    stopTheme();
    form.destroy();
  };
}

Install#

Terminal
npm install @birchui/forms

Styles are injected automatically when a form is created. To load them as a stylesheet instead, pass injectStyles: false and import @birchui/forms/styles.css. Importing the package has no side effects and never touches window, so it is safe in server-rendered code.

A first form#

service-request.ts
import { createForm, type FormSchema } from '@birchui/forms';

const serviceRequest: FormSchema = {
  title: 'Equipment service request',
  description: 'Northgate Facilities. We respond to urgent requests within four hours.',
  completedMessage: 'Thank you. Your request has been logged and a technician will contact you.',
  elements: [
    { type: 'text', name: 'contactName', title: 'Your name', required: true, width: 'half', autocomplete: 'name' },
    { type: 'email', name: 'contactEmail', title: 'Email', required: true, width: 'half' },
    {
      type: 'select',
      name: 'equipment',
      title: 'Equipment',
      required: true,
      choices: [
        { value: 'hvac', text: 'Heating and air conditioning' },
        { value: 'forklift', text: 'Forklift' },
        { value: 'dock-door', text: 'Loading dock door' },
        { value: 'other', text: 'Something else' },
      ],
    },
    { type: 'text', name: 'equipmentOther', title: 'Which equipment?', visibleIf: "{equipment} = 'other'", required: true },
    {
      type: 'radio',
      name: 'urgency',
      title: 'How urgent is it?',
      required: true,
      inline: true,
      choices: ['Routine', 'Within 24 hours', 'Urgent'],
    },
    { type: 'textarea', name: 'problem', title: 'Describe the problem', required: true, rows: 4, maxLength: 2000 },
    { type: 'file', name: 'photos', title: 'Photos', accept: 'image/*', multiple: true, maxFiles: 5, maxSize: 10_000_000 },
  ],
};

const form = createForm(document.querySelector<HTMLElement>('#service-request')!, { schema: serviceRequest });

form.on('formSubmit', async ({ data }) => {
  const body = new FormData();
  for (const [key, value] of Object.entries(data)) {
    if (key === 'photos') for (const file of value as File[]) body.append('photos', file);
    else body.append(key, typeof value === 'string' ? value : JSON.stringify(value));
  }
  await fetch('/api/service-requests', { method: 'POST', body });
});

The Which equipment? question appears only when the user picks "Something else", the photos field accepts up to five images of 10 MB each, and after a valid submission the form shows the completedMessage.

File fields hold browser File objects, so send them with FormData rather than JSON.stringify. Every other value is plain JSON.

The widget contract#

createForm(container, options) renders into container and returns a FormApi. Like every Birch UI widget it has four core members:

Member Purpose
element The form's root <form> element.
update(partial) Change options in place, for example { locale: 'de' }, { readOnly: true } or a new schema. Only the keys you pass change.
on(event, listener) Subscribe to an event. Returns an unsubscribe function.
destroy() Remove the form and release its listeners and timers.

On top of that it has methods to read and write values, validate, submit and navigate pages. See Validation and Multi-page forms, and the full list in the API reference.

TypeScript
form.setValue('urgency', 'Urgent');
console.log(form.getValue('urgency'));
console.log(form.getData());

const { valid, errors } = await form.validate();
const result = await form.submit();

Options#

FormOptionsinterface@birchui/formsFull reference
PropertyTypeDescription
schemaFormSchema—
dataoptionalFormValues—
localeoptionalstring—
messagesoptionalPartial<FormMessages>—
localeTextoptionalLocaleTextInput—
rtloptionalboolean—
validateOnoptionalValidateOn—
readOnlyoptionalboolean—
densityoptionalDensity—
themeoptional'light' | 'dark' | 'auto'—
injectStylesoptionalboolean—
functionsoptionalRecord<string, ExpressionFunction>—
customValidatorsoptionalRecord<string, CustomValidator>—
clearHiddenValuesoptionalClearHiddenValues—
showErrorSummaryoptionalboolean—
initialPageoptionalstring | number—
onDraftoptional(data: FormValues, meta: DraftMeta) => void—
draftDelayoptionalnumber—

data pre-fills the form. onDraft is called with the current data a short time after the user stops typing (draftDelay, 400 milliseconds by default), which makes auto-saving a draft a one-liner:

TypeScript
const saved = localStorage.getItem('service-request-draft');

createForm(container, {
  schema: serviceRequest,
  data: saved ? JSON.parse(saved) : undefined,
  onDraft: (data) => localStorage.setItem('service-request-draft', JSON.stringify(data)),
});

Events#

Event Payload When
ready { data } Once, right after the form is created. Listeners added immediately after createForm() receive it.
valueChange { name, value, data } The user changed a value, setValue() was called, or a repeating entry was added or removed.
formSubmit { data } The form was submitted and every visible field is valid.
validate { valid, errors } A page or the whole form was validated: on Next, on submit and on validate().
pageChange { from, to, page } The visible page changed. page is the new page's name.
formError { message, source? } A schema expression failed to parse or evaluate, a custom validator threw, or a validator is not registered.
TypeScript
form.on('valueChange', ({ name, value }) => console.log(`${name} is now`, value));
form.on('formError', ({ message, source }) => reportToMonitoring('form', message, source));

formError reports problems in the form definition, never user mistakes. When nobody listens for it, the message goes to console.warn. The form keeps working either way: a broken condition falls back to a safe default, such as showing the question.

Use it in your framework#

Forms plugs into the same framework adapters as the grid. There is no special forms package for each framework: pass formDefinition to the adapter's generic factory, once, and use the result like any component. Options become props or inputs, and events become the framework's event syntax.

TSX
import { createReactComponent } from '@birchui/react';
import { formDefinition, type FormApi } from '@birchui/forms';
import { useRef } from 'react';

export const BirchForm = createReactComponent(formDefinition);

export function ServiceRequestForm() {
  const form = useRef<FormApi>(null);
  return (
    <BirchForm
      ref={form}
      schema={serviceRequest}
      onFormSubmit={({ data }) => saveRequest(data)}
      onValueChange={({ name }) => console.log('changed', name)}
    />
  );
}

The Web Component uses the tag name from the definition, birchui-form, and dispatches each event as a kebab-case CustomEvent with the payload in detail. The framework guides, starting with React, explain refs, server rendering and typing for each adapter; everything there applies to forms too.

Theming and density#

Forms use the shared --lq-* design tokens, so a form matches a Birch UI grid on the same page. theme takes 'light', 'dark' or 'auto', and density takes 'compact', 'comfortable' (the default) or 'spacious'. Form-specific tokens include --lq-form-gap, --lq-form-control-height, --lq-form-max-width, --lq-form-danger and --lq-form-input-border. All classes start with lq-form.

CSS
.lq-form {
  --lq-accent: #0f766e;
  --lq-form-max-width: 720px;
  --lq-form-control-height: 40px;
}

Licensing#

The renderer and everything in @birchui/forms is MIT licensed. It never checks a license key, never shows a watermark and needs no purchase, in any number of apps.

The Form Builder, @birchui/forms/builder, is a commercial product: a one-time purchase of $349 per developer with free updates forever and unlimited apps and end users. You only need it if your code imports @birchui/forms/builder. See Pricing.

Next steps#

↑ ↓ to move, Enter to open, Esc to close