Skip to content
No code?Want forms without writing any code?Build them in KraftWizard

Docs

Forms documentation

Render forms from JSON with the MIT renderer, and give your users the designer to build them.

Install

Rendering forms takes two MIT packages. The designer is one more package, licensed, and you only add it where people build forms.

Terminal
npm install @kraftwizard/forms-core @kraftwizard/forms-components

# only where people build forms
npm install @kraftwizard/forms-builder

@kraftwizard/forms-core is a peer dependency of the components and the designer, so your app has one copy of the form engine, and the field types you register are the ones both use.

PackageWhat it isLicence
@kraftwizard/forms-coreThe schema, form store, renderer, and the logic, validation, action and language enginesMIT
@kraftwizard/forms-components64 accessible field componentsMIT
@kraftwizard/forms-themesFive CSS themesMIT
@kraftwizard/expressionsThe evaluator for computed fields, with no evalMIT
@kraftwizard/sanitize-dompurifyThe sanitizer for fields that render HTMLMIT
@kraftwizard/forms-builderThe drag-and-drop designerLicensed

What you need

  • React 18 or 19. Types are included, and every package ships ESM and CommonJS.
  • Any bundler. Each release is installed from its tarballs and built in a fresh Vite app and a Next.js App Router app before it ships.
  • Node.js 22 or later where the packages are installed, built or run on a server.
  • TypeScript's "moduleResolution": "bundler", "node16" or "nodenext" for the subpath entries such as @kraftwizard/forms-core/server/validate; the old "node" resolution doesn't read a package's exports.

Register the components and import their styles

Core draws no fields itself. Register the component set once, at startup or at module scope, and import its stylesheet beside it: the stylesheet is not a side effect of the JavaScript import, so your bundler can drop what you don't use.

forms-setup.ts
import { registerAllComponents } from '@kraftwizard/forms-components';
import '@kraftwizard/forms-components/styles.css';

registerAllComponents(); // safe to call more than once

The stylesheet carries no global reset, and its classes apply only inside a form (.kwf-root). Your app's own .hidden, .flex or .container keep doing what they did before.

Which stylesheet?

styles.css is the default. Its rules are in no cascade layer, so inside a form they beat your app's global button and input styles or a reset. On Tailwind v4, or any app that uses cascade layers, import styles.layer.css from the components and the designer instead: the same rules in a kwf layer after base and before components and utilities, so your utilities on a field win and Tailwind's Preflight doesn't restyle the form. Import it before your own CSS, so its first line sets the layers' order, or start your CSS with @layer theme, base, kwf, components, utilities;.

app.css
@import '@kraftwizard/forms-components/styles.layer.css';
@import '@kraftwizard/forms-builder/styles.layer.css';
@import 'tailwindcss';

Render a form

A form is a JSON schema. Give it to <KraftForm> and you get validation, conditional logic and accessible markup, with nothing else to wire up.

Contact.tsx
import { KraftForm } from '@kraftwizard/forms-core';
import { registerAllComponents } from '@kraftwizard/forms-components';
import '@kraftwizard/forms-components/styles.css';

registerAllComponents();

const schema = {
  id: 'contact',
  version: '1.0.0',
  fields: [
    {
      id: 'f1',
      name: 'fullName',
      type: 'text',
      props: { label: 'Your name', required: true },
      validation: [{ type: 'required', message: 'Name is required' }],
    },
    {
      id: 'f2',
      name: 'email',
      type: 'email',
      props: { label: 'Email address', placeholder: 'name@example.com' },
      validation: [{ type: 'email', message: 'Invalid email address' }],
    },
    {
      id: 'f3',
      name: 'message',
      type: 'textarea',
      props: { label: 'Message', rows: 4 },
    },
    { id: 'f4', type: 'button', props: { label: 'Send', buttonType: 'submit' } },
  ],
};

export function Contact() {
  return <KraftForm schema={schema} handlers={{ onSubmit: (v) => console.log(v) }} />;
}

Submitting logs { fullName: '…', email: '…', message: '…' }: the values, keyed by each field's name, once every field is valid. One submit runs at a time, so a double click doesn't post twice, and what it sends is what it checked: a value typed while a slow validator was still checking is checked too before anything is sent.

Keep the schema object stable: at module scope, in state, or in useMemo. A schema written inline in the JSX is a new object on every render. The form keeps what the user typed, because it compares the schema's content, but it reads the whole schema to do so and every field renders again with the parent, at a cost that grows with the form.

Give every field a name

id is opaque, and the designer generates it. name is the key a value is submitted under, what an error is reported against, and what conditions and expressions refer to. A field without a name submits under its id, as {"text-1738169400123": "…"}, which no backend can use. The designer derives a name from the label for you; when you write a schema by hand, set one.

The label lives in props with the field's other settings. A label set beside type is ignored, and the field renders without one.

field.ts
// Wrong: submits under "field-1" and renders with no label
{ id: 'field-1', type: 'email', label: 'Work email' }

// Right
{ id: 'field-1', name: 'workEmail', type: 'email',
  props: { label: 'Work email', required: true } }

Add a submit button

A button is a field like any other. It submits the form only with buttonType: 'submit'. 'reset' clears the form, and the default, 'button', does neither.

Put fields side by side

Fields stack one per row. columnSpan gives a field a share of a twelve-column grid; consecutive fields share a row until the twelve columns are used up. Containers such as panel, card and wizardStep lay their children out on the same grid.

layout.ts
fields: [
  { id: 'f1', name: 'firstName', type: 'text',
    props: { label: 'First name', columnSpan: 6 } },   // half
  { id: 'f2', name: 'lastName', type: 'text',
    props: { label: 'Last name', columnSpan: 6 } },    // half
  { id: 'f3', name: 'email', type: 'email',
    props: { label: 'Email', columnSpan: 8 } },        // two thirds
  { id: 'f4', name: 'phone', type: 'phone',
    props: { label: 'Phone', columnSpan: 4 } },        // one third
]

Handle what happens

HandlerCalled
handlers.onSubmit(values)Once every field is valid, with the values keyed by name. Also available as the onSubmit prop.
handlers.onChange(values)After every change, with all the values.
handlers.onError(errors)When validation stops a submit, with errors keyed by name, or when onSubmit throws, as { _form: message }.
handlers.onRenderError(error, field?)When a field throws while rendering. That field shows a short notice and the rest of the form keeps working. field is missing when the whole form could not render. Send these to your error tracker.

Edit an existing record

Pass the record as initialValues. If it arrives after the form is on screen, it is loaded as long as the user hasn't started editing. To drive the form from outside, take a handle with formRef:

EditCustomer.tsx
import { useRef } from 'react';
import { KraftForm, type FormHandle } from '@kraftwizard/forms-core';

