# Data Table

A table driven by column configuration, with local or remote data, search, filters, selection and plugins.

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

### Example: data-table-demo

```tsx
"use client";

import { Button } from "@workspace/ui/components/button";
import {
  bulkActions,
  DataTable,
  type DataTableColumn,
  dataTableLabelsZhCN,
  proPlugins,
} from "@workspace/ui/components/data-table";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@workspace/ui/components/dropdown-menu";
import { Archive, Download, Ellipsis, Plus, Trash2 } from "lucide-react";
import { useMemo } from "react";
import { userOptions } from "../support/data-table-columns";
import { fetchUsers, type User } from "../support/data-table-users";
import type { ExampleProps } from "../types";

export default function DataTableDemo({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const columns = useMemo<DataTableColumn<User>[]>(() => {
    const { status, role } = userOptions(zh);
    return [
      {
        key: "name",
        title: zh ? "姓名" : "Name",
        sortable: true,
        primary: true,
        search: { placeholder: zh ? "姓名或邮箱" : "Name or email" },
      },
      { key: "email", title: zh ? "邮箱" : "Email", copyable: true },
      {
        key: "status",
        title: zh ? "状态" : "Status",
        valueEnum: status,
        filter: false,
        search: true,
      },
      {
        key: "role",
        title: zh ? "角色" : "Role",
        valueEnum: role,
        search: { type: "multiSelect" },
      },
      {
        key: "amount",
        title: zh ? "消费" : "Spend",
        valueType: "money",
        align: "end",
        sortable: true,
        search: {
          transform: (value) => {
            const [min, max] = value as [string?, string?];
            return { minAmount: min, maxAmount: max };
          },
        },
      },
      {
        key: "usage",
        title: zh ? "用量" : "Usage",
        valueType: "percent",
        align: "end",
        tooltip: zh ? "本月配额使用比例" : "Share of this month's quota",
      },
      {
        key: "verified",
        title: zh ? "已验证" : "Verified",
        valueType: "boolean",
      },
      {
        key: "createdAt",
        title: zh ? "创建时间" : "Created",
        valueType: "date",
        sortable: true,
        search: {
          transform: (value) => {
            const [from, to] = value as [string?, string?];
            return { createdFrom: from, createdTo: to };
          },
        },
      },
      {
        id: "actions",
        title: zh ? "操作" : "Actions",
        fixed: "end",
        width: 72,
        align: "end",
        render: () => (
          <DropdownMenu>
            <DropdownMenuTrigger
              render={
                <Button
                  variant="ghost"
                  size="icon-sm"
                  aria-label={zh ? "更多" : "More"}
                />
              }
            >
              <Ellipsis />
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem>{zh ? "编辑" : "Edit"}</DropdownMenuItem>
              <DropdownMenuItem variant="destructive">
                {zh ? "删除" : "Delete"}
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        ),
      },
    ];
  }, [zh]);
  const plugins = useMemo(
    () => [
      ...proPlugins<User>({ urlSync: false }),
      bulkActions<User>([
        {
          label: zh ? "导出" : "Export",
          icon: <Download />,
          onClick: () => {},
        },
        {
          label: zh ? "归档" : "Archive",
          icon: <Archive />,
          onClick: () => {},
        },
        {
          label: zh ? "删除" : "Delete",
          icon: <Trash2 />,
          variant: "destructive",
          onClick: (_, table) => table.selection?.clear(),
        },
      ]),
    ],
    [zh],
  );
  return (
    <div className="h-[680px] w-full">
      <DataTable
        rowKey="id"
        columns={columns}
        request={fetchUsers}
        plugins={plugins}
        rowSelection
        labels={zh ? dataTableLabelsZhCN : undefined}
        title={zh ? "用户" : "Users"}
        toolbar={
          <Button size="sm">
            <Plus />
            {zh ? "新建" : "New"}
          </Button>
        }
      />
    </div>
  );
}
```

