Birch UI v0.1
Pricing

Save Form Builder schemas and render themBuilder

Persist schemas from the Form Builder with versioning and server-side checks, then load the published version and render it with createForm.

Open .md

Operations teams design their own inspection and intake forms in the Form Builder; technicians fill them in on site. This recipe saves drafts while the designer works, publishes numbered versions after a schema check, and renders the published version with createForm so every submission records which version it answered.

Steps#

  1. Load the latest draft into createFormBuilder().
  2. Auto-save drafts on schemaChange, debounced, and save explicitly on save.
  3. Publish: check the schema with validateSchema() on the server and store it as a new version.
  4. In the field app, fetch the published version and pass it to createForm().
  5. Submit the answers together with the schema version.

The designer#

inspection-designer.ts
import { createFormBuilder } from '@birchui/forms/builder';
import type { FormSchema } from '@birchui/forms';

const formId = 'site-inspection';
const draft = await fetch(`/api/forms/${formId}/draft`).then((r) => r.json() as Promise<FormSchema>);

const builder = createFormBuilder(document.querySelector<HTMLElement>('#designer')!, {
  schema: draft,
  licenseKey: import.meta.env.VITE_BIRCHUI_LICENSE_KEY,
  customValidators: { inServiceArea: () => true },
});

async function saveDraft(schema: FormSchema) {
  await fetch(`/api/forms/${formId}/draft`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(schema),
  });
  statusLine.textContent = 'Draft saved';
}

let timer: ReturnType<typeof setTimeout> | undefined;
builder.on('schemaChange', ({ schema }) => {
  clearTimeout(timer);
  statusLine.textContent = 'Unsaved changes';
  timer = setTimeout(() => void saveDraft(schema), 1000);
});

builder.on('save', ({ schema }) => {
  clearTimeout(timer);
  void saveDraft(schema);
});

publishButton.addEventListener('click', async () => {
  const response = await fetch(`/api/forms/${formId}/versions`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(builder.getSchema()),
  });
  const result = (await response.json()) as { version?: number; issues?: { path: string; message: string }[] };
  statusLine.textContent = response.ok
    ? `Published version ${result.version}`
    : `Fix before publishing: ${result.issues?.map((issue) => `${issue.path || 'form'}: ${issue.message}`).join('; ')}`;
});

save fires for the toolbar's Save button, Ctrl + S and builder.save(). The builder stores nothing itself.

The builder's preview runs custom validators, so register stand-ins for the ones your schemas reference, as with inServiceArea above. The real implementations live in the app that renders the form.

Publish on the server#

Check every schema before it becomes a version technicians see. validateSchema() reports unknown element types, duplicate names, broken expressions and more. Pass the names of your custom expression functions so they are not reported as unknown:

server/form-versions.ts
import { validateSchema, type FormSchema } from '@birchui/forms';

app.post('/api/forms/:formId/versions', async (request, response) => {
  const schema = request.body as FormSchema;
  const issues = validateSchema(schema, { functions: ['businessDaysBetween'] }).filter(
    (issue) => issue.severity === 'error',
  );
  if (issues.length) return response.status(422).json({ issues });

  const version = await db.formVersions.nextVersion(request.params.formId);
  await db.formVersions.insert({
    formId: request.params.formId,
    version,
    schema: JSON.stringify(schema),
    publishedBy: request.user.id,
    publishedAt: new Date(),
  });
  response.status(201).json({ version });
});

Store each version as a new row instead of overwriting: answers submitted against version 3 should still make sense when version 4 renames a field.

Render the published form#

field-app/inspection.ts
import { createForm, type FormSchema } from '@birchui/forms';

const { version, schema } = await fetch('/api/forms/site-inspection/published').then(
  (r) => r.json() as Promise<{ version: number; schema: FormSchema }>,
);

const form = createForm(document.querySelector<HTMLElement>('#inspection')!, {
  schema,
  customValidators: { inServiceArea },
});

form.on('formSubmit', async ({ data }) => {
  await fetch('/api/inspections', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ formId: 'site-inspection', version, answers: data }),
  });
});

To switch an open form to a newer version without losing answers, call form.setSchema(newSchema). The current data is kept, defaults are applied to new fields, and the form returns to its first page.

Pitfalls#

  • Do not save on every keystroke. schemaChange fires for each edit, including undo and redo. Debounce it.
  • getSchema() always uses pages. A schema loaded with top-level elements comes back as a one-page pages schema. Both render the same.
  • Unregistered validators. If the rendered form names a custom validator that is not registered, formError fires and the value is accepted. Keep the list of validators in one shared module.
  • Renamed fields. Field names are the keys of the submitted data. Renaming a field in a new version starts a new key; migrate reports that read old submissions.

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