export function EditCustomer({ customer }: { customer?: Record<string, unknown> }) {
  const form = useRef<FormHandle>(null);
  return (
    <>
      <KraftForm schema={schema} initialValues={customer} formRef={form} onSubmit={save} />
      <button onClick={() => form.current?.reset(customer)}>Discard changes</button>
    </>
  );
}

The handle has getValues(), setValues(values), reset(values?), validate() and submit().

Check a schema before you trust it

A schema is data. It may come from your database, an API or another user, so check it before you render or store it:

check.ts
import { validateSchema } from '@kraftwizard/forms-core';

const { valid, issues } = validateSchema(json);
// issues: [{ path: 'fields[3].name', code: 'duplicate-key', severity: 'error', message: '…' }]

It reports missing or malformed fields, duplicate ids, two fields sharing one name, unregistered types, unknown rule types, operators and actions, references to no field, and computed fields whose dependencies loop. In development builds the form logs these for every schema it renders.

For form files, the package ships a JSON Schema, so your editor or CI checks a form as it is written:

contact.form.json
{
  "$schema": "./node_modules/@kraftwizard/forms-core/schema.json",
  "id": "contact",
  "version": "1.0.0",
  "fields": []
}

Embed the builder

Mount the designer where your users build forms. It hands you the schema on save, and your app owns the database and everything around the designer. Between saves it keeps a draft in the browser's localStorage, offered back when the same form is opened again (storageKey, autosave).

Designer.tsx
'use client';

import { FormBuilder } from '@kraftwizard/forms-builder';
import '@kraftwizard/forms-components/styles.css';
import '@kraftwizard/forms-builder/styles.css';

export default function Designer() {
  return (
    <FormBuilder
      onSave={async (schema) => {
        await fetch('/api/forms', { method: 'POST', body: JSON.stringify(schema) });
      }}
    />
  );
}

The designer registers the built-in field types itself. Those two stylesheets are all it needs. Your app doesn't have to run Tailwind or scan the package, and nothing in them restyles the rest of your page. Try the designer full screen.

It fits the space you give it

The designer lays itself out by its own width, not the window's, so it works in a full page, a tab or a modal. From 1,180 px both side panels are docked. Between 900 and 1,179 px the palette becomes a drawer. Below 900 px both panels are drawers, and the toolbar's secondary actions move into a More menu.

In Next.js

Import it in a client component. The bundles carry their own "use client" banner, so no dynamic() wrapper is needed: the designer renders on the server, and restores its draft and checks its licence once it has mounted.

app/builder/page.tsx
'use client';

import { FormBuilder } from '@kraftwizard/forms-builder';
import '@kraftwizard/forms-components/styles.css';
import '@kraftwizard/forms-builder/styles.css';

export default function BuilderPage() {
  return (
    <div style={{ height: '100vh' }}>
      <FormBuilder onChange={(schema) => console.log(schema)} />
    </div>
  );
}

Open a saved form

Pass it as initialSchema. That replaces what the designer held, with a fresh undo history. Passing a form with another id opens that one; a re-render with the same form keeps the user's edits. onChange fires after every change the user makes, never for the form you opened. See Saving to your own backend for drafts and per-user keys.

What your users get

  • A canvas of your real components. The designer mounts the renderer in design mode and adds selection around each field, so the canvas, the preview, the published form and the PDF are one code path.
  • Five panels. Main (label, name, placeholder, help, size, default and the type's own settings), Style (span on the twelve-column grid, margins, colours), Actions (what runs on change, blur and focus), Rules (validation, and conditions on any other field, with “and” and “or” conditions and an “otherwise”) and Translate, for the field's text in other languages.
  • Templates. Five starters: validation and row layout, conditional logic, a multi-step wizard, containers and repeaters, and dependent selects. Pass your own as templates, a list of { id, name, description?, schema } or a function that fetches one, and they show above the starters; builtInTemplates={false} leaves only yours.
  • Worksheets. Selecting a table edits each column's kind (entry, read-only or calculated), formula, with what is wrong with it as you type, required, unit, decimals and total, a grid of fixedRows presets, and the columnGroups above the columns.
  • Calculations. A field's Main tab turns on computed, with its formula and what is wrong with it as you type, blankWhen and displayOnly, and marks it sensitive.
  • Document details. With no field selected, the inspector writes a controlled document's number, revision, issue date, header and footer to schema.document; with all of them empty there is no document.
  • Generated code. A React component in TypeScript or JavaScript, and a Zod schema that parses exactly what the form posts.
  • The form as JSON. Edit JSON in the toolbar opens the schema as text, with line numbers. What validateSchema finds, formulas included, and where the text stops being JSON, shows as you type; Apply puts the form on the canvas as one step to undo, and stays off while there are errors. Warnings, such as an unregistered type, don't stop it.
  • A theme editor that writes --kwf-* tokens into schema.settings.theme, so the theme travels with the form, plus a PDF export.

Keyboard

Shortcuts act only on keys pressed inside the designer: not elsewhere on your page, not in its dialogs, and not while someone types in a text field.

KeysDoes
TabNext field on the canvas, then the selected field's controls
Enter / SpaceSelect the focused field
Space on the drag handle, arrows, SpaceMove a field without a mouse (Esc cancels)
Alt + ↑ / ↓Move the selected field up or down one place
Cmd/Ctrl + Z, Shift + Cmd/Ctrl + ZUndo, redo
Cmd/Ctrl + DDuplicate
Cmd/Ctrl + C / VCopy, paste a field
Delete / BackspaceDelete the focused field, else the selected one
EscDeselect

Saving to your own backend

KraftWizard stores nothing. Two things travel to your server: the form definitions people design, and the answers people submit.

Save the form definition

The designer calls onSave with the whole schema. Store it as JSON; a JSON column is enough.

FormEditor.tsx
import { FormBuilder } from '@kraftwizard/forms-builder';

export function FormEditor({ form, user }) {
  return (
    <FormBuilder
      initialSchema={form.schema}
      storageKey={`drafts:${user.id}:${form.id}`}
      onSave={async (schema) => {
        await fetch(`/api/forms/${form.id}`, {
          method: 'PUT',
          headers: { 'content-type': 'application/json' },
          body: JSON.stringify(schema),
        });
      }}
    />
  );
}

On the server, check the schema with validateSchema before you store it, and reject it with its issues if it isn't valid.

server/forms.ts
import { validateSchema } from '@kraftwizard/forms-core/server';
import { registerAllComponents } from '@kraftwizard/forms-components';

registerAllComponents(); // so the check knows every field type

export async function saveForm(id: string, body: unknown) {
  const { valid, issues } = validateSchema(body);
  if (!valid) return { status: 422, issues };
  save({ id, schema: body }); // your database
  return { status: 204 };
}

Drafts

The designer autosaves a draft to localStorage and reopens it on the next visit, unless you pass initialSchema. That is a safety net for a refresh, not storage. The key defaults to kraftwizard.forms.builder.draft; in an app with accounts, give each user and form their own, and clear it on sign-out, so a shared computer never hands one person another's unsaved form.

sign-out.ts
import { clearBuilderDraft } from '@kraftwizard/forms-builder';

clearBuilderDraft(`drafts:${user.id}:${form.id}`);

autosave={false} turns drafts off.

Save the answers

onSubmit receives the values keyed by field name, after validation. Values that conditions hide are left out, so post what you receive.

Signup.tsx
<KraftForm
  schema={schema}
  handlers={{
    onSubmit: (values) =>
      fetch('/api/signups', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify(values),
      }),
  }}
