# Data Form

A form built by hand or from field configuration, with linked fields, validation, lists, steps and overlays.

Page: https://sui.draco.dev/docs/components/data-form

### Example: data-form-demo

```tsx
"use client";

import {
  DataForm,
  type DataFormFieldConfig,
  dataFormLabelsZhCN,
} from "@workspace/ui/components/data-form";
import { useMemo } from "react";
import type { ExampleProps } from "../types";
import { useSubmitted, wait } from "./data-form-support";

export default function DataFormDemo({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const [submitted, setSubmitted] = useSubmitted(zh);
  const invalidEmail = zh
    ? "请输入有效的邮箱地址。"
    : "Enter a valid email address.";
  const fields = useMemo<DataFormFieldConfig[]>(
    () => [
      {
        name: "name",
        label: zh ? "姓名" : "Name",
        required: true,
        placeholder: zh ? "例如 陈明" : "e.g. Alex Chen",
      },
      {
        name: "email",
        label: zh ? "邮箱" : "Email",
        required: true,
        fieldProps: { type: "email", autoComplete: "email" },
        placeholder: "name@example.com",
        validators: {
          onBlur: ({ value }) =>
            typeof value === "string" && !value.includes("@")
              ? invalidEmail
              : undefined,
        },
      },
      {
        name: "type",
        label: zh ? "账号类型" : "Account type",
        valueType: "radio",
        valueEnum: zh
          ? { personal: "个人", team: "团队" }
          : { personal: "Personal", team: "Team" },
        initialValue: "personal",
      },
      {
        name: "company",
        label: zh ? "团队名称" : "Team name",
        reactions: [
          {
            when: {
              logic: "and",
              rules: [{ field: "type", operator: "eq", value: "team" }],
            },
            fulfill: { required: true },
            otherwise: { hidden: true },
          },
        ],
      },
      {
        name: "role",
        label: zh ? "角色" : "Role",
        valueType: "select",
        valueEnum: zh
          ? { admin: "管理员", developer: "开发者", viewer: "访客" }
          : { admin: "Admin", developer: "Developer", viewer: "Viewer" },
      },
      {
        name: "notifications",
        label: zh ? "接收产品更新邮件" : "Email me product updates",
        valueType: "switch",
        initialValue: true,
      },
    ],
    [zh, invalidEmail],
  );
  return (
    <div className="flex w-full max-w-md flex-col gap-6">
      <DataForm
        fields={fields}
        labels={zh ? dataFormLabelsZhCN : undefined}
        onFinish={async (values) => {
          await wait();
          setSubmitted(values);
        }}
      />
      {submitted}
    </div>
  );
}
```

## Installation

```bash
npx shadcn@latest add @sui/data-form
```

With pnpm, Yarn or Bun, use `pnpm dlx`, `yarn dlx` or `bunx --bun` in place of `npx`, and `pnpm add`, `yarn add` or `bun add` in place of `npm install`.

Install with the shadcn CLI or use the shared `@workspace/ui` package. Follow the [installation guide](/docs/installation) to configure the registry, load styles, and choose import aliases.

```tsx
import { DataForm, DataFormItem } from "@workspace/ui/components/data-form"
```

## Usage

Wrap any control in `DataFormItem`. It adds the label, description and error from [Field](/docs/components/field), binds the value and blur, and sets `aria-invalid`, `aria-required` and `aria-describedby`. The control keeps its own props.

```tsx
<DataForm onFinish={async (values) => save(values)}>
  <DataFormItem name="title" label="Title" required>
    <Input placeholder="e.g. Export fails on Safari" />
  </DataFormItem>
  <DataFormItem name="urgent" label="Blocks my work">
    <Checkbox />
  </DataFormItem>
</DataForm>
```

Or describe fields once and let their `valueType` pick the control. Both write the same markup and can be mixed: `fields` render first, then `children`.

```tsx
<DataForm
  fields={[
    { name: "name", label: "Name", required: true },
    { name: "role", label: "Role", valueType: "select", valueEnum: { admin: "Admin", viewer: "Viewer" } },
    { name: "notifications", label: "Email me product updates", valueType: "switch" },
  ]}
  onFinish={save}
/>
```

`DataForm` is the default arrangement of smaller parts. Compose them when a page needs a different one:

### Example: data-form-composition

