Birch UI v0.1
Pricing

Form Builder APIBuilder

Options, methods, events and types of createFormBuilder, with examples for programmatic editing, selection, toolbox control and JSON Schema.

Open .md

createFormBuilder(container, options) from @birchui/forms/builder renders the designer into container and returns a FormBuilderApi. This page is the reference; the builder overview explains the features.

TypeScript
import { createFormBuilder } from '@birchui/forms/builder';

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

Options#

FormBuilderOptionsinterface@birchui/forms/builderFull reference
PropertyTypeDescription
schemaoptionalFormSchema—
licenseKeyoptionalstring—
localeoptionalstring—
localeTextoptionalLocaleTextInput—
rtloptionalboolean—
themeoptional'light' | 'dark' | 'auto'—
densityoptionalDensity—
injectStylesoptionalboolean—
toolboxoptionalreadonly ElementType[]—
functionsoptionalRecord<string, ExpressionFunction>—
customValidatorsoptionalRecord<string, CustomValidator>—
previewDataoptionalFormValues—
initialTaboptionalBuilderTab—
Option Default Effect
schema an empty one-page form The form to edit.
licenseKey the key from setLicenseKey() Your Form Builder or Complete license key.
locale 'en' The language used to show translated schema text, and for the preview and JSON Schema export.
theme 'light' 'light', 'dark' or 'auto'.
density 'comfortable' 'compact', 'comfortable' or 'spacious'.
injectStyles true Set false and import @birchui/forms/styles.css yourself.
toolbox every element type The element types users can add.
functions none Custom expression functions, so the expression editor accepts them and the preview can run them.
customValidators none Custom validators for the preview.
previewData none Sample answers for the preview.
initialTab 'designer' The tab to open first: 'designer', 'json' or 'preview'.

builder.update(partial) changes options in place. A new licenseKey is verified again, theme and density restyle the builder, toolbox re-renders the toolbox, and schema loads a new form like setSchema().

Events#

FormBuilderEventsinterface@birchui/forms/builderFull reference
PropertyTypeDescription
ready{ schema: FormSchema }—
schemaChange{ schema: FormSchema; reason: string }—
selectionChangeBuilderSelection—
save{ schema: FormSchema }—
TypeScript
builder.on('selectionChange', ({ kind, path, element }) => {
  breadcrumb.textContent = kind === 'element' && element ? `Editing ${String((element as { name?: string }).name)}` : kind;
  console.log(path);
});

Methods#

FormBuilderApiinterface@birchui/forms/builderFull reference
MemberTypeDescription
getSchema()() => FormSchema—
setSchema()(schema: FormSchema) => void—
undo()() => boolean—
redo()() => boolean—
canUndo()() => boolean—
canRedo()() => boolean—
select()(ref: ElementRef | null) => boolean—
getSelection()() => BuilderSelection—
addElement()(type: ElementType, at?: ElementPath) => number[] | null—
removeElement()(ref: ElementRef) => boolean—
moveElement()(from: ElementRef, to: ElementPath) => number[] | null—
duplicateElement()(ref?: ElementRef) => number[] | null—
updateElement()(ref: ElementRef, patch: Record<string, unknown>) => boolean—
copy()(ref?: ElementRef) => boolean—
cut()(ref?: ElementRef) => boolean—
paste()(at?: ElementPath) => number[] | null—
addPage()() => number—
removePage()(index: number) => boolean—
setActiveTab()(tab: BuilderTab) => void—
getActiveTab()() => BuilderTab—
exportJSONSchema()() => JsonSchema—
importJSONSchema()(jsonSchema: JsonSchema) => void—
save()() => void—
elementreadonlyHTMLElementInherited from Widget.
update()(options: Partial<FormBuilderOptions>) => voidInherited from Widget.
on()<K extends "ready" | "selectionChange" | "save" | "schemaChange">(event: K, listener: Listener<FormBuilderEvents[K]>) => () => voidInherited from Widget.
destroy()() => voidInherited from Widget.

The schema#

