# Form Builder

> A visual, keyboard-accessible designer for Birch UI Forms schemas, with drag and drop, a property panel, an expression editor, undo and redo, a JSON view and a live preview.

The Form Builder lets people design forms without writing JSON: product managers building onboarding flows, operations teams maintaining inspection checklists, or your customers configuring their own intake forms inside your SaaS. It edits the same [`FormSchema`](https://docs.birchui.com/forms/schema.md) the renderer displays, so whatever is designed in the builder renders identically with `createForm()`.

> **Form Builder: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md**
>
> The builder is a one-time purchase per developer with free updates forever, unlimited apps and unlimited end users. Without a license key every feature works; non-local hosts show a small watermark and the console shows one warning. The renderer stays MIT.

**Live demo: Form Builder** (runs on the HTML version of this page). Source of `demos/form-builder.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createFormBuilder } from '@birchui/forms/builder';
import { button, docsTheme, layout, onDocsThemeChange } from './_shared';
import { serviceRequest } from './_forms-data';

export const meta = { title: 'Form Builder', height: 620 };

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  const builder = createFormBuilder(body, {
    schema: serviceRequest,
    theme: docsTheme(),
  });
  const undo = button('Undo', () => builder.undo());
  const redo = button('Redo', () => builder.redo());
  const refresh = () => {
    undo.disabled = !builder.canUndo();
    redo.disabled = !builder.canRedo();
  };
  toolbar.append(undo, redo, 'Drag fields from the toolbox, select one to edit its properties, or open the JSON tab.');
  const offs = [
    builder.on('schemaChange', ({ reason, schema }) => {
      const fields = (schema.pages ?? []).reduce((n, page) => n + (page.elements?.length ?? 0), 0);
      status.textContent = `Schema changed (${reason}). ${fields} top-level elements.`;
      refresh();
    }),
    builder.on('selectionChange', ({ kind, element }) => {
      const name = element && 'name' in element ? String(element.name) : '';
      status.textContent = `Selected ${kind}${name ? `: ${name}` : ''}`;
    }),
    builder.on('save', ({ schema }) => {
      status.textContent = `Saved ${JSON.stringify(schema).length.toLocaleString()} characters of JSON.`;
    }),
  ];
  refresh();
  status.textContent = 'Edits appear here.';
  const stopTheme = onDocsThemeChange((theme) => builder.update({ theme }));
  return () => {
    for (const off of offs) off();
    stopTheme();
    builder.destroy();
  };
}
```

## What it includes

- **Toolbox** with every [field type](https://docs.birchui.com/forms/field-types.md), grouped as Basic, Choice, Date and time, Advanced and Layout. Click a type or drag it onto the canvas.
- **Canvas** showing the selected page as a tree of elements, with page tabs for multi-page forms. Drag elements to reorder them, into sections, or onto another page's tab.
- **Property panel** for the selected form, page or element: titles, names, choices, limits, layout width, conditions and validators.
- **Expression editor** for `visibleIf`, `enableIf`, `requiredIf`, computed expressions and expression validators, with field-name suggestions and live error checking as you type.
- **Undo and redo** for every change, up to 200 steps.
- **Copy, cut, paste and duplicate** of elements, with copies renamed so names stay unique.
- **JSON tab** with the schema as editable JSON. **Apply changes** is enabled only when the JSON parses and [`validateSchema()`](https://docs.birchui.com/forms/validation.md#check-schemas-before-you-ship) finds no errors; **Format** and **Revert** are next to it.
- **Preview tab** that runs the form with the real renderer, including your custom functions and validators, and shows the live and submitted data next to it.
- **JSON Schema import and export** from the toolbar.
- **Save** button and `Ctrl` + `S`, which emit a `save` event for you to persist the schema.

Everything is operable from the keyboard; see the [keyboard model](https://docs.birchui.com/forms/accessibility.md#form-builder-keyboard-model).

## Install and create

The builder ships in the same package as the renderer, as the `@birchui/forms/builder` entry point:

```bash
npm install @birchui/forms
```

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

const saved = await fetch('/api/forms/site-inspection').then((r) => r.json() as Promise<FormSchema>);

const builder = createFormBuilder(document.querySelector<HTMLElement>('#designer')!, {
  schema: saved,
  licenseKey: import.meta.env.VITE_BIRCHUI_LICENSE_KEY,
  locale: 'en-GB',
});

builder.on('save', async ({ schema }) => {
  await fetch('/api/forms/site-inspection', {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(schema),
  });
});
```

Give the container a height; the builder fills it, with the toolbox, canvas and property panel side by side on wide screens.

## Events

| Event | Payload | When |
| --- | --- | --- |
| `ready` | `{ schema }` | Once, right after creation. |
| `schemaChange` | `{ schema, reason }` | After every change, including undo, redo, import and `setSchema()`. `reason` is a short description such as `'Edit element'` or `'Undo Edit element'`. |
| `selectionChange` | `{ kind, path, element }` | The selection moved to the form, a page or an element. |
| `save` | `{ schema }` | The user pressed **Save** or `Ctrl` + `S`, or you called `save()`. |

The builder does not store anything itself. Persist on `save`, or auto-save on `schemaChange` with a debounce:

```ts
let timer: ReturnType<typeof setTimeout> | undefined;

builder.on('schemaChange', ({ schema }) => {
  clearTimeout(timer);
  timer = setTimeout(() => saveDraft(schema), 1000);
});
```

## Undo and redo

Each change is one undo step: adding, moving, editing or removing an element, adding a page, applying JSON. Typing in the same property within about one and a half seconds is merged into a single step, so undo does not go back one letter at a time. The history keeps the last 200 steps and is cleared by `setSchema()`, since that loads a different form.

Use the toolbar buttons, `Ctrl` + `Z` and `Ctrl` + `Shift` + `Z` (or `Ctrl` + `Y`), or the API:

```ts
undoButton.disabled = !builder.canUndo();
builder.undo();
builder.redo();
```

While the user is typing in a text field, the undo shortcuts are left to the browser, so they undo the typing.

## Copy and paste

`Ctrl` + `C`, `Ctrl` + `X` and `Ctrl` + `V` on a selected element copy, cut and paste it within the builder; `Ctrl` + `D` duplicates it in place. Pasted and duplicated elements, including the fields inside a copied section, get new names so the form stays valid. The clipboard belongs to the builder instance and does not touch the system clipboard.

## Preview with your own functions and validators

Pass the same `functions` and `customValidators` you give `createForm()`, so expressions using them are not reported as unknown and the preview behaves like production. `previewData` fills the preview with sample answers.

```ts
createFormBuilder(container, {
  schema: saved,
  functions: { businessDaysBetween },
  customValidators: { inServiceArea },
  previewData: { siteName: 'Trafford Park depot', inspector: 'Grace Okafor' },
});
```

## Limit the toolbox

`toolbox` lists the element types users can add. Use it to keep a builder simple, or to hide types your backend does not handle:

```ts
createFormBuilder(container, {
  schema: saved,
  toolbox: ['text', 'textarea', 'number', 'select', 'radio', 'checkbox', 'date', 'rating', 'markdown', 'panel'],
});
```

Elements of other types that already exist in the schema can still be edited.

## Show the result with the renderer

The schema from `getSchema()`, the `save` event or `schemaChange` is ready for `createForm()`:

```ts
import { createForm } from '@birchui/forms';

const preview = createForm(previewContainer, { schema: builder.getSchema() });
builder.on('schemaChange', ({ schema }) => preview.setSchema(schema));
```

## Use it in your framework

The builder plugs into the framework adapters through `formBuilderDefinition`, exactly like the renderer uses `formDefinition`; see [Use it in your framework](https://docs.birchui.com/forms/overview.md#use-it-in-your-framework).

**React**

```tsx
import { createReactComponent } from '@birchui/react';
import { formBuilderDefinition, type FormBuilderApi } from '@birchui/forms/builder';
import type { FormSchema } from '@birchui/forms';
import { useRef } from 'react';

const BirchFormBuilder = createReactComponent(formBuilderDefinition);

export function InspectionDesigner({ schema }: { schema: FormSchema }) {
  const builder = useRef<FormBuilderApi>(null);
  return (
    <BirchFormBuilder
      ref={builder}
      style={{ height: 720 }}
      schema={schema}
      onSave={({ schema: next }) => saveSchema(next)}
    />
  );
}
```

**Vue**

```vue
<script setup lang="ts">
import { createVueComponent } from '@birchui/vue';
import { formBuilderDefinition } from '@birchui/forms/builder';

const BirchFormBuilder = createVueComponent(formBuilderDefinition);
</script>

<template>
  <BirchFormBuilder style="height: 720px" :schema="schema" @save="({ schema }) => saveSchema(schema)" />
</template>
```

**Web Component**

```html
<birchui-form-builder id="designer" style="display: block; height: 720px"></birchui-form-builder>

<script type="module">
  import { createElementRegistration } from '@birchui/element';
  import { formBuilderDefinition } from '@birchui/forms/builder';

  createElementRegistration(formBuilderDefinition).define();

  const designer = document.querySelector('#designer');
  designer.options = { schema: savedSchema, licenseKey: 'LQ1.eyJ2IjoxLCJpZCI6...' };
  designer.addEventListener('save', (event) => saveSchema(event.detail.schema));
</script>
```

## Licensing

The Form Builder is a commercial product; the renderer is MIT and never needs a key.

| Tier | Price | Seats |
| --- | --- | --- |
| Developer | $349 | One named developer |
| Team | $1,299 | Up to 5 developers |
| Company | $3,499 | Unlimited developers in one organization |

Each is a one-time payment with free updates forever, including major versions, and unlimited apps and end users. Colleagues who only build or deploy the app need no seat. The Birch UI Complete bundle includes the builder. See [Pricing](https://docs.birchui.com/getting-started/pricing.md) and [Licensing & activation](https://docs.birchui.com/getting-started/licensing.md).

Activate it with the `licenseKey` option, or once for the whole app with `setLicenseKey()` from `@birchui/license`:

```ts
import { setLicenseKey } from '@birchui/license';

setLicenseKey(import.meta.env.VITE_BIRCHUI_LICENSE_KEY);
```

Keys for the Form Builder and for the Complete bundle are accepted. The key is checked offline, in the browser, without network calls. Without a valid key:

- every feature keeps working;
- a small watermark appears in the builder's corner on non-local hosts (not on `localhost`, `127.0.0.1` or `*.local`);
- the console shows one warning.

Changing the key with `builder.update({ licenseKey })` re-checks it immediately.

## Next

The full list of options, methods and types is on the [Form Builder API](https://docs.birchui.com/forms/builder-api.md) page.