```tsx
"use client";

import { Checkbox } from "@workspace/ui/components/checkbox";
import {
  DataFormErrorSummary,
  DataFormFooter,
  DataFormGroup,
  DataFormItem,
  DataFormReset,
  DataFormRoot,
  DataFormSubmit,
  dataFormLabelsZhCN,
  useDataForm,
} from "@workspace/ui/components/data-form";
import { Input } from "@workspace/ui/components/input";
import { Textarea } from "@workspace/ui/components/textarea";
import type { ExampleProps } from "../types";
import { useSubmitted, wait } from "./data-form-support";

export default function DataFormComposition({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const t = (en: string, cn: string) => (zh ? cn : en);
  const [submitted, setSubmitted] = useSubmitted(zh);
  const form = useDataForm({
    labels: zh ? dataFormLabelsZhCN : undefined,
    onFinish: async (values) => {
      await wait();
      setSubmitted(values);
    },
  });
  return (
    <div className="flex w-full max-w-md flex-col gap-6">
      <DataFormRoot form={form}>
        <DataFormErrorSummary />
        <DataFormGroup title={t("Report a bug", "报告问题")}>
          <DataFormItem name="title" label={t("Title", "标题")} required>
            <Input
              placeholder={t(
                "e.g. Export fails on Safari",
                "例如 Safari 中导出失败",
              )}
            />
          </DataFormItem>
          <DataFormItem
            name="steps"
            label={t("Steps to reproduce", "复现步骤")}
            description={t("One step per line.", "每行一个步骤。")}
            required
          >
            <Textarea rows={4} />
          </DataFormItem>
          <DataFormItem
            name="urgent"
            label={t("Blocks my work", "影响正常工作")}
          >
            <Checkbox />
          </DataFormItem>
        </DataFormGroup>
        <DataFormFooter>
          <DataFormReset />
          <DataFormSubmit>{t("Send report", "提交报告")}</DataFormSubmit>
        </DataFormFooter>
      </DataFormRoot>
      {submitted}
    </div>
  );
}
```

| Part | Renders |
| --- | --- |
| `DataFormRoot` | The `<form>` and its providers; takes `form`, `layout`, `columns` and `collapse` |
| `DataFormFields` | The form's `fields`, or the ones passed |
| `DataFormField` | One field by its value type, the same shape as an item of `fields` |
| `DataFormItem` | Any control, framed and bound |
| `DataFormGroup` | A titled group, separated by space rather than a card |
| `DataFormList` | Rows of the same fields |
| `DataFormFieldSet` | Several controls that make one value |
| `DataFormDependency` | Content drawn from the values of named fields |
| `DataFormErrorSummary` | The form's own error, and a list of fields after a failed submit of a long form |
| `DataFormFooter`, `DataFormReset`, `DataFormSubmit` | The buttons: Reset before Submit, a spinner while the request is in flight |
| `DataFormCancel` | Cancel, when a plugin such as `dialog()` gives the form one |
| `DataFormFill` | Marks a fixed-height frame: inside it the fields scroll and the footer stays in view |

## Value types

Each value type has an `edit` control and a `read` view. The read view is used by `readonly` forms and shows empty values as a muted dash.

| `valueType` | Control | Value |
| --- | --- | --- |
| `text`, `password`, `textarea` | Input, Textarea | `string` |
| `digit`, `money`, `percent` | Number input; read with `Intl.NumberFormat` and `fieldProps.format` | `number` |
| `digitRange` | Two number inputs | `[from, to]` |
| `select`, `multiSelect` | Select; a search box appears past 10 options | `string`, `string[]` |
| `radio`, `checkboxGroup` | RadioGroup, Checkbox list | `string`, `string[]` |
| `checkbox`, `switch`, `boolean` | Checkbox, Switch, Yes/No select | `boolean` |
| `date`, `dateTime`, `dateRange`, `dateTimeRange` | DatePicker | `Date`, `[Date, Date]` |
| `time`, `timeRange` | TimePicker | `"hh:mm"`, `[from, to]` |
| `color`, `tags`, `slider` | ColorPicker, TagInput, Slider | `string`, `string[]`, `number` |

`number`, `enum`, `numberRange`, `datetime` and `datetimeRange` are aliases of `digit`, `select`, `digitRange`, `dateTime` and `dateTimeRange`, the names DataTable uses. Date types keep `Date` values; `fieldProps.valueFormat: "string"` keeps local `yyyy-mm-dd` strings instead.

Every built-in type, in its edit and read-only views:

### Example: data-form-value-types