## Installation

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

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.

  DataTable installs as `components/ui/data-table/index.tsx`. If you installed it
  from SUI 5.4 or earlier, delete the old `components/ui/data-table.tsx` after
  updating: a file beside the folder wins over its index, so imports would
  keep the old version. See [Update installed
  source](/docs/registry#updating-source).

```tsx
import { DataTable, type DataTableColumn } from "@workspace/ui/components/data-table"
```

## Usage

Describe each column once with plain fields. `valueType` formats cells, `valueEnum` renders badges and adds a quick filter, `search` adds a query form field, and `sortable` adds a header menu.

```tsx
const columns: DataTableColumn<User>[] = [
  { key: "name", title: "Name", keyword: true, sortable: true },
  { key: "status", title: "Status", valueEnum: statusOptions },
  { key: "amount", title: "Spend", valueType: "money", align: "end", sortable: true },
  { key: "createdAt", title: "Created", valueType: "date", search: true },
  { key: "profile.city", title: "City", hidden: true },
  { id: "actions", title: "Actions", fixed: "end", render: (user) => <RowMenu user={user} /> },
]

<DataTable rowKey="id" columns={columns} data={users} />
```

`key` accepts typed dot paths, and `render(value, row)` receives the value type of that path. A column with `id` and no `key` is a display column such as row actions.

Pass `data` to sort, filter and page in the browser, or `request` to let the server do it:

```tsx
<DataTable
  rowKey="id"
  columns={columns}
  request={async ({ page, pageSize, sort, keyword, search, filters, advanced, signal }) => {
    const response = await fetch(`/api/users?${toQuery({ page, pageSize, sort, keyword, search, filters })}`, { signal })
    return response.json() // { data, total }
  }}
/>
```

Requests are cancelled when parameters change, so late responses never replace newer rows. Without `total`, pagination shows previous and next only.

## Local data and toolbar plugins

Columns with `keyword` share the toolbar search box. Enum columns get quick filters with option counts. Features beyond the core are plugins: `density()`, `columnSettings()` (visibility, drag ordering, pinning and header-edge width handles) and `exportCsv()` (current page, every match, or the selection).

The toolbar stays on one row. The search box and filters scroll sideways and the actions stay at the end. Date range columns sit on the row next to the quick filters, with `search.presets` for quick ranges such as the last seven days. Past `maxFilters` (2 by default), the first filter stays and the rest share one Filters button (`DataTableMoreFilters`), applied together. The filters are a light [Data Form](/docs/components/data-form): each quick filter is a compact button that sums up its value and applies at once, and the Filters panel is a draft form applied with Apply. Add `lightForm({ maxFilters })` to set it among other plugins. A column chooses where its quick filter goes with `filter: "inline"` (its dropdown on the row), `"popover"` (the default, with option counts) or `"more"` (always in Filters); date ranges take `search: { lightMode }`. On phones only the search box stays on the row. The `toolbarSearch` slot adds inputs right after the search box, and `DataTableChoiceMenu` is an icon button with a single-choice menu for toolbar options.

### Example: data-table-toolbar

```tsx
"use client";

import {
  DataTable,
  type DataTableColumn,
  dataTableLabelsZhCN,
  density,
} from "@workspace/ui/components/data-table";
import { useMemo } from "react";
import { userColumns } from "../support/data-table-columns";
import { type User, users } from "../support/data-table-users";
import type { ExampleProps } from "../types";

function daysAgo(days: number) {
  const date = new Date();
  date.setDate(date.getDate() - days);
  return date;
}

export default function DataTableToolbarExample({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const columns = useMemo<DataTableColumn<User>[]>(
    () => [
      ...userColumns(zh).map((column) =>
        "key" in column && column.key === "createdAt"
          ? {
              ...column,
              search: {
                type: "dateRange" as const,
                presets: [
                  {
                    label: zh ? "最近 7 天" : "Last 7 days",
                    value: () => ({ from: daysAgo(6), to: new Date() }),
                  },
                  {
                    label: zh ? "最近 30 天" : "Last 30 days",
                    value: () => ({ from: daysAgo(29), to: new Date() }),
                  },
                ],
              },
            }
          : column,
      ),
      {
        key: "verified",
        title: zh ? "已验证" : "Verified",
        valueType: "boolean",
        search: true,
      },
    ],
    [zh],
  );
  const plugins = useMemo(() => [density<User>()], []);
  return (
    <DataTable
      rowKey="id"
      layout="auto"
      columns={columns}
      data={users}
      plugins={plugins}
      labels={zh ? dataTableLabelsZhCN : undefined}
      className="w-full"
    />
  );
}
```

### Example: data-table-local

```tsx
"use client";

import {
  columnSettings,
  DataTable,
  dataTableLabelsZhCN,
  density,
  exportCsv,
} from "@workspace/ui/components/data-table";
import { useMemo } from "react";
import { userColumns } from "../support/data-table-columns";
import { type User, users } from "../support/data-table-users";
import type { ExampleProps } from "../types";

export default function DataTableLocal({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const columns = useMemo(() => userColumns(zh), [zh]);
  const plugins = useMemo(
    () => [
      density<User>(),
      columnSettings<User>(),
      exportCsv<User>({ filename: "users" }),
    ],
    [],
  );
  return (
    <DataTable
      rowKey="id"
      layout="auto"
      columns={columns}
      data={users}
      plugins={plugins}
      labels={zh ? dataTableLabelsZhCN : undefined}
      className="w-full"
    />
  );
}
```

## Value types

| `valueType` | Cell | Default search field |
| --- | --- | --- |
| `text` | Plain text; `ellipsis` and `copyable` add LongText and CopyText | `text` |
| `number`, `money`, `percent` | `Intl.NumberFormat`; set `format`, such as `{ currency: "CNY" }` | `numberRange` |
| `date`, `datetime` | `Intl.DateTimeFormat` with the `locale` of the labels | `dateRange`, `datetimeRange` |
| `enum` | Badge from `valueEnum`, with `color` per option | `select` |
| `boolean` | Yes or No from labels | `boolean` |

### Example: data-table-value-types

```tsx
"use client";

import {
  DataTable,
  type DataTableColumn,
  dataTableLabelsZhCN,
} from "@workspace/ui/components/data-table";
import { useMemo } from "react";
import type { ExampleProps } from "../types";

type Invoice = {
  id: string;
  customer: string;
  status: "paid" | "open" | "void";
  total: number;
  tax: number;
  quantity: number;
  issuedAt: string;
  updatedAt: string;
  sent: boolean;
};

const invoices: Invoice[] = [
  {
    id: "INV-1001",
    customer: "Northwind",
    status: "paid",
    total: 12840.5,
    tax: 13,
    quantity: 18,
    issuedAt: "2026-03-02",
    updatedAt: "2026-03-04T09:30:00Z",
    sent: true,
  },
  {
    id: "INV-1002",
    customer: "Contoso",
    status: "open",
    total: 5420,
    tax: 6,
    quantity: 4,
    issuedAt: "2026-03-11",
    updatedAt: "2026-03-12T16:05:00Z",
    sent: true,
  },
  {
    id: "INV-1003",
    customer: "Fabrikam",
    status: "void",
    total: 980.25,
    tax: 0,
    quantity: 1,
    issuedAt: "2026-04-01",
    updatedAt: "2026-04-01T08:12:00Z",
    sent: false,
  },
];

export default function DataTableValueTypes({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const columns = useMemo<DataTableColumn<Invoice>[]>(
    () => [
      { key: "id", title: zh ? "编号" : "Invoice", copyable: true },
      { key: "customer", title: zh ? "客户" : "Customer", valueType: "text" },
      {
        key: "status",
        title: zh ? "状态" : "Status",
        valueEnum: [
          { value: "paid", label: zh ? "已付款" : "Paid" },
          { value: "open", label: zh ? "待付款" : "Open", color: "outline" },
          {
            value: "void",
            label: zh ? "已作废" : "Void",
            color: "destructive",
          },
        ],
        filter: false,
      },
      {
        key: "total",
        title: zh ? "金额" : "Total",
        valueType: "money",
        format: { currency: zh ? "CNY" : "USD" },
        align: "end",
      },
      {
        key: "tax",
        title: zh ? "税率" : "Tax",
        valueType: "percent",
        align: "end",
      },
      {
        key: "quantity",
        title: zh ? "数量" : "Qty",
        valueType: "number",
        align: "end",
      },
      { key: "issuedAt", title: zh ? "开票日期" : "Issued", valueType: "date" },
      {
        key: "updatedAt",
        title: zh ? "更新时间" : "Updated",
        valueType: "datetime",
        format: { dateStyle: "medium", timeStyle: "short", timeZone: "UTC" },
      },
      { key: "sent", title: zh ? "已发送" : "Sent", valueType: "boolean" },
    ],
    [zh],
  );
  return (
    <DataTable
      rowKey="id"
      layout="auto"
      pagination={false}
      columns={columns}
      data={invoices}
      labels={zh ? dataTableLabelsZhCN : undefined}
      className="w-full"
    />
  );
}
```

## Query form

`queryForm()` builds a collapsible multi-field form from columns with `search`. Fields apply together when submitted. Field types are `text`, `number`, `numberRange`, `select`, `multiSelect`, `date`, `dateRange`, `datetimeRange`, `boolean` and `custom` (with `render`). Use `order` and `colSpan` for placement, `options` as a function and `dependencies` for linked fields such as province and city, `searchOnly` for fields without a table column, and `transform` to rename request parameters, for example a date range to `{ createdFrom, createdTo }`.

The form is a [Data Form](/docs/components/data-form) grid, so `search` also takes field options such as `reactions`, `validators`, `valueType` and `fieldProps`. Values keep the shapes the table stores, such as local date strings, so URL sync and requests read them as before.

### Example: data-table-query-form

```tsx
"use client";

import {
  DataTable,
  type DataTableColumn,
  dataTableLabelsZhCN,
  queryForm,
  reload,
} from "@workspace/ui/components/data-table";
import { useMemo } from "react";
import { userOptions } from "../support/data-table-columns";
import {
  citiesOf,
  provinces,
  type User,
  users,
} from "../support/data-table-users";
import type { ExampleProps } from "../types";

export default function DataTableQueryForm({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const columns = useMemo<DataTableColumn<User>[]>(() => {
    const { status, role } = userOptions(zh);
    return [
      {
        key: "name",
        title: zh ? "姓名" : "Name",
        search: true,
        sortable: true,
      },
      {
        key: "status",
        title: zh ? "状态" : "Status",
        valueEnum: status,
        filter: false,
        search: true,
      },
      {
        key: "role",
        title: zh ? "角色" : "Role",
        valueEnum: role,
        filter: false,
        search: { type: "multiSelect" },
      },
      {
        key: "amount",
        title: zh ? "消费" : "Spend",
        valueType: "money",
        align: "end",
        search: true,
      },
      {
        key: "createdAt",
        title: zh ? "创建时间" : "Created",
        valueType: "date",
        search: true,
      },
      {
        key: "profile.province",
        id: "province",
        title: zh ? "省份" : "Province",
        search: { type: "select", options: provinces, order: 1 },
      },
      {
        key: "profile.city",
        id: "city",
        title: zh ? "城市" : "City",
        search: {
          type: "select",
          order: 2,
          dependencies: ["province"],
          options: (values) => citiesOf(values.province),
        },
      },
      {
        key: "verified",
        title: zh ? "已验证" : "Verified",
        valueType: "boolean",
        searchOnly: true,
      },
    ];
  }, [zh]);
  const plugins = useMemo(
    () => [queryForm<User>({ collapsedCount: 3 }), reload<User>()],
    [],
  );
  return (
    <DataTable
      rowKey="id"
      layout="auto"
      columns={columns}
      data={users}
      plugins={plugins}
      labels={zh ? dataTableLabelsZhCN : undefined}
      className="w-full"
    />
  );
}
```

## Advanced filter

`advancedFilter()` adds a builder for field, operator and value rules joined with AND or OR. Operators follow the value type of each column. Pass `storageKey` to save named views in local storage.

### Example: data-table-advanced-filter

```tsx
"use client";

import {
  advancedFilter,
  DataTable,
  dataTableLabelsZhCN,
} from "@workspace/ui/components/data-table";
import { useMemo } from "react";
import { userColumns } from "../support/data-table-columns";
import { type User, users } from "../support/data-table-users";
import type { ExampleProps } from "../types";

export default function DataTableAdvancedFilter({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const columns = useMemo(() => userColumns(zh), [zh]);
  const plugins = useMemo(
    () => [advancedFilter<User>({ storageKey: "sui-docs-user-views" })],
    [],
  );
  return (
    <DataTable
      rowKey="id"
      layout="auto"
      columns={columns}
      data={users}
      plugins={plugins}
      labels={zh ? dataTableLabelsZhCN : undefined}
      initialState={{
        query: {
          advanced: {
            logic: "and",
            rules: [
              { id: "spend", field: "amount", operator: "gte", value: "1000" },
            ],
          },
        },
      }}
      className="w-full"
    />
  );
}
```

## Editing rows

`editable({ onSave })` edits a row in place. Each data column becomes the control of its value type, with the same validation and linking as a [Data Form](/docs/components/data-form) field; `form` on a column adds field options such as `required`, or `form: false` keeps it as text. Enter in a text field saves and Escape cancels; keys inside a select or calendar stay with that control. The Edit, Save and Cancel buttons sit in a column pinned to the end, kept out of column settings and exports. Return or throw `{ fields, form }` from `onSave` to show errors in the row; the row stays open until a save succeeds, and the page updates its own rows.

### Example: data-table-editable

```tsx
"use client";

import {
  DataTable,
  type DataTableColumn,
  dataTableLabelsZhCN,
  editable,
} from "@workspace/ui/components/data-table";
import { useMemo, useState } from "react";
import { userColumns } from "../support/data-table-columns";
import { type User, users } from "../support/data-table-users";
import type { ExampleProps } from "../types";

export default function DataTableEditable({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const [data, setData] = useState(() => users.slice(0, 6));
  const columns = useMemo<DataTableColumn<User>[]>(
    () =>
      userColumns(zh).map((column) =>
        column.key === "name"
          ? { ...column, form: { required: true } }
          : column,
      ),
    [zh],
  );
  const plugins = useMemo(
    () => [
      editable<User>({
        onSave: async (row, values) => {
          await new Promise((resolve) => setTimeout(resolve, 400));
          // Errors from the server land in the row, under their cell.
          if (values.email === "taken@example.com")
            return {
              fields: {
                email: zh ? "这个邮箱已被使用。" : "This email is in use.",
              },
            };
          setData((current) =>
            current.map((item) =>
              item.id === row.id ? ({ ...item, ...values } as User) : item,
            ),
          );
        },
      }),
    ],
    [zh],
  );
  return (
    <DataTable
      rowKey="id"
      layout="auto"
      columns={columns}
      data={data}
      plugins={plugins}
      // Spending is read-only here; nobody edits the creation date.
      access={{ amount: "readonly", createdAt: "readonly" }}
      pagination={false}
      labels={zh ? dataTableLabelsZhCN : undefined}
      className="w-full"
    />
  );
}
```

`access` maps column keys to `hidden`, which leaves a column out of the table, its filters and its exports, or `readonly`, which keeps `editable()` from editing it. An inline map can be written in place; a function is compared by identity, so memoize it.

## Forms from columns

`toFormFields(columns)` turns the table's columns into DataForm fields, so one definition serves the table, its filters, its row editing and its create and edit forms. The table's value types are DataForm value types too (a `boolean` column edits as a `switch`), `valueEnum` becomes the options, and `form` on a column adds field options or leaves it out.

### Example: data-table-form

```tsx
"use client";

import { Button } from "@workspace/ui/components/button";
import {
  DataForm,
  dataFormLabelsZhCN,
  sheet,
} from "@workspace/ui/components/data-form";
import {
  DataTable,
  dataTableLabelsZhCN,
  toFormFields,
} from "@workspace/ui/components/data-table";
import { useMemo, useState } from "react";
import { userColumns } from "../support/data-table-columns";
import { type User, users } from "../support/data-table-users";
import type { ExampleProps } from "../types";

export default function DataTableForm({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const [data, setData] = useState(() => users.slice(0, 5));
  const columns = useMemo(() => userColumns(zh), [zh]);
  // The same columns describe the table and the form; `form` on a column
  // adds field options, such as `required`, or leaves it out.
  const fields = useMemo(
    () =>
      toFormFields(columns).map((field) =>
        field.name === "name" || field.name === "email"
          ? { ...field, required: true }
          : field,
      ),
    [columns],
  );
  const plugins = useMemo(
    () => [
      sheet({
        title: zh ? "新建用户" : "New user",
        description: zh
          ? "字段来自表格的列配置。"
          : "The fields come from the table's columns.",
        trigger: <Button>{zh ? "新建用户" : "New user"}</Button>,
      }),
    ],
    [zh],
  );
  return (
    <DataTable
      rowKey="id"
      layout="auto"
      columns={columns}
      data={data}
      pagination={false}
      labels={zh ? dataTableLabelsZhCN : undefined}
      className="w-full"
      toolbar={
        <DataForm
          fields={fields}
          plugins={plugins}
          labels={zh ? dataFormLabelsZhCN : undefined}
          defaultValues={{ status: "invited", role: "viewer" }}
          onFinish={(values) =>
            setData((current) => [
              {
                ...(values as Partial<User>),
                id: `new-${current.length + 1}`,
                amount: Number(values.amount ?? 0),
                usage: 0,
                verified: false,
                createdAt:
                  String(values.createdAt ?? "") ||
                  new Date().toISOString().slice(0, 10),
                profile: { province: "", city: "" },
              } as User,
              ...current,
            ])
          }
        />
      }
    />
  );
}
```

## Clearing conditions

The toolbar stays one row. Each control already shows and clears its own value: the search box, the quick-filter badges, the date fields and the query form's fields. While any condition applies (a keyword, a search field, a quick filter or advanced rules), a **Clear all** button follows the filter controls on the same row and resets them together; with no conditions it is hidden. The query form keeps its own **Reset**.

Pass `chips` to also list the active conditions as removable chips below the toolbar, with their own clear-all button, for tables whose conditions are not all visible in the toolbar.

### Example: data-table-chips

```tsx
"use client";

import {
  DataTable,
  dataTableLabelsZhCN,
} from "@workspace/ui/components/data-table";
import { useMemo } from "react";
import { userColumns } from "../support/data-table-columns";
import { users } from "../support/data-table-users";
import type { ExampleProps } from "../types";

export default function DataTableChips({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const columns = useMemo(() => userColumns(zh), [zh]);
  return (
    <DataTable
      rowKey="id"
      layout="auto"
      chips
      columns={columns}
      data={users}
      labels={zh ? dataTableLabelsZhCN : undefined}
      initialState={{
        pageSize: 5,
        query: { keyword: "a", filters: { status: ["active", "invited"] } },
      }}
      className="w-full"
    />
  );
}
```

## Selection, bulk actions and expandable rows

`rowSelection` adds a checkbox column; selections persist across pages. `bulkActions([{ label, icon, onClick, variant }])` shows a floating bar of icon buttons, with labels as tooltips, above the pagination while rows are selected; pass a render function instead for custom content. Escape clears the selection. `expandable(render)` adds a toggle that reveals details with height motion.

### Example: data-table-expandable

```tsx
"use client";

import {
  bulkActions,
  DataTable,
  dataTableLabelsZhCN,
  density,
  expandable,
} from "@workspace/ui/components/data-table";
import { Download } from "lucide-react";
import { useMemo } from "react";
import { userColumns } from "../support/data-table-columns";
import { type User, users } from "../support/data-table-users";
import type { ExampleProps } from "../types";

export default function DataTableExpandable({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const columns = useMemo(() => userColumns(zh).slice(0, 4), [zh]);
  const plugins = useMemo(
    () => [
      expandable<User>((user) => (
        <dl className="grid grid-cols-[auto_1fr] gap-x-6 gap-y-1 text-sm sm:grid-cols-[auto_1fr_auto_1fr]">
          <dt className="text-muted-foreground">{zh ? "省份" : "Province"}</dt>
          <dd>{user.profile.province}</dd>
          <dt className="text-muted-foreground">{zh ? "城市" : "City"}</dt>
          <dd>{user.profile.city}</dd>
          <dt className="text-muted-foreground">{zh ? "用量" : "Usage"}</dt>
          <dd>{user.usage}%</dd>
          <dt className="text-muted-foreground">
            {zh ? "已验证" : "Verified"}
          </dt>
          <dd>{user.verified ? "✓" : "—"}</dd>
        </dl>
      )),
      density<User>(),
      bulkActions<User>([
        {
          label: zh ? "导出" : "Export",
          icon: <Download />,
          onClick: () => {},
        },
      ]),
    ],
    [zh],
  );
  return (
    <div className="h-[520px] w-full">
      <DataTable
        rowKey="id"
        columns={columns}
        data={users}
        plugins={plugins}
        rowSelection
        labels={zh ? dataTableLabelsZhCN : undefined}
      />
    </div>
  );
}
```

## Drag sorting

`dragSort({ onDragEnd })` adds a handle column. Rows move by pointer or keyboard (Space, arrow keys, Space). Sorting and pagination are off while it is active.

### Example: data-table-drag-sort

```tsx
"use client";

import {
  DataTable,
  type DataTableColumn,
  dataTableLabelsZhCN,
  dragSort,
} from "@workspace/ui/components/data-table";
import { useMemo, useState } from "react";
import type { ExampleProps } from "../types";

type Task = { id: string; title: string; priority: "high" | "medium" | "low" };

const tasks: Task[] = [
  { id: "1", title: "Write release notes", priority: "high" },
  { id: "2", title: "Review pull requests", priority: "medium" },
  { id: "3", title: "Update dependencies", priority: "low" },
  { id: "4", title: "Plan the next sprint", priority: "medium" },
  { id: "5", title: "Fix flaky tests", priority: "high" },
];

export default function DataTableDragSort({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const [order, setOrder] = useState(tasks.map((task) => task.id));
  const columns = useMemo<DataTableColumn<Task>[]>(
    () => [
      { key: "title", title: zh ? "任务" : "Task" },
      {
        key: "priority",
        title: zh ? "优先级" : "Priority",
        filter: false,
        valueEnum: [
          { value: "high", label: zh ? "高" : "High", color: "destructive" },
          { value: "medium", label: zh ? "中" : "Medium", color: "secondary" },
          { value: "low", label: zh ? "低" : "Low", color: "outline" },
        ],
      },
    ],
    [zh],
  );
  const plugins = useMemo(
    () => [
      dragSort<Task>({
        onDragEnd: (rows) => setOrder(rows.map((row) => row.id)),
      }),
    ],
    [],
  );
  return (
    <div className="w-full space-y-3">
      <DataTable
        rowKey="id"
        layout="auto"
        responsive={false}
        columns={columns}
        data={tasks}
        plugins={plugins}
        labels={zh ? dataTableLabelsZhCN : undefined}
      />
      <p className="text-muted-foreground text-sm">
        {zh ? "当前顺序：" : "Order: "}
        <code>{order.join(" → ")}</code>
      </p>
    </div>
  );
}
```

## Large lists

`virtual()` renders only the rows in view. Use it with `pagination={false}`; it turns off row layout animation.

### Example: data-table-virtual

```tsx
"use client";

import {
  DataTable,
  dataTableLabelsZhCN,
  virtual,
} from "@workspace/ui/components/data-table";
import { useMemo } from "react";
import { userColumns } from "../support/data-table-columns";
import { createUsers, type User } from "../support/data-table-users";
import type { ExampleProps } from "../types";

const manyUsers = createUsers(5000);

export default function DataTableVirtual({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const columns = useMemo(() => userColumns(zh), [zh]);
  const plugins = useMemo(() => [virtual<User>({ rowHeight: 41 })], []);
  return (
    <div className="h-[480px] w-full">
      <DataTable
        rowKey="id"
        pagination={false}
        responsive={false}
        columns={columns}
        data={manyUsers}
        plugins={plugins}
        labels={zh ? dataTableLabelsZhCN : undefined}
        title={zh ? `${manyUsers.length} 位用户` : `${manyUsers.length} users`}
      />
    </div>
  );
}
```

## Layout

The default `layout="fill"` takes the height of its parent like an admin page: the query form and toolbar stay at the top, rows scroll with a sticky header, and pagination stays at the bottom. Give the parent a height, for example `AppMain` with `flex-1 min-h-0`, or a fixed `h-[640px]` container. The table itself is only as tall as its rows: with a few rows the space falls between the table and the pagination, and with many it stops at the space left and scrolls. Use `layout="auto"` inside cards and dialogs to grow with the rows.

### Example: data-table-fill-few-rows

```tsx
"use client";

import {
  DataTable,
  dataTableLabelsZhCN,
} from "@workspace/ui/components/data-table";
import { useMemo } from "react";
import { userColumns } from "../support/data-table-columns";
import { createUsers } from "../support/data-table-users";
import type { ExampleProps } from "../types";

const fewUsers = createUsers(3);

export default function DataTableFillFewRows({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const columns = useMemo(() => userColumns(zh), [zh]);
  return (
    // A fixed height stands in for a page; three rows keep their own height
    // and the pagination stays at the bottom.
    <div className="h-[480px] w-full">
      <DataTable
        rowKey="id"
        columns={columns}
        data={fewUsers}
        labels={zh ? dataTableLabelsZhCN : undefined}
      />
    </div>
  );
}
```

On narrow screens rows become cards. Mark the heading column with `primary`, or set `responsive={false}` to keep the table.

## Composition

`useDataTable` returns the same table the component uses. Pass it to `DataTable` with children to arrange the parts yourself: `DataTableToolbar`, `DataTableSearch`, `DataTableFacetedFilter`, `DataTableFilterChips`, `DataTableSlotContent`, `DataTableContent` and `DataTablePagination`. The table also exposes state such as `total`, `selection` and `state`, and actions such as `reload()`.

### Example: data-table-composition

```tsx
"use client";

import { Badge } from "@workspace/ui/components/badge";
import {
  columnSettings,
  DataTable,
  DataTableContent,
  DataTableFacetedFilter,
  DataTableFilterChips,
  DataTablePagination,
  DataTableSearch,
  DataTableSlotContent,
  dataTableLabelsZhCN,
  useDataTable,
} from "@workspace/ui/components/data-table";
import { useMemo } from "react";
import { userColumns } from "../support/data-table-columns";
import { type User, users } from "../support/data-table-users";
import type { ExampleProps } from "../types";

export default function DataTableComposition({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const columns = useMemo(() => userColumns(zh), [zh]);
  const plugins = useMemo(() => [columnSettings<User>()], []);
  const table = useDataTable({
    rowKey: "id",
    columns,
    data: users,
    plugins,
    initialState: { pageSize: 5 },
    labels: zh ? dataTableLabelsZhCN : undefined,
  });
  return (
    <DataTable table={table} layout="auto" className="w-full">
      <div className="flex flex-wrap items-center gap-2">
        <DataTableSearch className="sm:w-56" />
        <DataTableFacetedFilter column="status" />
        <Badge variant="outline" className="ms-auto">
          {zh ? `匹配 ${table.total} 条` : `${table.total} matches`}
        </Badge>
        <DataTableSlotContent slot="toolbarEnd" />
      </div>
      <DataTableFilterChips />
      <DataTableContent className="rounded-xl border" />
      <DataTablePagination />
    </DataTable>
  );
}
```

## Views

`views({ grid, list, defaultView, onOpen })` lets readers switch the rows between the table, a list built from the columns, and a grid of cards when `grid` renders a row as a card. `persist` remembers the view a reader picked. Plugins can render views of their own with `renderView`, and the table exposes `view` and `setView()`.

### Example: data-table-views

```tsx
"use client";

import { Badge } from "@workspace/ui/components/badge";
import {
  DataTable,
  dataTableLabelsZhCN,
  views,
} from "@workspace/ui/components/data-table";
import { useMemo } from "react";
import { userColumns } from "../support/data-table-columns";
import { type User, users } from "../support/data-table-users";
import type { ExampleProps } from "../types";

export default function DataTableViews({ locale }: ExampleProps) {
  const zh = locale === "zh-CN";
  const columns = useMemo(() => userColumns(zh), [zh]);
  const plugins = useMemo(
    () => [
      views<User>({
        grid: (user) => (
          <div className="flex h-full flex-col gap-2 rounded-xl border p-4">
            <div className="font-medium">{user.name}</div>
            <div className="truncate text-muted-foreground text-sm">
              {user.email}
            </div>
            <div className="mt-auto flex gap-2">
              <Badge variant="secondary">{user.role}</Badge>
              <Badge variant="outline">{user.status}</Badge>
            </div>
          </div>
        ),
      }),
    ],
    [],
  );
  return (
    <DataTable
      rowKey="id"
      layout="auto"
      columns={columns}
      data={users}
      plugins={plugins}
      labels={zh ? dataTableLabelsZhCN : undefined}
      className="w-full"
    />
  );
}
```

## URL sync and persistence

`urlSync({ prefix })` keeps pagination, sorting, keyword, query form values, quick filters and advanced rules in the address bar with `history.replaceState`, without a router dependency. `persist({ key })` remembers column visibility, order, pinning, widths and density. `proPlugins()` combines the query form, advanced filter, reload, density, column settings, CSV export and URL sync.

```tsx
<DataTable
  rowKey="id"
  columns={columns}
  request={fetchUsers}
  rowSelection
  plugins={[...proPlugins<User>(), persist({ key: "users-table" }), bulkActions([{ label: "Delete", icon: <Trash2 />, variant: "destructive", onClick: deleteUsers }])]}
/>
```

Memoize the plugin list, for example with `useMemo`, so columns and features are not rebuilt on every render.

## Plugins

A plugin is an object with a `name` and any of these hooks into the core:

| Field | Purpose |
| --- | --- |
| `slots` | Render into `header`, `toolbarStart`, `toolbarSearch`, `toolbarFilters` (replaces the filters on the row), `toolbarEnd` or `floating` |
| `columns` | Add utility columns, such as checkboxes or handles |
| `features` | Turn on `virtual`, `dragSort`, `expandable` or `resizable` |
| `defaultView`, `initialView`, `renderView` | The starting view, a view restored for the reader (it wins over `defaultView`), or the rows in a view other than the table |
| `initialState`, `initialColumnState`, `initialDensity` | Restore state before the first request |
| `setup` | Runs as a hook in its own component, for effects such as syncing |
| `wrapBody`, `renderRow`, `renderAfterRow` | Wrap or extend rows |

## Labels

English is the default. Pass `labels={dataTableLabelsZhCN}` for Chinese, or override individual entries; the `locale` entry also formats numbers and dates.

## API

| Prop | Description |
| --- | --- |
| `columns` | Column configuration. |
| `data` | Local rows. |
| `request` | Remote rows: receives `{ page, pageSize, sort, keyword, search, filters, advanced, signal }` and returns `{ data, total? }`. |
| `rowKey` | Row identity, a key or a function. Required for selection, expansion and drag sorting. |
| `plugins` | Features beyond the core. |
| `rowSelection` | `true`, or `{ onChange, isDisabled }`. |
| `pagination` | `false`, or `{ pageSize, pageSizes }`. |
| `initialState` | Initial `page`, `pageSize`, `sort` and `query`. |
| `onStateChange` | Called with the state after each change. |
| `title`, `toolbar` | Toolbar heading and actions. |
| `maxFilters` | Filters on the toolbar row before the rest share a Filters button; defaults to `2`. |
| `chips` | `false` (default); `true` lists active conditions as removable chips below the toolbar. |
| `layout` | `fill` (default) or `auto`. |
| `responsive` | Cards on narrow screens; defaults to `true`. |
| `loading` | Loading state for local data. |
| `access` | Column permissions by key: `hidden` or `readonly`. |
| `labels` | Text overrides. |
| `actionRef` | Receives `{ reload, reset }`. |
| `table` | A table from `useDataTable`, instead of the options above. |

The design draws on [shadcn-admin](https://github.com/satnaing/shadcn-admin) tables for composable parts, Ant Design ProTable for column-driven search and requests, and motion tables for row transitions.
