# DataTable

A grid for query results.

The same engine as [ItemTable](./ItemTable.md) — one renderer, one column layout, one value pipeline — with the defaults an analytical grid wants rather than a list's.

## When to Use

Use `DataTable` for the output of a query: rows the user reads as a block, scans down a column of, and sorts by more than one thing at a time.

Use `ItemTable` for a list of things the user acts on — deployments, members, API keys. That is the one with selection, bulk actions, row menus and row links.

|  | `ItemTable` | `DataTable` |
| --- | --- | --- |
| Typography | `t3` | `t4` |
| Density | `medium` | `small` |
| Banded rows | off | **on** |
| Column resize | opt-in | **on** |
| Sorting | one column | **several, in precedence order** |
| Pinned rows | — | **totals, top and bottom** |
| Row numbers | — | **optional** |
| Selection | rows | **cells, as a rectangle** |
| Bulk actions, row menu, row link | yes | — |
| Column rules | off | **on** |

## It knows nothing about Cube

Measures, dimensions, pivots, drill-downs and calculated fields never reach this component as query concepts. They arrive as leaf columns, presentational column groups, `render` output and `column.header.menu` content — which is what keeps Cloud's column-header menu, and everything it knows about the query, in Cloud.

## Component

### Properties

#### Data

- **`data`** `readonly T[]` — The rows.
- **`columns`** `CubeDataTableColumnDefinition<T>[]` — Leaf columns use the same shape as `ItemTable`'s, plus `dataType`; group nodes contain nested `children`.
- **`rowKey`** `string` (default: `'id'`) — Property to read the row identity from.
- **`getRowKey`** `(row: T, index: number) => Key` — Wins over `rowKey`.
- **`getRowChildren`** `(row: T) => readonly T[] | undefined` — Enables nested treegrid rows; `data` contains roots.
- **`treeColumnKey`** `string` — Indented disclosure column. Defaults to the first visible data column.
- **`expandedKeys`** `Key[]` — Controlled expansion.
- **`defaultExpandedKeys`** `Key[]` — Initial expansion. Nothing is expanded by default.
- **`onExpand`** `(keys, info) => void` — Reports the resulting keys and toggled row metadata.
- **`pinnedTopRows`** `readonly T[]` — Rows stuck to the top of the scroller. Ordinary rows as far as the columns are concerned.
- **`pinnedBottomRows`** `readonly T[]` — The same, at the bottom. This is where totals go.

#### Status

- **`isLoading`** `boolean`
- **`loadingIndicator`** `'overlay' | 'skeleton' | 'none'` (default: `'overlay'`) — A translucent overlay keeps the previous result readable while the next one loads.
- **`skeletonRowCount`** `number` (default: `6`)
- **`error`** `ReactNode` — Takes precedence over both empty labels.
- **`emptyLabel`** `ReactNode` — Nothing to show at all.
- **`noResultsLabel`** `ReactNode` — Shown instead when `isFiltered`.
- **`isFiltered`** `boolean` — Tells the empty state a filter is why there is nothing.

#### Shape

- **`shape`** `'plain' | 'card'` (default: `'plain'`)
- **`size`** `SizeName` (default: `'small'`) — An analytical grid packs more rows than a list.
- **`rowSize`** `'small' | 'medium' | 'large'` — Row height as a named step: 28px / 32px / 40px. Rows only; the header keeps answering to `size`. Unset, the height comes from `size`.
- **`rowHeight`** `number` — An exact height, when none of the named steps is the answer. Wins over both `rowSize` and `size`.
- **`headerHeight`** `number` — Exact height of each header row in px.
- **`isStriped`** `boolean` (default: `true`) — Banding is what makes a wide row readable across.
- **`isHeaderHidden`** `boolean`
- **`isHeaderSticky`** `boolean` (default: `true`)
- **`isAutoHeight`** `boolean` (default: `false`) — Shrink-wraps the frame to the rendered rows instead of filling its flex pane. It takes precedence over root height/flex sizing and disables virtualization.
- **`isRowMoveAnimated`** `boolean` (default: `true`) — Slide rows to their new positions when the order changes, instead of teleporting them. Respects `prefers-reduced-motion`.
- **`showRowNumbers`** `boolean` (default: `false`) — A continuous count down the side, which stays continuous across pages.

#### Sorting

- **`sortMode`** `'client' | 'server' | 'off'`
- **`sorts`** `CubeTableSort[]` — Array order is the sort precedence.
- **`defaultSorts`** `CubeTableSort[]`
- **`onSortsChange`** `(sorts: CubeTableSort[]) => void`