```tsx
"use client";

import {
  DataForm,
  type DataFormFieldConfig,
  dataFormLabelsZhCN,
} from "@workspace/ui/components/data-form";
import { Label } from "@workspace/ui/components/label";
import { Switch } from "@workspace/ui/components/switch";
import { useId, useMemo, useState } from "react";
import type { ExampleProps } from "../types";
import { text } from "./data-form-support";

/** Every built-in value type with a sample value, in edit or read view. */
function valueTypeFields(zh: boolean): DataFormFieldConfig[] {
  const t = text(zh);
  const plans = {
    free: t("Free", "免费版"),
    team: { text: t("Team", "团队版"), color: "default" as const },
    enterprise: {
      text: t("Enterprise", "企业版"),
      color: "secondary" as const,
    },
  };
  const field = (
    valueType: string,
    label: string,
    extra: Partial<DataFormFieldConfig> = {},
  ): DataFormFieldConfig => ({
    name: valueType,
    label,
    valueType,
    description: valueType,
    ...extra,
  });
  return [
    field("text", t("Text", "文本")),
    field("password", t("Password", "密码")),
    field("textarea", t("Textarea", "多行文本"), { colSpan: 2 }),
    field("digit", t("Number", "数字")),
    field("digitRange", t("Number range", "数字范围")),
    field("money", t("Money", "金额"), {
      fieldProps: { format: { currency: zh ? "CNY" : "USD" } },
    }),
    field("percent", t("Percent", "百分比")),
    field("select", t("Select", "下拉选择"), { valueEnum: plans }),
    field("multiSelect", t("Multiple select", "多选"), { valueEnum: plans }),
    field("radio", t("Radio", "单选"), { valueEnum: plans }),
    field("checkboxGroup", t("Checkbox group", "复选组"), { valueEnum: plans }),
    field("checkbox", t("Checkbox", "复选框")),
    field("switch", t("Switch", "开关")),
    field("boolean", t("Yes or no", "是否")),
    field("date", t("Date", "日期")),
    field("dateRange", t("Date range", "日期范围")),
    field("dateTime", t("Date and time", "日期时间")),
    field("dateTimeRange", t("Date and time range", "日期时间范围")),
    field("time", t("Time", "时间")),
    field("timeRange", t("Time range", "时间范围")),
    field("color", t("Color", "颜色")),
    field("tags", t("Tags", "标签")),
    field("slider", t("Slider", "滑块"), { fieldProps: { max: 100 } }),
  ];
}

const sample = {
  text: "Alex Chen",
  password: "secret-pass",
  textarea: "First line\nSecond line",
  digit: 42,
  digitRange: [10, 99],
  money: 1280.5,
  percent: 37.5,
  select: "team",
  multiSelect: ["team", "enterprise"],
  radio: "free",
  checkboxGroup: ["free", "team"],
  checkbox: true,
  switch: false,
  boolean: true,
  date: "2026-03-18",
  dateRange: ["2026-03-01", "2026-03-31"],
  dateTime: "2026-03-18T09:30",
  dateTimeRange: ["2026-03-18T09:00", "2026-03-18T18:00"],
  time: "09:30",
  timeRange: ["09:00", "18:00"],
  color: "#0088FF",
  tags: ["design", "forms"],
  slider: 60,
};

export default function DataFormValueTypes({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const id = useId();
  const [readonly, setReadonly] = useState(false);
  const fields = useMemo(() => valueTypeFields(zh), [zh]);
  return (
    <div className="flex w-full max-w-3xl flex-col gap-6">
      <div className="flex items-center gap-2">
        <Switch id={id} checked={readonly} onCheckedChange={setReadonly} />
        <Label htmlFor={id}>{zh ? "只读展示" : "Read-only view"}</Label>
      </div>
      <DataForm
        layout="grid"
        columns={2}
        readonly={readonly}
        submitter={false}
        fields={fields}
        defaultValues={sample}
        labels={zh ? dataFormLabelsZhCN : undefined}
      />
    </div>
  );
}
```