/>

Files

A file field's value is a list of { name, size, type, file }, where file is the browser's File. JSON.stringify writes a File as {}, so post a form with files as FormData:

Apply.tsx
import { KraftForm } from '@kraftwizard/forms-core';
import { toFormData } from '@kraftwizard/forms-components';

<KraftForm
  schema={schema}
  handlers={{ onSubmit: (values) => fetch('/api/apply', { method: 'POST', body: toFormData(values) }) }}
/>;

Each file goes under its field's name, or its item path inside a repeater (lines.0.doc). accept and maxSize are checked in the browser only, so check uploads on the server as well. On the server, fromFormData(schema, await request.formData()) from @kraftwizard/forms-core/server/validate gives the values back as the form held them, numbers, ticks, choices, lists and files included, ready for validateValues.

Errors your server finds

An action can ask your server about a field and put the answer on it. The error stays until the user changes that field, and until then it blocks submit:

email-check.ts
import { registerAction } from '@kraftwizard/forms-core';

registerAction('checkEmailFree', async (ctx) => {
  const res = await fetch(`/api/accounts/exists?email=${encodeURIComponent(String(ctx.value))}`);
  const { exists } = await res.json();
  ctx.setError(ctx.fieldId, exists ? 'That address already has an account' : undefined);
});

// On the email field:
// actions: { onBlur: [{ type: 'checkEmailFree' }] }

For errors your server returns after a submit, see Server-side validation.

Theming and dark mode

Forms take your brand, not ours. Pick a theme, follow the system's dark mode, or set the tokens yourself.

Pick a theme

Five themes ship as plain CSS: default, dark, material, bootstrap and compact. Import the ones you use after the component styles, and name one on the form.

Signup.tsx
import '@kraftwizard/forms-components/styles.css';
import '@kraftwizard/forms-themes/default.css';
import '@kraftwizard/forms-themes/material.css';
import { KraftForm } from '@kraftwizard/forms-core';

export const Signup = () => <KraftForm schema={schema} theme="material" />;

Themes are scoped to [data-kwf-theme="<name>"], not :root, so two forms on one page can use different themes. default.css is the base the others adjust, so import it whatever else you use.

Dark mode

Forms follow the operating system through prefers-color-scheme. To force one, pass colorScheme:

Settings.tsx
<KraftForm schema={schema} colorScheme="light" />

Your own theme

A theme is a set of --kwf-* custom properties, with no build step:

brand.css
[data-kwf-theme='brand'] {
  --kwf-primary: #6d28d9;
  --kwf-primary-hover: #5b21b6;
  --kwf-background: #ffffff;
  --kwf-surface: #faf5ff;
  --kwf-border: #e9d5ff; /* dividers and cards */
  --kwf-control-border: #8b5cf6; /* inputs, checkboxes, switches */
  --kwf-text: #1e1b4b;
  --kwf-text-secondary: #6b7280;
  --kwf-text-placeholder: #6b7280;
  --kwf-error: #dc2626; /* invalid borders */
  --kwf-error-text: #b91c1c; /* error messages */
  --kwf-radius: 10px;
  --kwf-spacing: 8px;
  --kwf-font-family: 'Inter', system-ui, sans-serif;
}

Then pass its name as the theme prop, or pass tokens inline, as the designer's theme editor does: theme={{ primary: '#6d28d9', radius: '10px' }}. A theme saved in schema.settings.theme travels with the form; a theme prop wins over it. The --kwf-* names are public API and follow semver.

Keep it readable

The shipped themes meet WCAG AA in light and dark, and a test checks every pairing. Keep a custom theme to the same ratios:

  • --kwf-control-border, the edge of an input, select, checkbox or switch: 3:1 against the background. --kwf-border is for dividers and cards.
  • --kwf-text-placeholder: 4.5:1.
  • --kwf-success-text, --kwf-warning-text, --kwf-error-text and --kwf-info-text, text in a status colour: 4.5:1 on the background and on the status colour's tint.

One field

A field's className and style apply to its wrapper. Its color and backgroundColor props override --kwf-text and --kwf-background for it, so the label, the control and any nested field follow.

The designer's own theme

<FormBuilder theme="dark" /> sets the designer's light or dark look. Its Theme panel edits the theme of the form being designed.

Languages and right-to-left

locale sets the language of everything the form writes itself, such as buttons, calendars and validation messages, and its direction.

Contacto.tsx
<KraftForm schema={schema} locale="es" />

English, Spanish and French ship with the package. A schema can carry its own language in settings.locale; the prop wins over it. Messages already on screen switch when the language does.

Spanish and French from the first paint

English is built in. Spanish and French come in an entry of their own, so a page of English forms never downloads them. Import it once at startup to have them at the first paint, server rendering included:

forms-setup.ts
import '@kraftwizard/forms-core/locales';

Without it they load the first time a form asks for es or fr: the form shows English until they arrive and then switches, and a development build says so in the console. The designer imports them itself, and server-side validation fetches them for the first check that asks.

The form's own text

Labels, placeholders, help, option labels and your rules' messages are translated in the schema, under each field's translations, by locale tag; the form's title and description under settings.translations. The form reads its locale's entry by exact tag, else language, else the text as written, on the server too.

A translated field
{
  "id": "size", "type": "select",
  "props": { "label": "Size", "options": [{ "value": 1, "label": "Small" }] },
  "translations": { "es": { "label": "Talla", "options": { "1": "Pequeña" } } }
}

The designer writes them. Its inspector's Translate tab offers the languages registered and those the form already has text in, or one you add by tag; it lists the selected field's label, placeholder, help, tooltip and other text settings, its option labels and its rules' messages, each with the text as written as its hint, and marks and counts what is not translated yet, for the field and for the whole form. With no field selected, the form's title and description are translated the same way. Each edit is one step to undo; a cleared value takes its key away, and a language with no text writes nothing. Set the form's language (settings.locale) to see a translation on the canvas and in Preview.

Add a language

locales/de.ts
import { KraftForm, registerLocale } from '@kraftwizard/forms-core';

registerLocale({
  code: 'de-DE',
  name: 'Deutsch',
  direction: 'ltr',
  dateFormat: 'DD.MM.YYYY',
  timeFormat: 'HH:mm',
  numberFormat: {
    decimalSeparator: ',',
    thousandsSeparator: '.',
    currencySymbol: '€',
    currencyPosition: 'after'
  },
  translations: {
    ui: { selectDate: 'Datum wählen…', clear: 'Leeren' },
    validation: { required: 'Pflichtfeld' }
  }
});

