---
title: DataTable
description: Sort, select, paginate, expand, pin, and resize tabular data with
  createDataTable and the DataTable presenter from moraine/data-table.
package: moraine
version: 0.11.0
repository: https://github.com/subframe7536/moraine
---

# DataTable

> Sort, select, paginate, expand, pin, and resize tabular data with createDataTable and the DataTable presenter from moraine/data-table.

## Anatomy

```text
DataTable [component; slot=root; <table>]
├── header [slot; <thead>]
│   └── row [slot; <tr>]
│       └── head [slot; <th>]
│           ├── checkbox [slot; <button role="checkbox">]
│           │   └── icon [internal]
│           ├── sortButton [slot; <button>]
│           │   ├── sortIcon [slot]
│           │   └── sortIndex [slot]
│           └── resizer [slot; <div role="separator">]
├── body [slot; <tbody>]
│   ├── row [slot; <tr>]
│   │   ├── cell [slot; <td>]
│   │   │   ├── checkbox [slot; <button role="checkbox">]
│   │   │   │   └── icon [internal]
│   │   │   ├── radio [internal; <input type="radio">]
│   │   │   └── expandButton [slot; <button>]
│   │   └── empty [slot; <td>]
│   └── expandedRow [slot; <tr>]
│       └── expandedCell [slot; <td>]
└── footer [slot; <tfoot>]
    └── row [slot; <tr>]
        └── cell [slot; <td>]
```

The `table` sits inside a `container` element that also holds the `loading` overlay, a scroll
viewport, and the pagination toolbar. The scroll viewport wraps only the table, so the toolbar
stays in place while rows scroll. The `container` draws the outer border and rounded corners and
clips pinned and sticky cells to them; replace them through `classes.container`. A body row renders
either data `cell`s or, when there are no rows, one full-width `empty` cell.

## Usage