Pick by option count, as the [data entry pattern](/docs/design-patterns#data-entry) suggests: `switch` or `checkbox` for on and off, `radio` for two to five options, `select` for more. Register your own types once with `ValueTypeProvider`; DataForm reads them by name.

```tsx
<ValueTypeProvider valueTypes={{ rating: { edit: (props) => <Rating {...props} />, text: ({ value }) => `${value} / 5` } }}>
  <App />
</ValueTypeProvider>
```

A definition can also set `lightMode` (where it sits in a light row), `prefix` (it shows a label inside), `dateMode` (how its dates are submitted) and `persist: false` (kept out of drafts, as passwords are).

Options come from `request`, then `options`, then `valueEnum`. `valueEnum` also gives each option a badge `color` in read-only views.

## Linked fields

Link fields with functions or with JSON. A function receives the current values:

```tsx
{
  name: "city",
  valueType: "select",
  dependencies: ["province"],
  clearOnChange: true,
  disabled: (values) => !values.province,
  options: (values) => citiesOf(values.province),
}
```

JSON reactions use the same twelve operators as DataTable filters and never evaluate code, so a server can send them:

```json
{
  "name": "taxId",
  "reactions": [{
    "when": { "logic": "and", "rules": [{ "field": "invoice", "operator": "eq", "value": "company" }] },
    "fulfill": { "required": true },
    "otherwise": { "hidden": true, "value": null }
  }]
}
```

### Example: data-form-reactions

```tsx
"use client";

import {
  DataForm,
  type DataFormFieldConfig,
  dataFormLabelsZhCN,
} from "@workspace/ui/components/data-form";
import { useMemo } from "react";
import type { ExampleProps } from "../types";
import { text, useSubmitted, wait } from "./data-form-support";

const cities: Record<string, { value: string; label: string; zh: string }[]> = {
  zj: [
    { value: "hz", label: "Hangzhou", zh: "杭州" },
    { value: "nb", label: "Ningbo", zh: "宁波" },
  ],
  gd: [
    { value: "gz", label: "Guangzhou", zh: "广州" },
    { value: "sz", label: "Shenzhen", zh: "深圳" },
  ],
};

function invoiceFields(zh: boolean): DataFormFieldConfig[] {
  const t = text(zh);
  return [
    {
      name: "invoice",
      label: t("Invoice", "发票"),
      valueType: "radio",
      valueEnum: { none: t("None", "不需要"), company: t("Company", "企业") },
      initialValue: "none",
    },
    // JSON reactions: a server can send these as they are.
    {
      name: "taxId",
      label: t("Tax ID", "税号"),
      reactions: [
        {
          when: {
            logic: "and",
            rules: [{ field: "invoice", operator: "eq", value: "company" }],
          },
          fulfill: { required: true },
          otherwise: { hidden: true, value: null },
        },
      ],
    },
    // Function props: list `dependencies` so only this field renders again.
    {
      name: "province",
      label: t("Province", "省份"),
      valueType: "select",
      valueEnum: { zj: t("Zhejiang", "浙江"), gd: t("Guangdong", "广东") },
    },
    {
      name: "city",
      label: t("City", "城市"),
      valueType: "select",
      dependencies: ["province"],
      clearOnChange: true,
      disabled: (values) => !values.province,
      options: (values) =>
        (cities[String(values.province)] ?? []).map((city) => ({
          value: city.value,
          label: zh ? city.zh : city.label,
        })),
    },
  ];
}

export default function DataFormReactions({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const [submitted, setSubmitted] = useSubmitted(zh);
  const fields = useMemo(() => invoiceFields(zh), [zh]);
  return (
    <div className="flex w-full max-w-md flex-col gap-6">
      <DataForm
        fields={fields}
        labels={zh ? dataFormLabelsZhCN : undefined}
        onFinish={async (values) => {
          await wait();
          setSubmitted(values);
        }}
      />
      {submitted}
    </div>
  );
}
```

Each field follows only the values it reads, so a change renders the fields that depend on it and no others. Reactions declare their fields; list `dependencies` for function props, or the field follows every value. `clearOnChange` empties a field when someone edits a field it depends on; loading, restoring a draft or `reset` set values that belong together and clear nothing.

When the same property is set in several places, the later one wins: the field's own value, JSON reactions, function props, the form's `readonly`, then `access`. A hidden field keeps its value but is left out of submission and validation; fields on another step or behind Expand are only out of view, so they are sent and checked.

`serializeFields` turns `fields` into JSON and stops at the first function, naming its path. `parseFields` checks JSON against `dataFormSchema` and rejects value types that are not registered.

## Validation

Fields validate when they lose focus and on submit, never on each keystroke, and the message appears under the field. `required` adds a check, an asterisk and `aria-required`. `validators` take a function or a Standard Schema per phase, and `onChangeAsync` waits `debounceMs` after typing stops.

Pass a schema such as Zod to `validator` to check the whole form on submit, then on blur. Errors for hidden fields are dropped.

`onFinish` receives the payload. Return or throw `{ fields, form }` and the messages land under their fields and in an alert above the form; editing a field clears its message.

### Example: data-form-validation

```tsx
"use client";

import {
  DataForm,
  dataFormLabelsZhCN,
} from "@workspace/ui/components/data-form";
import { useMemo } from "react";
import { z } from "zod";
import type { ExampleProps } from "../types";
import { text, useSubmitted, wait } from "./data-form-support";

export default function DataFormValidation({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const t = text(zh);
  const [submitted, setSubmitted] = useSubmitted(zh);
  const schema = useMemo(() => {
    const copy = text(zh);
    return z.object({
      username: z
        .string(copy("Choose a username.", "请填写用户名。"))
        .min(3, copy("Use at least 3 characters.", "至少 3 个字符。")),
      password: z
        .string(copy("Choose a password.", "请设置密码。"))
        .min(8, copy("Use at least 8 characters.", "至少 8 个字符。")),
    });
  }, [zh]);
  return (
    <div className="flex w-full max-w-md flex-col gap-6">
      <DataForm
        validator={schema}
        labels={zh ? dataFormLabelsZhCN : undefined}
        fields={[
          {
            name: "username",
            label: t("Username", "用户名"),
            description: t("“taken” is already in use.", "“taken” 已被占用。"),
            required: true,
          },
          {
            name: "password",
            label: t("Password", "密码"),
            valueType: "password",
            required: true,
          },
        ]}
        onFinish={async (values) => {
          await wait();
          // The server's answer lands under the field it names.
          if (values.username === "taken")
            return {
              fields: {
                username: t(
                  "This username is taken. Try another.",
                  "这个用户名已被占用，请换一个。",
                ),
              },
            };
          setSubmitted({ ...values, password: "••••••••" });
        }}
      />
      {submitted}
    </div>
  );
}
```

After a failed submit, focus moves to the first invalid field. In a form with three or more errors, a summary lists them, and each entry moves focus to its field.

## Lists and groups

`DataFormList` repeats a set of fields. Adding a row moves focus into it, removing one moves focus to a neighbor, and both are announced to screen readers. Set `min`, `max` and `sortable`.

### Example: data-form-list

```tsx
"use client";

import {
  DataForm,
  DataFormList,
  dataFormLabelsZhCN,
} from "@workspace/ui/components/data-form";
import type { ExampleProps } from "../types";
import { useSubmitted, wait } from "./data-form-support";

export default function DataFormListDemo({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const t = (en: string, cn: string) => (zh ? cn : en);
  const [submitted, setSubmitted] = useSubmitted(zh);
  return (
    <div className="flex w-full max-w-2xl flex-col gap-6">
      <DataForm
        labels={zh ? dataFormLabelsZhCN : undefined}
        defaultValues={{ members: [{ email: "", role: "editor" }] }}
        fields={[{ name: "team", label: t("Team", "团队"), required: true }]}
        onFinish={async (values) => {
          await wait();
          setSubmitted(values);
        }}
      >
        <DataFormList
          name="members"
          label={t("Members", "成员")}
          min={1}
          max={5}
          sortable
          newRow={() => ({ email: "", role: "viewer" })}
          fields={[
            {
              name: "email",
              label: t("Email", "邮箱"),
              required: true,
              placeholder: "name@example.com",
            },
            {
              name: "role",
              label: t("Role", "角色"),
              valueType: "select",
              valueEnum: {
                editor: t("Editor", "编辑"),
                viewer: t("Viewer", "访客"),
              },
            },
          ]}
        />
      </DataForm>
      {submitted}
    </div>
  );
}
```

## Read-only and permissions

`readonly` shows every value through its read view, so one set of fields serves both a detail page and an edit page. `access` maps field names, or a function, to `edit`, `readonly` or `hidden`; it wins over every other rule. An inline map can be written in place; memoize a function.

### Example: data-form-readonly

```tsx
"use client";

import { Button } from "@workspace/ui/components/button";
import {
  DataForm,
  type DataFormAccessMap,
  dataFormLabelsZhCN,
} from "@workspace/ui/components/data-form";
import { useState } from "react";
import type { ExampleProps } from "../types";

const record = {
  name: "Alex Chen",
  status: "active",
  salary: 32000,
  joinedAt: "2024-03-18",
  note: "",
};

export default function DataFormReadonly({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const t = (en: string, cn: string) => (zh ? cn : en);
  const [editing, setEditing] = useState(false);
  const [manager, setManager] = useState(false);
  // Only managers see salaries; nobody edits the join date.
  const access: DataFormAccessMap = {
    salary: manager ? "edit" : "hidden",
    joinedAt: "readonly",
  };
  return (
    <div className="flex w-full max-w-md flex-col gap-6">
      <div className="flex gap-2">
        <Button
          variant="outline"
          size="sm"
          aria-pressed={editing}
          onClick={() => setEditing(!editing)}
        >
          {editing ? t("View", "查看") : t("Edit", "编辑")}
        </Button>
        <Button
          variant="outline"
          size="sm"
          aria-pressed={manager}
          onClick={() => setManager(!manager)}
        >
          {t("Manager access", "经理权限")}
        </Button>
      </div>
      <DataForm
        key={String(editing)}
        readonly={!editing}
        access={access}
        submitter={editing ? undefined : false}
        labels={zh ? dataFormLabelsZhCN : undefined}
        defaultValues={record}
        layout="horizontal"
        fields={[
          { name: "name", label: t("Name", "姓名"), required: true },
          {
            name: "status",
            label: t("Status", "状态"),
            valueType: "select",
            valueEnum: {
              active: { text: t("Active", "在职"), color: "default" },
              leave: { text: t("On leave", "休假"), color: "secondary" },
            },
          },
          {
            name: "salary",
            label: t("Salary", "薪资"),
            valueType: "money",
            fieldProps: { format: { currency: "CNY" } },
          },
          {
            name: "joinedAt",
            label: t("Joined", "入职日期"),
            valueType: "date",
          },
          { name: "note", label: t("Note", "备注"), valueType: "textarea" },
        ]}
      />
    </div>
  );
}
```

Read-only values are submitted, as an edit form needs ids. Use `transform`, or `access` to hide a field, to leave one out.

## Steps

`steps()` splits the form. Fields join a step with `step`. Next validates the current step only, Previous keeps the values, and the last step submits everything. Every field stays mounted, so a failed final submit returns to the first step with an error.

### Example: data-form-steps

```tsx
"use client";

import {
  DataForm,
  dataFormLabelsZhCN,
  steps,
} from "@workspace/ui/components/data-form";
import { useMemo } from "react";
import type { ExampleProps } from "../types";
import { text, useSubmitted, wait } from "./data-form-support";

export default function DataFormSteps({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const t = text(zh);
  const [submitted, setSubmitted] = useSubmitted(zh);
  const plugins = useMemo(() => {
    const copy = text(zh);
    return [
      steps({
        items: [
          {
            key: "account",
            title: copy("Account", "账号"),
            description: copy("How you sign in.", "用于登录。"),
          },
          { key: "workspace", title: copy("Workspace", "工作区") },
          { key: "invite", title: copy("Invite", "邀请成员") },
        ],
      }),
    ];
  }, [zh]);
  return (
    <div className="flex w-full max-w-2xl flex-col gap-6">
      <DataForm
        plugins={plugins}
        labels={zh ? dataFormLabelsZhCN : undefined}
        fields={[
          {
            name: "email",
            label: t("Email", "邮箱"),
            required: true,
            step: "account",
          },
          {
            name: "password",
            label: t("Password", "密码"),
            valueType: "password",
            required: true,
            step: "account",
          },
          {
            name: "workspace",
            label: t("Workspace name", "工作区名称"),
            required: true,
            step: "workspace",
          },
          {
            name: "size",
            label: t("Team size", "团队规模"),
            valueType: "radio",
            valueEnum: { small: "1–10", medium: "11–50", large: "50+" },
            step: "workspace",
          },
          {
            name: "invites",
            label: t("Invite by email", "通过邮箱邀请"),
            valueType: "tags",
            step: "invite",
          },
        ]}
        onFinish={async (values) => {
          await wait();
          setSubmitted({ ...values, password: "••••••••" });
        }}
      />
      {submitted}
    </div>
  );
}
```

## Dialogs and sheets

`dialog()` puts the form in a Dialog, and a bottom Drawer on phones; `sheet()` opens it from an edge while the list stays in view. Both stay mounted, keep the buttons in view while the fields scroll, ask before discarding changes, and close and reset after a successful submit. Cancel takes Reset's place, and joins the steps' Previous and Next when `steps()` is in the list too, in either order.

### Example: data-form-overlay

```tsx
"use client";

import { Button } from "@workspace/ui/components/button";
import {
  DataForm,
  type DataFormFieldConfig,
  dataFormLabelsZhCN,
  dialog,
  sheet,
} from "@workspace/ui/components/data-form";
import { useMemo } from "react";
import type { ExampleProps } from "../types";
import { text, useSubmitted, wait } from "./data-form-support";

function projectFields(zh: boolean): DataFormFieldConfig[] {
  const t = text(zh);
  return [
    { name: "name", label: t("Project name", "项目名称"), required: true },
    {
      name: "visibility",
      label: t("Visibility", "可见范围"),
      valueType: "radio",
      valueEnum: { private: t("Private", "私有"), team: t("Team", "团队") },
      initialValue: "private",
    },
  ];
}

export default function DataFormOverlay({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const [submitted, setSubmitted] = useSubmitted(zh);
  const fields = useMemo(() => projectFields(zh), [zh]);
  const inDialog = useMemo(() => {
    const t = text(zh);
    return [
      dialog({
        title: t("New project", "新建项目"),
        description: t("Projects group your work.", "项目用来归类你的工作。"),
        trigger: <Button>{t("New project", "新建项目")}</Button>,
      }),
    ];
  }, [zh]);
  const inSheet = useMemo(() => {
    const t = text(zh);
    return [
      sheet({
        title: t("Edit project", "编辑项目"),
        description: t(
          "Changes apply to everyone on the project.",
          "修改对项目所有成员生效。",
        ),
        trigger: (
          <Button variant="outline">
            {t("Edit in a sheet", "在侧边栏中编辑")}
          </Button>
        ),
      }),
    ];
  }, [zh]);
  const finish = async (values: Record<string, unknown>) => {
    await wait();
    setSubmitted(values);
  };
  const labels = zh ? dataFormLabelsZhCN : undefined;
  return (
    <div className="flex w-full max-w-md flex-col gap-6">
      <div className="flex flex-wrap gap-2">
        <DataForm
          fields={fields}
          plugins={inDialog}
          labels={labels}
          onFinish={finish}
        />
        <DataForm
          fields={fields}
          plugins={inSheet}
          labels={labels}
          defaultValues={{ name: "Website", visibility: "team" }}
          onFinish={finish}
        />
      </div>
      {submitted}
    </div>
  );
}
```

## Filters

`layout="grid"` with `collapse` is a query form: the first fields and an Expand button, then Reset and Search. Expanding and collapsing animate the height while the extra fields fade in, and drop the motion under reduced motion; collapsed fields stay mounted, so their values and validation remain. `layout="light"` with `submitOn="change"` shows each field as a compact button that sums up its value; fields past `collapse.count` share one Filters popover and apply together. Set `lightMode` per field to choose: `inline` puts the control itself on the row with its label, `popover` a compact button that opens it, and `more` the Filters popover whatever the count. Date and time pickers are `inline` by default, other controls `popover`. [Data Table](/docs/components/data-table)'s query form and toolbar filters are these two layouts.

### Example: data-form-filters

```tsx
"use client";

import {
  DataForm,
  type DataFormFieldConfig,
  dataFormLabelsZhCN,
} from "@workspace/ui/components/data-form";
import { useMemo, useState } from "react";
import type { ExampleProps } from "../types";
import { text } from "./data-form-support";

function filterFields(zh: boolean): DataFormFieldConfig[] {
  const t = text(zh);
  return [
    // `inline` puts the control on the row; `more` keeps it in Filters.
    { name: "keyword", label: t("Name", "名称"), lightMode: "inline" },
    {
      name: "status",
      label: t("Status", "状态"),
      valueType: "multiSelect",
      valueEnum: {
        open: t("Open", "进行中"),
        paused: t("Paused", "已暂停"),
        done: t("Done", "已完成"),
      },
    },
    {
      name: "createdAt",
      label: t("Created", "创建时间"),
      valueType: "dateRange",
    },
    { name: "amount", label: t("Amount", "金额"), valueType: "digitRange" },
    { name: "owner", label: t("Owner", "负责人") },
    {
      name: "archived",
      label: t("Archived", "已归档"),
      valueType: "boolean",
      lightMode: "more",
    },
  ];
}

function Payload({ value }: { value: unknown }) {
  return (
    <pre className="overflow-x-auto rounded-xl bg-muted p-3 font-mono text-xs">
      {JSON.stringify(value)}
    </pre>
  );
}

export default function DataFormFilters({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const t = text(zh);
  const [query, setQuery] = useState<unknown>({});
  const [light, setLight] = useState<unknown>({});
  const fields = useMemo(() => filterFields(zh), [zh]);
  const labels = zh ? dataFormLabelsZhCN : undefined;
  return (
    <div className="flex w-full flex-col gap-8">
      <section className="flex flex-col gap-3">
        <h3 className="font-semibold text-base">
          {t("Query form", "查询表单")}
        </h3>
        <DataForm
          layout="grid"
          columns={3}
          collapse={{ count: 3 }}
          fields={fields}
          labels={labels}
          onFinish={setQuery}
        />
        <Payload value={query} />
      </section>
      <section className="flex flex-col gap-3">
        <h3 className="font-semibold text-base">
          {t("Light filter", "轻量筛选")}
        </h3>
        <DataForm
          layout="light"
          submitOn="change"
          collapse={{ count: 3 }}
          fields={fields}
          labels={labels}
          onFinish={setLight}
        />
        <Payload value={light} />
      </section>
    </div>
  );
}
```

## Submission

The payload leaves out hidden fields, then applies each field's `transform` (return an object to replace the field with several keys, such as `{ startAt, endAt }`), writes dates as local `yyyy-mm-dd` (`dateFormatter`), drops `null` and `undefined` with `omitNil`, and finally runs the form's `transform`. `convertValue` reads stored values into the shape a control uses; it runs only on values that are present, so give a starting value with `initialValue`.

`request` loads the initial values, with skeletons in place of the controls. Reset returns to the values `request` or `reset(values)` last set. `Cmd`/`Ctrl` + `Enter` submits.

## Plugins

| Plugin | Adds |
| --- | --- |
| `dialog(options)`, `sheet(options)` | An overlay with `title`, `description`, `trigger`, `open`, `onOpenChange` |
| `steps(options)` | Steps from `items: [{ key, title, description }]`; `current` and `onCurrentChange` to control them |
| `persistDraft({ key })` | Keeps unsent changes in localStorage, with the current step, and offers to restore them; a successful submit clears the draft. Passwords and hidden fields are never stored |
| `confirmLeave()` | Asks before leaving the page with unsaved changes |

A plugin is an object with a `name` and any of `setup` (runs as a hook), `wrapForm`, `slots` (`header`, `footer`), `isFieldShown`, `beforeSubmit`, `onSubmitInvalid`, `onFinished` and `onReset`. `onCancel` gives every footer a Cancel button, and `persistKeys` names the plugin state a saved draft keeps, as the steps keep the current step. Memoize the plugin list.

## Labels

English is the default. Pass `labels={dataFormLabelsZhCN}` for Chinese, or override individual entries. Validation messages from a schema come from the schema.

## API

| Prop | Description |
| --- | --- |
| `fields` | Field configuration. |
| `children` | Content after `fields`, such as `DataFormItem`. |
| `defaultValues` | Initial values. |
| `request` | Loads the initial values. |
| `onFinish` | Receives the payload; may return `{ fields, form }`. |
| `onFinishFailed` | Called when validation fails or `onFinish` throws. |
| `validator` | A Standard Schema or function for the whole form. |
| `layout` | `vertical` (default), `horizontal`, `grid` or `light`. |
| `columns` | Grid columns on wide containers. |
| `collapse` | `true`, or `{ count, defaultCollapsed }`. |
| `submitOn` | `submit` (default) or `change`. |
| `readonly`, `access` | Read-only views and per-field permissions. |
| `submitter` | `false` hides the buttons; a node replaces them. |
| `stickyFooter` | Keeps the buttons in view on a long page. |
| `transform`, `convertValue`, `dateFormatter`, `omitNil` | Payload shaping. |
| `plugins`, `labels`, `valueTypes` | Plugins, text and custom value types. |
| `actionRef` | Receives `{ submit, reset, validate, validateFields, setValues, setErrors }`. `validate()` runs field and form validators, as submit does, and resolves `true` when the form is valid. |
| `form` | A form from `useDataForm`, instead of the options above. |

Field configuration:

| Field | Description |
| --- | --- |
| `name` | A dot or bracket path. |
| `label`, `description`, `tooltip`, `placeholder` | Text around the control. |
| `valueType`, `valueEnum`, `options`, `request`, `fieldProps` | The control and its options. |
| `hidden`, `required`, `disabled`, `readonly` | A value or a function of the values. |
| `reactions`, `dependencies`, `clearOnChange` | Linking. |
| `validators` | `onBlur`, `onSubmit`, `onChange`, `onBlurAsync`, `onChangeAsync`, `debounceMs`. |
| `initialValue`, `convertValue`, `transform` | Values in and out. |
| `colSpan`, `step`, `className`, `render` | Placement and a custom control. |
| `lightMode` | `inline`, `popover` or `more` in a light layout. |

The design draws on Ant Design ProForm for field configuration, value types and overlay forms, and on Formily for field reactions; state runs on [TanStack Form](https://tanstack.com/form).