<KraftForm schema={germanSchema} locale="de-DE" />

A code finds its exact locale, else its language, else any locale of that language: de-AT uses de-DE, and es_ES reads as es-ES. A message can have plural forms, chosen by its count: { one: '{count} item', other: '{count} items' }.

Right to left

Direction follows the language. Arabic, Hebrew, Persian and Urdu forms lay out right to left whether or not you registered a locale for them; settings.direction overrides it. A right-to-left form also prints mirrored to PDF, with Hebrew and Arabic in reading order.

Your own text

Labels, placeholders and help are the strings in your schema, so a form in several languages is one schema per language.

Values don't change with the language

  • Dates are calendar dates, YYYY-MM-DD, and date-times are local wall-clock time, YYYY-MM-DDTHH:mm. Neither shifts with the user's time zone. Use parseLocalDate and formatLocalDate rather than new Date('YYYY-MM-DD'), which parses as UTC.
  • Phone numbers are E.164, such as +919876543210.
  • Option values keep their type: { value: 1 } submits 1.

Custom components

Register your own field type and it works everywhere the built-ins do: the renderer, the designer's palette and properties panel, and the PDF export all read the same registry.

ColourSwatch.tsx
import { registerFieldType, type FieldComponentProps } from '@kraftwizard/forms-core';

function ColourSwatch({ field, value, onChange, error }: FieldComponentProps<string>) {
  return (
    <div className="kwf-field">
      <label className="kwf-label" htmlFor={field.id}>
        {field.props?.label as string}
      </label>
      <input
        id={field.id}
        type="color"
        className="kwf-input"
        value={(value as string) ?? '#000000'}
        onChange={(e) => onChange(e.target.value)}
      />
      {error && <p className="kwf-error-message" role="alert">{error}</p>}
    </div>
  );
}

registerFieldType({
  type: 'colourSwatch',
  component: ColourSwatch,
  label: 'Colour swatch',   // shown in the palette
  category: 'field',
  defaultValue: '#000000',
  a11yFixture: { label: 'Colour' },
});

Settings in the designer

Describe the type's settings and the designer generates its properties panel. supports says which shared settings apply, and impliedRules turns props into validation every field of the type carries.

rating.ts
registerFieldType({
  type: 'rating',
  component: RatingField,
  label: 'Rating',
  category: 'field',
  properties: [
    { key: 'max', label: 'Number of stars', kind: 'number', min: 1, max: 10 },
    { key: 'icon', label: 'Icon', kind: 'select', choices: [
      { value: 'star', label: 'Star' }, { value: 'heart', label: 'Heart' },
    ] },
  ],
  // Which shared settings apply; defaults follow `isInput`.
  supports: { placeholder: false, size: false },
  // Rules every field of this type carries, derived from its props.
  impliedRules: (props) => (props.max ? [{ type: 'max', value: props.max }] : []),
});

Descriptor keys

KeyMeaning
isInputHolds a value. Set false for static content, which is then left out of values, validation and submission.
isContainerAccepts child fields.
ownsChildLayoutFor containers that place their own children. Leave unset to get the twelve-column grid.
ownsChildValuesFor containers whose children are a template, like the repeater. Their values live inside the container's own value.
allowedChildTypesThe only child types this container renders, such as Tabs holding only Tab.
allowedParentTypesWhere the type belongs, such as a Tab only inside Tabs. The designer moves it there.
starterChildrenWhat a new instance starts with, so a freshly placed container is usable.
labelPlacementinline for controls that carry their label beside them, like a checkbox.
propertiesThe settings the designer offers for the type.
supportsWhich shared settings apply: placeholder, size, tooltip, read-only and so on.
impliedRulesValidation every field of the type carries, from its props.
defaultPropsMerged beneath a field's own props.
formatValueThe value as plain text, for PDF and CSV export.
a11yFixtureMinimal props to render the type in a test. The label and axe suites use it for every registered type.

Typed props

Add your types to FieldPropsMap for type-safe props, and author fields with defineField where you want the narrowing:

kraftwizard-forms.d.ts
declare module '@kraftwizard/forms-core' {
  interface FieldPropsMap {
    rating: { max: number; icon?: 'star' | 'heart' };
  }
}

A component that needs form state beyond its own props reads it with useFormState, which re-renders only when the slice it selects changes: const submitCount = useFormState((s) => s.submitCount);

Your own actions

Actions run on a field's onChange, onBlur, onFocus and onClick. Registered actions appear in the designer's Actions panel. The built-in log prints only what an unfinished response keeps: a password or a field marked sensitive shows as [sensitive].

postcode.ts
import { registerAction } from '@kraftwizard/forms-core';

registerAction('lookupPostcode', async (ctx) => {
  const res = await fetch(`/api/postcode/${ctx.value}`);
  const { city } = await res.json();
  ctx.setValue('city', city);
});

// Then, on a field:
// actions: { onBlur: [{ type: 'lookupPostcode' }] }

To scope an action to one form, pass it in <KraftForm actions={{ lookupPostcode }} /> instead.

Your own validators

password.ts
import { registerValidator, type FieldDefinition } from '@kraftwizard/forms-core';

// A validator returns the message to show, or undefined when the value is
// valid. It is given the value, its rule and all of the form's values.
registerValidator('passwordStrength', (value, rule) => {
  const text = String(value ?? '');
  const kinds = [/[A-Z]/, /[a-z]/, /[0-9]/, /[^A-Za-z0-9]/].filter((re) => re.test(text)).length;
  const needed = typeof rule.value === 'number' ? rule.value : 3;
  return kinds >= needed ? undefined : rule.message ?? 'Use a mix of letters, numbers and symbols';
});

// Use it in a field
const password: FieldDefinition = {
  id: 'password',
  type: 'password',
  validation: [
    { type: 'required' },
    {
      type: 'custom',
      validator: 'passwordStrength',
      value: 3,
      message: 'Use at least three of: upper case, lower case, a number, a symbol'
    }
  ]
};

Register validators before a form is shown. A rule naming one that isn't registered fails with “This field could not be checked”, and the console says which name is missing.

Limit the palette

paletteFilter decides which registered types the designer offers, such as hiding signature fields from one customer's users. Types you register appear on their own.

propertyEditors puts your own control in the inspector for a setting, by its key (placeholder) or by type and key (rating.max, which wins). Your component gets { field, name, value, onChange, id, label }; onChange is one change to undo, and the inspector's label names the control with id. By type and key, a setting the type doesn't declare is added under More settings. slots places your own panels: toolbar at the end of the toolbar, and inspector(field) at the foot of the inspector, given null for the form's own settings.

Logic and expressions

Conditions show, hide, enable or set fields from other fields' answers. Computed fields derive a value from an expression. Both are data in the schema, never code.

