# Schema Builder

> A React JSON schema builder for extraction schemas: named fields with unique keys, field and JSON types, required flags, nesting and a JSON view.

- Type: React component (Forms)
- Access: Pro (the source needs a Wingo UI Pro plan, see https://wingo-ui.com/pricing)
- Version: 1.0.0
- Install: `npx wingo-ui@latest add schema-builder`
- Docs: https://wingo-ui.com/components/schema-builder

## Interaction

Each row of the table is a field: Name (the label people read), Unique key, Type (the JSON type it stores, as a badge), a Required switch (a red asterisk marks required names) and Description. The Field type (the control a form shows: text, date, currency, select, address...) is set in Edit details and shown on phone cards. Typing a Name fills the key with its slug (Invoice number gives invoice_number, accents dropped) while the key is empty or still follows the name, marked with a link icon; edit the key and it stays yours. Keys are checked as you type, paste, import and move fields: empty, wrong format, or already used by a sibling (or anywhere, with uniqueKeys="global"), ignoring case and outer spaces. Every field involved is marked, the toolbar counts the problems, and clicking the count, or Enter / Shift+Enter in a marked input, steps through them. Picking a field type adjusts the type (Date stores a string with format date, Multi-select an array of options) and the type list offers what fits first; options typed for a select survive a switch to text and back. Groups, lists of objects and options open under their row from a Configure schema bar, each level a table of its own; the checkbox in the Required header marks a whole level required. Drag the grip on a row's left edge (it shows on hover and focus, always on touch) to reorder or to move a field into or out of a group: a line shows where it lands, in amber when the key already exists there. On touch, long press the grip. From the keyboard, Alt+↑/↓ moves a field, Alt+←/→ (on the grip, selects and the checkbox) moves it out of or into a group, and the ⋯ menu does the same plus Duplicate, Edit details and Delete (a field with children asks first). ⌘Z / ⇧⌘Z (Ctrl+Z / Ctrl+Y) undo and redo inside the builder, Escape in an input puts back what it held. Edit details opens a side panel with the format, placeholder, default value and options. The JSON tab shows the draft 2020-12 schema, highlighted, with Show changes for a diff against the schema it opened with. Import JSON reads a pasted or chosen file and points at the line of an error. Below 560px rows become cards that open the editor in a bottom sheet; menus and selects become bottom sheets on phones.

## Installation

```bash
npx wingo-ui@latest add schema-builder
```

Pro item: run `npx wingo-ui@latest login` once with a Pro account. The CLI adds the files, their dependencies and a version record for updates.

With shadcn: `npx shadcn@latest add @wingo-ui/schema-builder` (needs the @wingo-ui registry with your API key in components.json)

Files:

- `components/ui/schema-builder.tsx`

npm dependencies: `npm i @dnd-kit/core @dnd-kit/sortable @dnd-kit/utilities lucide-react motion`

Wingo UI dependencies (installed automatically):

- [Alert Dialog](https://wingo-ui.com/components/alert-dialog) ([Markdown](https://wingo-ui.com/components/alert-dialog.md))
- [Button](https://wingo-ui.com/components/button) ([Markdown](https://wingo-ui.com/components/button.md))
- [Checkbox](https://wingo-ui.com/components/checkbox) ([Markdown](https://wingo-ui.com/components/checkbox.md))
- [Code Block](https://wingo-ui.com/components/code-block) ([Markdown](https://wingo-ui.com/components/code-block.md))
- [Dialog](https://wingo-ui.com/components/dialog) ([Markdown](https://wingo-ui.com/components/dialog.md))
- [Diff Viewer](https://wingo-ui.com/components/diff-viewer) ([Markdown](https://wingo-ui.com/components/diff-viewer.md))
- [Dropdown Menu](https://wingo-ui.com/components/dropdown-menu) ([Markdown](https://wingo-ui.com/components/dropdown-menu.md))
- [Empty State](https://wingo-ui.com/components/empty-state) ([Markdown](https://wingo-ui.com/components/empty-state.md))
- [Input](https://wingo-ui.com/components/input) ([Markdown](https://wingo-ui.com/components/input.md))
- [JSON Viewer](https://wingo-ui.com/components/json-viewer) ([Markdown](https://wingo-ui.com/components/json-viewer.md))
- [Select](https://wingo-ui.com/components/select) ([Markdown](https://wingo-ui.com/components/select.md))
- [Sheet](https://wingo-ui.com/components/sheet) ([Markdown](https://wingo-ui.com/components/sheet.md))
- [Switch](https://wingo-ui.com/components/switch) ([Markdown](https://wingo-ui.com/components/switch.md))
- [Tabs](https://wingo-ui.com/components/tabs) ([Markdown](https://wingo-ui.com/components/tabs.md))
- [Textarea](https://wingo-ui.com/components/textarea) ([Markdown](https://wingo-ui.com/components/textarea.md))
- [Tooltip](https://wingo-ui.com/components/tooltip) ([Markdown](https://wingo-ui.com/components/tooltip.md))
- [useControllableState](https://wingo-ui.com/components/use-controllable-state) ([Markdown](https://wingo-ui.com/components/use-controllable-state.md))
- [useMediaQuery](https://wingo-ui.com/components/use-media-query) ([Markdown](https://wingo-ui.com/components/use-media-query.md))
- [Motion presets](https://wingo-ui.com/components/motion) ([Markdown](https://wingo-ui.com/components/motion.md))
- [Tones](https://wingo-ui.com/components/tones) ([Markdown](https://wingo-ui.com/components/tones.md))
- [UIProvider](https://wingo-ui.com/components/ui-config) ([Markdown](https://wingo-ui.com/components/ui-config.md))

## Usage

```tsx
import { SchemaBuilder, serializeSchema, type SchemaBuilderField } from "@/components/ui/schema-builder"

const fields: SchemaBuilderField[] = [
  { id: "number", name: "Invoice number", key: "invoice_number", fieldType: "text", type: "string", required: true, description: "The invoice ID" },
  { id: "issued", name: "Issue date", key: "issue_date", fieldType: "date", type: "string", format: "date", required: true, description: "" },
]

export function InvoiceSchema() {
  return (
    <SchemaBuilder
      defaultValue={fields}
      height="80dvh"
      onValueChange={(next) => console.log(serializeSchema(next).schema)}
      onValidationChange={(errors) => console.log(errors.length, "problems")}
    />
  )
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `defaultValue?` | `SchemaBuilderField[]` | `"[]"` | The fields it opens with while uncontrolled. The playground uses a Northwind Outfitters invoice. Show changes in the JSON tab compares against it. |
| `value?` | `SchemaBuilderField[]` |  | The fields, controlled. Pair it with onValueChange. |
| `onValueChange?` | `(fields: SchemaBuilderField[]) => void` |  | Called with the new fields after every edit, move, import, undo and redo. |
| `defaultTab?` | `"form" \| "json"` | `"form"` | The tab it opens on: the field table or the JSON Schema. |
| `tab?` | `"form" \| "json"` |  | The tab, controlled. Pair it with onTabChange. |
| `onTabChange?` | `(tab: "form" \| "json") => void` |  | Called when someone switches between Form and JSON. |
| `uniqueKeys?` | `"siblings" \| "global"` | `"siblings"` | siblings: a key must be unique among the fields of its level (one group, one list). global: unique in the whole schema. |
| `keyPattern?` | `string` | `"^[a-z][a-z0-9_]*$"` | A regular expression every key must match. The default allows snake_case; the other options camelCase and kebab-case. |
| `autoKey?` | `boolean` | `true` | The key follows the Name (its slug) while it is empty or unchanged; a link icon marks those keys. Off, keys are only typed by hand. |
| `readOnly?` | `boolean` | `false` | Shows the schema without editing: no grips, adds, imports or undo. Copy, download and the JSON tab stay. |
| `maxDepth?` | `number` | `5` | Levels of nesting allowed, 1 is flat. Deeper fields are reported; moves and drops that would go deeper are refused. |
| `defaultExpanded?` | `boolean` | `true` | Groups, lists and options open expanded. Off, only the top level shows; collapsed rows count the problems inside them. |
| `showToolbar?` | `boolean` | `true` | The toolbar with the Form / JSON tabs, the problem count, add, import, copy, download, undo and redo. |
| `showImport?` | `boolean` | `true` | Import JSON in the toolbar (the ⋯ menu when narrow) and in the empty state. |
| `showDownload?` | `boolean` | `true` | The download button, which saves the JSON Schema as fileName. |
| `fileName?` | `string` | `"schema.json"` | Name of the downloaded file, also shown in the download button's label. |
| `height?` | `number \| string` | `640` | Height of the builder: px as a number, any CSS length ("80dvh") to fill a pane, or "auto" to grow with the fields. |
| `variant?` | `"surface" \| "outline" \| "plain"` | `"surface"` | surface is a raised panel, outline a bordered box, plain has no frame for panes that bring their own. |
| `radius?` | `"none" \| "sm" \| "md" \| "lg"` | `"md"` | Corner radius of the frame: 0, 12, 16 or 24px. |
| `typeColors?` | `Partial<Record<SchemaBuilderTypeKey, string>>` |  | Tints for the type badges, any CSS color per type (string, number, enum, array<object>...). Badges are neutral by default, like the rest of the library; set colors to tell types apart at a glance. |
| `toolbarActions?` | `ReactNode` |  | Your own buttons at the end of the toolbar, before the ⋯ menu: save, publish, test on a document. |
| `ref?` | `Ref<SchemaBuilderHandle> (a useRef object or an (handle) => void callback)` |  | addField(parentId?), removeField(id), focusField(id, column?), validate() (shows every problem and returns them), getSchema(), getJsonSchema(), importJson(json), reset(), undo() and redo(). |
| `onJsonSchemaChange?` | `(schema: SchemaBuilderJsonSchema) => void` |  | Called with the serialized JSON Schema on open and after every change. |
| `onValidationChange?` | `(errors: SchemaBuilderError[]) => void` |  | Called on open and whenever the problems change: { id, path, field, code, message, otherId? } for each. |
| `onFieldAdd?` | `(field: SchemaBuilderField, parentId: string \| null) => void` |  | Called when a field is added, duplicated or pasted in, with the group or list it went into (null for the top level). |
| `onFieldRemove?` | `(field: SchemaBuilderField) => void` |  | Called with a deleted field, children included. |
| `labels?` | `Partial<SchemaBuilderLabels>` |  | Every string, English by default (DEFAULT_SCHEMA_BUILDER_LABELS): columns, field and JSON type names, menus, editor, import, JSON tab, announcements and every validation message, with functions for the ones that take a value (errorKeyDuplicate(otherName), problems(count)...). |
| `classNames?` | `Partial<Record<"toolbar" \| "viewport" \| "header" \| "row" \| "card" \| "options" \| "json" \| "notice" \| "editor" \| "state", string>>` |  | Extra classes for the toolbar, the scrolling form, each level header, each row and card, the options editor, the JSON tab, the import notice, the editor panel and the empty state. |
| `className?` | `string` |  | Extra classes for the frame, merged last. Other div props are forwarded to it. |

## Parts

### serializeSchema (function)

serializeSchema(fields, options?) returns { schema, errors }: a draft 2020-12 JSON Schema (title from Name, description, format, enum with x-enum-descriptions, items, required on the parent, default, x-placeholder, x-field-type) and the problems. strict: true throws instead when there are any.

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `fields` | `SchemaBuilderField[]` |  | The fields to serialize. Fields without a key are left out; on a duplicate key the first one wins. |
| `options?` | `{ strict?, uniqueKeys?, keyPattern?, maxDepth?, schemaUri?, title?, labels? }` |  | strict throws an error with the list on error.errors; schemaUri: false drops $schema. |

### parseSchema (function)

parseSchema(json, options?) reads a JSON Schema, as text or an object, into fields and never throws: { fields, errors, warnings }. A JSON syntax error comes with its line and column; $ref, allOf and other unsupported parts are reported in warnings.

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `json` | `string \| object` |  | The schema. Titles become names, formats pick the field type, oneOf / anyOf consts become options. |
| `options?` | `{ idPrefix?: string; labels? }` |  | idPrefix keeps the generated ids stable and distinct between imports. |

### validateSchema (function)

validateSchema(fields, options?) returns every problem in reading order: empty names and keys, key format, duplicate keys (case and outer spaces ignored), options, empty groups, a field type that cannot store the type, nesting past maxDepth.

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `fields` | `SchemaBuilderField[]` |  | The fields to check. |
| `options?` | `{ uniqueKeys?: "siblings" \| "global"; keyPattern?: string \| RegExp; maxDepth?: number; labels? }` |  | The same rules the builder uses. |

### slugifyKey (function)

slugifyKey(name) turns a name into a key: "Invoice number" gives invoice_number, "Preț unitar" gives pret_unitar, a leading digit gets field_.

### typeKeyOf (function)

typeKeyOf(field) returns the type as one value: "string", "enum", or "array<object>" for an array of objects.

### SchemaBuilderField (type)

A field: { id, name, key, fieldType, type, required, description, enumValues?, properties?, items?, format?, placeholder?, defaultValue? }. properties holds an object's children, items what an array holds ({ type, properties?, enumValues? }).

### SchemaBuilderEnumValue (type)

An option of a select, radio or multi-select field: { id, value, description? }.

### SchemaBuilderFieldType (type)

text, textarea, number, currency, percent, select, multi-select, radio, checkbox, switch, date, datetime, time, email, phone, url, file, signature, address, group or list.

### SchemaBuilderType (type)

string, number, integer, boolean, null, object, array or enum: the JSON type a field stores.

### SchemaBuilderError (type)

A problem: { id, path ("vendor.address.city", "line_items[].amount"), field ("name" | "key" | "type" | "enumValues" | "properties"), code, message, otherId? }.

### SchemaBuilderJsonSchema (type)

What serializeSchema, getJsonSchema() and onJsonSchemaChange give you: { $schema?, type: "object", properties, required? }.

### SchemaBuilderHandle (type)

What the ref gets: addField, removeField, focusField, validate, getSchema, getJsonSchema, importJson, reset, undo and redo.

### SchemaBuilderLabels (type)

The shape of labels: every string the builder renders and every message it reports.

### DEFAULT_SCHEMA_BUILDER_LABELS (constant)

The English labels. Spread it to translate a few strings.

### SchemaBuilderTypeKey (type)

A type as one value: "string", "enum", "object", "array<object>", "array<enum>", "array<string>"...

### DEFAULT_KEY_PATTERN (constant)

^[a-z][a-z0-9_]*$, the key pattern used when keyPattern is not set.

## Examples

- **JSON and problems outside the builder**: onJsonSchemaChange hands you the draft 2020-12 schema on every change, onValidationChange the list of problems with their paths.
- **Duplicate keys in the data**: “total” and “total ” clash at the root, “amount” and “Amount” inside the line items: case and spaces are ignored, every field involved is marked.
- **Unique across the whole schema**: uniqueKeys="global": the vendor's and the customer's "name" now clash too. Collapsed groups count the problems inside them.
- **Import an existing JSON Schema**: A purchase order schema read with parseSchema: formats become Date and Email fields, oneOf consts become options. The second button shows the import error.
- **Empty schema**: No fields yet: add the first one or import a JSON Schema.
- **Read-only**: readOnly shows the schema without editing; the row menu keeps View details and Copy key, the toolbar keeps Copy JSON and Download.
- **Your own toolbar actions**: toolbarActions adds Save, which calls validate() on the ref and reads getJsonSchema().
- **On a phone**: Rows become cards with the name as title and a Required switch; tap one to edit it in a bottom sheet, long press the grip to drag.

## See also

- [JSON Viewer](https://wingo-ui.com/components/json-viewer) ([Markdown](https://wingo-ui.com/components/json-viewer.md))
- [Diff Viewer](https://wingo-ui.com/components/diff-viewer) ([Markdown](https://wingo-ui.com/components/diff-viewer.md))
- [Rule Builder](https://wingo-ui.com/components/rule-builder) ([Markdown](https://wingo-ui.com/components/rule-builder.md))
- [Filter Builder](https://wingo-ui.com/components/filter-builder) ([Markdown](https://wingo-ui.com/components/filter-builder.md))
- [Form Wizard](https://wingo-ui.com/components/form-wizard) ([Markdown](https://wingo-ui.com/components/form-wizard.md))

---

Canonical: https://wingo-ui.com/components/schema-builder
More components: https://wingo-ui.com/components · Index for agents: https://wingo-ui.com/llms.txt