#### Pagination

- **`paginationMode`** `'client' | 'server' | 'off'` (default: `'client'`)
- **`page`** `number` — 1-based.
- **`defaultPage`** `number`
- **`onPageChange`** `(page: number) => void`
- **`pageSize`** `number`
- **`defaultPageSize`** `number` (default: `100`)
- **`onPageSizeChange`** `(pageSize: number) => void`
- **`pageSizeOptions`** `number[]`
- **`total`** `number` — Server mode: the row count behind the current page.
- **`totalPages`** `number` — Supply instead of `total` when only the page count is known.
- **`hasNextPage`** `boolean` — When neither count is known.
- **`summary`** `boolean | ((info: CubeTablePageInfo) => ReactNode)`
- **`autoHidePagination`** `boolean` (default: `true`) — Hides the footer when it can do nothing: one page, and fewer rows than the smallest page size.
- **`footerStart`** `ReactNode`
- **`footerCenter`** `ReactNode`
- **`footerEnd`** `ReactNode`

#### Cell selection

- **`cellSelectionMode`** `'none' | 'cell' | 'range'` (default: `'range'`) — Click selects a cell; shift-click and drag grow a rectangle.
- **`isCellSelectable`** `(ctx) => boolean` — Vetoes individual cells. `ctx` is `{ row, rowKey, columnKey, section }`.
- **`selectedCellRange`** `CubeTableCellRange | null` — Two opposite corners.
- **`defaultSelectedCellRange`** `CubeTableCellRange | null`
- **`onCellRangeChange`** `(range: CubeTableCellRange | null) => void`

#### Columns

- **`isResizable`** `boolean` (default: `true`) — A result grid is the case resizing exists for.
- **`columnWidths`** `Record<string, number>`
- **`defaultColumnWidths`** `Record<string, number>`
- **`onColumnResize`** `(columnKey: string, width: number, all: Record<string, number>) => void`
- **`isColumnReorderable`** `boolean` (default: `false`) — Drag column headers sideways to reorder them.
- **`columnOrder`** `string[]` — Controlled order, as column keys. Works with or without dragging.
- **`defaultColumnOrder`** `string[]`
- **`onColumnOrderChange`** `(order: string[]) => void` — The full key list, including hidden and pinned columns.