Show a field when another has a value

company.ts
{
  id: 'f3', name: 'companyName', type: 'text',
  props: { label: 'Company name' },
  conditions: [
    {
      when: { field: 'accountType', operator: 'equals', value: 'business' },
      then: { action: 'show' },
      else: { action: 'hide' },
    },
  ],
}

Operators: equals, notEquals, contains, notContains, startsWith, endsWith, matches, gt, gte, lt, lte, isEmpty and isNotEmpty, plus long-form aliases of the four comparisons. Actions: show, hide, enable, disable, setValue and setProps.

Combine conditions

Nest with and and or, which evaluate as (base AND all(and)) OR any(or):

when.ts
when: {
  field: 'country', operator: 'equals', value: 'US',
  and: [{ field: 'age', operator: 'gte', value: 21 }],
}

A rule acts on the field it is written on, unless a branch names another with target, by id or name. A rule whose when.field is empty is skipped.

The designer's Rules tab builds all of this: + And and + Or on a condition add to its and and or, two levels deep, and Otherwise sets the rule's else. A rule you don't change keeps its shape, with no empty lists added.

What hidden and disabled mean

  • A show or enable rule with no else also means “and otherwise not”: the field stays hidden or disabled until the rule holds.
  • A hidden field, or one inside a hidden container, is not validated, and its value is left out of what onSubmit receives. Set settings.submitHiddenFields: true to submit hidden values anyway.
  • A hidden field reads as empty to other fields' conditions and to computed fields, whatever it still holds, and so does a field hidden because of it. A tick box that hides with true in it no longer keeps the field it controls on screen, and a server checking the submission sees the same form the browser did.
  • A disabled field is not validated, as in HTML, but its value is still submitted.
  • setProps changes validation too: { required: true } makes the field required, and props such as min or pattern bring their rules.

Worksheets

A table with fixedRows holds a technical worksheet. Its rows are presets by column id, and each column has a kind: entry by default, readOnly from the presets, or computed from an expression over the row's cells and the form's fields, worked out by the form and again by validateValues. A column's total adds a footer, unit and decimals set how it reads, and columnGroups adds headers above the columns. On a narrow form each row becomes a card.

A weighted reading
{
  "id": "readings", "name": "readings", "type": "table",
  "props": {
    "label": "Readings",
    "columns": [
      { "id": "minutes", "header": "Minutes", "kind": "readOnly", "type": "number" },
      { "id": "load", "header": "Load", "type": "number", "unit": "kN", "required": true },
      { "id": "weight", "header": "Weight", "kind": "readOnly", "type": "number" },
      { "id": "weighted", "header": "Weighted", "kind": "computed", "expression": "load * weight", "total": "sum" }
    ],
    "fixedRows": [{ "minutes": 0, "weight": 1 }, { "minutes": 30, "weight": 2 }]
  }
}

A blank reading isn't 0: a row stays blank until the cells it names are filled, and a computed field lists what it needs in blankWhen (readings.weighted for a column). Read a column from a formula with sumOf(readings, "weighted"), and give a computed field displayOnly to show a result rather than an input. A form that is a controlled document carries document: { number, revision, issued, header, footer }.

Check a worksheet's formulas before anyone fills it in with validateSchema(schema, { expressions: schemaExpressionIssues }), from @kraftwizard/expressions/checks: what doesn't parse, an unknown function or name, sum(a, b), and ^, which is XOR here. To write a table's answers out elsewhere, tableRows, tableHeaderRows and tableTotal give its rows, header rows and totals as the form shows them; the last two are on @kraftwizard/forms-core/server too.

Computed values

Core ships no expression parser, so a form without computed fields never pays for one. Install the evaluator once at startup; until you do, a computed field keeps whatever value it has and logs a warning.

forms-setup.ts
import { setExpressionEvaluator } from '@kraftwizard/forms-core';
import { evaluateExpression } from '@kraftwizard/expressions';

setExpressionEvaluator(evaluateExpression);
invoice.ts
fields: [
  { id: 'sub', name: 'subtotal', type: 'number',
    props: { label: 'Subtotal' } },
  { id: 'rate', name: 'taxRate', type: 'number',
    defaultValue: 20, props: { label: 'Tax rate (%)' } },

  { id: 'tax', name: 'taxAmount', type: 'number',
    props: { label: 'Tax', readOnly: true },
    computed: {
      expression: 'round(subtotal * taxRate / 100, 2)',
      dependencies: ['subtotal', 'taxRate'],
    } },

  // A computed field may depend on another computed field.
  { id: 'total', name: 'total', type: 'number',
    props: { label: 'Total', readOnly: true },
    computed: {
      expression: 'round(subtotal + taxAmount, 2)',
      dependencies: ['subtotal', 'taxAmount'],
    } },
]

The form store recomputes with every change, including fields that aren't on screen, such as a later wizard step. Computed fields whose dependencies form a cycle are reported in the console and not computed.

The expression language

Expressions refer to other fields by name. They may contain literals, member access, array literals, the ternary, and arithmetic, comparison and logical operators; &&, || and ?? short-circuit. Calls are allowed only to these functions, by name:

FunctionReturns
abs(x) ceil(x) floor(x) sqrt(x)The usual maths on x
log(x) log10(x) exp(x) fixed(x, places)Logarithms, e to a power, and a number as text with fixed decimals. Powers are **: ^ is XOR, as in JavaScript
sumOf(rows, key) median(...xs) stdev(...xs)One column of rows added up, the middle value, and the sample deviation; blanks are left out
round(x, places?)x rounded to places decimals (default 0)
min(...xs) max(...xs) pow(x, y)The smallest or largest argument; x to the power y
sum(list) avg(list) count(list)A list's total, mean (0 when empty) or length
concat(...xs) upper(s) lower(s) trim(s) len(x)Text joined, cased or trimmed; the length of a list or text
substring(s, start, end?) replace(s, search, replacement)Part of s; s with every search replaced, as plain text
split(s, separator) join(list, separator?) contains(x, value)Text to a list and back; whether a list or text contains a value
startsWith(s, prefix) endsWith(s, suffix)Whether s starts or ends with the given text
ifElse(condition, a, b) isEmpty(x) coalesce(...xs)A choice; whether x is empty; the first argument that isn't empty
toNumber(x) toString(x) toBoolean(x)x converted
formatNumber(x, locale?) formatCurrency(x, currency?, locale?)x formatted for a locale, or as money (default USD)
now() today() year(date) daysBetween(a, b)The time as ISO; today as YYYY-MM-DD; a date's year; whole days between dates. A date-time without a zone, as a date-time field holds it, is read as the clock time written, the same in the browser and on a server

Assignment, new, function literals, method calls and any name such as __proto__, constructor or prototype are rejected. There is no window, globalThis or process to reach. Each evaluation is bounded: 256 levels of nesting, 10,000 steps, 100 ms, a million characters in any text it produces (a list turned into text by +, a comparison or json() included, stopped before it is built), 100,000 items in any list, and exponents up to ±1,000. Past a limit it throws an ExpressionError.