Use DataTable when the table owns behavior: sorting, row selection, pagination, expansion, column
pinning, resizing, or server-driven data. For a static table you compose by hand, use
[Table](https://moraine.subf.dev/components/table.md). For a fully custom grid built on TanStack Table, compose `Table` parts
yourself, as in the TanStack example on the Table page.

DataTable ships from `moraine/data-table`, so the main `moraine` entry never imports TanStack Table.
Install the optional peer dependency first:

```shell title="pnpm" group-id="install"
pnpm add @tanstack/table-core
```

```shell title="bun" group-id="install"
bun add @tanstack/table-core
```

```shell title="npm" group-id="install"
npm install @tanstack/table-core
```

```shell title="yarn" group-id="install"
yarn add @tanstack/table-core
```

Create the instance with `createDataTable` inside a component, then pass it to `DataTable`.
Behavior lives on the instance; presentation lives on `DataTable`.

```tsx
import { DataTable, createDataTable } from 'moraine/data-table'
import type { DataTableT } from 'moraine/data-table'

interface User {
  id: string
  name: string
  role: string
}

const users: User[] = [
  { id: '1', name: 'Alice', role: 'Engineer' },
  { id: '2', name: 'Bob', role: 'Designer' },
]

const columns: DataTableT.Column<User>[] = [
  { accessorKey: 'name', header: 'Name' },
  { accessorKey: 'role', header: 'Role' },
]

export function Users() {
  const table = createDataTable({
    data: users,
    columns,
    getRowId: (user) => user.id,
    selectionMode: 'multiple',
  })

  return <DataTable table={table} aria-label="Users" />
}
```

### Options and props

`createDataTable` options configure behavior. The generated API reference does not cover them, so
they are listed here. `DataTable` props configure presentation and are in the API reference below.

| Concern     | `createDataTable` options                                                         | Default                                         |
| ----------- | --------------------------------------------------------------------------------- | ----------------------------------------------- |
| Data        | `data`, `columns`, `getRowId`                                                     | Row ids are indexes (`'0'`, nested `'0.1'`).    |
| Sorting     | `columnSortable`                                                                  | `true`                                          |
| Selection   | `selectionMode` (`'multiple'` or `'single'`), `canSelectRow`                      | No selection column.                            |
| Expansion   | `expandable` (`true` or a row predicate)                                          | Only rows with sub-rows expand.                 |
| Pagination  | `paginated` (`true` or `{ pageSize, pageSizes }`)                                 | Off. When on: 10 rows, sizes `[5, 10, 20, 50]`. |
| Resizing    | `resizable`                                                                       | `false`                                         |
| Server mode | `manual`, `rowCount`                                                              | `false`                                         |
| State       | `initialState`, `state`, `on[Slice]Change` callbacks                              | Uncontrolled.                                   |
| Other       | `tableOptions`: TanStack options without a top-level option, such as `getSubRows` | None.                                           |

| Concern       | `DataTable` props                                                             |
| ------------- | ----------------------------------------------------------------------------- |
| Instance      | `table` (required)                                                            |
| Layout        | `sticky`, `maxHeight`, `size`, `highlightOnHover`, `border`                   |
| Content       | `emptyRender`, `loading`, `loadingRender`, `expandedRowRender`, `virtualizer` |
| Rows, headers | `rowProps`, `headProps`, `onRowClick`, `onRowDoubleClick`                     |
| Styling, i18n | `classes`, `styles`, `class`, `style`, `wrapperRef`, `translations`           |

Other native `table` attributes, such as `aria-label`, are forwarded to the `table` element.

### Reactive options

Options are read reactively through the options object. Declare a getter for any value that
changes, on the options object or inside `state`. A plain value is read once.

```tsx
const table = createDataTable({
  get data() {
    return rows()
  },
  columns,
})
```

`createDataTable` tracks `data` and `columns` by reference. Return the same array until the data
actually changes; a new array on every read resets pagination and expansion each time.

### Columns

Columns are TanStack column definitions typed as `DataTableT.Column<TData>`. A column's id is its
`id`, else its `accessorKey` (with dots replaced by `_`), else a string `header`. State such as
`columnOrder`, `columnPinning`, and `columnSizing` refers to these ids.

`meta` adds Moraine presentation to the column's cells:

| `meta` field | Effect                                                        |
| ------------ | ------------------------------------------------------------- |
| `align`      | `'start'` (default), `'center'`, or `'end'` text.             |
| `truncated`  | Keeps cell text on one line with an ellipsis.                 |
| `class`      | Extra classes on the column's header, body, and footer cells. |

```tsx
const columns: DataTableT.Column<Invoice>[] = [
  { accessorKey: 'customer', header: 'Customer', meta: { truncated: true } },
  { accessorKey: 'amount', header: 'Amount', size: 120, meta: { align: 'end' } },
]
```

`selectionMode` and `expandable` prepend generated columns with the reserved ids `'select'` and
`'expand'`. Pin or order them by those ids. A column of your own whose id resolves to a reserved id
replaces the generated column. When that id comes from `accessorKey` or `header`, a development
warning suggests an explicit `id`, which keeps both columns.

### Sorting

Sorting is on by default, and each sortable header has a sort button. Shift-click a second
header to sort by more than one column. While more than one column is sorted, each sorted header
shows its priority (`sortIndex` slot), and screen readers hear it through the localized
`sortPriority` message. Set `columnSortable: false` to turn sorting off for every column, or
`enableSorting` in a column definition to override it for one column. Turn multi-column sorting off
with `tableOptions.enableMultiSort: false`.

The `alphanumeric`, `text`, and `datetime` sort functions are registered for a column's `sortingFn`.

### Controlled state

Each state slice is uncontrolled by default. Seed it with `initialState`, or control it through
`state`. A slice listed in `state` is owned by you; pair it with its change callback. Callbacks
receive the resolved next value, not a TanStack updater function, so a signal setter works
directly.

| Slice              | Callback                   |
| ------------------ | -------------------------- |
| `sorting`          | `onSortingChange`          |
| `pagination`       | `onPaginationChange`       |
| `rowSelection`     | `onRowSelectionChange`     |
| `expanded`         | `onExpandedChange`         |
| `columnOrder`      | `onColumnOrderChange`      |
| `columnPinning`    | `onColumnPinningChange`    |
| `columnVisibility` | `onColumnVisibilityChange` |
| `columnSizing`     | `onColumnSizingChange`     |
| `columnFilters`    | `onColumnFiltersChange`    |
| `globalFilter`     | `onGlobalFilterChange`     |

```tsx
const [sorting, setSorting] = createSignal<DataTableT.State['sorting']>([])

const table = createDataTable({
  data,
  columns,
  state: {
    get sorting() {
      return sorting()
    },
  },
  onSortingChange: setSorting,
})
```

A callback without a matching `state` key only listens; the slice stays uncontrolled.

`tableOptions` cannot set options that a top-level option already configures: `state`,
`initialState`, the change callbacks, `getRowId`, `getRowCanExpand`, the `enable*` switches for
sorting, selection, and resizing, `rowCount`, and the `manual*` modes. Use the top-level option
instead.

### Instance methods

The instance is a TanStack Solid Table instance. Call its methods for actions that have no
built-in control, such as filtering or reading the selection.

```tsx
table.setGlobalFilter('designer')
table.getColumn('role')?.setFilterValue('Engineer')

const selectedUsers = () => table.getSelectedRowModel().rows.map((row) => row.original)
```

The `includesString`, `equals`, `weakEquals`, `arrIncludes`, `inNumberRange`, and `inDateRange`
filter functions are registered.

### Selection

`selectionMode: 'multiple'` adds a checkbox to each row and a select-all checkbox to the header.
Select-all toggles the rows on the current page, and is then named with the `selectPage` message.
With tree data, a parent's checkbox follows its sub-rows: checked when all are selected and mixed
when some are. `selectionMode: 'single'` adds radio buttons; selecting a row clears the others.
`canSelectRow` disables the control of every row it rejects.

```tsx
const table = createDataTable({
  data: nodes,
  columns,
  getRowId: (node) => node.id,
  selectionMode: 'single',
  canSelectRow: (row) => row.original.status !== 'terminated',
})
```

Set `getRowId` when you read or store `rowSelection`. Its keys are row ids, and index ids point to
different records once the data is replaced or sorted on the server.

Selected rows get `data-selected` for styling. They do not get `aria-selected`, which is only valid
in a grid; the checkboxes and radios carry the selection semantics instead. Single-selection radios
share one name per table, so the group is one tab stop and arrow keys move the selection, skipping
disabled rows.

### Expansion

Rows expand in two different ways:

- **Detail rows.** Set `expandable` and pass `expandedRowRender`. An expanded row shows a
  full-width detail row below it, with an open and close animation. `expandable: true` lets every
  row expand; a predicate decides per row.
- **Tree data.** Pass `tableOptions.getSubRows`. Sub-rows render as ordinary rows under their
  parent. Without `expandable`, only rows with sub-rows can expand. To also show the chevron
  column, pass `expandable: (row) => row.subRows.length > 0`. Sub-rows indent the first data
  column, after the selection and expand columns, by one step per level. The step is the
  `--mo-data-table-indent` variable (`1.25rem`); override it with `styles.root`.

```tsx
const table = createDataTable({
  data: orders,
  columns,
  expandable: true,
})

return (
  <DataTable
    table={table}
    expandedRowRender={(props) => <OrderItems items={props.row.original.items} />}
  />
)
```

Control which rows are open with `state.expanded` and `onExpandedChange`.

### Pagination and server data

Pagination is off by default, and every row renders. Pass `paginated: true` for ten rows per
page, or `paginated: { pageSize, pageSizes }`. The toolbar below the table shows page navigation,
a page-size menu (`pageSizes: false` hides it), and a row summary: the total row count, or
"n of total selected" once a row is selected. The menu always lists the current page size.

For server-side sorting, filtering, and paging, set `manual: true`. Then `data` is the current
page, `rowCount` is the total across all pages, and the change callbacks tell you what to fetch.
In manual mode, the page index does not reset when the data changes.

```tsx
const [sorting, setSorting] = createSignal<DataTableT.State['sorting']>([])
const [pagination, setPagination] = createSignal({ pageIndex: 0, pageSize: 20 })

const table = createDataTable({
  get data() {
    return page()?.rows ?? []
  },
  get rowCount() {
    return page()?.total ?? 0
  },
  columns,
  manual: true,
  paginated: { pageSizes: [10, 20, 50] },
  state: {
    get sorting() {
      return sorting()
    },
    get pagination() {
      return pagination()
    },
  },
  onSortingChange: setSorting,
  onPaginationChange: setPagination,
})

return <DataTable table={table} loading={page.loading} />
```

### Loading and empty states

`loading` covers the table with an overlay and keeps the current rows visible underneath. While it
is set, the table has `aria-busy="true"`, and a `status` region that stays mounted announces the
localized `loading` text. The default overlay shows a spinner; replace it with `loadingRender`.

With no rows, the body shows one full-width cell with the `empty` message, or `emptyRender`. The
empty message is hidden while `loading` is set. Both render props receive `colSpan`.

```tsx
<DataTable
  table={table}
  loading={isFetching()}
  emptyRender={
    <Empty>
      <Empty.Title>No invoices</Empty.Title>
      <Empty.Description>Invoices you send appear here.</Empty.Description>
    </Empty>
  }
/>
```

### Pinned columns and sticky sections

Pin columns with `initialState.columnPinning` or `state.columnPinning`. Pinned columns stay at the
start or end edge while the rest scroll horizontally. The innermost pinned column on each side
draws a divider.

```tsx
const table = createDataTable({
  data,
  columns,
  selectionMode: 'multiple',
  initialState: {
    columnPinning: { start: ['select', 'id'], end: ['actions'] },
  },
})
```

Header and footer rows render each pinned region separately. A group header over both pinned and
unpinned columns splits into one cell per region, so only the pinned part sticks.

`sticky` keeps the header (`'header'`), the footer (`'footer'`), or both (`true`) in view. It needs
a bounded height, so pair it with `maxHeight`. The whole `thead` or `tfoot` sticks, so grouped
header and footer rows stay stacked.

```tsx
<DataTable table={table} sticky maxHeight={360} />
```

Pinning and resizing switch the table to a fixed layout with explicit column widths. Give columns a
`size` to control those widths.

### Column resizing

`resizable: true` adds a resize handle to each column header. Widths stay within each column's
`minSize` and `maxSize`. Columns without a `maxSize`, in their definition or in
`tableOptions.defaultColumn`, are capped at 1000px so the handle can report a range. Only leaf
headers have a handle: a group header is as wide as its columns, so resize those instead. The new
width commits when a drag ends; set
`tableOptions.columnResizeMode: 'onChange'` to resize while dragging.

Each handle is a focusable separator named after its column, such as "Name Resize column". It
reports the column's current, minimum, and maximum width.

| Key                                          | Action                                                |
| -------------------------------------------- | ----------------------------------------------------- |
| <kbd>ArrowLeft</kbd> / <kbd>ArrowRight</kbd> | Narrows or widens the column by 10px.                 |
| <kbd>Shift</kbd> + arrows                    | Narrows or widens the column by 50px.                 |
| <kbd>Home</kbd>                              | Sets the column to its `minSize`.                     |
| <kbd>End</kbd>                               | Sets the column to its `maxSize` (1000px unless set). |

The arrows swap direction when `tableOptions.columnResizeDirection` is `'rtl'`.

### Column order

`state.columnOrder` lists column ids in display order. Columns it does not list follow in
definition order. To let users drag headers, pass the header registration from
`createListSortable` (`moraine/dnd`) to `headProps`, as in
[Reorder columns by dragging their headers](#reorder-columns-by-dragging-their-headers).

```tsx
const [columnOrder, setColumnOrder] = createSignal(['name', 'role', 'department'])

const table = createDataTable({
  data,
  columns,
  state: {
    get columnOrder() {
      return columnOrder()
    },
  },
  onColumnOrderChange: setColumnOrder,
})
```

### Row events

`onRowClick` and `onRowDoubleClick` receive the row and the mouse event, and give rows a pointer
cursor. Clicks on the built-in checkboxes, radios, and expand buttons do not reach them. Return
`class` from `rowProps` to add classes per row.

```tsx
<DataTable
  table={table}
  onRowClick={(row) => navigate(`/users/${row.original.id}`)}
  rowProps={({ row }) => ({ class: row.original.archived && 'opacity-60' })}
/>
```

Row clicks are pointer-only. Keep a link or button in a cell so keyboard users can reach the same
action.

`rowProps` adds attributes to each body `<tr>`. It runs once per row, inside that row, so it can
call row-level hooks. Its `ref`, `onClick`, and `onDblClick` are composed with the table's own
(its click handlers run before `onRowClick` and `onRowDoubleClick`); `class` merges into the `row`
slot. `headProps` does the same for each header `<th>`, except that `class`, `style`, `colSpan`,
and `aria-sort` stay owned by the table.

```tsx
<DataTable
  table={table}
  rowProps={(context) => ({ 'aria-describedby': `hint-${context.row.id}` })}
/>
```

### Drag to reorder rows

`createListSortable` from `moraine/dnd` (needs `@dnd-kit/dom`) reorders rows through `rowProps`.
Pass the rendered rows as `items`, wrap the table in `sortable.Provider`, and return
`sortable.useRow(context).props` from `rowProps`. With `getId: (row) => row.id`, a cell can render
the drag handle through `sortable.handleRefFor(row.id)`.

```tsx
import { createListSortable } from 'moraine/dnd'

const sortable = createListSortable({
  items: () => table.getRowModel().rows,
  getId: (row) => row.id,
  onReorder: (event) => setData(event.items.map((row) => row.original)),
})

<sortable.Provider>
  <DataTable table={table} rowProps={(context) => sortable.useRow(context).props} />
</sortable.Provider>
```

`event.items` holds the rendered rows in their new order, so mapping it back to `data` is right only
when the rows render in data order. Otherwise, update `data` from the moved `event.item` and the
`event.target` row with `event.position`:

- **Sorting**: the rendered order is not the data order. Control `state.sorting` with a signal and
  pause dragging with `isDisabled: () => sorting().length > 0`, or turn sorting off.
- **Pagination**: `from` and `to` are page positions. Add the page offset and move the item in
  `data` with `moveItem(data, offset + event.from, offset + event.to)`.
- **Sub-rows**: pass `canDrop: (source, target) => source.parentId === target.parentId` so rows
  move only among their siblings.

The table styles the drag: the row stays in place while a copy at 60% opacity follows the pointer
(`data-dnd-dragging`), the target row keeps the hover background, and its cells draw a line on the
`before` or `after` edge. Override them through the `row` and `cell` slots.

With a `virtualizer`, pass `table.getPrePaginatedRowModel().rows` as `items` and
`rangeExtractor: sortable.rangeExtractor` to `createTableVirtualizer`, so the dragged row stays
mounted while it is scrolled out of view.

### Virtualization

Pass a `virtualizer` from `createTableVirtualizer` (`moraine/virtualizer`) to mount only the rows
near the viewport. Give the table a bounded height with `maxHeight`. The virtualizer measures the
header above the body, including a sticky header, so you do not set `scrollMargin`.

```tsx
import { createTableVirtualizer } from 'moraine/virtualizer'

const virtualizer = createTableVirtualizer<DataTableT.Row<Task>>({
  estimateSize: () => 41,
  getItemKey: (row) => row.id,
})

return <DataTable table={table} virtualizer={virtualizer} sticky maxHeight={320} />
```

A virtualized table shows every row in one scroll, which changes three behaviors:

- `paginated` is ignored, with a development warning, and the toolbar is hidden.
- Select-all toggles every row, not one page.
- `expandedRowRender` is ignored, with a development warning, because the virtualizer cannot
  measure a second row per entry. Tree sub-rows still expand, because each is its own entry.

See the [Virtualization guide](https://moraine.subf.dev/docs/virtualization.md#data-table) for sizing and keys.

For tables with many columns, add the `columns` option to the virtualizer. DataTable then renders
only the body cells of the unpinned columns near the viewport, using each column's `size` as its
width:

```tsx
const virtualizer = createTableVirtualizer<DataTableT.Row<Metric>>({
  estimateSize: () => 41,
  getItemKey: (row) => row.id,
  columns: { overscan: 2 },
})
```

- Header and footer rows render every column, so grouped headers keep their `colSpan`. Body rows
  replace the skipped columns with a placeholder cell on each side.
- Pinned columns always render, so pin the columns users need while scrolling sideways.
- The table switches to a fixed layout with a `<colgroup>` of column widths. Give columns a `size`;
  columns without one are 150px wide.
- The table gets `aria-colcount`, and each rendered body cell gets `aria-colindex`, so screen
  readers still announce column positions.

### Localization

Override text for one table with `translations`, or for the whole app with the `dataTable` key of
`MoraineProvider` `messages`. Sort buttons and resize handles prefix the column header to their
text, so the sort button of a Name column is named "Name Sort", then "Name Sorted ascending".

| Key                                           | Default                                         |
| --------------------------------------------- | ----------------------------------------------- |
| `empty`                                       | `No results.`                                   |
| `loading`                                     | `Loading`                                       |
| `selectAll`, `selectRow`                      | `Select all rows`, `Select row`                 |
| `selectPage`                                  | `Select all rows on this page`                  |
| `expandRow`, `collapseRow`                    | `Expand row`, `Collapse row`                    |
| `sort`, `sortedAscending`, `sortedDescending` | `Sort`, `Sorted ascending`, `Sorted descending` |
| `resizeColumn`                                | `Resize column`                                 |
| `sortPriority({ index })`                     | `` `Sort priority ${index}` ``                  |
| `rowCount({ total })`                         | `` `${total} rows` `` (`1 row` for one)         |
| `selectedCount({ selected, total })`          | `` `${selected} of ${total} selected` ``        |
| `pageSize({ size })`                          | `` `${size} / page` ``                          |

## Examples

### Sort, select, and page through team members

A typical list: custom cells for the member and the role, multiple selection, and five rows per
page. The table starts sorted by role, and the role column sorts by rank with a `sortingFn` instead
of alphabetically. Shift-click another header to add a second sort; the headers then show their
priority.

```tsx
import { Badge } from 'moraine'
import { DataTable, createDataTable } from 'moraine/data-table'
import type { DataTableT } from 'moraine/data-table'

interface Member {
  id: string
  name: string
  email: string
  role: 'Owner' | 'Admin' | 'Member' | 'Viewer'
  team: string
  joined: string
}

const MEMBERS: Member[] = [
  {
    id: 'u1',
    name: 'Alice Johnson',
    email: 'alice@acme.dev',
    role: 'Owner',
    team: 'Platform',
    joined: '2023-02-14',
  },
  {
    id: 'u2',
    name: 'Bob Smith',
    email: 'bob@acme.dev',
    role: 'Admin',
    team: 'Product',
    joined: '2023-06-01',
  },
  {
    id: 'u3',
    name: 'Carmen Diaz',
    email: 'carmen@acme.dev',
    role: 'Member',
    team: 'Platform',
    joined: '2024-01-09',
  },
  {
    id: 'u4',
    name: 'Dmitri Ivanov',
    email: 'dmitri@acme.dev',
    role: 'Member',
    team: 'Security',
    joined: '2024-03-22',
  },
  {
    id: 'u5',
    name: 'Elena Novak',
    email: 'elena@acme.dev',
    role: 'Admin',
    team: 'Security',
    joined: '2023-11-30',
  },
  {
    id: 'u6',
    name: 'Farah Khan',
    email: 'farah@acme.dev',
    role: 'Viewer',
    team: 'Finance',
    joined: '2025-05-17',
  },
  {
    id: 'u7',
    name: 'Gus Moreau',
    email: 'gus@acme.dev',
    role: 'Member',
    team: 'Product',
    joined: '2024-08-04',
  },
  {
    id: 'u8',
    name: 'Hana Sato',
    email: 'hana@acme.dev',
    role: 'Member',
    team: 'Platform',
    joined: '2025-01-12',
  },
  {
    id: 'u9',
    name: 'Ivan Petrov',
    email: 'ivan@acme.dev',
    role: 'Viewer',
    team: 'Finance',
    joined: '2025-07-28',
  },
  {
    id: 'u10',
    name: 'Julia Weber',
    email: 'julia@acme.dev',
    role: 'Member',
    team: 'Product',
    joined: '2024-10-19',
  },
  {
    id: 'u11',
    name: 'Kofi Mensah',
    email: 'kofi@acme.dev',
    role: 'Admin',
    team: 'Platform',
    joined: '2023-09-05',
  },
  {
    id: 'u12',
    name: 'Lina Haddad',
    email: 'lina@acme.dev',
    role: 'Member',
    team: 'Security',
    joined: '2025-03-03',
  },
]

const ROLE_TONE = {
  Owner: 'primary',
  Admin: 'info',
  Member: 'neutral',
  Viewer: 'neutral',
} as const

// Sort roles by rank instead of alphabetically.
const ROLE_RANK: Record<Member['role'], number> = { Owner: 0, Admin: 1, Member: 2, Viewer: 3 }

const COLUMNS: DataTableT.Column<Member>[] = [
  {
    accessorKey: 'name',
    header: 'Member',
    cell: (props) => (
      <div class="flex flex-col">
        <span class="font-medium">{props.row.original.name}</span>
        <span class="text-xs text-muted-foreground">{props.row.original.email}</span>
      </div>
    ),
  },
  {
    accessorKey: 'role',
    header: 'Role',
    sortFn: (a, b) => ROLE_RANK[a.original.role] - ROLE_RANK[b.original.role],
    cell: (props) => (
      <Badge tone={ROLE_TONE[props.row.original.role]} variant="subtle" size="sm">
        {props.row.original.role}
      </Badge>
    ),
  },
  { accessorKey: 'team', header: 'Team' },
  {
    accessorKey: 'joined',
    header: 'Joined',
    cell: (props) => (
      <span class="text-muted-foreground tabular-nums">{props.row.original.joined}</span>
    ),
  },
]

export default function BasicExample() {
  const table = createDataTable({
    data: MEMBERS,
    columns: COLUMNS,
    getRowId: (member) => member.id,
    selectionMode: 'multiple',
    paginated: { pageSize: 5 },
    initialState: { sorting: [{ id: 'role', desc: false }] },
  })

  return <DataTable table={table} aria-label="Team members" highlightOnHover />
}
```

### Switch between single and multiple selection

Read `selectionMode` from a signal and control `state.rowSelection`, so the toolbar can count and clear
the selection. `canSelectRow` locks terminated nodes, and `rowProps` mutes their text.

```tsx
import { Badge, Button, ButtonGroup, ToggleButton } from 'moraine'
import { DataTable, createDataTable } from 'moraine/data-table'
import type { DataTableT } from 'moraine/data-table'
import { Show, createSignal } from 'solid-js'

interface ServerNode {
  id: string
  name: string
  cluster: string
  vcpu: number
  ram: string
  status: 'running' | 'stopped' | 'terminated'
}

const NODES: ServerNode[] = [
  {
    id: 'node-us-east-1a',
    name: 'api-ingress-gateway-01',
    cluster: 'k8s-prod-primary',
    vcpu: 16,
    ram: '64 GB',
    status: 'running',
  },
  {
    id: 'node-us-east-1b',
    name: 'api-ingress-gateway-02',
    cluster: 'k8s-prod-primary',
    vcpu: 16,
    ram: '64 GB',
    status: 'running',
  },
  {
    id: 'node-us-east-1c',
    name: 'worker-queue-consumer-01',
    cluster: 'k8s-prod-primary',
    vcpu: 32,
    ram: '128 GB',
    status: 'stopped',
  },
  {
    id: 'node-us-east-2a',
    name: 'analytics-clickhouse-replica',
    cluster: 'k8s-analytics-cluster',
    vcpu: 64,
    ram: '256 GB',
    status: 'running',
  },
  {
    id: 'node-us-east-2b',
    name: 'legacy-monolith-decom-01',
    cluster: 'k8s-legacy-decom',
    vcpu: 8,
    ram: '32 GB',
    status: 'terminated',
  },
  {
    id: 'node-us-east-2c',
    name: 'cache-redis-shard-01',
    cluster: 'k8s-prod-primary',
    vcpu: 16,
    ram: '64 GB',
    status: 'running',
  },
]

const NODE_STATUS = {
  running: { label: 'Running', tone: 'success' },
  stopped: { label: 'Stopped', tone: 'warning' },
  terminated: { label: 'Terminated', tone: 'neutral' },
} as const

const COLUMNS: DataTableT.Column<ServerNode>[] = [
  {
    accessorKey: 'id',
    header: 'Node ID',
    size: 160,
    cell: (props) => <span class="text-xs font-mono">{props.row.original.id}</span>,
  },
  {
    accessorKey: 'name',
    header: 'Instance Name',
    size: 220,
    cell: (props) => <span class="font-medium">{props.row.original.name}</span>,
  },
  {
    accessorKey: 'cluster',
    header: 'Cluster',
    size: 180,
    cell: (props) => <span class="text-muted-foreground">{props.row.original.cluster}</span>,
  },
  {
    accessorKey: 'vcpu',
    header: 'vCPU',
    size: 80,
    meta: { align: 'end' },
    cell: (props) => <span class="tabular-nums">{props.row.original.vcpu}</span>,
  },
  {
    accessorKey: 'ram',
    header: 'RAM',
    size: 90,
    meta: { align: 'end' },
    cell: (props) => <span class="tabular-nums">{props.row.original.ram}</span>,
  },
  {
    accessorKey: 'status',
    header: 'Status',
    size: 120,
    cell: (props) => {
      const status = () => NODE_STATUS[props.row.original.status]
      return (
        <Badge tone={status().tone} variant="subtle" size="sm">
          {status().label}
        </Badge>
      )
    },
  },
]

export default function SelectionModesExample() {
  const [mode, setMode] = createSignal<'multiple' | 'single'>('multiple')
  const [selectedRows, setSelectedRows] = createSignal<DataTableT.State['rowSelection']>({})

  const selectedCount = () => Object.keys(selectedRows()).length

  const changeMode = (next: 'multiple' | 'single') => {
    setMode(next)
    setSelectedRows({})
  }

  const table = createDataTable({
    data: NODES,
    columns: COLUMNS,
    get selectionMode() {
      return mode()
    },
    canSelectRow: (row) => row.original.status !== 'terminated',
    state: {
      get rowSelection() {
        return selectedRows()
      },
    },
    onRowSelectionChange: setSelectedRows,
  })

  return (
    <div class="flex flex-col gap-3 w-full">
      <div class="flex flex-wrap gap-2 min-h-8 items-center justify-between">
        <ButtonGroup size="sm" variant="outline" aria-label="Selection mode">
          <ToggleButton
            pressed={mode() === 'multiple'}
            onPressedChange={() => changeMode('multiple')}
          >
            Multiple
          </ToggleButton>
          <ToggleButton pressed={mode() === 'single'} onPressedChange={() => changeMode('single')}>
            Single
          </ToggleButton>
        </ButtonGroup>

        <Show when={selectedCount() > 0}>
          <div class="flex gap-2 items-center">
            <span class="text-sm text-muted-foreground">{selectedCount()} selected</span>
            <Button size="sm" variant="outline" onClick={() => setSelectedRows({})}>
              Clear
            </Button>
            <Button size="sm" variant="solid" tone="primary">
              Restart
            </Button>
          </div>
        </Show>
      </div>

      <DataTable
        table={table}
        rowProps={({ row }) => ({
          class: row.original.status === 'terminated' && 'text-muted-foreground',
        })}
        highlightOnHover
      />

      <div class="text-xs text-muted-foreground">
        Terminated nodes are locked by <code class="font-mono">canSelectRow</code> and cannot be
        selected.
      </div>
    </div>
  )
}
```

### Search and filter rows

Bind an `Input` to `state.globalFilter` for a search across all columns, and a `Select` to the role
column's filter with `column.setFilterValue`. The role column uses `filterFn: 'equals'` for an
exact match. TanStack returns to the first page whenever a filter changes, and the toolbar below
the table counts the matching rows.

```tsx
import { Button, Input, Select } from 'moraine'
import { DataTable, createDataTable } from 'moraine/data-table'
import type { DataTableT } from 'moraine/data-table'
import { createSignal } from 'solid-js'

interface Employee {
  id: string
  name: string
  role: string
  department: string
}

const ROLES = ['Engineer', 'Designer', 'Manager', 'Analyst'] as const
const DEPARTMENTS = ['Platform', 'Product', 'Security', 'Growth', 'Finance'] as const
const NAMES = ['Alice', 'Bob', 'Carmen', 'Dmitri', 'Elena', 'Farah', 'Gus', 'Hana', 'Ivan']

const DATA: Employee[] = Array.from({ length: 36 }, (_, index) => ({
  id: String(index + 1),
  name: `${NAMES[index % NAMES.length]} ${String.fromCodePoint(65 + (index % 26))}.`,
  role: ROLES[index % ROLES.length]!,
  department: DEPARTMENTS[index % DEPARTMENTS.length]!,
}))

const COLUMNS: DataTableT.Column<Employee>[] = [
  { accessorKey: 'name', header: 'Name' },
  // `equals` matches the role exactly, so "Engineer" does not also match "Engineering".
  { accessorKey: 'role', header: 'Role', filterFn: 'equals' },
  { accessorKey: 'department', header: 'Department' },
]

export default function FilteringExample() {
  const [globalFilter, setGlobalFilter] = createSignal('')

  const table = createDataTable({
    data: DATA,
    columns: COLUMNS,
    getRowId: (row) => row.id,
    paginated: { pageSize: 5 },
    state: {
      get globalFilter() {
        return globalFilter()
      },
    },
    onGlobalFilterChange: (value) => setGlobalFilter(typeof value === 'string' ? value : ''),
  })

  const roleFilter = () =>
    table.getColumn('role')?.getFilterValue() as (typeof ROLES)[number] | undefined

  return (
    <div class="flex flex-col gap-3 w-full">
      <div class="flex flex-wrap gap-2 items-center">
        <Input
          aria-label="Search employees"
          placeholder="Search name, role, or department..."
          value={globalFilter()}
          onValueChange={(value) => table.setGlobalFilter(value)}
          class="max-w-xs"
        />
        <Select
          aria-label="Filter by role"
          placeholder="All roles"
          items={[...ROLES]}
          value={roleFilter()}
          onValueChange={(value) => table.getColumn('role')?.setFilterValue(value)}
          clearable
          class="w-40"
        />
        <Button
          variant="ghost"
          size="sm"
          disabled={!globalFilter() && !roleFilter()}
          onClick={() => {
            table.setGlobalFilter('')
            table.resetColumnFilters()
          }}
        >
          Reset
        </Button>
      </div>
      <DataTable
        table={table}
        aria-label="Employees"
        emptyRender={<span>No employees match the filters.</span>}
      />
    </div>
  )
}
```

### Load pages from a server

Set `manual: true` and control `sorting` and `pagination`. Combine them with the debounced search
into one query, so each change sends one request. Pass the current page as `data`, the total as
`rowCount`, and the request state as `loading`. Sorting and searching return to the first page,
and the previous page stays on screen while the next one loads.

```tsx
import { Input } from 'moraine'
import { DataTable, createDataTable } from 'moraine/data-table'
import type { DataTableT } from 'moraine/data-table'
import type { PaginationState, SortingState } from '@tanstack/table-core'
import { createMemo, createResource, createSignal, onCleanup } from 'solid-js'

interface Order {
  id: string
  customer: string
  status: 'Pending' | 'Shipped' | 'Delivered'
  total: number
}

interface OrderQuery {
  pageIndex: number
  pageSize: number
  sorting: SortingState
  search: string
}

interface OrderPage {
  rows: Order[]
  total: number
}

const CUSTOMERS = ['Acme', 'Globex', 'Initech', 'Umbrella', 'Hooli', 'Stark', 'Wayne']
const STATUSES = ['Pending', 'Shipped', 'Delivered'] as const

// Stands in for a server: the client never holds these 240 rows.
const SERVER_ORDERS: Order[] = Array.from({ length: 240 }, (_, index) => ({
  id: `ORD-${String(index + 1).padStart(4, '0')}`,
  customer: CUSTOMERS[index % CUSTOMERS.length]!,
  status: STATUSES[index % STATUSES.length]!,
  total: ((index * 7919) % 90_000) / 100 + 10,
}))

async function fetchOrders(query: OrderQuery): Promise<OrderPage> {
  await new Promise((resolve) => setTimeout(resolve, 400))
  const search = query.search.trim().toLowerCase()
  let rows = search
    ? SERVER_ORDERS.filter((order) =>
        [order.id, order.customer, order.status].some((value) =>
          value.toLowerCase().includes(search),
        ),
      )
    : SERVER_ORDERS
  const [sort] = query.sorting
  if (sort) {
    const key = sort.id as keyof Order
    rows = [...rows].sort((a, b) => {
      const order = a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0
      return sort.desc ? -order : order
    })
  }
  const start = query.pageIndex * query.pageSize
  return { rows: rows.slice(start, start + query.pageSize), total: rows.length }
}

const COLUMNS: DataTableT.Column<Order>[] = [
  { accessorKey: 'id', header: 'Order' },
  { accessorKey: 'customer', header: 'Customer' },
  { accessorKey: 'status', header: 'Status' },
  {
    accessorKey: 'total',
    header: 'Total',
    meta: { align: 'end' },
    cell: (props) => <span class="tabular-nums">${props.row.original.total.toFixed(2)}</span>,
  },
]

const SEARCH_DELAY = 300

export default function ServerDataExample() {
  const [sorting, setSorting] = createSignal<SortingState>([])
  const [pagination, setPagination] = createSignal<PaginationState>({ pageIndex: 0, pageSize: 10 })
  const [searchInput, setSearchInput] = createSignal('')
  const [search, setSearch] = createSignal('')

  // Debounce typing, and go back to the first page whenever the search changes.
  let searchTimer: ReturnType<typeof setTimeout> | undefined
  const onSearchInput = (value: string) => {
    setSearchInput(value)
    clearTimeout(searchTimer)
    searchTimer = setTimeout(() => {
      setSearch(value)
      setPagination((current) => ({ ...current, pageIndex: 0 }))
    }, SEARCH_DELAY)
  }
  onCleanup(() => clearTimeout(searchTimer))

  // Every state slice that changes the result goes into one query, so one change sends one request.
  const query = createMemo<OrderQuery>(() => ({
    ...pagination(),
    sorting: sorting(),
    search: search(),
  }))
  const [page] = createResource(query, fetchOrders)
  // Keep the previous page on screen while the next one loads.
  const rows = createMemo<Order[]>((previous) => page.latest?.rows ?? previous, [])
  const total = createMemo<number>((previous) => page.latest?.total ?? previous, 0)

  const table = createDataTable({
    get data() {
      return rows()
    },
    columns: COLUMNS,
    getRowId: (row) => row.id,
    manual: true,
    get rowCount() {
      return total()
    },
    paginated: true,
    state: {
      get sorting() {
        return sorting()
      },
      get pagination() {
        return pagination()
      },
    },
    onSortingChange: (next) => {
      setSorting(next)
      setPagination((current) => ({ ...current, pageIndex: 0 }))
    },
    onPaginationChange: setPagination,
  })

  return (
    <div class="flex flex-col gap-3 w-full">
      <Input
        aria-label="Search orders"
        placeholder="Search order, customer, or status..."
        value={searchInput()}
        onValueChange={onSearchInput}
        class="max-w-xs"
      />
      <DataTable table={table} aria-label="Orders" loading={page.loading} />
    </div>
  )
}
```

### Reorder columns by dragging their headers

Drag a header to move its column; the sort button still sorts. `headProps` registers each header
cell with a horizontal `createListSortable` over `table.getVisibleLeafColumns()`, and `onReorder`
writes the new order to the controlled `state.columnOrder`. The header stays in place while a copy
follows the pointer, and the target header shows a line on the side the column lands on.

```tsx
import { DataTable, createDataTable } from 'moraine/data-table'
import type { DataTableT } from 'moraine/data-table'
import { createListSortable } from 'moraine/dnd'
import { createSignal } from 'solid-js'

interface Employee {
  id: string
  name: string
  email: string
  role: string
  department: string
  location: string
}

const DATA: Employee[] = [
  {
    id: '1',
    name: 'Alice Johnson',
    email: 'alice@acme.dev',
    role: 'Engineer',
    department: 'Platform',
    location: 'Austin',
  },
  {
    id: '2',
    name: 'Bob Smith',
    email: 'bob@acme.dev',
    role: 'Designer',
    department: 'Product',
    location: 'Berlin',
  },
  {
    id: '3',
    name: 'Laura Croft',
    email: 'laura@acme.dev',
    role: 'Engineer',
    department: 'Security',
    location: 'London',
  },
  {
    id: '4',
    name: 'Evan Wright',
    email: 'evan@acme.dev',
    role: 'Developer',
    department: 'Mobile',
    location: 'Tokyo',
  },
]

const COLUMNS: DataTableT.Column<Employee>[] = [
  { accessorKey: 'name', header: 'Name' },
  { accessorKey: 'email', header: 'Email' },
  { accessorKey: 'role', header: 'Role' },
  { accessorKey: 'department', header: 'Department' },
  { accessorKey: 'location', header: 'Location' },
]

const DEFAULT_ORDER = ['name', 'email', 'role', 'department', 'location']

export default function ColumnSettingsExample() {
  const [columnOrder, setColumnOrder] = createSignal(DEFAULT_ORDER)

  const table = createDataTable({
    data: DATA,
    columns: COLUMNS,
    getRowId: (row) => row.id,
    state: {
      get columnOrder() {
        return columnOrder()
      },
    },
    onColumnOrderChange: setColumnOrder,
  })

  // The header cells are the visible leaf columns in display order.
  const sortable = createListSortable({
    items: () => table.getVisibleLeafColumns(),
    getId: (column) => column.id,
    orientation: 'horizontal',
    onReorder: (event) => table.setColumnOrder(event.items.map((column) => column.id)),
  })

  return (
    <sortable.Provider>
      <DataTable
        table={table}
        aria-label="Employees"
        headProps={(context) => sortable.useRow(context).props}
      />
    </sortable.Provider>
  )
}
```

### Let users resize columns

Set `resizable: true` and give columns a `size`, plus `minSize` and `maxSize` to bound them. Drag a
header edge, or focus the handle and use the arrow keys.

```tsx
import { Badge } from 'moraine'
import { DataTable, createDataTable } from 'moraine/data-table'
import type { DataTableT } from 'moraine/data-table'

interface ServiceMetric {
  id: string
  service: string
  region: string
  rps: number
  p95Latency: string
  errorRate: string
  cpu: string
  status: 'healthy' | 'degraded' | 'critical'
}

const METRICS: ServiceMetric[] = [
  {
    id: '1',
    service: 'auth-service',
    region: 'us-east-1 (N. Virginia)',
    rps: 14250,
    p95Latency: '18ms',
    errorRate: '0.01%',
    cpu: '34%',
    status: 'healthy',
  },
  {
    id: '2',
    service: 'payment-gateway',
    region: 'us-west-2 (Oregon)',
    rps: 3820,
    p95Latency: '142ms',
    errorRate: '0.24%',
    cpu: '68%',
    status: 'degraded',
  },
  {
    id: '3',
    service: 'search-indexer',
    region: 'eu-central-1 (Frankfurt)',
    rps: 8900,
    p95Latency: '35ms',
    errorRate: '0.00%',
    cpu: '52%',
    status: 'healthy',
  },
  {
    id: '4',
    service: 'notification-worker',
    region: 'ap-northeast-1 (Tokyo)',
    rps: 1200,
    p95Latency: '210ms',
    errorRate: '3.12%',
    cpu: '94%',
    status: 'critical',
  },
  {
    id: '5',
    service: 'media-transcoder',
    region: 'us-east-2 (Ohio)',
    rps: 450,
    p95Latency: '480ms',
    errorRate: '0.05%',
    cpu: '78%',
    status: 'healthy',
  },
]

const HEALTH = {
  healthy: { label: 'Healthy', tone: 'success' },
  degraded: { label: 'Degraded', tone: 'warning' },
  critical: { label: 'Critical', tone: 'danger' },
} as const

const COLUMNS: DataTableT.Column<ServiceMetric>[] = [
  {
    accessorKey: 'service',
    header: 'Service Name',
    size: 200,
    minSize: 120,
    maxSize: 320,
    cell: (props) => <span class="text-foreground font-medium">{props.row.original.service}</span>,
  },
  {
    accessorKey: 'region',
    header: 'Deployment Region',
    size: 220,
    minSize: 160,
    maxSize: 360,
    cell: (props) => <span class="text-muted-foreground">{props.row.original.region}</span>,
  },
  {
    accessorKey: 'rps',
    header: 'Requests / sec',
    size: 150,
    minSize: 110,
    maxSize: 220,
    meta: { align: 'end' },
    cell: (props) => <span class="tabular-nums">{props.row.original.rps.toLocaleString()}</span>,
  },
  {
    accessorKey: 'p95Latency',
    header: 'Latency (p95)',
    size: 140,
    minSize: 100,
    maxSize: 200,
    meta: { align: 'end' },
    cell: (props) => <span class="tabular-nums">{props.row.original.p95Latency}</span>,
  },
  {
    accessorKey: 'errorRate',
    header: 'Error Rate',
    size: 130,
    minSize: 100,
    maxSize: 180,
    meta: { align: 'end' },
    cell: (props) => {
      const elevated = () => Number.parseFloat(props.row.original.errorRate) > 1
      return (
        <span
          class="tabular-nums"
          classList={{
            'text-danger font-medium': elevated(),
            'text-muted-foreground': !elevated(),
          }}
        >
          {props.row.original.errorRate}
        </span>
      )
    },
  },
  {
    accessorKey: 'cpu',
    header: 'CPU Usage',
    size: 120,
    minSize: 90,
    maxSize: 180,
    meta: { align: 'end' },
    cell: (props) => <span class="tabular-nums">{props.row.original.cpu}</span>,
  },
  {
    accessorKey: 'status',
    header: 'Health',
    size: 120,
    minSize: 100,
    maxSize: 180,
    cell: (props) => {
      const health = () => HEALTH[props.row.original.status]
      return (
        <Badge tone={health().tone} variant="subtle" size="sm">
          {health().label}
        </Badge>
      )
    },
  },
]

export default function ResizableColumnsExample() {
  const table = createDataTable({
    data: METRICS,
    columns: COLUMNS,
    resizable: true,
  })

  return (
    <div class="flex flex-col gap-3 w-full">
      <div class="text-sm text-muted-foreground">
        Drag the boundary between two column headers to resize a column.
      </div>
      <DataTable table={table} border="both" highlightOnHover />
    </div>
  )
}
```

### Keep the ID and actions visible while scrolling sideways

Pin the selection and ID columns to the start and the actions column to the end with
`initialState.columnPinning`. Give every column a `size`, because pinning uses a fixed layout.

```tsx
import { Badge, Button, DropdownMenu } from 'moraine'
import { DataTable, createDataTable } from 'moraine/data-table'
import type { DataTableT } from 'moraine/data-table'

interface Customer {
  id: string
  name: string
  email: string
  avatar: string
  plan: 'Enterprise' | 'Pro' | 'Starter'
  spend: string
  invoices: number
  lastPayment: string
  method: string
  status: 'active' | 'past_due' | 'canceled'
}

const CUSTOMERS: Customer[] = [
  {
    id: 'CUST-8021',
    name: 'Sarah Connor',
    email: 'sarah.connor@cyberdyne.io',
    avatar: 'SC',
    plan: 'Enterprise',
    spend: '$4,800.00',
    invoices: 18,
    lastPayment: 'Oct 24, 2026',
    method: 'Visa •••• 4242',
    status: 'active',
  },
  {
    id: 'CUST-8022',
    name: 'Alexander Hayes',
    email: 'a.hayes@acme-corp.com',
    avatar: 'AH',
    plan: 'Enterprise',
    spend: '$7,250.00',
    invoices: 32,
    lastPayment: 'Oct 22, 2026',
    method: 'Mastercard •••• 8821',
    status: 'active',
  },
  {
    id: 'CUST-8023',
    name: 'Elena Rostova',
    email: 'elena@vanguard-tech.net',
    avatar: 'ER',
    plan: 'Pro',
    spend: '$1,450.00',
    invoices: 8,
    lastPayment: 'Sep 15, 2026',
    method: 'Bank Transfer',
    status: 'past_due',
  },
  {
    id: 'CUST-8024',
    name: 'David Kim',
    email: 'david.kim@nexus-labs.dev',
    avatar: 'DK',
    plan: 'Pro',
    spend: '$2,100.00',
    invoices: 12,
    lastPayment: 'Oct 19, 2026',
    method: 'Visa •••• 9912',
    status: 'active',
  },
  {
    id: 'CUST-8025',
    name: 'Mia Thorne',
    email: 'm.thorne@solis-energy.com',
    avatar: 'MT',
    plan: 'Starter',
    spend: '$490.00',
    invoices: 3,
    lastPayment: 'Aug 02, 2026',
    method: 'PayPal',
    status: 'canceled',
  },
  {
    id: 'CUST-8026',
    name: 'Lucas Silva',
    email: 'lucas@hyperion-cloud.io',
    avatar: 'LS',
    plan: 'Enterprise',
    spend: '$9,800.00',
    invoices: 45,
    lastPayment: 'Oct 25, 2026',
    method: 'Amex •••• 1004',
    status: 'active',
  },
]

const PLAN_TONE = {
  Enterprise: 'primary',
  Pro: 'info',
  Starter: 'neutral',
} as const

const STATUS = {
  active: { label: 'Active', tone: 'success' },
  past_due: { label: 'Past Due', tone: 'warning' },
  canceled: { label: 'Canceled', tone: 'danger' },
} as const

const COLUMNS: DataTableT.Column<Customer>[] = [
  {
    accessorKey: 'id',
    header: 'Customer ID',
    size: 130,
    cell: (props) => <span class="text-xs font-medium font-mono">{props.row.original.id}</span>,
  },
  {
    accessorKey: 'name',
    header: 'Customer',
    size: 260,
    cell: (props) => (
      <div class="flex gap-3 items-center">
        <div class="text-xs text-primary font-medium rounded-full bg-primary/10 flex shrink-0 size-8 items-center justify-center">
          {props.row.original.avatar}
        </div>
        <div class="flex flex-col min-w-0">
          <span class="text-foreground font-medium truncate">{props.row.original.name}</span>
          <span class="text-xs text-muted-foreground truncate">{props.row.original.email}</span>
        </div>
      </div>
    ),
  },
  {
    accessorKey: 'plan',
    header: 'Plan',
    size: 120,
    cell: (props) => (
      <Badge tone={PLAN_TONE[props.row.original.plan]} variant="subtle" size="sm">
        {props.row.original.plan}
      </Badge>
    ),
  },
  {
    accessorKey: 'spend',
    header: 'Monthly Spend',
    size: 140,
    meta: { align: 'end' },
    cell: (props) => <span class="font-medium tabular-nums">{props.row.original.spend}</span>,
  },
  {
    accessorKey: 'invoices',
    header: 'Invoices',
    size: 100,
    meta: { align: 'end' },
    cell: (props) => <span class="tabular-nums">{props.row.original.invoices}</span>,
  },
  {
    accessorKey: 'lastPayment',
    header: 'Last Payment',
    size: 140,
    cell: (props) => <span class="text-muted-foreground">{props.row.original.lastPayment}</span>,
  },
  {
    accessorKey: 'method',
    header: 'Billing Method',
    size: 180,
  },
  {
    accessorKey: 'status',
    header: 'Status',
    size: 120,
    cell: (props) => {
      const status = () => STATUS[props.row.original.status]
      return (
        <Badge tone={status().tone} variant="subtle" size="sm">
          {status().label}
        </Badge>
      )
    },
  },
  {
    id: 'actions',
    header: () => <span class="sr-only">Actions</span>,
    size: 56,
    meta: { align: 'center' },
    cell: (props) => (
      <DropdownMenu>
        <DropdownMenu.Trigger
          as={Button}
          variant="ghost"
          size="icon-sm"
          leading="i-lucide:ellipsis"
          aria-label={`Open actions for ${props.row.original.name}`}
        />
        <DropdownMenu.Content
          items={[
            {
              label: 'View customer profile',
              onSelect: () => console.log('Viewing', props.row.original.id),
            },
            {
              label: 'Download tax invoices',
              onSelect: () => console.log('Invoices for', props.row.original.id),
            },
            {
              label: 'Manage subscription',
              onSelect: () => console.log('Managing', props.row.original.id),
            },
          ]}
        />
      </DropdownMenu>
    ),
  },
]

export default function PinnedColumnsExample() {
  const table = createDataTable({
    data: CUSTOMERS,
    columns: COLUMNS,
    selectionMode: 'multiple',
    initialState: {
      columnPinning: { start: ['select', 'id'], end: ['actions'] },
    },
  })

  return (
    <div class="flex flex-col gap-3 w-full">
      <div class="text-sm text-muted-foreground">
        Scroll horizontally: the selection and Customer ID columns stay pinned on the left, and the
        actions column stays pinned on the right.
      </div>
      <DataTable table={table} highlightOnHover />
    </div>
  )
}
```

### Keep the header and totals in view

Set `sticky` and `maxHeight` so the header and footer stay in view while 30 audit events scroll.
The footers read the current rows from the table, so they update with the data.

```tsx
import { Badge } from 'moraine'
import { DataTable, createDataTable } from 'moraine/data-table'
import type { DataTableT } from 'moraine/data-table'

interface AuditEvent {
  id: string
  timestamp: string
  actor: string
  action: string
  resource: string
  ip: string
  severity: 'low' | 'medium' | 'high' | 'critical'
}

const AUDIT_EVENTS: AuditEvent[] = Array.from({ length: 30 }, (_, i) => {
  const severities: AuditEvent['severity'][] = ['low', 'medium', 'high', 'critical']
  const actions = [
    'iam.role.assume',
    's3.object.put',
    'auth.mfa.verify',
    'kms.key.decrypt',
    'k8s.pod.restart',
    'db.cluster.snapshot',
    'api.token.generate',
  ]
  const actors = [
    'dev-deployer@internal.corp',
    'admin.ops@internal.corp',
    'github-actions[bot]',
    'security-scanner@internal.corp',
    'app-backend-svc',
  ]
  const pad = (n: number) => String(n).padStart(2, '0')
  const date = `2026-10-25 10:${pad(59 - i)}:${pad((i * 7) % 60)}`

  return {
    id: `EVT-${1000 + i}`,
    timestamp: date,
    actor: actors[i % actors.length]!,
    action: actions[i % actions.length]!,
    resource: `arn:aws:prod:service/${actions[i % actions.length]!.split('.')[0]}-${(i % 5) + 1}`,
    ip: `192.168.${(i % 10) + 1}.${((i * 13) % 254) + 1}`,
    severity: severities[i % severities.length]!,
  }
})

const SEVERITY = {
  low: { label: 'Low', tone: 'neutral' },
  medium: { label: 'Medium', tone: 'info' },
  high: { label: 'High', tone: 'warning' },
  critical: { label: 'Critical', tone: 'danger' },
} as const

const COLUMNS: DataTableT.Column<AuditEvent>[] = [
  {
    accessorKey: 'timestamp',
    header: 'Timestamp',
    footer: (props) => <span>{props.table.getRowModel().rows.length} events</span>,
    size: 170,
    cell: (props) => (
      <span class="text-xs text-muted-foreground font-mono">{props.row.original.timestamp}</span>
    ),
  },
  {
    accessorKey: 'actor',
    header: 'Principal / Actor',
    size: 200,
    cell: (props) => <span class="font-medium">{props.row.original.actor}</span>,
  },
  {
    accessorKey: 'action',
    header: 'Action',
    size: 180,
    cell: (props) => (
      <span class="text-xs font-mono px-1.5 py-0.5 border border-border rounded bg-muted">
        {props.row.original.action}
      </span>
    ),
  },
  {
    accessorKey: 'resource',
    header: 'Target Resource',
    size: 240,
    cell: (props) => (
      <span class="text-xs text-muted-foreground font-mono">{props.row.original.resource}</span>
    ),
  },
  {
    accessorKey: 'ip',
    header: 'IP Address',
    size: 140,
    cell: (props) => (
      <span class="text-xs text-muted-foreground font-mono">{props.row.original.ip}</span>
    ),
  },
  {
    accessorKey: 'severity',
    header: 'Severity',
    footer: (props) => {
      const critical = () =>
        props.table.getRowModel().rows.filter((row) => row.original.severity === 'critical').length
      return <span class="text-danger">{critical()} critical</span>
    },
    size: 110,
    cell: (props) => {
      const severity = () => SEVERITY[props.row.original.severity]
      return (
        <Badge tone={severity().tone} variant="subtle" size="sm">
          {severity().label}
        </Badge>
      )
    },
  },
]

export default function StickySectionsExample() {
  const table = createDataTable({
    data: AUDIT_EVENTS,
    columns: COLUMNS,
  })

  return (
    <div class="flex flex-col gap-3 w-full">
      <DataTable
        table={table}
        aria-label="Audit log"
        sticky
        maxHeight={360}
        highlightOnHover
        size="sm"
      />
    </div>
  )
}
```

### Show order details in expandable rows

Set `expandable: true` and render the line items, shipping address, and tracking code with
`expandedRowRender`.

```tsx
import { Badge } from 'moraine'
import { DataTable, createDataTable } from 'moraine/data-table'
import type { DataTableT } from 'moraine/data-table'
import { For } from 'solid-js'

interface OrderItem {
  sku: string
  name: string
  qty: number
  price: string
  total: string
}

interface Order {
  id: string
  customer: string
  date: string
  total: string
  fulfillment: 'delivered' | 'in_transit' | 'processing'
  shippingAddress: string
  tracking: string
  items: OrderItem[]
}

const ORDERS: Order[] = [
  {
    id: 'ORD-2026-9041',
    customer: 'Catherine Vance',
    date: 'Oct 24, 2026',
    total: '$1,249.00',
    fulfillment: 'delivered',
    shippingAddress: '742 Evergreen Terrace, Springfield, OR 97477',
    tracking: '1Z9999999999999999',
    items: [
      {
        sku: 'HW-DISP-4K',
        name: 'UltraSharp 32" 4K Thunderbolt Monitor',
        qty: 1,
        price: '$899.00',
        total: '$899.00',
      },
      {
        sku: 'ACC-KBD-MECH',
        name: 'Custom Wireless Mechanical Keyboard',
        qty: 1,
        price: '$250.00',
        total: '$250.00',
      },
      {
        sku: 'CBL-TB4-2M',
        name: 'Active Thunderbolt 4 Pro Cable (2m)',
        qty: 1,
        price: '$100.00',
        total: '$100.00',
      },
    ],
  },
  {
    id: 'ORD-2026-9042',
    customer: 'Marcus Brody',
    date: 'Oct 24, 2026',
    total: '$340.00',
    fulfillment: 'in_transit',
    shippingAddress: '221B Baker Street, Marylebone, London NW1 6XE',
    tracking: '1Z8888888888888888',
    items: [
      {
        sku: 'ACC-MOU-ERG',
        name: 'Vertical Ergonomic Mouse with USB-C Dongle',
        qty: 2,
        price: '$120.00',
        total: '$240.00',
      },
      {
        sku: 'ACC-PAD-DESK',
        name: 'Waterproof Wool Felt Desk Mat (Large)',
        qty: 1,
        price: '$100.00',
        total: '$100.00',
      },
    ],
  },
  {
    id: 'ORD-2026-9043',
    customer: 'Liam Henderson',
    date: 'Oct 25, 2026',
    total: '$2,850.00',
    fulfillment: 'processing',
    shippingAddress: '1000 Vin Scully Ave, Los Angeles, CA 90012',
    tracking: 'Pending Label',
    items: [
      {
        sku: 'SRV-NODE-RACK',
        name: 'Compact 1U Rackmount Network Storage Appliance',
        qty: 1,
        price: '$2,450.00',
        total: '$2,450.00',
      },
      {
        sku: 'NET-SFP-10G',
        name: '10GBase-SR SFP+ Optical Transceiver Module',
        qty: 4,
        price: '$100.00',
        total: '$400.00',
      },
    ],
  },
]

const FULFILLMENT = {
  delivered: { label: 'Delivered', tone: 'success' },
  in_transit: { label: 'In Transit', tone: 'info' },
  processing: { label: 'Processing', tone: 'warning' },
} as const

const COLUMNS: DataTableT.Column<Order>[] = [
  {
    accessorKey: 'id',
    header: 'Order #',
    size: 150,
    cell: (props) => <span class="text-xs font-medium font-mono">{props.row.original.id}</span>,
  },
  {
    accessorKey: 'customer',
    header: 'Customer',
    size: 180,
    cell: (props) => <span class="font-medium">{props.row.original.customer}</span>,
  },
  {
    accessorKey: 'date',
    header: 'Order Date',
    size: 140,
    cell: (props) => <span class="text-muted-foreground">{props.row.original.date}</span>,
  },
  {
    accessorKey: 'fulfillment',
    header: 'Fulfillment',
    size: 130,
    cell: (props) => {
      const fulfillment = () => FULFILLMENT[props.row.original.fulfillment]
      return (
        <Badge tone={fulfillment().tone} variant="subtle" size="sm">
          {fulfillment().label}
        </Badge>
      )
    },
  },
  {
    accessorKey: 'total',
    header: 'Total',
    size: 120,
    meta: { align: 'end' },
    cell: (props) => <span class="font-medium tabular-nums">{props.row.original.total}</span>,
  },
]

export default function ExpandableRowsExample() {
  const table = createDataTable({
    data: ORDERS,
    columns: COLUMNS,
    expandable: true,
  })

  return (
    <div class="flex flex-col gap-3 w-full">
      <div class="text-sm text-muted-foreground">
        Click the chevron on any row to inspect its line items and shipping details.
      </div>
      <DataTable
        table={table}
        highlightOnHover
        expandedRowRender={(props) => (
          <div class="flex flex-col gap-3">
            <div class="text-xs flex flex-wrap gap-x-6 gap-y-1">
              <div class="text-muted-foreground">
                <span class="text-foreground font-medium">Ship to:</span>{' '}
                {props.row.original.shippingAddress}
              </div>
              <div class="text-muted-foreground">
                <span class="text-foreground font-medium">Tracking:</span>{' '}
                <span class="font-mono">{props.row.original.tracking}</span>
              </div>
            </div>
            <div class="border border-border rounded-md bg-background divide-border divide-y">
              <For each={props.row.original.items}>
                {(item) => (
                  <div class="text-xs px-3 py-2 flex gap-4 items-center justify-between">
                    <div class="flex flex-col min-w-0">
                      <span class="text-foreground font-medium truncate">{item.name}</span>
                      <span class="text-muted-foreground font-mono">{item.sku}</span>
                    </div>
                    <div class="flex shrink-0 gap-6 items-center tabular-nums">
                      <span class="text-muted-foreground">
                        {item.qty} × {item.price}
                      </span>
                      <span class="text-foreground font-medium text-right w-16">{item.total}</span>
                    </div>
                  </div>
                )}
              </For>
            </div>
          </div>
        )}
      />
    </div>
  )
}
```

### Browse files as tree data

Pass `tableOptions.getSubRows` to render nested rows, and `expandable` with a predicate so only
folders get a chevron. Sub-rows indent the name column. Selecting a folder selects its files, and a
partly selected folder shows a mixed checkbox. `getRowId` returns the file name; sub-row ids get
their parent's id as a prefix (`src.components`), which is also how `initialState.expanded` opens
the nested folders.

```tsx
import { DataTable, createDataTable } from 'moraine/data-table'
import type { DataTableT } from 'moraine/data-table'
import { createSignal } from 'solid-js'

interface FileNode {
  path: string
  name: string
  kind: 'folder' | 'file'
  size: number
  modified: string
  children?: FileNode[]
}

const FILES: FileNode[] = [
  {
    path: 'src',
    name: 'src',
    kind: 'folder',
    size: 0,
    modified: '2026-10-28',
    children: [
      {
        path: 'src/components',
        name: 'components',
        kind: 'folder',
        size: 0,
        modified: '2026-10-28',
        children: [
          {
            path: 'src/components/button.tsx',
            name: 'button.tsx',
            kind: 'file',
            size: 4_812,
            modified: '2026-10-27',
          },
          {
            path: 'src/components/table.tsx',
            name: 'table.tsx',
            kind: 'file',
            size: 9_340,
            modified: '2026-10-28',
          },
          {
            path: 'src/components/tree.tsx',
            name: 'tree.tsx',
            kind: 'file',
            size: 7_115,
            modified: '2026-10-21',
          },
        ],
      },
      {
        path: 'src/theme',
        name: 'theme',
        kind: 'folder',
        size: 0,
        modified: '2026-10-19',
        children: [
          {
            path: 'src/theme/tokens.ts',
            name: 'tokens.ts',
            kind: 'file',
            size: 12_480,
            modified: '2026-10-19',
          },
        ],
      },
      { path: 'src/index.ts', name: 'index.ts', kind: 'file', size: 1_204, modified: '2026-10-28' },
    ],
  },
  { path: 'package.json', name: 'package.json', kind: 'file', size: 2_310, modified: '2026-10-26' },
  { path: 'README.md', name: 'README.md', kind: 'file', size: 5_902, modified: '2026-10-12' },
]

/** Folders report the total size of their files. */
function totalSize(node: FileNode): number {
  return node.children ? node.children.reduce((sum, child) => sum + totalSize(child), 0) : node.size
}

const formatSize = (bytes: number) =>
  bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`

const COLUMNS: DataTableT.Column<FileNode>[] = [
  {
    accessorKey: 'name',
    header: 'Name',
    size: 260,
    cell: (props) => (
      <span class="inline-flex gap-2 items-center">
        <span
          aria-hidden="true"
          class={
            props.row.original.kind === 'folder'
              ? 'i-lucide:folder text-muted-foreground'
              : 'i-lucide:file text-muted-foreground'
          }
        />
        <span class={props.row.original.kind === 'folder' ? 'font-medium' : undefined}>
          {props.row.original.name}
        </span>
      </span>
    ),
  },
  {
    id: 'size',
    header: 'Size',
    size: 120,
    accessorFn: totalSize,
    meta: { align: 'end' },
    cell: (props) => (
      <span class="text-muted-foreground tabular-nums">
        {formatSize(props.getValue() as number)}
      </span>
    ),
  },
  {
    accessorKey: 'modified',
    header: 'Modified',
    size: 140,
    cell: (props) => (
      <span class="text-muted-foreground tabular-nums">{props.row.original.modified}</span>
    ),
  },
]

export default function TreeDataExample() {
  const [rowSelection, setRowSelection] = createSignal<DataTableT.State['rowSelection']>({})

  const table = createDataTable({
    data: FILES,
    columns: COLUMNS,
    // Sub-row ids get their parent's id as a prefix, so `src` > `components` becomes
    // `src.components`. Stable ids keep the selection across sorting and collapsing.
    getRowId: (node) => node.name,
    selectionMode: 'multiple',
    // Show the chevron only on folders.
    expandable: (row) => row.subRows.length > 0,
    initialState: { expanded: { src: true, 'src.components': true } },
    state: {
      get rowSelection() {
        return rowSelection()
      },
    },
    onRowSelectionChange: setRowSelection,
    tableOptions: { getSubRows: (node) => node.children },
  })

  const selectedFiles = () =>
    table
      .getSelectedRowModel()
      .flatRows.filter((row) => row.original.kind === 'file')
      .map((row) => row.original.path)

  return (
    <div class="flex flex-col gap-3 w-full">
      <DataTable table={table} aria-label="Project files" highlightOnHover />
      <p class="text-sm text-muted-foreground" aria-live="polite">
        {selectedFiles().length > 0
          ? `Selected files: ${selectedFiles().join(', ')}`
          : 'Select a folder to select every file in it.'}
      </p>
    </div>
  )
}
```

### Edit cells in place

Render an editable value in the column's `cell`. Double-click it, or focus it and press Enter or
F2, to swap in an `Input`. Enter or leaving the field saves a valid value into the `data` signal,
and Escape cancels. The table reads `data` through a getter, so the saved value shows at once.

```tsx
import { Input } from 'moraine'
import { DataTable, createDataTable } from 'moraine/data-table'
import type { DataTableT } from 'moraine/data-table'
import type { CellContext } from '@tanstack/table-core'
import type { JSX } from 'solid-js'
import { Show, createSignal } from 'solid-js'

interface Product {
  id: string
  name: string
  sku: string
  stock: number
}

type EditableKey = 'name' | 'stock'

interface EditingCell {
  rowId: string
  columnId: EditableKey
}

const INITIAL_PRODUCTS: Product[] = [
  { id: '1', name: 'Desk lamp', sku: 'LMP-204', stock: 18 },
  { id: '2', name: 'Monitor arm', sku: 'ARM-118', stock: 7 },
  { id: '3', name: 'USB-C dock', sku: 'DCK-330', stock: 42 },
  { id: '4', name: 'Keyboard tray', sku: 'TRY-052', stock: 0 },
]

/** Returns an error message, or `undefined` when the draft is valid. */
function validate(columnId: EditableKey, draft: string): string | undefined {
  if (columnId === 'name') {
    return draft.trim() ? undefined : 'Name is required.'
  }
  return /^\d+$/.test(draft.trim()) ? undefined : 'Stock must be a whole number.'
}

export default function EditableCellsExample() {
  const [products, setProducts] = createSignal(INITIAL_PRODUCTS)
  const [editing, setEditing] = createSignal<EditingCell>()
  const [lastChange, setLastChange] = createSignal('Double-click a name or stock cell to edit it.')

  const isEditing = (rowId: string, columnId: EditableKey) =>
    editing()?.rowId === rowId && editing()?.columnId === columnId

  const commit = (rowId: string, columnId: EditableKey, draft: string) => {
    const value = columnId === 'stock' ? Number(draft.trim()) : draft.trim()
    const name = products().find((row) => row.id === rowId)?.name
    setProducts((rows) =>
      rows.map((row) => (row.id === rowId ? { ...row, [columnId]: value } : row)),
    )
    setEditing(undefined)
    setLastChange(`Saved ${columnId} of ${name}: ${value}`)
  }

  /** Renders a value that turns into an input on double-click, Enter, or F2. */
  function EditableCell(props: {
    context: CellContext<DataTableT.Features, Product>
    columnId: EditableKey
    label: string
    children: JSX.Element
  }): JSX.Element {
    const rowId = () => props.context.row.id
    const initial = () => String(props.context.row.original[props.columnId])
    const [draft, setDraft] = createSignal('')
    const error = () => validate(props.columnId, draft())

    const start = () => {
      setDraft(initial())
      setEditing({ rowId: rowId(), columnId: props.columnId })
    }
    const cancel = () => setEditing(undefined)
    const save = () => {
      // Removing the input fires `blur` after Enter or Escape has already finished the edit.
      if (!isEditing(rowId(), props.columnId) || error()) {
        return
      }
      if (draft().trim() === initial()) {
        cancel()
        return
      }
      commit(rowId(), props.columnId, draft())
    }

    return (
      <Show
        when={isEditing(rowId(), props.columnId)}
        fallback={
          <div
            role="button"
            tabIndex={0}
            aria-label={`Edit ${props.label}: ${initial()}`}
            class="px-1 py-0.5 rounded min-h-6 cursor-text -mx-1 focus-visible:(outline-none ring-2 ring-ring/50) hover:bg-accent/60"
            onDblClick={start}
            onKeyDown={(event) => {
              if (event.key === 'Enter' || event.key === 'F2') {
                event.preventDefault()
                start()
              }
            }}
          >
            {props.children}
          </div>
        }
      >
        <div class="flex flex-col gap-1">
          <Input
            aria-label={props.label}
            aria-invalid={error() ? true : undefined}
            size="sm"
            autofocus
            inputMode={props.columnId === 'stock' ? 'numeric' : undefined}
            value={draft()}
            onValueChange={setDraft}
            onBlur={save}
            onKeyDown={(event: KeyboardEvent) => {
              if (event.key === 'Enter') {
                event.preventDefault()
                save()
              } else if (event.key === 'Escape') {
                event.preventDefault()
                cancel()
              }
            }}
          />
          <Show when={error()}>
            <span class="text-xs text-danger">{error()}</span>
          </Show>
        </div>
      </Show>
    )
  }

  const columns: DataTableT.Column<Product>[] = [
    {
      accessorKey: 'name',
      header: 'Product',
      size: 240,
      cell: (context) => (
        <EditableCell context={context} columnId="name" label="Product name">
          {context.row.original.name}
        </EditableCell>
      ),
    },
    {
      accessorKey: 'sku',
      header: 'SKU',
      size: 120,
      cell: (context) => <span class="text-muted-foreground">{context.row.original.sku}</span>,
    },
    {
      accessorKey: 'stock',
      header: 'Stock',
      size: 120,
      meta: { align: 'end' },
      cell: (context) => (
        <EditableCell context={context} columnId="stock" label="Stock">
          <span class="tabular-nums">{context.row.original.stock}</span>
        </EditableCell>
      ),
    },
  ]

  const table = createDataTable({
    get data() {
      return products()
    },
    columns,
    getRowId: (row) => row.id,
  })

  return (
    <div class="flex flex-col gap-3 w-full">
      <DataTable table={table} aria-label="Inventory" />
      <p class="text-sm text-muted-foreground" aria-live="polite">
        {lastChange()}
      </p>
    </div>
  )
}
```

### Reorder a release queue

Drag the grip in the first column, or focus it and press Space, then the arrow keys. The column
renders the handle with `sortable.handleRefFor(row.id)`. The table styles the drag itself: the row
stays in place while a copy at 60% opacity follows the pointer, and the target row shows a line on
the side the row lands on.

```tsx
import { Icon } from 'moraine'
import { DataTable, createDataTable } from 'moraine/data-table'
import type { DataTableT } from 'moraine/data-table'
import { createListSortable } from 'moraine/dnd'
import { createSignal } from 'solid-js'

interface Release {
  id: string
  version: string
  owner: string
  status: string
}

const RELEASES: Release[] = [
  { id: 'r1', version: '2.4.0', owner: 'Elena', status: 'Ready' },
  { id: 'r2', version: '2.3.2', owner: 'Marcus', status: 'In review' },
  { id: 'r3', version: '2.3.1', owner: 'Priya', status: 'Blocked' },
  { id: 'r4', version: '2.3.0', owner: 'Jonas', status: 'Draft' },
  { id: 'r5', version: '2.2.9', owner: 'Aiko', status: 'Ready' },
]

export default function SortableRowsExample() {
  const [releases, setReleases] = createSignal(RELEASES)

  const table = createDataTable({
    get data() {
      return releases()
    },
    columns: [
      {
        id: 'drag',
        header: () => <span class="sr-only">Reorder</span>,
        size: 44,
        cell: (props) => (
          <button
            ref={sortable.handleRefFor(props.row.id)}
            type="button"
            aria-label={`Reorder ${props.row.original.version}`}
            class="text-muted-foreground rounded-sm flex size-6 cursor-grab items-center justify-center hover:bg-accent"
          >
            <Icon name="i-lucide:grip-vertical" />
          </button>
        ),
      },
      { accessorKey: 'version', header: 'Version' },
      { accessorKey: 'owner', header: 'Owner' },
      { accessorKey: 'status', header: 'Status' },
    ] satisfies DataTableT.Column<Release>[],
    getRowId: (row) => row.id,
    columnSortable: false,
  })

  // Rows render in data order here: no sorting, filtering, or pagination reorders them.
  const sortable = createListSortable({
    items: () => table.getRowModel().rows,
    getId: (row) => row.id,
    onReorder: (event) => setReleases(event.items.map((row) => row.original)),
  })

  return (
    <sortable.Provider>
      <DataTable
        table={table}
        aria-label="Release queue"
        rowProps={(context) => sortable.useRow(context).props}
      />
    </sortable.Provider>
  )
}
```

### Scroll 10,000 rows and 100 columns

Pass a `virtualizer` from `createTableVirtualizer`, with `getItemKey` set to the row id, and bound
the table with `maxHeight`. The virtualizer's `columns` option also virtualizes the hour columns, so
only the cells near the viewport mount. The pinned server column stays in view while the hours
scroll sideways. Leave out `columns` to virtualize rows only.

```tsx
import { DataTable, createDataTable } from 'moraine/data-table'
import type { DataTableT } from 'moraine/data-table'
import { createTableVirtualizer } from 'moraine/virtualizer'

interface MetricRow {
  id: number
  server: string
  readings: number[]
}

const ROW_HEIGHT = 37
const HOUR_COUNT = 100

const REGIONS = ['eu-west', 'us-east', 'ap-south', 'sa-east'] as const

const ROWS: MetricRow[] = Array.from({ length: 10_000 }, (_, row) => ({
  id: row + 1,
  server: `${REGIONS[row % REGIONS.length]}-${String(row + 1).padStart(5, '0')}`,
  readings: Array.from({ length: HOUR_COUNT }, (_, hour) => ((row * 31 + hour * 17) % 97) + 1),
}))

const COLUMNS: DataTableT.Column<MetricRow>[] = [
  {
    accessorKey: 'server',
    header: 'Server',
    size: 160,
    cell: (props) => <span class="font-medium">{props.row.original.server}</span>,
  },
  ...Array.from({ length: HOUR_COUNT }, (_, hour): DataTableT.Column<MetricRow> => ({
    id: `h${hour}`,
    header: `H${hour + 1}`,
    accessorFn: (row) => row.readings[hour],
    size: 72,
    meta: { align: 'end' },
    cell: (props) => <span class="tabular-nums">{props.row.original.readings[hour]}%</span>,
  })),
]

export default function VirtualizationExample() {
  const virtualizer = createTableVirtualizer<DataTableT.Row<MetricRow>>({
    estimateSize: () => ROW_HEIGHT,
    getItemKey: (row) => row.id,
    overscan: 10,
    columns: { overscan: 2 },
  })

  const table = createDataTable({
    data: ROWS,
    columns: COLUMNS,
    getRowId: (row) => String(row.id),
    columnSortable: false,
    initialState: { columnPinning: { start: ['server'], end: [] } },
  })

  return (
    <DataTable
      table={table}
      virtualizer={virtualizer}
      sticky="header"
      maxHeight={360}
      size="sm"
      aria-label="CPU usage per hour"
    />
  )
}
```

## API Reference

### Attributes

| Attributes | Slot | Description |
| --- | --- | --- |
| `data-empty` | `data-table-row` | — |
| `data-expanded` | `data-table-row`, `data-table-expanded-row`, `data-table-expanded-cell`, `data-table-expand-button` | Present when the panel, accordion, or menu is expanded. |
| `data-selected` | `data-table-row` | Present when the item or tab is selected. |
| `data-pinned` | `data-table-head`, `data-table-cell` | Present when the item or column is pinned. |
| `data-pinned-edge` | `data-table-head`, `data-table-cell` | — |
| `data-tree` | `data-table-cell` | — |
| `data-sorted` | `data-table-sort-icon` | — |
| `data-resizing` | `data-table-resizer` | Present while resizable handles are actively dragging. |
| `data-checked` | `data-table-checkbox` | Present when the item or toggle is checked. |
| `data-disabled` | `data-table-checkbox` | Present when the component, slot, or item is disabled. |
| `data-indeterminate` | `data-table-checkbox` | Present when the checkbox or progress state is indeterminate. |
| `data-unchecked` | `data-table-checkbox` | Present when the checkbox, radio item, or switch is unchecked. |
| `data-closed` | `data-table-expanded-row`, `data-table-expanded-cell` | Present when disclosure or transition content is closed. |

### Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| border | 'row' \| 'col' \| 'both' \| undefined | 'row' | Border divider layout. |
| emptyRender | JSX.Element \| Component<EmptyRenderProps> \| undefined | — | Replaces the default `No results.` message inside the single empty-state cell, rendered when<br>the table has no rows and is not `loading`. A component receives the visible column count<br>as `colSpan`. |
| expandedRowRender | Component<ExpandedRowRenderProps<TData>> \| undefined | — | Component rendered in a detail row below each expanded row, spanning every column. Rows<br>expand through the `expandable` option, tree `getSubRows` data, or the row's<br>`toggleExpanded()`. Receives the `row`. Ignored, with a development warning, when<br>`virtualizer` is set. |
| headProps | ((context: HeadPropsContext<TData>) => HeadAttributes) \| undefined | — | Extra attributes for each header cell (`<th>`), such as drag wiring from<br>`createListSortable().useRow` to reorder columns. Called once per header cell, under its<br>owner; read `context` fields lazily to follow index changes. Its `ref` is composed with the<br>table's own. |
| highlightOnHover | boolean \| undefined | false | Highlight row on mouse hover. |
| loading | boolean \| undefined | — | Whether the table is loading. Shows the loading overlay (a spinner, or `loadingRender`) over<br>the table, sets `aria-busy`, and announces the localized `loading` message to screen<br>readers. Rows stay rendered, and the empty state is hidden while loading. |
| loadingRender | JSX.Element \| Component<LoadingRenderProps> \| undefined | — | Replaces the default spinner inside the loading overlay shown while `loading` is `true`.<br>A component receives the visible column count as `colSpan`. |
| maxHeight | number \| string \| undefined | — | Maximum height of the table scroll container. A number is in pixels and a string is any CSS<br>length (e.g. `400` or `'50vh'`). Rows scroll vertically beyond it; combine with `sticky` to<br>keep the header visible. Unset or `0` leaves the height unbounded. |
| onRowClick | ((row: Row<TData>, event: MouseEvent) => void) \| undefined | — | Called when a body row is clicked, with the row and the click event, and gives rows a<br>clickable style. Clicks on the selection control and the expand button do not reach it.<br>A click handler returned by `rowProps` runs first. |
| onRowDoubleClick | ((row: Row<TData>, event: MouseEvent) => void) \| undefined | — | Called when a body row is double-clicked, with the row and the event. Like `onRowClick`, it<br>gives rows a clickable style, and the selection and expand controls do not trigger it. |
| rowProps | ((context: RowPropsContext<TData>) => RowAttributes) \| undefined | — | Extra attributes for each body row (`<tr>`), such as drag wiring from<br>`createListSortable().useRow`. Called once per row, under that row's owner, so it may call<br>row-level hooks; read `context` fields lazily to follow index changes. Its `class` merges<br>into the `row` slot, and its `ref`, `onClick`, and `onDblClick` run alongside the table's<br>own (before `onRowClick` and `onRowDoubleClick`). |
| size | 'sm' \| 'md' \| 'lg' \| undefined | 'md' | Size density of table cells, text, and padding. |
| sticky | boolean \| 'header' \| 'footer' \| undefined | false | Whether the header and/or footer stick to the edges of the scroll container (`true` sticks both). |
| table* | Instance<TData> | — | Table instance created with `createDataTable`. Sorting, selection, pagination, expansion,<br>and the other behavior live on it; `DataTable` only renders it. Without the instance's<br>pagination settings (a plain TanStack table), no pagination toolbar is rendered. |
| translations | Translations \| undefined | — | Localized messages for this data table, merged per key over the provider messages. Some<br>entries are functions that receive a context object. |
| virtualizer | Virtualizer<TData> \| undefined | — | Renders only the visible rows, and the visible center columns when the virtualizer has the<br>`columns` option. Create it with `createTableVirtualizer()` from `moraine/virtualizer`.<br>Disables pagination (the toolbar is hidden and every row is shown in one scroll) and<br>`expandedRowRender`. Bound the scroll area with `maxHeight`. |
| wrapperRef | Ref<HTMLDivElement> \| undefined | — | Ref callback or variable for the outer container `<div>`, which wraps the scrolling table,<br>the loading overlay, and the pagination toolbar. The inherited `ref` targets the `<table>`. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| classes | Classes \| undefined | — | Family slot class defaults for this instance. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |
| styles | Styles \| undefined | — | Family slot style defaults for this instance. |

**`emptyRender` example**

```tsx
import { DataTable, createDataTable } from 'moraine/data-table'

const table = createDataTable({
  data: [],
  columns: [{ accessorKey: 'name', header: 'Name' }],
})

<DataTable table={table} emptyRender={() => <p>No users yet. Invite someone to get started.</p>} />
```

**`expandedRowRender` example**

```tsx
import { DataTable, createDataTable } from 'moraine/data-table'

const table = createDataTable({
  data: [{ name: 'Ada', bio: 'Mathematician' }],
  columns: [{ accessorKey: 'name', header: 'Name' }],
  expandable: true,
})

<DataTable table={table} expandedRowRender={(props) => <p>{props.row.original.bio}</p>} />
```

**`headProps` example**

```tsx
import { DataTable, createDataTable } from 'moraine/data-table'

const table = createDataTable({
  data: [{ name: 'Ada' }],
  columns: [{ accessorKey: 'name', header: 'Name' }],
})

<DataTable table={table} headProps={({ header }) => ({ title: `Column ${header.column.id}` })} />
```

**`loadingRender` example**

```tsx
import { DataTable, createDataTable } from 'moraine/data-table'

const table = createDataTable({
  data: [],
  columns: [{ accessorKey: 'name', header: 'Name' }],
})

<DataTable table={table} loading loadingRender={<span>Fetching rows…</span>} />
```

**`onRowClick` example**

```tsx
import { DataTable, createDataTable } from 'moraine/data-table'

const table = createDataTable({
  data: [{ id: 'a', name: 'Ada' }],
  columns: [{ accessorKey: 'name', header: 'Name' }],
})

<DataTable table={table} onRowClick={(row, event) => console.log(row.original.id, event.metaKey)} />
```

**`rowProps` example**

```tsx
import { DataTable, createDataTable } from 'moraine/data-table'

const table = createDataTable({
  data: [{ id: 'a', name: 'Ada', active: false }],
  columns: [{ accessorKey: 'name', header: 'Name' }],
})

<DataTable
  table={table}
  rowProps={({ row }) => ({ class: row.original.active ? undefined : 'opacity-60', title: row.id })}
/>
```

**`translations` example**

```tsx
import { DataTable, createDataTable } from 'moraine/data-table'

const table = createDataTable({
  data: [{ name: 'Ada' }],
  columns: [{ accessorKey: 'name', header: 'Name' }],
  paginated: true,
})

<DataTable
  table={table}
  translations={{ empty: 'Aucun résultat', rowCount: ({ total }) => `${total} ligne(s)` }}
/>
```

**`virtualizer` example**

```tsx
import { DataTable, createDataTable } from 'moraine/data-table'
import type { DataTableT } from 'moraine/data-table'
import { createTableVirtualizer } from 'moraine/virtualizer'

interface Person {
  name: string
}
const people: Person[] = Array.from({ length: 5000 }, (_, i) => ({ name: `Person ${i}` }))
const table = createDataTable({ data: people, columns: [{ accessorKey: 'name', header: 'Name' }] })
const virtualizer = createTableVirtualizer<DataTableT.Row<Person>>({ estimateSize: () => 40 })

<DataTable table={table} virtualizer={virtualizer} maxHeight={400} />
```