Per column, on `CubeDataTableColumn`: `isReorderable`, `color` and `colorScope` — see [Column Colors](#column-colors) for the last two.

#### Column menu

- **`columnContextMenu`** `boolean | 'context-only'` (default: `true`) — Where a column's `header.menu` is exposed.
- **`onColumnMenuAction`** `(action: string, columnKey: string) => void` — The pressed key, as written.
- **`columnMenuTriggerProps`** `Record<string, any>`
- **`columnMenuProps`** `Record<string, any>`

#### Virtualization

- **`isVirtualized`** `boolean | 'auto'` (default: `'auto'`) — On when the grid is height-bounded and has more rows than the threshold. Ignored when `isAutoHeight` is enabled.
- **`virtualizeThreshold`** `number`

Wide bounded tables window default text body cells horizontally while retaining all headers and the complete grouped-column layout. Pinned/structural columns, row headers, tree disclosure, wrapping cells, custom renderers and per-column cell styles remain mounted. Custom body/row/cell styles, arbitrary `cellProps` and auto-height or `isVirtualized={false}` retain the complete body layout. Logical cell-range selection and copy include offscreen columns.

- **`overscan`** `number`

#### Other

- **`getRowProps`** `(ctx: CubeTableRowContext<T>) => Record<string, any>` — Per-row mods, styles and height.
- **`storageKey`** `string` — Persists page size, column widths and column order.
- **`ariaLabel`** `string`
- **`isChecked`** `boolean` — Base checked-state modifier.
- **`place`** `string` — Tasty placement shorthand on the root frame.
- **`scrollMargin`** `string | number` — Scroll margin on the root frame.

#### `dataType`

Presentational, not a Cube type. `number` right-aligns the column and switches it to tabular figures, so digits line up down the column and a total lines up with the rows above it.

The figures sit under the column's own `cellStyles`, so those still apply in either form. A function is still called per cell, and its result is merged over the figures.

#### Column `cellStyles`

Tasty styles for one column's body cells, exactly as in [ItemTable](./ItemTable.md): tokens, units, presets and state maps all work, and a state key asks about the cell itself. In the table-level `cellStyles` a bare key asks about the table instead, so a map copied from there that keys on `shape=card` or `column-dividers` matches nothing in a column; `@own(...)` asks about the cell in both. Values read as tasty, not CSS: `paddingLeft: 24` sets all four sides (the others to 0), so set one side with the CSS longhand and a unit (`paddingInlineStart: '24px'`); a bare number takes a unit on tasty's own properties (pass `lineHeight: '1.2'` for a unitless one) but not on plain CSS ones (`borderRadius: '4px'`, or `radius`); colors inside `border` / `outline` must be tokens (`'1px solid #red'`); a vendor key needs its CSS name in quotes (`'-webkit-line-clamp': 2`), since a capitalised `WebkitLineClamp` reads as a sub-element; and `textOverflow: 'ellipsis'` also adds `overflow: hidden` and `white-space: nowrap`. The function form runs per cell with the cell's context, which is how a pinned row is styled apart from the body:

```jsx
{
  key: 'orders',
  title: 'Orders',
  dataType: 'number',
  cellStyles: (ctx) =>
    ctx.section === 'pinnedBottom' ? { color: '#surface-text-soft-2' } : undefined,
}
```

Cells with equal styles share one class, so a function that returns a few distinct objects costs a few classes, however many rows there are. A column's own styles win over the table's cell paint, its `color` tint and the table-level `cellStyles` below.

Loading, empty and error states, pagination, footer slots, virtualization, column resize and persistence all behave exactly as they do in `ItemTable` — they come from the shared renderer.

### Base Properties

Supports [Base Properties](../../BaseProperties.md).

### Styling Properties

#### styles

Customizes the root frame. Every internal part of the grid is a **sub-element** reachable from this one prop — the same contract, and the same sub-element names, as [ItemTable](./ItemTable.md#styling-properties).

`DataTable` adds `StateCell`, the full-span cell that carries the empty, no-results and error content, and `HeaderGroupCell`, a spanning cell in a multi-row header. `StateCell` is deliberately not a `Cell`, so it takes none of the row's banding or hover paint.

#### Targeted slots

Each merges into the corresponding sub-element at the same selector and specificity, so an override lands later in source order and wins without `!important`.

- **`headerStyles`** `Styles` — The column header row.
- **`headerCellStyles`** `Styles`
- **`bodyStyles`** `Styles`
- **`rowStyles`** `Styles`
- **`cellStyles`** `Styles`
- **`footerStyles`** `Styles`

### Style Properties

These properties allow direct style application without using the `styles` prop:

- **Base:** `display`, `font`, `preset`, `hide`, `whiteSpace`, `opacity`, `transition`
- **Position:** `gridArea`, `order`, `gridColumn`, `gridRow`, `placeSelf`, `alignSelf`, `justifySelf`, `zIndex`, `margin`, `blockMargin`, `inlineMargin`, `inset`, `blockInset`, `inlineInset`, `position`, `scrollMargin`, `blockScrollMargin`, `inlineScrollMargin`, `scrollPadding`, `blockScrollPadding`, `inlineScrollPadding`
- **Dimension:** `width`, `height`, `blockSize`, `inlineSize`, `flexBasis`, `flexGrow`, `flexShrink`, `flex`
- **Block:** `border`, `blockBorder`, `inlineBorder`, `radius`, `shadow`, `outline`, `padding`, `blockPadding`, `inlinePadding`, `overflow`, `scrollbar`, `textAlign`
- **Color:** `color`, `fill`, `fade`, `image`
- **Flow:** `flow`, `place`, `placeItems`, `placeContent`, `alignItems`, `alignContent`, `justifyItems`, `justifyContent`, `align`, `justify`, `gap`, `columnGap`, `rowGap`, `gridColumns`, `gridRows`, `gridTemplate`, `gridAreas`

### Modifiers

| Modifier | Type | Description |
| --- | --- | --- |
| `size` | `SizeName` | Row height scale |
| `shape` | `'plain' \| 'card'` | Frame treatment |
| `sticky-header` | `boolean` | Header is pinned |
| `column-dividers` | `boolean` | Vertical rules between columns — always on here |
| `range-dragging` | `boolean` | A cell-range drag is in progress |

Cell-level, in addition to `ItemTable`'s: `cell-selected`, `last-column`, `pinned`.

## Pivoted Results and Column Groups

Pass group nodes in `columns` to render real multi-row headers. Groups may nest to any depth; their `children` eventually resolve to ordinary leaf columns, and only those leaves participate in sorting, resizing, ranges and copying.

```jsx
const columns = [
  { key: 'region', title: 'Region', pin: 'start' },
  {
    key: 'organic',
    title: 'Organic',
    children: [
      { key: 'organic_orders', title: 'Orders', dataType: 'number' },
      { key: 'organic_revenue', title: 'Revenue', dataType: 'number' },
    ],
  },
  {
    key: 'paid',
    title: 'Paid',
    children: [
      { key: 'paid_orders', title: 'Orders', dataType: 'number' },
      { key: 'paid_revenue', title: 'Revenue', dataType: 'number' },
    ],
  },
];

<DataTable data={pivotRows} columns={columns} isAutoHeight />;
```

The data/query layer still owns the pivot calculation. DataTable only renders the already-shaped rows and generated column hierarchy. Leaf resizing and sorting remain available; drag column reordering is ignored while groups are present because moving one leaf cannot preserve an arbitrary hierarchy.

## Tree Rows

Tree mode uses the same nested-data contract as `ItemTable`:

```jsx
<DataTable
  data={regions}
  columns={columns}
  getRowChildren={(row) => row.children}
  treeColumnKey="region"
  defaultExpandedKeys={['americas']}
/>
```

Multi-sort is recursive: every sibling collection is sorted by the same precedence. Client pagination slices roots and keeps complete subtrees together; server pages are rendered exactly as supplied and `total` counts roots. Pinned rows remain ordinary non-hierarchical totals.

Only visible descendants participate in cell ranges and virtualization. Collapsing a range endpoint makes the effective range inactive; a controlled or uncontrolled range is restored when that endpoint becomes visible again. Client row numbers remain continuous across root pages, while server tree pages restart at 1 because preceding descendant counts are unknown.

The native table exposes `role="treegrid"`, `aria-level`, `aria-expanded`, `aria-posinset` and `aria-setsize`. Right/Left expand, collapse or move to the parent; Up/Down traverse visible rows, and typeahead reads `treeColumnKey`. Customize the hierarchy chrome with `styles.TreeContent`, `styles.TreeToggle` and `styles.TreeValue`.

## Examples

### Multi-Column Sorting

The main behavioural difference from `ItemTable`. Clicking a second header adds it to the sort rather than replacing it, and each sorted column shows its place in the precedence.

```jsx
<DataTable
  data={rows}
  columns={columns}
  sorts={sorts}
  onSortsChange={setSorts}
/>
```

A newly sorted column is **appended**, so it is the least significant — the ordering the user already established keeps leading. Cycling a column through `ascending → descending → unsorted` leaves the others untouched.

`sortMode="server"` reports the array and never reorders, which is the shape Cloud's reports already send to the query.

### Pinned Totals

Pinned rows stick to the edges of the scroller while the rest scrolls under them. They are excluded from sorting and paging — a total is not a row competing for a position.

### The Whole Result

Above `virtualizeThreshold` a bounded grid virtualizes on its own, so `paginationMode="off"` is a reasonable default for a result the user scrolls.

For a compact result that should participate in normal page flow, set `isAutoHeight`. The frame then ends at the last rendered row rather than filling its flex pane. This renders the complete result and disables virtualization, so keep larger results bounded instead.

```jsx
<DataTable
  data={summaryRows}
  columns={columns}
  paginationMode="off"
  isAutoHeight
/>
```

### Sorting Moves Rows

When a sort reorders rows, they slide to their new positions over 120ms rather than jumping. The point is to be able to follow one row to where it went — a table that teleports gives the eye nothing to track.

Only rows that were already on screen slide: a row arriving from outside the window, or from another page, has no position to come from. Scrolling is never mistaken for movement, and `prefers-reduced-motion` turns it off. Set `isRowMoveAnimated={false}` to opt out.

### Cell Selection

A list is acted on by row; a result grid is read by cell. Click one, shift-click or drag to grow a rectangle, and `⌘/Ctrl+C` copies the block as tab-separated values — the format Excel and Sheets both paste as a grid rather than as one run of text. `Escape` clears it.

The range is stored as two opposite corners rather than a set of keys, so it survives sorting and paging the way a keyed row selection does.

A pinned total takes part — a total is a figure like any other, and selecting the column it sums only to copy it separately is the wrong trade. It joins by press or shift-click, but a drag will not sweep through it: a pinned row sits _over_ the scrolling ones and is last in the row order, so brushing it mid-drag would otherwise snap the range to the whole rest of the grid.

(ag-grid excludes pinned rows from a range outright. This is a deliberate departure.)

The structural columns — row numbers, the checkbox, the row-menu button — stay out of every range. They are the grid's own furniture, not data.

`isCellSelectable` vetoes anything else. A total's label cell is the motivating case — `"Total"` is a caption for the row, not a figure:

```jsx
<DataTable
  isCellSelectable={({ section, columnKey }) =>
    !(section === 'pinnedBottom' && columnKey === 'region')
  }
/>
```

A vetoed cell is **inert**, not merely unpainted: pressing it neither starts a range nor disturbs the standing one, and it cannot be extended onto. A range that spans it skips it and copies an empty field in its place, so the pasted block keeps its shape.

### Pagination With Totals

The total sits outside the page window, so it stays put as you move through the pages and keeps summing the whole result rather than the rows on screen. It is excluded from sorting for the same reason.

Copying reports the count in a toast, since nothing on screen changes when a copy succeeds.

### Sorting Affordance

A sortable header shows nothing at rest. Hover it — or focus it from the keyboard — and the sort arrow fades in at 40%, pointing the way a press would sort it (ascending, for a column that is currently unsorted). Press it and the arrow goes solid and stays that way with the pointer gone, which is what separates a hint from a state.

The arrow keeps its slot throughout, so none of this shifts the label. A non-sortable column has no arrow at all — the hint is not a reason to render one.

### Column Menu

A column exposes a menu through `header.menu`, opened from a `⋮` trigger in the header, by right-click or a touch long press, or with `Shift`+`F10`. The contents are opaque — the grid mounts the node and reports the pressed key back through `onColumnMenuAction`, which is what keeps Cube vocabulary out of the kit.

Sorting is the exception, because it is the one thing the table itself can do. `columnSortMenu()` returns `sort-asc` / `sort-desc` / `clear-sort` items that the table labels from the current locale, disables when they would do nothing, and applies before telling the consumer. Everything else is yours:

```tsx
import { columnSortMenu, Menu } from '@cube-dev/ui-kit';

const columns = [
  {
    key: 'revenue',
    title: 'Revenue',
    isSortable: true,
    header: {
      menu: (
        <>
          {columnSortMenu()}
          <Menu.Item key="pin">Pin column</Menu.Item>
        </>
      ),
    },
  },
];

<DataTable
  columns={columns}
  onColumnMenuAction={(action, columnKey) => {
    if (action === 'pin') pinColumn(columnKey);
  }}
/>;
```

Pressing the trigger never sorts the column: the header's `Item` swallows the click, which is why it sits _inside_ the `<th>` rather than being it.

### Column Reordering

`isColumnReorderable` lets a user drag a header sideways, or move the focused column with `Alt`+`←` / `→`. Clicking still sorts and the resize handle still resizes.

Structural and pinned columns stay put — `pin` is already the ordering authority for a pinned column — and a single column opts out with `isReorderable: false`. `columnOrder` works on its own too, so a column manager elsewhere in the page can drive the order without any dragging.

A stale order is safe: keys for columns that no longer exist are ignored, and a column missing from the list lands after the neighbour it had in `columns` rather than being swept to the end.

### Column Colors

`column.color` tints a whole column — header, cells and pinned totals. It takes a palette theme name, any CSS color, a `{ hue, saturation }` seed, or a `{ fill, text }` pair for full manual control.

Every form but the last is _derived_: only the hue and saturation are kept, and the tone ramp plus an AA/AAA text floor are re-solved for light, dark and high-contrast. A column cannot end up unreadable in a scheme nobody checked.

```tsx
const columns = [
  { key: 'orders', title: 'Orders', color: 'note' },
  { key: 'revenue', title: 'Revenue', color: 'success' },
  { key: 'conversion', title: 'Conversion', color: '#0ea5e9' },
  // Header only, cells left neutral.
  { key: 'region', title: 'Region', color: 'danger', colorScope: ['header'] },
];
```

Row banding survives inside a tinted column: the tint carries its own band one tone step away, so the stripe still reads down the column instead of being painted over.

Under the hood each distinct color becomes a small adaptive theme named by a hash of its config, registered once per document — so ten columns sharing a color cost one set of tokens. That machinery is public as `useColorTheme` if you want it elsewhere.

## Accessibility

The table is a `role="grid"` with document-absolute `aria-rowindex` / `aria-colindex`, and `aria-rowcount` counts pinned rows and every visible header row. Group cells use native `scope="colgroup"` / `colSpan`; ungrouped leaf headers span the remaining rows. Every sorted leaf column carries `aria-sort`, not just the first.

A header cell takes a tab stop when it is interactive — sortable, carrying a menu, or reorderable. `Shift`+`F10` opens the column menu from the keyboard, and `Alt`+`←` / `→` moves a reorderable column, so neither needs a pointer.

## Related Components

- [ItemTable](./ItemTable.md) — a list of things to act on.
- [Pagination](../navigation/Pagination.md) — the footer control.