Repeating groups

A repeater's children are the fields of one item. Its value is a list of records keyed by those fields' names, and each field keeps its own rules in every item. A condition on an item field reads that item's own fields first, so “show Serial when Type is Hardware” follows each item's Type. An item field's error is keyed by its path, such as lines.1.sku, and itemFieldPath('lines', 1, 'sku') builds the same key.

Server-side validation

The browser's checks help people fill a form in. They don't protect your API: anyone can post to it. Check every submission on the server with the same schema before you store it.

Check a submission

validateValues runs the form store the renderer runs, so the server applies exactly the rules the browser did. It is in its own entry, @kraftwizard/forms-core/server/validate, with no "use client" directive and no React, so it can be called from a route handler or a Server Action:

app/api/forms/[id]/submissions/route.ts
import { setExpressionEvaluator, validateValues } from '@kraftwizard/forms-core/server/validate';
import { evaluateExpression } from '@kraftwizard/expressions';

// Computed fields are computed again on the server, not taken from the request.
setExpressionEvaluator(evaluateExpression);

export async function POST(req: Request) {
  // `form` is the stored form this route serves; `save` writes to your database.
  const result = await validateValues(form.schema, await req.json());
  if (!result.valid) return Response.json({ errors: result.errors }, { status: 422 });
  save(result.values);
  return new Response(null, { status: 201 });
}

It applies required fields, lengths and bounds, each type's own rules (email, URL, phone, date limits), patterns, custom validators and conditions, and always: settings.validateOnSubmit: false only lets the browser submit unchecked. A field that conditions hide is not checked, and its value is left out of values, just as onSubmit leaves it out in the browser. Errors are keyed by field name, or by item path inside a repeater (lines.1.sku), as the form keys them.

A request can carry what the form never would, so the server is stricter. Each value must have its type's shape (text for a text field, a list for a checkbox group), and a choice must be one of the field's options unless the field sets allowCustom. Keys no field holds are dropped from values; pass { keepUnknownKeys: true } to keep them. Computed fields are computed again rather than taken from the request, so a form with any needs setExpressionEvaluator; without it validateValues throws. A schema that is not a valid form, or values that are not an object, come back as { valid: false } with the reason under _form.

The built-in field types are known without registering the components, which a route handler cannot do. Register custom field types and custom validators on the server too, and pass { locale: 'es' } for messages in another language.

'today', in a date limit or a condition, is the respondent's today. Send their time zone with the submission (Intl.DateTimeFormat().resolvedOptions().timeZone in the browser) and pass it as { timeZone }; without it the server reads today in its own zone, which for someone in Auckland is a day behind for half of every day.

Checking a schema rather than a submission? validateSchema, migrateSchema and the form's logic are in @kraftwizard/forms-core/server, which does not carry the form store.

Show the server's errors on the form

useKraftForm(), called inside the form, returns setErrors. Give <KraftForm> children and it renders them inside the form instead of its default renderer:

Signup.tsx
import { useEffect, useRef, type MutableRefObject } from 'react';
import { KraftForm, FormRenderer, useKraftForm } from '@kraftwizard/forms-core';

type SetErrors = (errors: Record<string, string | undefined>) => void;

// Rendered inside the form, so it can reach the form's store.
function ServerErrors({ to }: { to: MutableRefObject<SetErrors | null> }) {
  const { setErrors } = useKraftForm();
  useEffect(() => { to.current = setErrors; }, [to, setErrors]);
  return null;
}

export function Signup() {
  const setErrors = useRef<SetErrors | null>(null);
  return (
    <KraftForm
      schema={schema}
      onSubmit={async (values) => {
        const res = await fetch('/api/forms/signup/submissions', { method: 'POST', body: JSON.stringify(values) });
        if (res.status === 422) setErrors.current?.((await res.json()).errors);
      }}
    >
      <FormRenderer />
      <ServerErrors to={setErrors} />
    </KraftForm>
  );
}

Each error stays on its field until the user changes that field, and until then it blocks another submit.

Typed code from the designer

The designer's Code panel also writes a Zod schema that parses exactly what the form posts, keyed by field name, if you'd rather keep typed validation in your own code. generateCode(schema, 'zod') from @kraftwizard/forms-builder writes the same file. Unlike the store, it doesn't know which fields conditions hide.

Licence keys

The designer needs a licence in production. The renderer, the components and the themes never check one.

Designer.tsx
<FormBuilder licenseKey={process.env.NEXT_PUBLIC_KRAFTWIZARD_LICENSE} />

Without a key

The designer is fully functional and has no time limit. Served from an origin that isn't exempt, it shows an “Unlicensed — evaluation only” watermark in the corner. It never breaks your build, blocks a feature or degrades at runtime. localhost, *.localhost and loopback addresses (127.0.0.1, [::1]) never need a key. A .local name is another machine on the network and needs one, as does 0.0.0.0.

Domains

TierDomainsDeployment
StartUp1Your own product
Business3Your own products
EnterpriseUnlimited, each listedIncludes public SaaS deployment

A key lists its domains, each exactly: there is no wildcard. A licence for acme.com covers app.acme.com only when it was issued with subdomains. Preview deployments are covered when the key lists their project, up to as many as it has domains and at most five, and don't count against the domains: acme.vercel.app covers acme-git-main-team.vercel.app, acme.netlify.app covers deploy-preview-42--acme.netlify.app, and acme.pages.dev covers abc123.acme.pages.dev. Compare the licences.

How a key is checked

  • A key is an ECDSA P-256 signature over a small JSON payload: customer, tier, domains, subdomains and previews, issue date and the date updates run until. It is verified against a public key in the package. There is no network call and no telemetry, and it works air-gapped.
  • On pages served over plain HTTP, where browsers withhold WebCrypto, the check runs in plain JavaScript instead.
  • Keys name the signing key that issued them, so signing keys can rotate, and a single refunded or leaked key can be revoked in a release without touching anyone else's.
  • The licence is perpetual for versions released before your updates end. A lapsed update window never disables what you already run, and a version released after it stays licensed, with no watermark: the console says to renew for updates.

Being a check that runs on the user's machine, it can't stop a determined attacker. It is an honest customer's reminder and a compliance record, which is what the licence terms rest on.

A designer built from the blocks

Composing your own designer from Palette, Canvas, PropertiesPanel, Toolbar, TreeView and PreviewPanel? Wrap them in BuilderLicense, which checks the key once. A block used outside it checks for itself.

MyDesigner.tsx
<BuilderLicense licenseKey={key}>
  <Palette />
  <Canvas />
  <PropertiesPanel />
</BuilderLicense>

Strict Content Security Policy

Forms run under a Content Security Policy without 'unsafe-eval'. Nothing in the packages calls eval or the Function constructor.