Method Purpose
getSchema() A copy of the current schema. It always uses the pages form, even if you loaded a single-page schema with elements.
setSchema(schema) Loads a different form. Clears the undo history and the selection, opens the first page, and emits schemaChange with the reason 'Load schema'.
save() Emits save with the current schema, the same as the Save button or Ctrl + S.

Addressing elements#

Methods that act on an element take an ElementRef: either the element's name, or an ElementPath, an array of indexes starting with the page:

Path Refers to
[0] The first page.
[0, 2] The third element on the first page.
[1, 0, 3] The fourth element inside the first element, a panel or repeating section, on the second page.

A name is looked up among elements first, then among pages. Methods that insert, such as addElement() and paste(), take a path to the insertion point and return the new element's path, or null if nothing changed.

Editing#

Method Purpose
addElement(type, at?) Adds a new element of type with a default title and a unique name such as text1. Without at, it goes after the selection, inside a selected section, or at the end of the page.
updateElement(ref, patch) Merges properties into an element, or into a page when the path has one index. A property set to undefined is removed.
removeElement(ref) Removes an element.
moveElement(from, to) Moves an element to a new path, including into another page or section. An element cannot move into itself.
duplicateElement(ref?) Inserts a copy after the element, or after the selection.
copy(ref?), cut(ref?) Copy or cut an element, or the selection, to the builder's clipboard.
paste(at?) Inserts the clipboard element. Names are made unique.
addPage() Adds an empty page at the end and returns its index.
removePage(index) Removes a page. A form always keeps at least one page, so removing the last one returns false.

Every edit is one undoable step and emits schemaChange.

TypeScript
const at = builder.addElement('select', [0, 0]);
if (at) {
  builder.updateElement(at, {
    name: 'siteType',
    title: 'Site type',
    required: true,
    choices: ['Warehouse', 'Retail unit', 'Office', 'Construction site'],
  });
}

builder.updateElement('hazardNotes', { visibleIf: "{hazardsFound} = true", required: true });
builder.moveElement('photos', [1, 0]);

History#

Method Purpose
undo(), redo() Step back or forward. Return false when there is nothing to undo or redo.
canUndo(), canRedo() For enabling your own buttons.

Selection and tabs#

Method Purpose
select(ref) Selects an element or a page, or the form with null. Returns false for an unknown reference.
getSelection() The current selection: its kind ('form', 'page' or 'element'), path and element.
setActiveTab(tab), getActiveTab() Switch between 'designer', 'json' and 'preview'.
TypeScript
builder.select('dateOfInspection');
builder.setActiveTab('preview');

JSON Schema#

Method Purpose
exportJSONSchema() The form as JSON Schema, using toJSONSchema() with the builder's locale.
importJSONSchema(jsonSchema) Replaces the form with one built by fromJSONSchema(). Undoable. Parts that could not be imported are listed in one console warning.

The Export and Import toolbar buttons open dialogs that do the same.

Toolbox catalog#

The toolbox definition is exported, which helps when you build your own palette or labels:

Export Purpose
TOOLBOX_ITEMS Every element type with its label and group, such as { type: 'textarea', label: 'Long text', group: 'Basic' }.
typeLabel(type) The display label of a type: typeLabel('dynamicpanel') is "Repeating section".
createDefaultElement(type, nameFor) The element the builder inserts for a type, with your function choosing its name.
TypeScript
import { TOOLBOX_ITEMS } from '@birchui/forms/builder';

const groups = new Map<string, string[]>();
for (const item of TOOLBOX_ITEMS) groups.set(item.group, [...(groups.get(item.group) ?? []), item.label]);

Types#

Type Description
FormBuilderOptions, FormBuilderApi, FormBuilderEvents Options, API and events.
BuilderSelection, SelectionKind The selection and its kind.
BuilderTab 'designer', 'json' or 'preview'.
ElementPath, ElementRef Element addresses.
ToolboxItem, ToolboxGroup Toolbox catalog entries.

All of them, with every property, are in the API reference.

Framework adapters#

formBuilderDefinition (tag name birchui-form-builder, events ready, schemaChange, selectionChange and save) plugs into the generic factories of each adapter, such as createReactComponent(formBuilderDefinition). See the builder overview for examples.

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