Scripts

Computed fields are parsed to a syntax tree and walked by an allowlist interpreter, so a schema from your database can't run code, and script-src 'self' is enough. An expression reads only the form's own values: $("constructor") or $("__proto__") reads nothing, not JavaScript's built-in objects. The designer's PDF export loads jsPDF on demand, as a chunk of your own bundle.

Styles

The stylesheets are files you import, so style-src 'self' covers them. A form also sets a few styles through React, such as grid spans and theme token overrides. On the client React applies them through the DOM, which a policy allows. Server-rendered HTML carries them as style attributes, which a policy without 'unsafe-inline' for style-src-attr blocks: allow that, or render forms on the client.

Features that reach other hosts

FeatureAllow
The callApi actionIts hosts in connect-src. It is off until you list them in allowedApiHosts too.
Image and file previewsblob: and your image hosts in img-src
The googleMap fieldThe hosts Google lists for the Maps JavaScript API
A starting policy
Content-Security-Policy:
  default-src 'self';
  script-src 'self';
  style-src 'self';
  img-src 'self' blob:;
  connect-src 'self' https://api.example.com

The HTML sanitizer

The html and staticText fields render escaped text by default. To render real markup, give the form a sanitizer.

Terms.tsx
import { KraftForm } from '@kraftwizard/forms-core';
import { sanitize } from '@kraftwizard/sanitize-dompurify';

<KraftForm schema={schema} sanitize={sanitize} />;

Pass the same function to <FormBuilder sanitize={sanitize} /> so HTML fields show as HTML on the canvas and in the preview. Opting in is a deliberate act, and a form that never renders markup doesn't pay for DOMPurify's 20 kB.

Why not a regular expression

Sanitizers built from regular expressions are defeated by markup they don't anticipate, so the package wraps DOMPurify, which parses the document instead. Its tests run 18 payloads that beat regex sanitizers and check that nothing executable survives, including:

Payloads it neutralises
<img src=x onerror=alert(1)>        <!-- unquoted handler -->
<svg onload=alert(1)>               <!-- not a script tag -->
<a href="javascript:alert(1)">      <!-- not an attribute handler -->
<iframe srcdoc="<script>…"></iframe>

Configure it

The default profile allows formatting, links, lists and tables. It forbids script, style, iframe, object, embed, form and input, drops every on* handler and javascript: URL, and rejects data-* attributes.

sanitizer.ts
import { createSanitizer } from '@kraftwizard/sanitize-dompurify';

const sanitize = createSanitizer({
  allowedTags: ['b', 'i', 'em', 'strong', 'a', 'p', 'br'],
  allowedAttributes: ['href', 'title'],
});
OptionEffect
allowedTagsReplaces the default tag list
allowedAttributesReplaces the default attribute list
allowImagesAdds <img> with src, alt, width and height. Off by default, because an image URL is a request that can track whoever views the form.

Server rendering

DOMPurify needs a DOM, which a server doesn't have. HTML fields render their text on the server and while the page hydrates, and switch to the sanitized HTML once the page is live.

Renderer

<KraftForm> from @kraftwizard/forms-core: the provider and the renderer in one component.

PropTypeNotes
schemaFormSchemaThe form: fields, rules and settings. Older schemas are migrated on the way in.
initialValuesRecord<string, unknown>Values to start from, keyed by name. Values that arrive later load until the user edits.
formRefRef<FormHandle>getValues(), setValues(values), reset(values?), validate(), submit()
handlersFormEventHandlersonSubmit, onChange, onError, onRenderError, onStepChange, onFieldFocus, onFieldBlur and onPartial
onSubmit(values) => void | PromiseShorthand for handlers.onSubmit
themestring | Record<string, string>A theme name or token overrides. Wins over schema.settings.theme.
colorScheme'light' | 'dark'Overrides the operating system's scheme
localestringLanguage and direction of the built-in text, such as es or ar
sanitize(html) => stringRenders HTML fields as HTML. Without it they show text.
actionsRecord<string, ActionHandler>Actions for this form only; a name here shadows a global one
allowedApiHostsstring[]Hosts the callApi action may reach: a hostname, or a URL such as https://api.example.com/forms for that origin and paths under that path only. Empty, and so off, by default.
submitLabelstring | booleanDraws a Submit button after the fields when the schema has none; false draws none
beforeFields, afterFieldsReactNodeContent inside the form, before or after the fields: a notice, a bot check, a status line
noncestringThe nonce for the style elements the form adds, under a CSP with neither a hash nor 'unsafe-inline'
partialDebounceMsnumberHow long an unfinished response waits for the respondent to pause before onPartial reports it. Two seconds by default. It never holds a sensitive field, nor one derived from it: a computed field that reads it, the field its copyToField writes, a setValue rule that tests it.
idPrefixstringPrefix of every field's DOM id; unique per form by default. "" uses the field ids as they are.
className, rootClassNamestringClasses for the form element and for the provider's root element
childrenReactNodeRendered inside the form instead of the default <FormRenderer />
debugbooleanDebug logging

Fields

Every entry in fields is a FieldDefinition. The label lives in props, with the field's other settings.

FieldDefinition
interface FieldDefinition {
  id: string;              // Unique within the schema
  name?: string;           // Key this field submits under
  type: FieldType;         // Registered type: 'text', 'select', 'panel', …
  props?: FieldProps;      // Everything the component reads, including `label`
  defaultValue?: unknown;  // Starting value
  validation?: ValidationRule[];  // Rules checked on blur and on submit
  conditions?: ConditionalRule[]; // Show / hide / enable from other fields
  computed?: ComputedSpec;        // Value derived from an expression
  dependencies?: string[];        // Extra keys a computed value reads
  actions?: FieldActionsSpec;     // Side effects on change, blur, focus
  children?: FieldDefinition[];   // Child fields, for container types
  className?: string;
  style?: CSSProperties;
}

Hooks

Inside a form: useKraftForm() returns the values, errors, touched and submit state, and the actions setValue, setValues, setError, setErrors, reset, validateField, validateForm and submit. Narrower hooks re-render less: useFormValue(name), useFormValues(), useFormValid(), useFormDirty(), useFormSubmitting(), useField(name) and useFormState(selector). useFormState((s) => s.visibleErrorCount()) counts the errors on fields on screen, as “fields need attention” does. useField(name).inputProps carries the form's own DOM id for the input, so two forms on a page share none.

Composing the parts

KraftFormProvider takes the same props as <KraftForm> and holds the form's state; FormRenderer draws its fields. Use them apart to put your own layout between them.

Builder

<FormBuilder> from @kraftwizard/forms-builder, licensed. Import @kraftwizard/forms-builder/styles.css with it.

PropTypeNotes
initialSchemaFormSchemaThe form to open, with a fresh undo history
valueFormSchemaThe form, controlled: each new value is shown as one undoable step, and passing back what onChange reported changes nothing
schemaKeystringWhich form initialSchema is, when its id doesn't say
onChange(schema) => voidAfter each change the user makes
onSave(schema) => void | Promise<unknown>The Save button and Cmd/Ctrl+S. Only the form as it was when the save began is marked saved. Without it, Save only flushes the local draft.
onDirtyChange(isDirty) => voidCalled when the form gains or loses unsaved changes, for a "leave without saving?" prompt
licenseKeystringSee Licence keys
sanitize(html) => stringShows HTML fields as HTML on the canvas and in the preview
storageKeystringThe draft's localStorage key
autosavebooleanKeep a draft and restore it. Default true.
storeBuilderStoreFrom createBuilderStore(), to read or drive the designer from outside
colorScheme'light' | 'dark'Light or dark for the forms on the canvas and in Preview; left unset they follow the device
theme'light' | 'dark'The designer's own look. Its colours, radii, shadows, fonts and panel sizes are --kwfb-* tokens, public API listed with their values in the builder's README; set them on .kwf-builder, .kwf-builder-layer
paletteFilter(descriptor) => booleanWhich registered types the palette offers
templatesHostTemplate[] | () => Promise<HostTemplate[]>Your templates in the Forms tab, above the built-in ones; a function is called the first time the tab opens
builtInTemplatesbooleanOffer the five built-in templates too; true by default
propertyEditorsRecord<string, ComponentType<PropertyEditorProps>>Your controls for field settings, by key or by type and key
slots{ toolbar?, inspector? }Your panels at the end of the toolbar and at the foot of the inspector
hideToolbar, hidePalette, hidePropertiesbooleanHide a part of the designer
logoReactNodeThe header's mark; null for none. By default KraftWizard's, which a licensed designer leaves out
helpUrlstringA Documentation link in the header; none by default
noncestringYour Content-Security-Policy's style nonce, for the styles popups add on the canvas and in Preview
locale, messagesstring, MessagesThe language of the designer's own interface (es loads a Spanish draft; Arabic, Hebrew, Persian and Urdu lay it out right to left), and strings over the shipped ones. Not the form's language
zIndexnumberThe z-index of the layer at the end of <body> that dialogs, the Code panel, Preview and the drag overlay open in; 100000 by default
classNamestring

Other exports

ExportWhat it is
clearBuilderDraft(key?), DEFAULT_STORAGE_KEYRemove a draft; the default key, kraftwizard.forms.builder.draft
createBuilderStore(), BuilderStoreProvider, useBuilderStore(selector)The designer's state, to share with your own UI: pass the store you made as store and read it with store.getState(); inside a designer, or in panels under <BuilderStoreProvider value={store}>, select from it with the hook
Palette, Canvas, PropertiesPanel, Toolbar, TreeView, PreviewPanel, BuilderLicenseThe blocks, for a designer of your own
templates, getTemplate(id)The five starter forms
generateCode(schema, target), codeFilename, installCommandCode for 'react-tsx', 'react-jsx', 'zod' or 'json', its file name, and the install command for the packages a schema needs
verifyLicense(key, hostname, 'forms'), isExemptOrigin(hostname)Check a key yourself. Never throws: a bad key is { state: 'unlicensed', reason }, and a key whose updates have ended is { state: 'licensed', payload, warning: 'updates_lapsed' } on a version released after them.

PDF export

downloadFormAsPDF(schema, options) and exportFormToPDF(schema, options), from @kraftwizard/forms-builder/pdf-export, load jsPDF only when called. The output is vector text, and it needs no DOM, so it runs on a server too.

export.ts
import { downloadFormAsPDF } from '@kraftwizard/forms-builder/pdf-export';

downloadFormAsPDF(schema, {
  title: 'Application form',
  // jsPDF's built-in font draws Windows-1252 only; pass a font for other scripts.
  font: { family: 'NotoSans', normal: notoSansBase64, bold: notoSansBoldBase64 },
  values: submittedValues, // print the answers too
});

With values it's the filled report: a table prints its rows, header groups, units, decimals and totals, across pages if it's long; a matrix marks its answers; a repeater prints each item; a signature prints its picture, from a PNG or JPEG data URL only, never fetched, and otherwise the text approvals gives it, or an empty box; and a form's document number, revision, header and footer go on every page. Pass the values validateValues returned, computed ones included. The paper is always light, whatever the form's theme, and a font draws all of it, headers, footers, units and table cells included. ☐, ☒ and ✓ are drawn as shapes, so they print whatever the font.

Other options: orientation, format ('a4', 'letter' or a size), margin, pageNumbers, includeDescription, labelFontSize, valueFontSize and direction.

Core and the other packages

Everything else you can import, by package.

@kraftwizard/forms-core

ExportWhat it does
validateSchema(json, options?)Check a schema: { valid, issues }
migrateSchema(schema), SCHEMA_FORMAT_VERSIONBring a schema up to the current format; the format it writes
isFormSchema(value), isFieldList(value)Shape checks for JSON that arrives at run time
registerFieldType(descriptor), componentRegistryAdd a field type; the registry every surface reads
registerValidator(name, fn)A rule for { type: 'custom', validator: name }
registerAction(name, fn), unregisterAction(name), setAllowedApiHosts(hosts)Actions for every form; the global callApi allowlist
setExpressionEvaluator(fn), hasExpressionEvaluator()Install the evaluator for computed fields
registerLocale(config), getAvailableLocales(), resolveLocale(code), getTextDirection(code)Languages and direction
createFormStore(schema, options)A form's state without React: see Server-side validation
defineField(field)Author a field with its props type-checked for its type
getFieldKey(field), walkFields, itemFieldPath(list, index, name)The key a value is stored under; walking a schema; a repeater item's error key
parseLocalDate, formatLocalDate, todayLocalCalendar dates without time zones
safeUrl(url)The URL check the navigate action uses

The other packages

PackageExports
@kraftwizard/forms-componentsregisterAllComponents(), toFormData(values), parseByteSize(size); registerGoogleMap() from @kraftwizard/forms-components/google-map, which needs @react-google-maps/api
@kraftwizard/forms-themesThe five CSS files; themes and themeNames
@kraftwizard/expressionsevaluateExpression, tryEvaluate, collectDependencies(expression), parse, evaluateAst, ExpressionError, builtInFunctionNames
@kraftwizard/sanitize-dompurifysanitize(html), createSanitizer(options)

Versions and migrations

Every package follows semver, and saved forms keep loading across releases. Read the changelog.

Saved forms migrate themselves

The renderer and the form store pass every schema through migrateSchema, which brings it up to the current format and records formatVersion, so the next change has a path too. The designer migrates settings saved under older keys when it opens a form. You never rewrite stored JSON by hand.

What counts as a breaking change

Exports, props, the schema format and the --kwf-* token names are public API. Changing any of them in a way that breaks existing code waits for a major version, with a migration note in the changelog.