# Tree Grid

> DataGrid tree mode for hierarchical data. Nested or flat self-referential rows, expansion, tree keys, filter and paging modes, checkbox cascade, child summaries, drag and indent, and lazy remote children.

Canonical: https://salmonui.dev/docs/data-grid/tree

A tree grid is `DataGrid` with the `tree` option: the same component,
engine, columns and API, with rows indented by depth in one column.
A second component would
repeat every Data Grid prop, event, method and docs page and ship a second
renderer, so the tree is a row model of the one grid instead. No
`TreeGrid` alias is exported. Tree mode is opt-in: a grid without `tree` loads none of the tree code.

## Enabling tree mode

Nested rows keep their children in an array field. `tree` (or
`tree={{ childrenField: 'children' }}`) reads them; the nested rows are taken by reference, never
copied:

```tsx
import { DataGrid } from '@salmonui/data-grid';
import '@salmonui/data-grid/styles.css';

const plan = [
  { id: 'plan', name: 'Planning', hours: 2, children: [{ id: 'scope', name: 'Scope', hours: 4 }] },
  { id: 'launch', name: 'Launch', hours: 2 },
];

<DataGrid data={plan} columns={columns} tree />
```

Flat self-referential rows name their parent's row id in a field
(`idMapping` + `parentIdMapping`). The row id comes from
`getRowId` or the `primaryKey` column; a missing, `null` or unknown parent
id makes a root:

```tsx
<DataGrid data={employees} columns={columns} getRowId={(row) => row.id} tree={{ parentIdField: 'managerId' }} />
```

Orphans (an unknown parent id) become roots and cycles break at the first
repeated id, each with a development warning. `tree` is read when
the grid is created; its options (`filterMode`, `expandedRows`,
`checkbox`, ...) are reactive afterwards.

### Live demo: Tree basics

Live demo: https://salmonui.dev/demos/data-grid/tree-basic

A nested project plan in DataGrid tree mode with the tree column toggle, expand and collapse methods, tree keys, cancelable toggle events, sibling sorting and child summary rows.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridAggregateRow, type DataGridApi, type DataGridColumn, type DataGridTreeToggleEvent } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';

interface Task {
  readonly id: string;
  readonly name: string;
  readonly owner: string;
  readonly hours: number;
  readonly children?: readonly Task[];
}

// Nested rows (`tree: true` reads the `children` field); rows are kept by reference.
const plan: Task[] = [
  {
    id: 'plan',
    name: 'Planning',
    owner: 'Ana',
    hours: 2,
    children: [
      { id: 'scope', name: 'Scope', owner: 'Ana', hours: 4, children: [{ id: 'interviews', name: 'Interviews', owner: 'Ben', hours: 6 }, { id: 'brief', name: 'Brief', owner: 'Ana', hours: 3 }] },
      { id: 'budget', name: 'Budget', owner: 'Chen', hours: 3 },
    ],
  },
  {
    id: 'build',
    name: 'Build',
    owner: 'Dev',
    hours: 1,
    children: [
      { id: 'backend', name: 'Backend', owner: 'Eli', hours: 20, children: [{ id: 'api', name: 'API', owner: 'Eli', hours: 12 }, { id: 'db', name: 'Database', owner: 'Fay', hours: 8 }] },
      { id: 'frontend', name: 'Frontend', owner: 'Gus', hours: 18 },
      { id: 'tests', name: 'Tests', owner: 'Hal', hours: 9 },
    ],
  },
  { id: 'launch', name: 'Launch', owner: 'Ivy', hours: 2, children: [{ id: 'notes', name: 'Release notes', owner: 'Ivy', hours: 2 }] },
];

const columns: DataGridColumn<Task>[] = [
  { field: 'name', header: 'Task', width: 260 },
  { field: 'id', header: 'ID', primaryKey: true, width: 110 },
  { field: 'owner', header: 'Owner', width: 120 },
  { field: 'hours', header: 'Hours', type: 'number', align: 'end', width: 130 },
];

// A child summary row under each expanded parent.
const aggregates: DataGridAggregateRow<Task>[] = [
  { columns: [{ field: 'hours', type: 'sum', renderChildFooter: ({ formatted }) => <>Subtotal {formatted['sum']}</> }] },
];

export default function TreeBasicDemo() {
  const api = useRef<DataGridApi<Task> | null>(null);
  const [log, push] = useEventLog();
  const [summaries, setSummaries] = useState(true);
  const [lockBuild, setLockBuild] = useState(false);
  const onBefore = (event: DataGridTreeToggleEvent<Task>) => {
    if (lockBuild && event.rowId === 'build' && !event.expanded) {
      event.preventDefault();
      push('collapse of Build cancelled');
    }
  };
  const onToggle = (event: DataGridTreeToggleEvent<Task>) => push(`${event.row?.name ?? event.rowId} ${event.expanded ? 'expanded' : 'collapsed'} (depth ${event.depth}, ${event.source})`);
  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" type="button" onClick={() => api.current?.expandAllTreeRows()}>
          Expand all
        </Button>
        <Button variant="outline" type="button" onClick={() => api.current?.collapseAllTreeRows()}>
          Collapse all
        </Button>
        <Button variant="outline" type="button" onClick={() => api.current?.expandTreeLevel(0)}>
          Expand level 0
        </Button>
        <Button variant="outline" type="button" onClick={() => api.current?.collapseTreeLevel(1)}>
          Collapse level 1
        </Button>
        <Button variant="outline" type="button" onClick={() => api.current?.toggleTreeRow('backend')}>
          Toggle Backend
        </Button>
      </div>
      <div className="demo-toolbar">
        <Checkbox checked={summaries} onCheckedChange={(checked) => setSummaries(checked)}>
          Child summaries
        </Checkbox>
        <Checkbox checked={lockBuild} onCheckedChange={(checked) => setLockBuild(checked)}>
          Cancel collapsing Build
        </Checkbox>
      </div>
      <DataGrid<Task>
        ref={api}
        aria-label="Project plan"
        data={plan}
        columns={columns}
        tree
        sorting
        height={420}
        {...(summaries ? { aggregates } : {})}
        onBeforeTreeToggle={onBefore}
        onTreeToggle={onToggle}
      />
      <p className="demo-status">
        Click a chevron, or focus a Task cell and press ArrowRight / ArrowLeft, Ctrl+Shift+ArrowDown / ArrowUp (this row) or Ctrl+ArrowDown / ArrowUp (all rows). Sorting orders siblings inside each parent.
      </p>
      <EventLog entries={log} />
    </>
  );
}
```

## The tree column

The hierarchy shows in the first visible data column, or in the column
named by `tree.column` (field or column id);
it follows reordering, pinning and hiding. Its cells hold the
expand toggle (`DataGridTreeToggle`, class `.salmon-data-grid-tree-toggle`)
and an indentation of 1.25rem per depth through `padding-inline-start`.
Rows carry `data-depth`, `data-expanded` and `data-has-children`
for styles, and `getRowProps(row, index, ctx)`
receives `ctx.tree`.

`column.renderCell(ctx)` on the tree column renders after the toggle, and
`ctx.tree` carries `{ depth, hasChildren, expanded, loadStatus }`.
Row templates (`renderRow`) compose `DataGridRow`, `DataGridCell` and
`DataGridTreeToggle`. Detail rows (`renderDetail`) follow their
tree row and hide with it.

### Live demo: Tree templates

Live demo: https://salmonui.dev/demos/data-grid/tree-templates

An org chart in DataGrid tree mode with a tree column cell template that reads ctx.tree, row props and classes per depth, a row template that keeps the toggle, detail rows that follow their tree row, row spans inside each parent, and grid lines and alternate rows.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, DataGridRow, type DataGridColumn, type DataGridLines } from '@salmonui/data-grid';
import { Select } from '@salmonui/dropdowns/select';

interface Unit {
  readonly id: string;
  readonly name: string;
  readonly kind: 'division' | 'team' | 'person';
  readonly site: string;
  readonly budget: number;
  readonly note?: string;
  readonly children?: readonly Unit[];
}

const unitId = (unit: Unit) => unit.id;

const person = (id: string, name: string, site: string, budget: number, note: string): Unit => ({ id, name, kind: 'person', site, budget, note });

// Nested rows (`tree: true` reads `children`).
const org: Unit[] = [
  {
    id: 'eng',
    name: 'Engineering',
    kind: 'division',
    site: 'Lisbon',
    budget: 0,
    children: [
      {
        id: 'platform',
        name: 'Platform',
        kind: 'team',
        site: 'Lisbon',
        budget: 0,
        children: [
          person('p-ana', 'Ana Duarte', 'Lisbon', 98_000, 'Owns the build pipeline and the release train.'),
          person('p-ben', 'Ben Okafor', 'Lisbon', 91_000, 'On call this week; prefers async reviews.'),
          person('p-chen', 'Chen Wei', 'Remote', 88_000, 'Migrating the CI runners to the new cluster.'),
        ],
      },
      {
        id: 'web',
        name: 'Web',
        kind: 'team',
        site: 'Berlin',
        budget: 0,
        children: [
          person('p-dara', 'Dara Novak', 'Berlin', 94_000, 'Leads the accessibility audit.'),
          person('p-eli', 'Eli Haddad', 'Berlin', 86_000, 'Joined in March; mentoring by Dara.'),
        ],
      },
    ],
  },
  {
    id: 'ops',
    name: 'Operations',
    kind: 'division',
    site: 'Berlin',
    budget: 0,
    children: [
      {
        id: 'support',
        name: 'Support',
        kind: 'team',
        site: 'Dublin',
        budget: 0,
        children: [
          person('p-fay', 'Fay Murphy', 'Dublin', 72_000, 'Runs the weekly incident review.'),
          person('p-gus', 'Gus Lindqvist', 'Dublin', 70_000, 'Writes the help-centre articles.'),
        ],
      },
    ],
  },
];

const KIND_LABEL: Record<Unit['kind'], string> = { division: 'Division', team: 'Team', person: 'Person' };

const columns: DataGridColumn<Unit>[] = [
  {
    field: 'name',
    header: 'Unit',
    width: 300,
    // The tree column template renders after the toggle; `ctx.tree` carries depth, expansion and load status.
    renderCell: ({ value, tree }) => (
      <span>
        {String(value)}{' '}
        {tree?.hasChildren ? (
          <span className="demo-badge" data-tone={tree.expanded ? 'info' : undefined}>
            {tree.expanded ? 'open' : 'closed'} · level {tree.depth + 1}
          </span>
        ) : null}
      </span>
    ),
  },
  { field: 'kind', header: 'Kind', width: 110, valueGetter: (row) => KIND_LABEL[row.kind] },
  // Equal neighbouring values merge; a span never crosses a parent row.
  { field: 'site', header: 'Site', width: 120, rowSpan: true },
  { field: 'budget', header: 'Budget', type: 'number', format: 'C0', align: 'end', width: 130, renderCell: ({ formattedValue, row }) => (row.kind === 'person' ? formattedValue : '') },
];

const LINES: readonly DataGridLines[] = ['default', 'both', 'horizontal', 'vertical', 'none'];
const LINE_OPTIONS = LINES.map((value) => ({ value, label: value }));

export default function TreeTemplatesDemo() {
  const [cards, setCards] = useState(false);
  const [lines, setLines] = useState<DataGridLines>('default');
  const [striped, setStriped] = useState(true);
  return (
    <>
      <div className="demo-toolbar">
        <Checkbox checked={cards} onCheckedChange={(checked) => setCards(checked)}>
          Row template (card rows)
        </Checkbox>
        <label>
          Grid lines{' '}
          <Select aria-label="Grid lines" data={LINE_OPTIONS} value={lines} onValueChange={(value) => value != null && setLines(value as DataGridLines)} />
        </label>
        <Checkbox checked={striped} onCheckedChange={(checked) => setStriped(checked)}>
          Alternate rows
        </Checkbox>
      </div>
      <DataGrid<Unit>
        aria-label="Organization"
        getRowId={unitId}
        data={org}
        columns={columns}
        tree
        height={420}
        locale="en-US"
        currency="EUR"
        gridLines={lines}
        striped={striped}
        highlightOnHover
        // Row hooks see `ctx.tree`; rows also carry data-depth, data-expanded and data-has-children.
        getRowProps={(row, _index, ctx) => ({
          'data-kind': row.kind,
          ...(ctx.tree ? { title: `${KIND_LABEL[row.kind]} at level ${ctx.tree.depth + 1}` } : {}),
          ...(ctx.tree?.depth === 0 ? { style: { fontWeight: 600 } } : {}),
        })}
        rowClassName={(row) => (row.site === 'Remote' ? 'demo-row--flagged' : undefined)}
        // A row template keeps role, aria attributes and the tree toggle by spreading rowProps around the default cells.
        {...(cards
          ? {
              renderRow: ({ rowProps, cells }) => (
                <DataGridRow {...rowProps} className={`${rowProps.className ?? ''} demo-card-row`}>
                  {cells}
                </DataGridRow>
              ),
            }
          : {})}
        // Detail rows follow their tree row and hide with it when a parent collapses.
        hasDetail={(row) => row.kind === 'person'}
        renderDetail={({ row }) => <p style={{ margin: 0 }}>{row.note}</p>}
      />
      <p className="demo-status">
        Open a person&apos;s detail toggle, then collapse the team: the detail row hides with its row and comes back on expand. The remote engineer is flagged by a row class.
      </p>
    </>
  );
}
```

## Expansion

| Option | Behavior |
| --- | --- |
| `defaultExpanded: true` (default) | Every parent starts expanded. |
| `defaultExpanded: false` | Every parent starts collapsed. |
| `defaultExpanded: n` | Parents at depths below `n` start expanded. |
| `expandedField: 'isExpanded'` | Initial expansion from a boolean data field (`expandStateMapping`). |
| `expandedRows: { [rowId]: boolean }` | Reactive overrides over the default (*Salmon*). |

Methods return a `DataGridActionResult`:

```ts
api.expandAllTreeRows();           // expandAll()
api.collapseAllTreeRows();         // collapseAll()
api.expandTreeLevel(0);            // expandAtLevel(level); 0 is the roots
api.collapseTreeLevel(1);          // collapseAtLevel(level)
api.expandTreeRows(['a', 'b']);    // expandByKey(key)
api.collapseTreeRows('a');         // collapseByKey(key)
api.toggleTreeRow('a', false);     // expandRow / collapseRow (ids, not elements)
```

`onBeforeTreeToggle` runs before a row expands or collapses and
`preventDefault()` cancels it; a
bulk toggle (expand or collapse all, a level) runs it once per rendered
parent that would change, and one cancel cancels the whole command;
`onTreeToggle` follows (`expanded` / `collapsed`). Both receive
`{ rowId, row, expanded, depth, lazy, source }` with `source` `'pointer'`,
`'keyboard'` or `'api'`. Expansion is keyed by row id, so it
survives sorting, filtering, paging and data updates, and it is
part of the grid state (see [State, RTL and adaptive](https://salmonui.dev/docs/data-grid/tree#state-rtl-and-adaptive)).

### Live demo: Tree expansion state

Live demo: https://salmonui.dev/demos/data-grid/tree-state

Flat ticket rows with initial expansion from a data field, reactive expandedRows overrides, expansion saved with persistState and getState / restoreState, an orphan and a parent cycle shown as roots, shared grid events, and tree mode winning over a grouping prop.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import type { RowId } from '@salmonui/core/data';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridApi, type DataGridColumn, type DataGridPersistState, type DataGridState } from '@salmonui/data-grid';
import { Select } from '@salmonui/dropdowns/select';
import { EventLog, useEventLog } from '../../components/demo-kit';

interface Ticket {
  readonly id: string;
  readonly parentId: string | null;
  readonly title: string;
  readonly assignee: string;
  readonly points: number;
  /** Initial expansion read through `tree.expandedField`. */
  readonly open: boolean;
}

// Flat rows. With the checkbox, T-9 names a parent that does not exist (an orphan) and T-10 / T-11 point at each
// other (a cycle): both end up as roots instead of disappearing.
const tickets: Ticket[] = [
  { id: 'T-1', parentId: null, title: 'Checkout redesign', assignee: 'Ana', points: 13, open: true },
  { id: 'T-2', parentId: 'T-1', title: 'Payment step', assignee: 'Ben', points: 5, open: false },
  { id: 'T-3', parentId: 'T-2', title: 'Card form validation', assignee: 'Ben', points: 3, open: false },
  { id: 'T-4', parentId: 'T-2', title: 'Wallet buttons', assignee: 'Chen', points: 2, open: false },
  { id: 'T-5', parentId: 'T-1', title: 'Order summary', assignee: 'Dara', points: 3, open: false },
  { id: 'T-6', parentId: null, title: 'Search speed-up', assignee: 'Eli', points: 8, open: false },
  { id: 'T-7', parentId: 'T-6', title: 'Index warm-up', assignee: 'Eli', points: 5, open: false },
  { id: 'T-8', parentId: 'T-6', title: 'Result cache', assignee: 'Fay', points: 3, open: false },
];

// Added from the checkbox: the grid then logs one development warning for each problem.
const broken: Ticket[] = [
  { id: 'T-9', parentId: 'T-404', title: 'Orphan: parent was deleted', assignee: 'Gus', points: 1, open: false },
  { id: 'T-10', parentId: 'T-11', title: 'Cycle: blocks T-11', assignee: 'Hal', points: 2, open: false },
  { id: 'T-11', parentId: 'T-10', title: 'Cycle: blocks T-10', assignee: 'Hal', points: 2, open: false },
];

const withProblems: Ticket[] = [...tickets, ...broken];

const PARENTS = ['T-1', 'T-2', 'T-6'] as const;
const OVERRIDES = [
  { value: 'default', label: 'from data' },
  { value: 'true', label: 'expanded' },
  { value: 'false', label: 'collapsed' },
];

const fieldsetStyle = { margin: '0 0 var(--salmon-space-4)', padding: 'var(--salmon-space-2) var(--salmon-space-3) var(--salmon-space-3)', border: '1px solid var(--salmon-border-default)', borderRadius: 'var(--salmon-radius-md)' } as const;

const columns: DataGridColumn<Ticket>[] = [
  { field: 'title', header: 'Ticket', width: 280 },
  { field: 'id', header: 'ID', primaryKey: true, width: 90 },
  { field: 'assignee', header: 'Assignee', width: 120 },
  { field: 'points', header: 'Points', type: 'number', align: 'end', width: 90 },
];

// Saved to localStorage under `salmon-data-grid:docs-tree-state` after every change, the tree
// expansion included, and restored after mount. Constant: the prop is read on mount.
const persistState: DataGridPersistState = { version: 1 };

export default function TreeStateDemo() {
  const api = useRef<DataGridApi<Ticket> | null>(null);
  const [overrides, setOverrides] = useState<Readonly<Record<RowId, boolean>>>({});
  const [withGrouping, setWithGrouping] = useState(false);
  const [withBroken, setWithBroken] = useState(false);
  const [saved, setSaved] = useState<DataGridState | null>(null);
  const [log, push] = useEventLog();
  const setOverride = (rowId: RowId, value: boolean | null) =>
    setOverrides((current) => {
      const next = { ...current };
      if (value === null) delete next[rowId];
      else next[rowId] = value;
      return next;
    });
  return (
    <>
      <fieldset className="demo-toolbar" style={fieldsetStyle}>
        <legend>tree.expandedRows (reactive overrides)</legend>
        {PARENTS.map((rowId) => (
          <label key={rowId}>
            {rowId}{' '}
            <Select aria-label={rowId} data={OVERRIDES} value={rowId in overrides ? String(overrides[rowId]) : 'default'} onValueChange={(value) => value != null && setOverride(rowId, value === 'default' ? null : value === 'true')} />
          </label>
        ))}
      </fieldset>
      <div className="demo-toolbar">
        <Button
          variant="outline"
          onClick={() => {
            const state = api.current?.getState() ?? null;
            setSaved(state);
            push(`getState(): tree.expandedRows ${JSON.stringify(state?.tree?.expandedRows ?? {})}`);
          }}
        >
          Save state
        </Button>
        <Button
          variant="outline"
          disabled={saved === null}
          onClick={() => {
            if (!saved) return;
            const result = api.current?.restoreState(saved);
            push(`restoreState(): ${result?.status ?? 'no grid'}`);
          }}
        >
          Restore state
        </Button>
        <Checkbox checked={withBroken} onCheckedChange={(checked) => setWithBroken(checked)}>
          Add an orphan and a cycle
        </Checkbox>
        <Checkbox checked={withGrouping} onCheckedChange={(checked) => setWithGrouping(checked)}>
          Also pass grouping by Assignee
        </Checkbox>
      </div>
      <DataGrid<Ticket>
        // A new grid when the grouping prop changes: `tree` and `grouping` are read when the grid is created.
        key={withGrouping ? 'grouped' : 'plain'}
        ref={api}
        id="docs-tree-state"
        aria-label="Tickets"
        data={withBroken ? withProblems : tickets}
        columns={columns}
        getRowId={(row) => row.id}
        // Initial expansion from the `open` field, overridden per row by `expandedRows`.
        tree={{ parentIdField: 'parentId', expandedField: 'open', expandedRows: overrides }}
        {...(withGrouping ? { grouping: { groupBy: ['assignee'] } } : {})}
        persistState={persistState}
        sorting
        selection={{ multiple: true }}
        height={400}
        onTreeToggle={(event) => push(`onTreeToggle ${String(event.rowId)} ${event.expanded ? 'expanded' : 'collapsed'} (${event.source})`)}
        // Shared Data Grid events keep their meaning in tree mode.
        onSortChange={(event) => push(`onSortChange ${JSON.stringify(event.sortBy)}`)}
        onSelectionChange={(event) => push(`onSelectionChange ${api.current?.getSelectedRowIds().join(', ') ?? ''} (${event.source})`)}
      />
      <p className="demo-status">
        T-1 starts expanded because its <code>open</code> field is true. Toggle rows, sort, then reload the page: the expansion comes back from storage. With grouping passed too, the grid stays a tree (tree wins; development builds warn).
      </p>
      <EventLog entries={log} />
    </>
  );
}
```

`api.getTreeRow(rowId)` returns `{ rowId, depth, parentId, hasChildren,
childCount, expanded, loadStatus, posinset, setsize, context, visible }`
`api.getChildRows(rowId)` the kept children in
view order (`null` for the roots), and `api.getVisibleRows()` the visible
rows.

## Keyboard and accessibility

The grid root is `role="treegrid"` in tree mode. Rows carry `aria-level`
(depth + 1), `aria-posinset` and `aria-setsize` from the tree index (correct
for virtualized rows too), and parents carry `aria-expanded`; the toggle
has no `aria-expanded` of its own, so the state is announced once.

| Keys | Behavior |
| --- | --- |
| Ctrl+Shift+ArrowDown / ArrowUp (⌘ on macOS) | Expand / collapse the focused row |
| Ctrl+ArrowDown / ArrowUp (⌘ on macOS) | Expand / collapse every row |
| Enter or Space on the toggle | Toggle the row |
| ArrowRight on the tree cell of a collapsed parent | Expand (WAI-ARIA treegrid) |
| ArrowLeft on the tree cell of an expanded parent | Collapse; on a collapsed parent or a leaf, move to the parent row |
| Alt+Shift+ArrowRight / ArrowLeft | Indent / outdent the focused or selected rows (*Salmon*) |

The ArrowRight / ArrowLeft tree keys apply when the tree column is the
first visible column; ArrowRight and ArrowLeft keep their cell-move meaning
everywhere else. The key commands are
`tree.expandFocused`, `tree.collapseFocused`, `tree.indent` and
`tree.outdent`; Ctrl+ArrowDown / ArrowUp are the shared
`group.expandAll` / `group.collapseAll` commands, which expand or collapse
every tree row in tree mode. `keyBindings` can rebind all of them. A
polite live region announces "{row} expanded, {count} children",
"{row} collapsed", "Loading children" and "Could not load children".
The texts are `localeText` keys: `treeExpand`, `treeCollapse`,
`treeExpanded`, `treeCollapsed`, `treeLoading`, `treeLoadError`,
`treeRetry`, `treeLevel`, `indent` and `outdent`. See
[Accessibility](https://salmonui.dev/docs/data-grid/accessibility) for the rest of the grid.

## Sorting, filtering and searching

Sorting orders siblings within each parent; a row never moves under another
parent. Filtering and search keep rows by `tree.filterMode`:

| `filterMode` | Rows kept |
| --- | --- |
| `'ancestors'` (default) | Matches and their ancestor chain |
| `'descendants'` | Matches and their subtrees |
| `'both'` | Matches, their ancestors and their subtrees |
| `'none'` | Matches only, re-parented to their nearest kept ancestor |

Rows kept only as context carry `data-tree-context` and are dimmed. A
filter never changes the expansion state: a match inside a collapsed
parent stays hidden until the parent expands, so call `expandTreeRows` from
`onFilterChange` to reveal matches. Excel and checkbox filter
lists count matching rows of every depth.

### Live demo: Tree filtering and paging

Live demo: https://salmonui.dev/demos/data-grid/tree-flat-filter

Flat self-referential rows (parentIdField) with a filter row, the four tree filter modes, sibling sorting and paging by visible rows or by root rows.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { DataGrid, type DataGridColumn, type DataGridTreeFilterMode } from '@salmonui/data-grid';
import { Select } from '@salmonui/dropdowns/select';

interface Employee {
  readonly id: string;
  readonly parentId: string | null;
  readonly name: string;
  readonly role: string;
  readonly city: string;
}

// Flat self-referential rows: `parentId` names the manager's row id (`getRowId` via the primary key).
const cities = ['Lyon', 'Oslo', 'Porto', 'Kyoto'];
const roles = ['Engineer', 'Designer', 'Analyst', 'Support'];
const firstNames = ['Ada', 'Bo', 'Cy', 'Dee', 'Eve', 'Finn', 'Gil', 'Hana', 'Ira', 'Jo', 'Kai', 'Liv'];

function createStaff(): Employee[] {
  const rows: Employee[] = [{ id: 'e0', parentId: null, name: 'Mara Quist', role: 'CEO', city: 'Oslo' }];
  let n = 1;
  for (let d = 0; d < 4; d++) {
    const director = `e${n++}`;
    rows.push({ id: director, parentId: 'e0', name: `${firstNames[d * 3]} Director`, role: 'Director', city: cities[d]! });
    for (let m = 0; m < 3; m++) {
      const manager = `e${n++}`;
      rows.push({ id: manager, parentId: director, name: `${firstNames[(d * 3 + m) % 12]} Lead ${d}${m}`, role: 'Manager', city: cities[(d + m) % 4]! });
      for (let r = 0; r < 5; r++) {
        const i = n++;
        rows.push({ id: `e${i}`, parentId: manager, name: `${firstNames[i % 12]} ${String.fromCharCode(65 + (i % 26))}.`, role: roles[(i + r) % 4]!, city: cities[(i * 7) % 4]! });
      }
    }
  }
  return rows;
}

const staff = createStaff();

const columns: DataGridColumn<Employee>[] = [
  { field: 'name', header: 'Name', width: 280 },
  { field: 'id', header: 'ID', primaryKey: true, width: 90 },
  { field: 'role', header: 'Role', width: 130 },
  { field: 'city', header: 'City', width: 120 },
];

const modes: readonly DataGridTreeFilterMode[] = ['ancestors', 'descendants', 'both', 'none'];
const MODES = modes.map((mode) => ({ value: mode, label: mode }));
const PAGE_BY = [
  { value: 'all', label: 'all (visible rows)' },
  { value: 'root', label: 'root (root rows with their subtrees)' },
];

export default function TreeFlatFilterDemo() {
  const [filterMode, setFilterMode] = useState<DataGridTreeFilterMode>('ancestors');
  const [pageBy, setPageBy] = useState<'all' | 'root'>('all');
  return (
    <>
      <div className="demo-toolbar">
        <label>
          Filter mode{' '}
          <Select aria-label="Filter mode" data={MODES} value={filterMode} onValueChange={(value) => value != null && setFilterMode(value as DataGridTreeFilterMode)} />
        </label>
        <label>
          Page by{' '}
          <Select aria-label="Page by" data={PAGE_BY} value={pageBy} onValueChange={(value) => value != null && setPageBy(value as 'all' | 'root')} />
        </label>
      </div>
      <DataGrid<Employee>
        // pageBy is read with the paging setup, so a switch mounts a new grid.
        key={pageBy}
        aria-label="Organization chart"
        data={staff}
        columns={columns}
        tree={{ parentIdField: 'parentId', filterMode, pageBy, defaultExpanded: 2 }}
        filtering={{ ui: 'row' }}
        sorting
        paging={{ pageSize: 15 }}
        height={460}
      />
      <p className="demo-status">
        Type Lyon in the City filter: ancestors keeps each match with its managers, descendants keeps matches with their reports, none lists matches only. Rows kept only as context are dimmed.
      </p>
    </>
  );
}
```

## Paging

`tree.pageBy: 'all'` (default) pages the visible rows; `'root'` pages root
rows with their subtrees.
Expanding or collapsing re-pages without a remote read.

```tsx
<DataGrid data={rows} columns={columns} tree={{ parentIdField: 'parentId', pageBy: 'root' }} paging={{ pageSize: 10 }} />
```

## Checkboxes and selection

`tree.checkbox: true` adds a checkbox after the toggle (column
`showCheckbox`). The checkbox state is the row selection, so
`api.getSelectedRows()`, `api.getSelectedRowIds()` and
`api.selectRows(rowIds)` replace `getCheckedRecords`,
`getCheckedRowIndexes` and `selectCheckboxes`, and
`onBeforeSelectionChange` / `onSelectionChange` report `target: 'checkbox'`
(`checkboxChange`).

| `checkbox.cascade` | Behavior |
| --- | --- |
| `false` (default) | The checkbox selects its row only |
| `true` | A parent selects or deselects its whole subtree |
| `'filtered'` | The cascade reaches only rows the filter keeps |

A subtree toggle is one range command over the tree, not one event per
row. A partly selected parent shows the indeterminate state
(`aria-checked="mixed"`), derived from descendant counts, never stored per
row. Selection is id-based: collapsing a parent never deselects
its rows, and a cascade reaches hidden descendants.

### Live demo: Tree checkbox cascade

Live demo: https://salmonui.dev/demos/data-grid/tree-checkbox

Checkboxes in the tree column whose state is the row selection, with self, hierarchy and filtered hierarchy cascade modes and tri-state parents.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, type DataGridApi, type DataGridColumn } from '@salmonui/data-grid';
import { Select } from '@salmonui/dropdowns/select';
import { EventLog, useEventLog } from '../../components/demo-kit';

interface Item {
  readonly id: string;
  readonly name: string;
  readonly size: number;
  readonly children?: readonly Item[];
}

const files: Item[] = [
  {
    id: 'src',
    name: 'src',
    size: 0,
    children: [
      { id: 'src/app', name: 'app', size: 0, children: [{ id: 'src/app/page.tsx', name: 'page.tsx', size: 4 }, { id: 'src/app/layout.tsx', name: 'layout.tsx', size: 2 }] },
      { id: 'src/lib', name: 'lib', size: 0, children: [{ id: 'src/lib/api.ts', name: 'api.ts', size: 7 }, { id: 'src/lib/format.ts', name: 'format.ts', size: 3 }, { id: 'src/lib/theme.ts', name: 'theme.ts', size: 1 }] },
      { id: 'src/index.ts', name: 'index.ts', size: 1 },
    ],
  },
  { id: 'docs', name: 'docs', size: 0, children: [{ id: 'docs/guide.md', name: 'guide.md', size: 12 }, { id: 'docs/api.md', name: 'api.md', size: 9 }] },
  { id: 'package.json', name: 'package.json', size: 1 },
];

const columns: DataGridColumn<Item>[] = [
  { field: 'name', header: 'Name', width: 280 },
  { field: 'id', header: 'Path', primaryKey: true, width: 200 },
  { field: 'size', header: 'KB', type: 'number', align: 'end', width: 90 },
];

type Cascade = 'self' | 'cascade' | 'filtered';

const CASCADE_MODES = [
  { value: 'self', label: 'self (cascade: false)' },
  { value: 'cascade', label: 'hierarchy (cascade: true)' },
  { value: 'filtered', label: "filtered hierarchy (cascade: 'filtered')" },
];

export default function TreeCheckboxDemo() {
  const api = useRef<DataGridApi<Item> | null>(null);
  const [log, push] = useEventLog();
  const [mode, setMode] = useState<Cascade>('cascade');
  const [checked, setChecked] = useState<readonly string[]>([]);
  const cascade = mode === 'self' ? false : mode === 'cascade' ? true : 'filtered';
  return (
    <>
      <div className="demo-toolbar">
        <label>
          Checkbox mode{' '}
          <Select aria-label="Checkbox mode" data={CASCADE_MODES} value={mode} onValueChange={(value) => value != null && setMode(value as Cascade)} />
        </label>
        <Button variant="outline" type="button" onClick={() => api.current?.selectRows(['docs'])}>
          Select docs
        </Button>
        <Button variant="outline" type="button" onClick={() => api.current?.clearSelection()}>
          Clear
        </Button>
      </div>
      <DataGrid<Item>
        // The cascade mode is read when the tree is set up, so a switch mounts a new grid.
        key={mode}
        ref={api}
        aria-label="Project files"
        data={files}
        columns={columns}
        tree={{ checkbox: { cascade } }}
        selection={{ multiple: true }}
        filtering={{ ui: 'row' }}
        height={400}
        onSelectionChange={(event) => {
          setChecked(event.rowIds.map(String));
          push(`${event.target ?? event.source}: +${event.added.length} −${event.removed.length}, ${event.rowIds.length} selected`);
        }}
      />
      <p className="demo-status" aria-live="polite">
        Checked: {checked.length === 0 ? 'none' : checked.join(', ')}
      </p>
      <EventLog entries={log} />
    </>
  );
}
```

## Aggregates and child summaries

Footer aggregates cover the kept rows of every depth.
`renderChildFooter` on an aggregate adds a child summary row under each
expanded parent, over its descendants; `renderFooter` and `renderChildFooter` are the footer templates.
An aggregate with only `renderChildFooter` does not show in the
grid footer.

```tsx
<DataGrid
  data={plan}
  columns={columns}
  tree
  aggregates={[{ columns: [{ field: 'hours', type: 'sum', renderChildFooter: ({ formatted }) => <>Subtotal {formatted.sum}</> }] }]}
/>
```

### Live demo: Tree aggregates and filters

Live demo: https://salmonui.dev/demos/data-grid/tree-aggregates

A flat budget tree with footer aggregates of several types and templates, child summary rows, Excel and checklist filters whose value lists count rows of every depth, expansion that survives sorting, filtering and paging, and the tree row info methods.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, type DataGridAggregateRow, type DataGridApi, type DataGridColumn, type DataGridFilterUi } from '@salmonui/data-grid';
import { Select } from '@salmonui/dropdowns/select';
import { EventLog, useEventLog } from '../../components/demo-kit';

interface Item {
  readonly id: string;
  readonly parentId: string | null;
  readonly name: string;
  readonly owner: string;
  readonly status: 'Open' | 'Done' | 'Blocked';
  readonly cost: number;
  readonly billable: boolean;
}

// Flat self-referential rows: `parentId` names the parent's row id.
const items: Item[] = [
  { id: 'mkt', parentId: null, name: 'Marketing', owner: 'Ana', status: 'Open', cost: 1_200, billable: false },
  { id: 'mkt-web', parentId: 'mkt', name: 'Website refresh', owner: 'Ben', status: 'Open', cost: 8_400, billable: true },
  { id: 'mkt-web-copy', parentId: 'mkt-web', name: 'Copywriting', owner: 'Chen', status: 'Done', cost: 2_100, billable: true },
  { id: 'mkt-web-photos', parentId: 'mkt-web', name: 'Product photos', owner: 'Ben', status: 'Blocked', cost: 3_600, billable: true },
  { id: 'mkt-ads', parentId: 'mkt', name: 'Search ads', owner: 'Ana', status: 'Open', cost: 5_000, billable: false },
  { id: 'sales', parentId: null, name: 'Sales', owner: 'Dara', status: 'Open', cost: 900, billable: false },
  { id: 'sales-fair', parentId: 'sales', name: 'Trade fair', owner: 'Eli', status: 'Done', cost: 12_500, billable: true },
  { id: 'sales-fair-booth', parentId: 'sales-fair', name: 'Booth', owner: 'Eli', status: 'Done', cost: 6_000, billable: true },
  { id: 'sales-fair-travel', parentId: 'sales-fair', name: 'Travel', owner: 'Fay', status: 'Open', cost: 2_800, billable: false },
  { id: 'sales-crm', parentId: 'sales', name: 'CRM licences', owner: 'Dara', status: 'Blocked', cost: 4_300, billable: false },
  { id: 'it', parentId: null, name: 'IT', owner: 'Gus', status: 'Open', cost: 500, billable: false },
  { id: 'it-laptops', parentId: 'it', name: 'Laptops', owner: 'Gus', status: 'Done', cost: 9_900, billable: false },
  { id: 'it-vpn', parentId: 'it', name: 'VPN renewal', owner: 'Hal', status: 'Open', cost: 1_400, billable: false },
];

const columns: DataGridColumn<Item>[] = [
  { field: 'name', header: 'Item', width: 180 },
  { field: 'id', header: 'ID', primaryKey: true, width: 110 },
  { field: 'owner', header: 'Owner', width: 100 },
  { field: 'status', header: 'Status', width: 100 },
  { field: 'cost', header: 'Cost', type: 'number', format: 'C0', align: 'end', width: 330 },
  { field: 'billable', header: 'Billable', type: 'boolean', width: 110 },
];

// Footer aggregates over the kept rows of every depth, several types per column, with
// footer templates; `renderChildFooter` adds a child summary row under each expanded parent.
const aggregates: DataGridAggregateRow<Item>[] = [
  {
    columns: [
      {
        field: 'cost',
        type: ['sum', 'average', 'min', 'max'],
        format: 'C0',
        renderFooter: ({ formatted }) => (
          <>
            Total {formatted['sum']} · avg {formatted['average']} · {formatted['min']}–{formatted['max']}
          </>
        ),
        renderChildFooter: ({ formatted }) => (
          <>
            Subtotal {formatted['sum']} · max {formatted['max']}
          </>
        ),
      },
      { field: 'status', type: 'count', renderFooter: ({ values }) => <>{String(values['count'])} items</> },
      { field: 'billable', type: ['trueCount', 'falseCount'], renderFooter: ({ values }) => <>{`${String(values['trueCount'])} yes / ${String(values['falseCount'])} no`}</> },
      { field: 'owner', type: 'custom', custom: (rows) => new Set(rows.map((row) => row.owner)).size, renderFooter: ({ values }) => <>{String(values['custom'])} owners</> },
    ],
  },
];

const FILTER_UI_OPTIONS = [
  { value: 'excel', label: 'Excel' },
  { value: 'checklist', label: 'Checklist' },
  { value: 'menu', label: 'Menu' },
];

export default function TreeAggregatesDemo() {
  const api = useRef<DataGridApi<Item> | null>(null);
  const [ui, setUi] = useState<DataGridFilterUi>('excel');
  const [log, push] = useEventLog();
  const describe = (rowId: string) => {
    const grid = api.current;
    const info = grid?.getTreeRow(rowId);
    if (!grid || !info) return;
    const children = grid.getChildRows(rowId).map((row) => row.name);
    push(`${rowId}: depth ${info.depth}, parent ${String(info.parentId)}, ${info.childCount} children (${children.join(', ') || 'none'}), ${info.expanded ? 'expanded' : 'collapsed'}, ${info.posinset} of ${info.setsize}`);
  };
  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => api.current?.expandTreeRows(['mkt', 'sales'])}>
          Expand Marketing and Sales
        </Button>
        <Button variant="outline" onClick={() => api.current?.collapseTreeRows('mkt')}>
          Collapse Marketing
        </Button>
        <Button variant="outline" onClick={() => describe('sales-fair')}>
          Row info of Trade fair
        </Button>
        <Button variant="outline" onClick={() => push(`visible rows: ${api.current?.getVisibleRows().map((row) => row.id).join(', ') ?? ''}`)}>
          Visible rows
        </Button>
        <label>
          Filter UI{' '}
          <Select aria-label="Filter UI" data={FILTER_UI_OPTIONS} value={ui} onValueChange={(value) => value != null && setUi(value as DataGridFilterUi)} />
        </label>
      </div>
      <DataGrid<Item>
        ref={api}
        aria-label="Budget items"
        data={items}
        columns={columns}
        getRowId={(row) => row.id}
        tree={{ parentIdField: 'parentId', defaultExpanded: 1 }}
        aggregates={aggregates}
        sorting
        filtering={{ ui }}
        paging={{ pageSize: 8 }}
        height={460}
        locale="en-US"
        currency="USD"
        onTreeToggle={(event) => push(`${String(event.rowId)} ${event.expanded ? 'expanded' : 'collapsed'} (${event.source})`)}
        onFilterChange={(event) => push(`filter ${event.field ?? 'all'}: ${JSON.stringify(event.filters)}`)}
      />
      <p className="demo-status">
        Open the Status or Owner filter: the value list counts rows of every depth, not only roots. Expand a row, then sort, filter or change the page: the expansion stays because it is keyed by row id.
      </p>
      <EventLog entries={log} />
    </>
  );
}
```

## Editing

Cell, row, dialog and batch editing, the command column and validation
work in a tree; editing the tree column keeps the toggle, and
batch editing works with row virtualization.
`editing.newRowPosition` places added rows:

| `newRowPosition` | Added row |
| --- | --- |
| `'top'` (default), `'bottom'` | First or last root |
| `'above'`, `'below'` | Sibling before or after the focused row |
| `'child'` | Last child of the focused row |

An added row joins its parent: `WriteRequest.added` carries its `parentId`
and the local source inserts it into the tree. Deleting a parent
deletes its subtree: `api.deleteRows(rowIds)` writes every descendant id in
`WriteRequest.deleted`.

## Drag, indent and outdent

`rowDrag` in tree mode drops before a row (top quarter), into it (middle
half) or after it (bottom quarter). Dragging a parent moves its
subtree; dropping a row into itself or its own descendant is invalid with
reason `'descendant'`. `onRowDragStart`, `onRowDrag`,
`onBeforeRowDrop` (cancel) and `onRowDrop` report `position` (`'before'`,
`'after'`, `'into'`) and `parentId`; `api.moveRows(rowIds, { targetRowId,
position })` replaces `reorderRows`. Selection and a primary key
column are not required. `rowDrag.targetId` drops into another
grid and onto custom targets with the subtrees in the payload.

`api.indentRows(rowIds)` makes rows the last children of their previous
sibling and `api.outdentRows(rowIds)` makes them siblings after their
parent; the toolbar items `'indent'` and `'outdent'` are disabled when the
focused row cannot move. Alt+Shift+ArrowRight / ArrowLeft is the
keyboard alternative. Flat data writes the changed parent id
field, so a remote source can persist the move.

```tsx
<DataGrid data={steps} columns={columns} tree={{ parentIdField: 'parentId' }} rowDrag toolbar={['indent', 'outdent']} />
```

The toolbar and context menu work as in a flat grid, plus the tree items.

### Live demo: Tree drag and indent

Live demo: https://salmonui.dev/demos/data-grid/tree-indent

Flat tree rows reordered by drag (before, after or into a row), the indent and outdent toolbar items, methods and keys, new rows above, below or as a child of the focused row, and subtree delete.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, type DataGridApi, type DataGridColumn, type DataGridRowDragEvent } from '@salmonui/data-grid';
import { Select } from '@salmonui/dropdowns/select';
import { EventLog, useEventLog } from '../../components/demo-kit';

interface Step {
  readonly id: string;
  readonly parentId: string | null;
  readonly name: string;
  readonly days: number;
}

const steps: Step[] = [
  { id: 's1', parentId: null, name: 'Design', days: 5 },
  { id: 's2', parentId: 's1', name: 'Wireframes', days: 3 },
  { id: 's3', parentId: 's1', name: 'Visual review', days: 1 },
  { id: 's4', parentId: null, name: 'Implementation', days: 12 },
  { id: 's5', parentId: 's4', name: 'Data layer', days: 4 },
  { id: 's6', parentId: 's4', name: 'Screens', days: 6 },
  { id: 's7', parentId: null, name: 'Accessibility pass', days: 2 },
  { id: 's8', parentId: null, name: 'Ship', days: 1 },
  { id: 's9', parentId: null, name: 'Retro', days: 1 },
];

const columns: DataGridColumn<Step>[] = [
  { field: 'name', header: 'Step', width: 260 },
  { field: 'id', header: 'ID', primaryKey: true, width: 90, editable: false },
  { field: 'days', header: 'Days', type: 'number', align: 'end', width: 90 },
];

type Position = 'below' | 'above' | 'child' | 'top' | 'bottom';

const POSITIONS = [
  { value: 'child', label: 'child of the focused row' },
  { value: 'below', label: 'below the focused row' },
  { value: 'above', label: 'above the focused row' },
  { value: 'top', label: 'top' },
  { value: 'bottom', label: 'bottom' },
];

export default function TreeIndentDemo() {
  const api = useRef<DataGridApi<Step> | null>(null);
  const [log, push] = useEventLog();
  const [position, setPosition] = useState<Position>('child');
  // Ids of added rows; read only in the newRow callback, never while rendering.
  const nextId = useRef(10);
  const onDrop = (event: DataGridRowDragEvent<Step>) =>
    push(`${event.rowIds.join(', ')} ${event.position ?? 'dropped'} ${event.targetRowId ?? ''} → parent ${event.parentId ?? 'root'} (${event.source})`);
  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => api.current?.indentRows(['s7'])}>
          Indent Accessibility pass
        </Button>
        <Button variant="outline" onClick={() => api.current?.outdentRows(['s6'])}>
          Outdent Screens
        </Button>
        <label>
          New row position{' '}
          <Select aria-label="New row position" data={POSITIONS} value={position} onValueChange={(value) => value != null && setPosition(value as Position)} />
        </label>
      </div>
      <DataGrid<Step>
        ref={api}
        aria-label="Release plan"
        data={steps}
        columns={columns}
        tree={{ parentIdField: 'parentId' }}
        rowDrag
        editing={{ newRowPosition: position, newRow: () => ({ id: `s${nextId.current++}`, parentId: null, name: 'New step', days: 1 }) }}
        toolbar={['indent', 'outdent', 'add', 'delete', 'save', 'cancel']}
        height={420}
        onRowDrop={onDrop}
      />
      <p className="demo-status">
        Drag a grip onto the middle of a row to drop into it, near its top or bottom edge to drop before or after. Alt+Shift+ArrowRight / ArrowLeft indents or outdents the focused row. Deleting a parent deletes its subtree.
      </p>
      <EventLog entries={log} />
    </>
  );
}
```

### Live demo: Tree drag to other targets

Live demo: https://salmonui.dev/demos/data-grid/tree-drag-targets

Rows of a nested backlog tree dragged into another tree grid (before, after or into a row) or onto a custom archive element, with each parent's subtree travelling along in the drop payload.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { DataGrid, type DataGridColumn, type DataGridRowDragEvent } from '@salmonui/data-grid';
import { Select } from '@salmonui/dropdowns/select';
import { EventLog, useDemoStore, useEventLog } from '../../components/demo-kit';

interface Story {
  readonly id: string;
  readonly title: string;
  readonly points: number;
  readonly children?: readonly Story[];
}

const backlog: Story[] = [
  {
    id: 'b-search',
    title: 'Search',
    points: 8,
    children: [
      { id: 'b-search-filters', title: 'Saved filters', points: 3 },
      { id: 'b-search-typo', title: 'Typo tolerance', points: 5, children: [{ id: 'b-search-typo-de', title: 'German stemming', points: 2 }] },
    ],
  },
  { id: 'b-export', title: 'Export', points: 5, children: [{ id: 'b-export-pdf', title: 'PDF page numbers', points: 2 }] },
  { id: 'b-dark', title: 'Dark mode polish', points: 3 },
];

const storyId = (story: Story) => story.id;

const sprint: Story[] =[{ id: 's-goal', title: 'Sprint 14 goal', points: 0, children: [] }];

const columns: DataGridColumn<Story>[] = [
  { field: 'title', header: 'Story', width: 230 },
  { field: 'points', header: 'Points', type: 'number', align: 'end', width: 80 },
];

type Target = 'tree-drag-sprint' | 'tree-drag-archive';

const DROP_TARGET_OPTIONS = [
  { value: 'tree-drag-sprint', label: 'The sprint tree grid' },
  { value: 'tree-drag-archive', label: 'The archive element' },
];

export default function TreeDragTargetsDemo() {
  const [target, setTarget] = useState<Target>('tree-drag-sprint');
  const [log, push] = useEventLog();
  const [archived, archivedStore] = useDemoStore<readonly string[]>([]);
  const onDrop = (event: DataGridRowDragEvent<Story>) => {
    // `rows()` holds the dragged rows with their subtrees, in tree order.
    const moved = event.rows().map((row) => row.id);
    if (event.targetGridId === 'tree-drag-sprint') push(`${event.rowIds.join(', ')} → sprint grid ${event.position ?? ''} ${event.targetRowId ?? ''} (with ${moved.length - event.rowIds.length} descendants)`);
    else if (event.targetGridId === null && event.target?.closest('#tree-drag-archive')) {
      // A custom element target: the grid moves nothing; the app decides.
      archivedStore.set((list) => [...list, ...moved]);
      push(`archived ${moved.join(', ')}`);
    }
  };
  return (
    <>
      <div className="demo-toolbar">
        <label>
          Drop target
          <Select aria-label="Drop target" data={DROP_TARGET_OPTIONS} value={target} onValueChange={(value) => value != null && setTarget(value as Target)} />
        </label>
      </div>
      <div className="demo-columns">
        <DataGrid<Story>
          id="tree-drag-backlog"
          getRowId={storyId}
          aria-label="Backlog"
          data={backlog}
          columns={columns}
          tree
          rowDrag={{ targetId: target }}
          height={300}
          onRowDrop={onDrop}
        />
        <div>
          <DataGrid<Story> id="tree-drag-sprint" getRowId={storyId}aria-label="Sprint" data={sprint} columns={columns} tree rowDrag height={200} />
          <div id="tree-drag-archive" className="demo-drop-zone" aria-label="Archive drop zone">
            Archive: {archived.length ? archived.join(', ') : 'drop backlog rows here'}
          </div>
        </div>
      </div>
      <p className="demo-status">Drag a parent by its grip: its subtree travels with it, into the sprint grid (before, after or into a row) or onto the archive element.</p>
      <EventLog entries={log} />
    </>
  );
}
```

## Remote and lazy children

Rows whose children load on demand name a boolean field in
`tree.hasChildrenField`. Such a row
renders collapsed with a toggle, on the server and the client alike, and
its children load on the first expand:

- Local data: `tree.loadChildren({ rowId, row, signal })` returns the
  children (or a promise of them); they join the data under the row.
- A remote data source (`mode: 'remote'`): the grid reads `read({
  parentRowId: null })` for the roots and `read({ parentRowId })` on
  expand. Items are tree envelopes `{ kind: 'tree', row, parentId,
  hasChildren, childCount, children }`; children are cached per parent
  until the query changes. `createJsonDataSource` from `@salmonui/data`
  sends the parent on the wire, and the reference handler
  (`@salmonui/data/server`) serves tree levels with a `parentField`.

The grid wires a remote source through `createRemoteTree(source, {
getRowId, onError })` from `@salmonui/data-grid/engine/tree-remote`, loaded only when a remote source is in tree mode; call it
yourself only when you build an engine without `DataGrid`. Envelopes that
carry `children` load whole subtrees at once (`loadChildOnDemand: false`), remote nested data is accepted, and the query (filter,
search, sort) travels with root and child reads, so a server that returns
matches with their ancestor chain keeps a lazy tree filtered.
`pageBy: 'root'` pages roots on the server. `createOfflineDataSource`,
`createControlledDataSource` with `request.parentRowId`
 and server
aggregates (`DataSourceResult.aggregates`) work in tree mode.

While children load, the toggle shows a spinner, the row carries
`aria-busy` and `api.getTreeRow(rowId).loadStatus` is `'loading'`; then
`'loaded'`, or `'error'` after a failed read, which calls `onError` with
`action: 'treeChildren'` and the `rowId`. Clicking the toggle again or
`api.reloadTreeChildren(rowId)` retries (*Salmon*). Rows of a
lazy parent being loaded can show skeleton rows
(`virtualization.skeletonRows`).

### Live demo: Tree lazy children

Live demo: https://salmonui.dev/demos/data-grid/tree-remote

A remote tree whose children load on expand through read({ parentRowId }), with the per-row load status, a failed child read reported by onError and a retry.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import type { DataSource } from '@salmonui/data-grid/engine';
import type { DataSourceRequest, DataSourceResult } from '@salmonui/core/data';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridApi, type DataGridColumn } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';

interface Folder {
  readonly id: string;
  readonly parentId: string | null;
  readonly name: string;
  readonly items: number;
}

/** A deterministic folder tree, three levels deep, generated per parent id. */
function childrenOf(parentId: string | null): Folder[] {
  const depth = parentId === null ? 0 : parentId.split('/').length;
  const count = depth === 0 ? 6 : 4;
  return Array.from({ length: count }, (_, i) => {
    const id = parentId === null ? `r${i + 1}` : `${parentId}/${i + 1}`;
    return { id, parentId, name: depth === 0 ? `Region ${i + 1}` : depth === 1 ? `Site ${id}` : `Rack ${id}`, items: ((i + 3) * (depth + 2) * 7) % 97 };
  });
}

interface FakeServer {
  readonly source: DataSource<Folder>;
  failNext: boolean;
}

/**
 * A fake remote source: `read({ parentRowId })` answers one tree level after
 * a delay, as tree envelopes with `hasChildren`. Any source with
 * `mode: 'remote'` and `parentRowId` reads works the same way, for example
 * `createJsonDataSource` from `@salmonui/data` against a server that serves
 * tree levels.
 */
function createFakeServer(onRead: (parent: string | null, failed: boolean) => void): FakeServer {
  const server: FakeServer = {
    failNext: false,
    source: {
      mode: 'remote',
      capabilities: { treeChildren: true },
      read(request: DataSourceRequest): Promise<DataSourceResult<Folder>> {
        const parent = request.parentRowId === undefined || request.parentRowId === null ? null : String(request.parentRowId);
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            if (parent !== null && server.failNext) {
              server.failNext = false;
              onRead(parent, true);
              reject(new Error('Network error'));
              return;
            }
            onRead(parent, false);
            const level = childrenOf(parent);
            const depth = parent === null ? 0 : parent.split('/').length;
            const rows = level.map((row) => ({ kind: 'tree' as const, row, parentId: parent, hasChildren: depth < 2 }));
            resolve({ version: request.version, rows: rows as never, totalRowCount: rows.length, performed: ['search', 'filter', 'sort', 'aggregate', 'page'] });
          }, 400);
        });
      },
    },
  };
  return server;
}

const columns: DataGridColumn<Folder>[] = [
  { field: 'name', header: 'Folder', width: 280 },
  { field: 'id', header: 'ID', primaryKey: true, width: 120 },
  { field: 'items', header: 'Items', type: 'number', align: 'end', width: 100 },
];

export default function TreeRemoteDemo() {
  const api = useRef<DataGridApi<Folder> | null>(null);
  const [log, push] = useEventLog();
  const [failed, setFailed] = useState<string | null>(null);
  const [failNext, setFailNext] = useState(false);
  // Created once per mounted grid (data sources are initial-only).
  const [server] = useState(() => createFakeServer((parent, didFail) => push(`read parentRowId=${parent ?? 'null'}${didFail ? ' failed' : ''}`)));
  return (
    <>
      <div className="demo-toolbar">
        <Checkbox
          checked={failNext}
          onCheckedChange={(checked) => {
            server.failNext = checked;
            setFailNext(checked);
          }}
        >
          Fail the next child read
        </Checkbox>
        <Button variant="outline" disabled={failed === null} onClick={() => failed !== null && api.current?.reloadTreeChildren(failed)}>
          Retry {failed ?? ''}
        </Button>
      </div>
      <DataGrid<Folder>
        ref={api}
        aria-label="Remote folders"
        data={server.source}
        columns={columns}
        tree={{ parentIdField: 'parentId', defaultExpanded: false }}
        height={420}
        onTreeToggle={(event) => {
          if (event.expanded && event.lazy) push(`expand ${String(event.rowId)}: ${api.current?.getTreeRow(event.rowId)?.loadStatus ?? ''}`);
        }}
        onError={(event) => {
          if (event.action !== 'treeChildren') return;
          const rowId = (event as { rowId?: unknown }).rowId;
          setFailed(rowId === undefined ? null : String(rowId));
          setFailNext(false);
          push(`onError treeChildren ${String(rowId)}: ${event.error.message}`);
        }}
      />
      <p className="demo-status">
        Roots load first; expanding a folder reads its children once (the toggle spins while loading) and caches them. A failed read sets loadStatus to error; retry with the button or the toggle.
      </p>
      <EventLog entries={log} />
    </>
  );
}
```

### Live demo: Tree data sources

Live demo: https://salmonui.dev/demos/data-grid/tree-data-sources

One catalog tree over five data sources - an offline source that loads once, a controlled source that answers each read by parentRowId with paged roots, nested envelopes that load whole subtrees, the @salmonui/data JSON source over the reference server handler with server filtering and aggregates, and infinite scroll over blocks of root rows with skeleton rows.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import type { DataSource } from '@salmonui/data-grid/engine';
import type { DataSourceRequest, DataSourceResult, WriteResult } from '@salmonui/core/data';
import { createControlledDataSource, createJsonDataSource, tupleColumns, tupleRowId, type TupleRow } from '@salmonui/data';
import { createOfflineDataSource } from '@salmonui/data/local';
import { createJsonQueryHandler } from '@salmonui/data/server';
import { Button } from '@salmonui/buttons/button';
import { Select } from '@salmonui/dropdowns/select';
import { DataGrid, type DataGridAggregateRow, type DataGridApi, type DataGridColumn } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';

interface Item {
  readonly id: string;
  readonly parentId: string | null;
  readonly name: string;
  readonly stock: number;
}

/** A product catalog as flat rows: category > range > product. */
const catalog: Item[] = [
  ['coffee', null, 'Coffee', 0],
  ['coffee-beans', 'coffee', 'Whole beans', 0],
  ['coffee-beans-1', 'coffee-beans', 'Ethiopia Guji', 42],
  ['coffee-beans-2', 'coffee-beans', 'Colombia Huila', 18],
  ['coffee-beans-3', 'coffee-beans', 'Brazil Cerrado', 64],
  ['coffee-ground', 'coffee', 'Ground', 0],
  ['coffee-ground-1', 'coffee-ground', 'Espresso blend', 30],
  ['coffee-ground-2', 'coffee-ground', 'Filter blend', 25],
  ['tea', null, 'Tea', 0],
  ['tea-green', 'tea', 'Green tea', 0],
  ['tea-green-1', 'tea-green', 'Sencha', 12],
  ['tea-green-2', 'tea-green', 'Gyokuro', 4],
  ['tea-black', 'tea', 'Black tea', 0],
  ['tea-black-1', 'tea-black', 'Assam', 22],
  ['tea-black-2', 'tea-black', 'Darjeeling', 9],
  ['gear', null, 'Brewing gear', 0],
  ['gear-1', 'gear', 'Pour-over cone', 15],
  ['gear-2', 'gear', 'Burr grinder', 6],
  ['gear-3', 'gear', 'Gooseneck kettle', 11],
  ['gifts', null, 'Gift boxes', 0],
  ['gifts-1', 'gifts', 'Tasting box', 20],
  ['gifts-2', 'gifts', 'Tea sampler', 14],
].map(([id, parentId, name, stock]) => ({ id: id as string, parentId: parentId as string | null, name: name as string, stock: stock as number }));

const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));

const columns: DataGridColumn<Item>[] = [
  { field: 'name', header: 'Item', width: 240 },
  { field: 'id', header: 'ID', primaryKey: true, width: 160 },
  { field: 'stock', header: 'Stock', type: 'number', align: 'end', width: 100 },
];

type Log = (entry: string) => void;

/** Offline: one load, then expansion, sorting and filtering run locally. */
function OfflineTree({ push }: { push: Log }) {
  const [source] = useState(() =>
    createOfflineDataSource<Item>({
      load: async () => {
        push('load(): every row, once');
        await delay(300);
        return catalog;
      },
    }),
  );
  return <DataGrid<Item> aria-label="Catalog, offline source" data={source} columns={columns} getRowId={(row) => row.id} tree={{ parentIdField: 'parentId' }} sorting filtering height={380} />;
}

/** Controlled: the app answers every read, roots and children, keyed by request.parentRowId. */
function ControlledTree({ push, nested }: { push: Log; nested: boolean }) {
  const [source] = useState(() => {
    const envelope = (row: Item): unknown => {
      const kids = catalog.filter((r) => r.parentId === row.id);
      // Nested envelopes carry whole subtrees: no child reads follow.
      return nested ? { kind: 'tree', row, parentId: row.parentId, children: kids.map(envelope) } : { kind: 'tree', row, parentId: row.parentId, hasChildren: kids.length > 0, childCount: kids.length };
    };
    return createControlledDataSource<Item>({
      capabilities: { treeChildren: true },
      async onQueryChange(request: DataSourceRequest): Promise<DataSourceResult<Item>> {
        const parent = request.parentRowId === undefined || request.parentRowId === null ? null : String(request.parentRowId);
        let level = catalog.filter((row) => row.parentId === parent);
        const total = level.length;
        const paging = request.query.paging;
        // `pageBy: 'root'`: the app pages the root level.
        if (parent === null && paging) level = level.slice((paging.page - 1) * paging.pageSize, paging.page * paging.pageSize);
        push(`onQueryChange parentRowId=${parent ?? 'null'}${parent === null && paging ? `, page ${paging.page}` : ''}`);
        await delay(250);
        return { version: request.version, rows: level.map(envelope) as Item[], totalRowCount: total };
      },
    });
  });
  return (
    <DataGrid<Item>
      aria-label="Catalog, controlled source"
      data={source}
      columns={columns}
      getRowId={(row) => row.id}
      tree={{ parentIdField: 'parentId', defaultExpanded: false, pageBy: 'root' }}
      paging={{ pageSize: 2 }}
      height={380}
    />
  );
}

const FIELDS = ['id', 'parentId', 'name', 'stock'] as const;
const tupleCols = tupleColumns<DataGridColumn<TupleRow>>(
  [
    { field: 'name', header: 'Item', width: 240 },
    { field: 'id', header: 'ID', width: 160 },
    { field: 'stock', header: 'Stock', type: 'number', align: 'end', width: 160 },
  ],
  FIELDS,
);
const remoteAggregates: DataGridAggregateRow<TupleRow>[] = [{ columns: [{ field: 'stock', type: 'sum', renderFooter: ({ formatted }) => <>Server total {formatted['sum']}</> }] }];

/**
 * Server: the `@salmonui/data` JSON source over the reference handler of
 * `@salmonui/data/server`. The handler runs in this tab through an in-process transport; in an
 * app it answers POSTs from `createJsonDataSource({ url })`.
 */
function ServerTree({ push }: { push: Log }) {
  const [source] = useState(() => {
    const handler = createJsonQueryHandler(catalog as unknown as Record<string, unknown>[], {
      key: 'id',
      parentField: 'parentId',
      fields: FIELDS,
      types: { id: 'string', parentId: 'string', name: 'string', stock: 'number' },
    });
    const transport = handler.transport();
    return createJsonDataSource<TupleRow>({
      key: 'id',
      fields: FIELDS,
      batch: false,
      transport: async (request, ctx) => {
        const body = request as unknown as { parent?: unknown; query?: { where?: unknown; search?: unknown; aggregates?: unknown } };
        push(`POST parent=${String(body.parent ?? 'null')}${body.query?.where || body.query?.search ? ', filtered' : ''}${body.query?.aggregates ? ', aggregates' : ''}`);
        await delay(250);
        return transport(request, ctx);
      },
    });
  });
  return (
    <DataGrid<TupleRow>
      aria-label="Catalog, server source"
      data={source}
      columns={tupleCols}
      getRowId={tupleRowId(FIELDS, 'id')}
      tree={{ parentIdField: 'parentId', defaultExpanded: false }}
      aggregates={remoteAggregates}
      toolbar={['search']}
      filtering
      sorting
      height={380}
    />
  );
}

interface Task {
  readonly id: string;
  readonly parentId: string | null;
  readonly name: string;
  readonly stock: number;
}

/** A remote tree of 2,000 roots with three children each; root reads honour `range` (blocks). */
function createBlockSource(push: Log): DataSource<Task> {
  const names = new Map<string, string>();
  const root = (i: number): Task => ({ id: `w${i}`, parentId: null, name: names.get(`w${i}`) ?? `Warehouse ${i + 1}`, stock: (i * 37) % 500 });
  const child = (i: number, k: number): Task => ({ id: `w${i}-${k}`, parentId: `w${i}`, name: names.get(`w${i}-${k}`) ?? `Bay ${i + 1}.${k + 1}`, stock: (i * 7 + k * 13) % 90 });
  return {
    mode: 'remote',
    capabilities: { treeChildren: true, write: true },
    async read(request) {
      const parent = request.parentRowId === undefined || request.parentRowId === null ? null : String(request.parentRowId);
      await delay(parent === null ? 400 : 700);
      if (parent === null) {
        const start = request.range?.start ?? 0;
        const end = Math.min(request.range?.end ?? 2000, 2000);
        push(`read roots ${start}–${end - 1}`);
        const rows = Array.from({ length: Math.max(0, end - start) }, (_, k) => ({ kind: 'tree', row: root(start + k), parentId: null, hasChildren: true, childCount: 3 }));
        return { version: request.version, rows: rows as unknown as Task[], totalRowCount: 2000 };
      }
      push(`read children of ${parent}`);
      const i = Number(parent.slice(1));
      const rows = [0, 1, 2].map((k) => ({ kind: 'tree', row: child(i, k), parentId: parent, hasChildren: false }));
      return { version: request.version, rows: rows as unknown as Task[], totalRowCount: 3 };
    },
    async write(request): Promise<WriteResult<Task>> {
      for (const change of request.changed) names.set(String(change.rowId), change.row.name);
      push(`write: ${request.changed.map((c) => `${String(c.rowId)} → ${c.row.name}`).join(', ')}`);
      return { version: request.version, status: 'applied', changed: request.changed.map((c) => ({ rowId: c.rowId, row: c.row })) };
    },
  };
}

const blockColumns: DataGridColumn<Task>[] = [
  { field: 'name', header: 'Location', width: 240 },
  { field: 'id', header: 'ID', primaryKey: true, width: 120, editable: false },
  { field: 'stock', header: 'Stock', type: 'number', align: 'end', width: 100, editable: false },
];

/** Infinite scroll: blocks of root rows, collapsed start, editing and id selection across blocks; skeleton rows while children load. */
function InfiniteTree({ push }: { push: Log }) {
  const api = useRef<DataGridApi<Task> | null>(null);
  const [source] = useState(() => createBlockSource(push));
  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => push(`selectRows(['w1', 'w1500']): ${api.current?.selectRows(['w1', 'w1500']).status ?? 'no grid'}`)}>
          Select w1 and w1500 by id
        </Button>
        <Button variant="outline" onClick={() => push(`selected: ${api.current?.getSelectedRowIds().join(', ') ?? ''}`)}>
          Read the selection
        </Button>
      </div>
      <DataGrid<Task>
        ref={api}
        aria-label="Warehouses, infinite scroll"
        data={source}
        columns={blockColumns}
        tree={{ parentIdField: 'parentId', defaultExpanded: false }}
        infiniteScroll={{ blockSize: 50, initialBlocks: 1 }}
        virtualization={{ skeletonRows: true }}
        selection={{ multiple: true }}
        editing={{ mode: 'cell' }}
        height={380}
      />
    </>
  );
}

type Kind = 'offline' | 'controlled' | 'nested' | 'server' | 'infinite';

const LABELS: Record<Kind, string> = {
  offline: 'Offline: load once',
  controlled: 'Controlled: one level per read, roots paged',
  nested: 'Controlled: nested envelopes (whole subtrees)',
  server: 'Server: reference handler',
  infinite: 'Infinite scroll: blocks of roots',
};
const KINDS = (Object.keys(LABELS) as Kind[]).map((value) => ({ value, label: LABELS[value] }));

export default function TreeDataSourcesDemo() {
  const [kind, setKind] = useState<Kind>('offline');
  const [log, push] = useEventLog();
  return (
    <>
      <div className="demo-toolbar">
        <label>
          Data source{' '}
          <Select aria-label="Data source" data={KINDS} value={kind} onValueChange={(value) => value != null && setKind(value as Kind)} />
        </label>
      </div>
      {kind === 'offline' ? <OfflineTree push={push} /> : null}
      {kind === 'controlled' ? <ControlledTree key="controlled" push={push} nested={false} /> : null}
      {kind === 'nested' ? <ControlledTree key="nested" push={push} nested /> : null}
      {kind === 'server' ? <ServerTree push={push} /> : null}
      {kind === 'infinite' ? <InfiniteTree push={push} /> : null}
      <p className="demo-status">
        Expand rows and watch the reads in the log. With the server source, search &quot;sencha&quot; or filter Item: the server returns the matches with their ancestor chain, and the footer total comes from the server. With infinite scroll, scroll down for more roots and expand one to see a skeleton row while its children load.
      </p>
      <EventLog entries={log} label="Data source reads" />
    </>
  );
}
```

## Export, print and copy

Exports write the tree view: Excel rows get an outline level per
depth (clamped at 7), PDF indents the tree column, and CSV writes rows in
visible pre-order. `tree: 'expanded'` (default) exports the visible rows;
`tree: 'all'` exports every kept row regardless of expansion:

```ts
await api.exportToExcel({ tree: 'all', outlineCollapsed: true }); // collapsed parents stay collapsed in Excel
await api.exportToCsv({ tree: 'all', treeDepthColumn: 'Level' });  // adds a depth column (true: "Depth")
```

Server export runs the same model with depths. `print()` prints
the expanded view with indentation, or every row with `printing={{ tree:
'all' }}` or `print({ tree: 'all' })`. `tree.copyMode` widens
`api.copy()` and Ctrl+C with the copied rows' ancestors (`'ancestors'`,
default), descendants, both, or none. See [Export](https://salmonui.dev/docs/data-grid/export) and
[Print](https://salmonui.dev/docs/data-grid/print).

### Live demo: Tree export, print and copy

Live demo: https://salmonui.dev/demos/data-grid/tree-export-print

A bill of materials in tree mode exported to Excel with outline levels, CSV with a depth column and PDF with indentation, either the expanded rows or every row, a server export of the same tree and state, print with indentation, and copy that adds ancestors or descendants.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import type { ColumnDef } from '@salmonui/data-grid/engine';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, downloadBlob, serializeDataGridState, type DataGridApi, type DataGridColumn, type DataGridExportWriters, type DataGridTreeFilterMode } from '@salmonui/data-grid';
import { Select } from '@salmonui/dropdowns/select';
import { TextArea } from '@salmonui/inputs/text-field';
import { EventLog, useEventLog } from '../../components/demo-kit';

interface Part {
  readonly id: string;
  readonly parentId: string | null;
  readonly name: string;
  readonly qty: number;
  readonly unitCost: number;
}

// A bill of materials as flat self-referential rows.
const parts: Part[] = [
  { id: 'bike', parentId: null, name: 'City bike', qty: 1, unitCost: 0 },
  { id: 'frame', parentId: 'bike', name: 'Frame set', qty: 1, unitCost: 0 },
  { id: 'frame-tube', parentId: 'frame', name: 'Aluminium frame', qty: 1, unitCost: 120 },
  { id: 'frame-fork', parentId: 'frame', name: 'Fork', qty: 1, unitCost: 45 },
  { id: 'wheels', parentId: 'bike', name: 'Wheel set', qty: 1, unitCost: 0 },
  { id: 'wheel-rim', parentId: 'wheels', name: 'Rim', qty: 2, unitCost: 28 },
  { id: 'wheel-spokes', parentId: 'wheels', name: 'Spoke', qty: 64, unitCost: 0.4 },
  { id: 'wheel-tyre', parentId: 'wheels', name: 'Tyre', qty: 2, unitCost: 22 },
  { id: 'drive', parentId: 'bike', name: 'Drivetrain', qty: 1, unitCost: 0 },
  { id: 'drive-chain', parentId: 'drive', name: 'Chain', qty: 1, unitCost: 18 },
  { id: 'drive-hub', parentId: 'drive', name: 'Hub gear', qty: 1, unitCost: 140 },
  { id: 'lights', parentId: null, name: 'Light kit', qty: 1, unitCost: 0 },
  { id: 'lights-front', parentId: 'lights', name: 'Front light', qty: 1, unitCost: 25 },
  { id: 'lights-rear', parentId: 'lights', name: 'Rear light', qty: 1, unitCost: 12 },
];

// Core column definitions: the same array serves the grid and the server export below.
const coreColumns: ColumnDef<Part>[] = [
  { field: 'name', header: 'Part', width: 220 },
  { field: 'id', header: 'Part no.', primaryKey: true, width: 130 },
  { field: 'qty', header: 'Qty', type: 'number', align: 'end', width: 80 },
  { field: 'unitCost', header: 'Unit cost', type: 'number', format: 'C2', align: 'end', width: 110 },
];
const columns: DataGridColumn<Part>[] = coreColumns;

const tree = { parentIdField: 'parentId', defaultExpanded: 2 } as const;

// Module-level: the dynamic imports keep both writers out of the page bundle until first use.
const writers: DataGridExportWriters = {
  excel: () => import('@salmonui/export/xlsx'),
  pdf: () => import('@salmonui/export/pdf'),
};

const ROWS_OPTIONS = [
  { value: 'expanded', label: 'Expanded (visible rows)' },
  { value: 'all', label: 'All, collapsed included' },
];

const COPY_ADDS_OPTIONS = [
  { value: 'ancestors', label: 'ancestors' },
  { value: 'descendants', label: 'descendants' },
  { value: 'both', label: 'both' },
  { value: 'none', label: 'none' },
];

export default function TreeExportPrintDemo() {
  const api = useRef<DataGridApi<Part> | null>(null);
  const [scope, setScope] = useState<'expanded' | 'all'>('expanded');
  const [copyMode, setCopyMode] = useState<DataGridTreeFilterMode>('ancestors');
  const [copied, setCopied] = useState('');
  const [log, push] = useEventLog();

  // Server export: `exportToResponse` from `@salmonui/data-grid/engine/export-server` takes the
  // rows, the core columns, the same `tree` options and the client state (expansion included). In
  // an app it runs in a route handler; this static site runs it in the tab, as its demo backend does.
  const serverExport = async () => {
    const grid = api.current;
    if (!grid) return;
    const { exportToResponse } = await import('@salmonui/data-grid/engine/export-server');
    const response = await exportToResponse(
      { rows: parts, columns: coreColumns, tree, state: serializeDataGridState(grid.getState()), locale: 'en-US', currency: 'EUR' },
      { format: 'excel', fileName: 'bill-of-materials-server', tree: scope, outlineCollapsed: true },
    );
    if (!response) return;
    const blob = await response.blob();
    push(`server export (${scope}): ${blob.size} bytes`);
    downloadBlob(blob, 'bill-of-materials-server.xlsx');
  };

  return (
    <>
      <div className="demo-toolbar" aria-label="Export and print">
        <label>
          Rows
          <Select aria-label="Rows" data={ROWS_OPTIONS} value={scope} onValueChange={(value) => value != null && setScope(value as 'expanded' | 'all')} />
        </label>
        <Button variant="outline" onClick={() => void api.current?.exportToExcel({ fileName: 'bill-of-materials', tree: scope, outlineCollapsed: true }).then(() => push(`Excel (${scope}): outline per depth`))}>
          Excel
        </Button>
        <Button variant="outline" onClick={() => void api.current?.exportToCsv({ fileName: 'bill-of-materials', tree: scope, treeDepthColumn: 'Level' }).then(() => push(`CSV (${scope}) with a Level column`))}>
          CSV
        </Button>
        <Button variant="outline" onClick={() => void api.current?.exportToPdf({ fileName: 'bill-of-materials', tree: scope, header: 'Bill of materials' }).then(() => push(`PDF (${scope}): indented tree column`))}>
          PDF
        </Button>
        <Button variant="outline" onClick={() => void serverExport()}>
          Server Excel
        </Button>
        <Button variant="outline" onClick={() => api.current?.print({ tree: scope })}>
          Print
        </Button>
      </div>
      <div className="demo-toolbar">
        <label>
          Copy adds
          <Select aria-label="Copy adds" data={COPY_ADDS_OPTIONS} value={copyMode} onValueChange={(value) => value != null && setCopyMode(value as DataGridTreeFilterMode)} />
        </label>
        <Button variant="outline" onClick={() => push(`copy(): ${api.current?.copy().status ?? 'no grid'}`)}>
          Copy selected rows
        </Button>
      </div>
      <DataGrid<Part>
        ref={api}
        aria-label="Bill of materials"
        data={parts}
        columns={columns}
        getRowId={(row) => row.id}
        tree={{ ...tree, copyMode }}
        selection={{ mode: 'row', multiple: true }}
        // Read-only copy: `editing` registers the clipboard; every edit capability is off.
        editing={{ edit: false, add: false, delete: false }}
        exportWriters={writers}
        height={380}
        locale="en-US"
        currency="EUR"
        onBeforeCopy={(event) => setCopied(event.data)}
      />
      <label className="demo-status" style={{ display: 'grid', gap: 'var(--salmon-space-2)', justifyItems: 'start' }}>
        Last copy (TSV)
        <TextArea aria-label="Last copy" readOnly rows={5} value={copied} style={{ inlineSize: 'min(100%, 36rem)' }} />
      </label>
      <p className="demo-status">
        Collapse Wheel set, then export with each row scope. Excel writes an outline level per depth and, with all rows, keeps collapsed parents collapsed; PDF and print indent the Part column. Select Spoke and press Ctrl+C or Copy: the copy adds the rows the copy mode names.
      </p>
      <EventLog entries={log} />
    </>
  );
}
```

## State, RTL and adaptive

`persistState`, `api.getState()` and `api.restoreState()` include the tree
expansion as `tree.expandedRows`. With `dir="rtl"` the
indentation, the chevron, ArrowRight / ArrowLeft and the indent keys mirror.
Adaptive vertical rows show the toggle and "Level n" in each
card instead of the indentation, with a 44 × 44 px toggle target.

### Live demo: Tree RTL, locale and adaptive

Live demo: https://salmonui.dev/demos/data-grid/tree-rtl-locale

An office tree in right-to-left mode with mirrored indentation, chevrons and keys, German localeText for the tree strings, locale number, currency and date formats, a lookup column and validation while editing, and adaptive cards that show the toggle and the level.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridColumn, type DataGridLocaleText } from '@salmonui/data-grid';
import { Select } from '@salmonui/dropdowns/select';
import { germanLocaleText } from '../../lib/locale-de';

interface Office {
  readonly id: string;
  readonly parentId: string | null;
  readonly name: string;
  readonly country: string;
  readonly revenue: number;
  readonly opened: Date;
}

// Dates in UTC: the same text on the server and in the browser.
const offices: Office[] = [
  { id: 'emea', parentId: null, name: 'EMEA', country: 'DE', revenue: 0, opened: new Date(Date.UTC(2014, 2, 1)) },
  { id: 'emea-de', parentId: 'emea', name: 'Berlin', country: 'DE', revenue: 1_284_500.5, opened: new Date(Date.UTC(2014, 2, 1)) },
  { id: 'emea-de-mu', parentId: 'emea-de', name: 'Munich', country: 'DE', revenue: 642_100, opened: new Date(Date.UTC(2019, 8, 15)) },
  { id: 'emea-ae', parentId: 'emea', name: 'Dubai', country: 'AE', revenue: 918_250.75, opened: new Date(Date.UTC(2017, 0, 9)) },
  { id: 'emea-eg', parentId: 'emea', name: 'Cairo', country: 'EG', revenue: 311_900, opened: new Date(Date.UTC(2021, 5, 20)) },
  { id: 'apac', parentId: null, name: 'APAC', country: 'SG', revenue: 0, opened: new Date(Date.UTC(2016, 10, 3)) },
  { id: 'apac-sg', parentId: 'apac', name: 'Singapore', country: 'SG', revenue: 1_050_000, opened: new Date(Date.UTC(2016, 10, 3)) },
  { id: 'apac-my', parentId: 'apac', name: 'Kuala Lumpur', country: 'MY', revenue: 402_330.2, opened: new Date(Date.UTC(2020, 3, 27)) },
];

// Lookup rows: the cell stores the code and shows the name (lookup column).
const COUNTRIES = {
  en: [
    { code: 'DE', name: 'Germany' },
    { code: 'AE', name: 'United Arab Emirates' },
    { code: 'EG', name: 'Egypt' },
    { code: 'SG', name: 'Singapore' },
    { code: 'MY', name: 'Malaysia' },
  ],
  de: [
    { code: 'DE', name: 'Deutschland' },
    { code: 'AE', name: 'Vereinigte Arabische Emirate' },
    { code: 'EG', name: 'Ägypten' },
    { code: 'SG', name: 'Singapur' },
    { code: 'MY', name: 'Malaysia' },
  ],
};

// The tree keys of `localeText` (toggle labels, announcements, adaptive level, indent items).
const germanTreeText: DataGridLocaleText = {
  ...germanLocaleText,
  treeExpand: '{row} aufklappen',
  treeCollapse: '{row} zuklappen',
  treeExpanded: '{row} aufgeklappt, {count} Unterelemente',
  treeCollapsed: '{row} zugeklappt',
  treeLoading: 'Unterelemente werden geladen',
  treeLoadError: 'Unterelemente konnten nicht geladen werden',
  treeRetry: 'Unterelemente von {row} erneut laden',
  treeLevel: 'Ebene {level}',
  indent: 'Einrücken',
  outdent: 'Ausrücken',
};

type Lang = 'en' | 'de';

function columnsFor(lang: Lang): DataGridColumn<Office>[] {
  return [
    { field: 'name', header: lang === 'de' ? 'Standort' : 'Office', width: 220, validation: { required: true } },
    { field: 'country', header: lang === 'de' ? 'Land' : 'Country', width: 200, lookup: { data: COUNTRIES[lang], keyField: 'code', displayField: 'name' } },
    { field: 'revenue', header: lang === 'de' ? 'Umsatz' : 'Revenue', type: 'number', format: 'C2', align: 'end', width: 150, validation: { min: 0 } },
    { field: 'opened', header: lang === 'de' ? 'Eröffnet' : 'Opened', type: 'date', format: 'yMMMd', width: 140 },
    // Hidden key column: edits address rows by it.
    { field: 'id', header: 'ID', primaryKey: true, hidden: true },
  ];
}

const DIRECTION_OPTIONS = [
  { value: 'rtl', label: 'Right to left' },
  { value: 'ltr', label: 'Left to right' },
];

const LANGUAGE_OPTIONS = [
  { value: 'de', label: 'German (de-DE)' },
  { value: 'en', label: 'English (en-US)' },
];

export default function TreeRtlLocaleDemo() {
  const [dir, setDir] = useState<'ltr' | 'rtl'>('rtl');
  const [lang, setLang] = useState<Lang>('de');
  const [adaptive, setAdaptive] = useState(false);
  return (
    <>
      <div className="demo-toolbar">
        <label>
          Direction
          <Select aria-label="Direction" data={DIRECTION_OPTIONS} value={dir} onValueChange={(value) => value != null && setDir(value as 'ltr' | 'rtl')} />
        </label>
        <label>
          Language
          <Select aria-label="Language" data={LANGUAGE_OPTIONS} value={lang} onValueChange={(value) => value != null && setLang(value as Lang)} />
        </label>
        <Checkbox checked={adaptive} onCheckedChange={(checked) => setAdaptive(checked)}>
          Adaptive cards
        </Checkbox>
      </div>
      <DataGrid<Office>
        // Adaptive mode is read when the grid is created: a new grid when it changes.
        key={adaptive ? 'adaptive' : 'table'}
        aria-label="Offices"
        data={offices}
        columns={columnsFor(lang)}
        getRowId={(row) => row.id}
        tree={{ parentIdField: 'parentId' }}
        dir={dir}
        locale={lang === 'de' ? 'de-DE' : 'en-US'}
        currency="EUR"
        timeZone="UTC"
        {...(lang === 'de' ? { localeText: germanTreeText } : {})}
        {...(adaptive ? { adaptive: { target: 'both', rowLayout: 'vertical' } as const } : {})}
        editing={{ mode: 'cell' }}
        toolbar={['indent', 'outdent']}
        rowDrag
        height={420}
      />
      <p className="demo-status">
        In right-to-left mode the indentation and chevrons mirror, and ArrowLeft expands while ArrowRight collapses; Alt+Shift+ArrowLeft indents. The toolbar items, the toggle labels and the expand announcements follow the language, and numbers, currency and dates follow the locale. Edit a revenue below zero or clear an office name to see validation; the Country column edits a lookup.
      </p>
    </>
  );
}
```

## With other features

Tree mode keeps the rest of the grid: columns and column chrome (templates,
types, formats, lookup columns, resize, reorder, auto-fit, pinning, column
menu and chooser, stacked headers), row and column spans (a row
span ends at a parent boundary), lookup columns and validation,
templates and theming, globalization, and
every shared Data Grid method and event. Row virtualization is
always on over the tree view, with no per-row materialization, and it works
with checkboxes, detail and row templates, batch editing, cell selection
and variable heights. Column virtualization keeps the toggle on the tree column.
Infinite scroll loads blocks of root rows and allows a
collapsed initial state: with a remote source and
`infiniteScroll={{ blockSize, initialBlocks, threshold }}` the first read
asks for `initialBlocks` blocks of root rows (`read({ parentRowId: null,
range })`) and scrolling near the last tree row reads the next block.
Children still load on expand. Expansion, detail rows, editing and
`selectRows` by id keep working across block loads. `cache`, `maxBlocks`,
`initialResult` and `api.engine.infiniteScroll` do not apply in tree mode;
blocks are appended as they land.

`tree` does not combine with `grouping` or `childGrid`: `tree` wins and a development warning names the ignored
prop. Use `renderDetail` for detail rows under tree rows.

### Live demo: Large tree

Live demo: https://salmonui.dev/demos/data-grid/tree-large

A 28,208-row sales tree with 24 month columns under stacked year headers, row and column virtualization, cascading checkboxes, batch editing across scrolled-out rows, and resize, reorder, pin, column menu and chooser on a tree.

`Demo.tsx`:

```tsx
'use client';

import { useRef } from 'react';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, type DataGridApi, type DataGridColumn } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';

interface Node {
  readonly id: string;
  readonly parentId: string | null;
  readonly name: string;
  readonly budget: number;
}

const REGIONS = ['North', 'South', 'East', 'West', 'Central', 'Coast', 'Highlands', 'Islands'];

/**
 * A deterministic sales tree: 8 regions × 25 areas × 20 stores × 6 departments
 * = 24,000 departments, 28,208 rows in all. Flat rows with `parentId`.
 */
function createSalesTree(): Node[] {
  const rows: Node[] = [];
  REGIONS.forEach((region, r) => {
    const rId = `r${r}`;
    rows.push({ id: rId, parentId: null, name: `${region} region`, budget: 0 });
    for (let a = 0; a < 25; a++) {
      const aId = `${rId}-a${a}`;
      rows.push({ id: aId, parentId: rId, name: `${region} area ${a + 1}`, budget: 0 });
      for (let s = 0; s < 20; s++) {
        const sId = `${aId}-s${s}`;
        rows.push({ id: sId, parentId: aId, name: `Store ${r + 1}.${a + 1}.${s + 1}`, budget: 0 });
        for (let d = 0; d < 6; d++) rows.push({ id: `${sId}-d${d}`, parentId: sId, name: ['Grocery', 'Bakery', 'Produce', 'Dairy', 'Household', 'Pharmacy'][d] as string, budget: 1_000 + ((r * 7 + a * 13 + s * 17 + d * 31) % 90) * 100 });
      }
    }
  });
  // Parents start with the sum of their children (rows are in pre-order, so walk them backwards).
  const sums = new Map<string, number>();
  for (let i = rows.length - 1; i >= 0; i--) {
    const row = rows[i] as Node;
    const budget = sums.get(row.id) ?? row.budget;
    if (sums.has(row.id)) rows[i] = { ...row, budget };
    if (row.parentId !== null) sums.set(row.parentId, (sums.get(row.parentId) ?? 0) + budget);
  }
  return rows;
}

const nodes = createSalesTree();

const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

/** A month's sales derived from the budget (read-only, no stored field). */
const monthColumn = (year: number, m: number): DataGridColumn<Node> => ({
  id: `y${year}m${m + 1}`,
  header: MONTHS[m] as string,
  type: 'number',
  format: 'N0',
  align: 'end',
  width: 90,
  editable: false,
  valueGetter: (row) => (row.budget === 0 ? null : Math.round((row.budget / 12) * (0.8 + (((row.budget + m * 37 + year) % 41) / 100)))),
});

// 2 × 12 month columns under stacked year headers; the center zone virtualizes its columns.
const columns: DataGridColumn<Node>[] = [
  { field: 'name', header: 'Unit', width: 260, pinned: 'start' },
  { field: 'id', header: 'ID', primaryKey: true, width: 140, editable: false },
  { field: 'budget', header: 'Budget', type: 'number', format: 'C0', align: 'end', width: 120, validation: { min: 0 } },
  ...[2025, 2026].map((year): DataGridColumn<Node> => ({ id: `y${year}`, header: String(year), columns: MONTHS.map((_, m) => monthColumn(year, m)) })),
];

export default function TreeLargeDemo() {
  const api = useRef<DataGridApi<Node> | null>(null);
  const [log, push] = useEventLog();
  const time = (label: string, run: () => unknown) => {
    const start = performance.now();
    run();
    push(`${label}: ${(performance.now() - start).toFixed(1)} ms`);
  };
  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => time('expand all (28,208 rows)', () => api.current?.expandAllTreeRows())}>
          Expand all
        </Button>
        <Button variant="outline" onClick={() => time('collapse all', () => api.current?.collapseAllTreeRows())}>
          Collapse all
        </Button>
        <Button
          variant="outline"
          onClick={() => {
            api.current?.expandTreeRows(['r7', 'r7-a24', 'r7-a24-s19']);
            api.current?.scrollToRow('r7-a24-s19-d5');
          }}
        >
          Reveal the last department
        </Button>
        <Button variant="outline" onClick={() => api.current?.scrollToColumn('y2026m12')}>
          Scroll to Dec 2026
        </Button>
        <Button
          variant="outline"
          onClick={() => {
            const preview = api.current?.getBatchPreview();
            push(`pending: ${preview?.dirtyCellCount ?? 0} dirty cells; selected: ${api.current?.getSelectedRowIds().length ?? 0} rows`);
          }}
        >
          Read pending changes
        </Button>
      </div>
      <DataGrid<Node>
        ref={api}
        aria-label="Sales tree, 28,208 rows by 27 columns"
        data={nodes}
        columns={columns}
        getRowId={(row) => row.id}
        // Row virtualization is always on over the tree view; the checkbox cascade is one range command.
        tree={{ parentIdField: 'parentId', defaultExpanded: 1, checkbox: { cascade: true } }}
        virtualization={{ columns: true }}
        selection={{ multiple: true }}
        editing={{ mode: 'batch', confirmDiscard: false, guardUnsaved: false }}
        toolbar={['save', 'cancel', 'columnChooser']}
        columnMenu
        resizable
        reorderable
        sorting
        height={460}
        rowHeight={32}
        locale="en-US"
        currency="USD"
        onSave={(event) => push(`saved: ${event.changed.length} rows`)}
      />
      <p className="demo-status">
        Expand all, scroll, then edit Budget cells far apart: batch drafts survive scrolling out of view. Check a region to select its whole subtree. Resize, reorder, pin or hide columns through the header, column menu or chooser; the Unit column keeps its toggle.
      </p>
      <EventLog entries={log} />
    </>
  );
}
```

## Server rendering

Tree mode renders on the server: nested and flat rows, the toggle, the
indentation and the treegrid ARIA attributes are in the server markup, so
hydration does not change them. Lazy parents (`hasChildrenField`) render
collapsed with a toggle and never load children on the server; child reads,
the key handlers and the skeleton row start after mount. `persistState`
reads its storage only after mount, so a restored expansion applies after
hydration, not in the server markup.

## Virtualization and data updates

- There is no separate DOM virtualization mode: rows are always
  DOM-virtualized with one model, and buffer sizes, DOM pools and scroll
  throttling are internal, held to the scroll budgets. Tune the overscan
  with `virtualization.rowOverscan`, and use `estimatedRowHeight` for
  measured, variable row heights.
- There is no immutable mode: the engine always applies data
  changes as id-keyed row deltas, so a mode switch would only add a slower
  default. Keep stable row ids (`getRowId`), which tree mode needs anyway;
  `setRowData`, `setCellValue` and new `data` arrays are diffed by row id.

## API reference

The `tree` prop is [`DataGridTree`](https://salmonui.dev/docs/reference/data-grid/DataGridTree),
the tree methods are [`DataGridTreeApi`](https://salmonui.dev/docs/reference/data-grid/DataGridTreeApi)
on [`DataGridApi`](https://salmonui.dev/docs/reference/data-grid/DataGridApi), the row info
is [`DataGridTreeRowInfo`](https://salmonui.dev/docs/reference/data-grid/DataGridTreeRowInfo),
the toggle events are
[`DataGridTreeToggleEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridTreeToggleEvent),
`ctx.tree` is [`DataGridTreeContext`](https://salmonui.dev/docs/reference/data-grid/DataGridTreeContext),
and row templates use
[`DataGridTreeToggle`](https://salmonui.dev/docs/reference/data-grid/DataGridTreeToggle).

## Performance

The tree index is built once per data identity in typed arrays (no per-row
objects) and patched on row changes: a move, indent or outdent splices the
moved subtree into the index instead of rebuilding it. The visible rows
are a list of ranges, so expanding or collapsing a branch and every scroll
lookup are independent of the row count. The budgets
are: index build of 50,000 rows ≤ 25 ms, one branch ≤ 16 ms, expand all
≤ 60 ms, a cascade over 100,000 descendants ≤ 16 ms, sibling sort and
`'ancestors'` filter of 1,000,000 rows within 1.2 × the flat budgets once
the sort keys are cached (and within 1.86 × the same query on a flat grid
from cold), indent, outdent or a drop `into` a row of a million-row tree
≤ 16 ms to painted, and the flat scroll budgets on a fully expanded
million-row tree. The demo below generates either benchmark tree and
shows each measured time next to its budget.

### Live demo: Tree performance

Live demo: https://salmonui.dev/demos/data-grid/tree-performance

Generate the 50,000-row or the 1,000,000-row benchmark tree and read the measured time of grid creation, expand and collapse, a 100,000-row cascade, sibling sort, an ancestors filter, indent and outdent next to the tree mode release budgets.

`Demo.tsx`:

```tsx
'use client';

import { useId, useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, type DataGridApi, type DataGridColumn } from '@salmonui/data-grid';
import { Select } from '@salmonui/dropdowns/select';

type Value = string | number | boolean | Date | null;
type TreeRow = Record<string, Value> & { readonly id: string; readonly parentId: string | null };

/** The benchmark fixtures of the tree budgets (rows per level, roots first). */
const FIXTURES = {
  hierarchy: { label: 'hierarchy: 50,000 rows, depth 4', levels: [20, 180, 1800, 48000] },
  'tree-large': { label: 'tree-large: 1,000,000 rows, depth 6', levels: [10, 90, 900, 9000, 90000, 900000] },
} as const;
type FixtureName = keyof typeof FIXTURES;
const FIXTURE_ITEMS = (Object.keys(FIXTURES) as FixtureName[]).map((name) => ({ value: name, label: FIXTURES[name].label }));

const KINDS = ['s', 's', 's', 's', 'n', 'n', 'n', 'd', 'd', 'b'] as const;
const KEYS = KINDS.map((kind, c) => `${kind}${c}`);

/**
 * The fixture generator of the benchmark (one LCG, seed 1; 10 columns of the
 * `large` mix; each row's parent drawn from the level above). App work: never timed.
 */
function createTree(levels: readonly number[]): TreeRow[] {
  let state = 1;
  const next = (): number => {
    state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
    return state;
  };
  const words = Array.from({ length: 256 }, (_, i) => `word-${i.toString(36)}-${(i * 7919) % 1000}`);
  const dates = Array.from({ length: 365 }, (_, i) => new Date(Date.UTC(2025, 0, 1 + i)));
  const rows: TreeRow[] = new Array(levels.reduce((a, b) => a + b, 0));
  let r = 0;
  let prevStart = 0;
  let prevSize = 0;
  for (const size of levels) {
    const start = r;
    for (let i = 0; i < size; i++, r++) {
      const row: Record<string, Value> = { id: `t${r}`, parentId: prevSize === 0 ? null : `t${prevStart + (next() % prevSize)}` };
      KINDS.forEach((kind, c) => {
        const key = KEYS[c] as string;
        if (kind === 's') row[key] = words[next() & 255] as string;
        else if (kind === 'n') row[key] = next() % 100000;
        else if (kind === 'd') row[key] = dates[next() % 365] as Date;
        else row[key] = ((next() >>> 16) & 1) === 1;
      });
      rows[r] = row as TreeRow;
    }
    prevStart = start;
    prevSize = size;
  }
  return rows;
}

const columns: DataGridColumn<TreeRow>[] = [
  { field: 'id', header: 'ID', primaryKey: true, width: 100 },
  ...KEYS.map((field, c): DataGridColumn<TreeRow> => {
    const kind = KINDS[c];
    if (kind === 'n') return { field, header: `Number ${c}`, type: 'number', format: 'N0', align: 'end', width: 120 };
    if (kind === 'd') return { field, header: `Date ${c}`, type: 'date', format: 'yMMMd', width: 130 };
    if (kind === 'b') return { field, header: `Flag ${c}`, type: 'boolean', align: 'center', width: 90 };
    return { field, header: `Text ${c}`, type: 'string', width: c === 0 ? 260 : 150 };
  }),
];

/**
 * A small preview of the same generator (36 rows, depth 3), shown until a run
 * swaps in the generated fixture. Deterministic and immutable, so the server
 * and the client render the same markup.
 */
const PREVIEW: readonly TreeRow[] = createTree([3, 9, 24]);

// Tree column s0, every parent expanded, checkbox cascade (its state is the row selection).
const TREE = { parentIdField: 'parentId', column: 's0', filterMode: 'ancestors', checkbox: { cascade: true } } as const;

/**
 * Tree mode budgets, each defined on one fixture; `limit` applies to that fixture only.
 */
interface Budget {
  readonly text: string;
  readonly fixture: FixtureName;
  readonly limit?: number;
}
const BUDGETS = {
  create: { text: 'creation ≤ 500 ms (tree-large; index build alone ≤ 25 ms on hierarchy)', fixture: 'tree-large', limit: 500 },
  all: { text: '≤ 60 ms (hierarchy)', fixture: 'hierarchy', limit: 60 },
  branch: { text: '≤ 16 ms (hierarchy)', fixture: 'hierarchy', limit: 16 },
  cascade: { text: '≤ 16 ms (100,000 descendants, tree-large root)', fixture: 'tree-large', limit: 16 },
  sortCold: { text: '≤ 1.86 × the same sort on a flat grid (tree-large; flat side not run here)', fixture: 'tree-large' },
  sortWarm: { text: '≤ 180 ms warm (1.2 × flat, tree-large)', fixture: 'tree-large', limit: 180 },
  filterCold: { text: '≤ 1.86 × the same filter on a flat grid (tree-large; flat side not run here)', fixture: 'tree-large' },
  filterWarm: { text: '≤ 120 ms warm (1.2 × flat, tree-large)', fixture: 'tree-large', limit: 120 },
  move: { text: '≤ 16 ms to painted (hierarchy and tree-large)', fixture: 'tree-large', limit: 16 },
} satisfies Record<string, Budget>;
type BudgetKey = keyof typeof BUDGETS;

interface Timing {
  readonly row: string;
  readonly action: string;
  readonly ms: number;
  readonly budget: BudgetKey;
}

const TABLE = { inlineSize: '100%', minInlineSize: 640, marginBlockStart: 'var(--salmon-space-4)', borderCollapse: 'collapse', fontSize: 'var(--salmon-font-size-sm)' } as const;
const TD = { padding: 'var(--salmon-space-1) var(--salmon-space-3)', borderBlockEnd: '1px solid var(--salmon-border-subtle)', textAlign: 'start', verticalAlign: 'top' } as const;
const TH = { ...TD, borderBlockEnd: '1px solid var(--salmon-border-default)' } as const;

const fmt = (n: number) => n.toLocaleString('en-US');
const nextFrame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
/** Two frames, so the previous step's render is painted before the next one starts. */
const settle = async () => {
  await nextFrame();
  await nextFrame();
};

function verdict(t: Timing, fixture: FixtureName): string {
  const budget: Budget = BUDGETS[t.budget];
  if (budget.limit === undefined) return 'reference only';
  if (budget.fixture !== fixture && t.budget !== 'move') return 'not the budget fixture';
  return t.ms <= budget.limit ? 'within budget' : 'over budget';
}

/** Generates a budget-sized tree, then times the tree operations through the public DataGrid API next to their budgets. */
export default function TreePerformanceDemo() {
  const id = useId();
  const [fixture, setFixture] = useState<FixtureName>('hierarchy');
  const [grid, setGrid] = useState<{ readonly rows: TreeRow[]; readonly fixture: FixtureName; readonly key: number } | null>(null);
  const [timings, setTimings] = useState<Timing[]>([]);
  const [status, setStatus] = useState('Showing a 36-row preview. Pick a fixture and press "Generate and measure"; nothing is timed until you do.');
  const [running, setRunning] = useState(false);
  // Resolves the run's wait for the mounted grid (written by the click handler, read by onReady).
  const ready = useRef<((api: DataGridApi<TreeRow>) => void) | null>(null);

  const run = async () => {
    setRunning(true);
    setTimings([]);
    const name = fixture;
    const levels = FIXTURES[name].levels;
    const total = levels.reduce((a, b) => a + b, 0);
    const rowLabel = fmt(total);
    const results: Timing[] = [];
    const record = (action: string, ms: number, budget: BudgetKey) => {
      results.push({ row: rowLabel, action, ms, budget });
      setTimings([...results]);
    };
    try {
      setStatus(`Generating ${rowLabel} rows…`);
      await settle();
      const g0 = performance.now();
      const rows = createTree(levels);
      const generation = performance.now() - g0;

      setStatus('Creating the grid…');
      const mounted = new Promise<DataGridApi<TreeRow>>((resolve) => {
        ready.current = resolve;
      });
      const c0 = performance.now();
      setGrid((prev) => ({ rows, fixture: name, key: (prev?.key ?? 0) + 1 }));
      const api = await mounted;
      record('Create the grid (engine, tree index, first render)', performance.now() - c0, 'create');
      await settle();

      // Engine time: the API call plus the snapshot read that computes the view (render excluded).
      const engine = (label: string, budget: BudgetKey, call: () => void) => {
        const t0 = performance.now();
        call();
        void api.engine.getSnapshot().rows.count;
        record(label, performance.now() - t0, budget);
      };
      // To painted: the call at the start of a frame, ended by a task after that frame's rendering.
      const painted = (label: string, budget: BudgetKey, call: () => void) =>
        new Promise<void>((resolve) => {
          requestAnimationFrame(() => {
            const t0 = performance.now();
            call();
            const channel = new MessageChannel();
            channel.port1.onmessage = () => {
              record(label, performance.now() - t0, budget);
              resolve();
            };
            channel.port2.postMessage(0);
          });
        });

      setStatus('Measuring…');
      engine('Collapse all', 'all', () => api.collapseAllTreeRows());
      await settle();
      engine('Expand all', 'all', () => api.expandAllTreeRows());
      await settle();
      engine('Collapse one branch (root t0)', 'branch', () => api.toggleTreeRow('t0', false));
      await settle();
      engine('Expand one branch (root t0)', 'branch', () => api.toggleTreeRow('t0', true));
      await settle();
      engine('Cascade-check root t0 (its whole subtree)', 'cascade', () => api.engine.dispatch({ type: 'tree.check', rowId: 't0', checked: true }));
      await settle();
      engine('Cascade-uncheck root t0', 'cascade', () => api.engine.dispatch({ type: 'tree.check', rowId: 't0', checked: false }));
      await settle();
      engine('Sort siblings by Number 4, cold (sort keys extracted)', 'sortCold', () => api.sortColumn('n4', 'asc'));
      await settle();
      engine('Sort siblings by Number 4 descending, warm', 'sortWarm', () => api.sortColumn('n4', 'desc'));
      await settle();
      engine('Sort siblings by Number 4 ascending, warm', 'sortWarm', () => api.sortColumn('n4', 'asc'));
      await settle();
      api.clearSorting();
      await settle();
      engine("Filter Text 1 contains 'word-1', ancestors kept (first run)", 'filterCold', () => api.filterColumn('s1', 'contains', 'word-1'));
      await settle();
      api.clearFiltering();
      await settle();
      engine("Filter Text 1 contains 'word-1', ancestors kept (warm)", 'filterWarm', () => api.filterColumn('s1', 'contains', 'word-1'));
      await settle();
      api.clearFiltering();
      await settle();

      // A rendered row with a previous sibling: indent it under that sibling, then outdent it back.
      const rendered = [...(api.element?.querySelectorAll<HTMLElement>('[role="row"][data-row-id]') ?? [])].map((el) => el.dataset['rowId'] ?? '');
      const target = rendered.find((rowId) => {
        const info = api.getTreeRow(rowId);
        return info !== null && info.depth >= 1 && info.posinset > 1;
      });
      if (target) {
        await painted(`Indent row ${target}`, 'move', () => api.indentRows(target));
        await settle();
        await painted(`Outdent row ${target}`, 'move', () => api.outdentRows(target));
        await settle();
      }
      setStatus(`Done: ${fmt(total)} rows on ${FIXTURES[name].label}. Row generation took ${generation.toFixed(0)} ms and is excluded from every timing.`);
    } finally {
      ready.current = null;
      setRunning(false);
    }
  };

  const shown = grid?.fixture ?? fixture;
  return (
    <div>
      <div className="demo-toolbar" role="group" aria-label="Benchmark fixture">
        <label htmlFor={`${id}-fixture`}>Fixture</label>
        <Select id={`${id}-fixture`} aria-label="Fixture" data={FIXTURE_ITEMS} value={fixture} disabled={running} onValueChange={(value) => value != null && setFixture(value as FixtureName)} />
        <Button variant="outline" type="button" disabled={running} onClick={() => void run()}>
          Generate and measure
        </Button>
      </div>
      <p className="demo-status" role="status">
        {status}
      </p>
      <DataGrid<TreeRow>
        key={grid?.key ?? 0}
        aria-label={grid ? `Generated tree, ${fmt(grid.rows.length)} rows` : `Preview tree, ${PREVIEW.length} rows`}
        data={grid?.rows ?? PREVIEW}
        columns={columns}
        getRowId={(row) => row.id}
        tree={TREE}
        selection={{ multiple: true }}
        sorting
        filtering
        rowDrag
        height={360}
        rowHeight={32}
        timeZone="UTC"
        locale="en-US"
        onReady={(api) => ready.current?.(api)}
      />
      {timings.length > 0 ? (
        <div style={{ overflowX: 'auto' }}>
        <table className="demo-timings" aria-label="Measured tree times" style={TABLE}>
          <thead>
            <tr>
              <th scope="col" style={TH}>
                Action
              </th>
              <th scope="col" style={{ ...TH, textAlign: 'end' }}>
                Rows
              </th>
              <th scope="col" style={{ ...TH, textAlign: 'end' }}>
                Measured
              </th>
              <th scope="col" style={TH}>
                Budget
              </th>
              <th scope="col" style={TH}>
                Result
              </th>
            </tr>
          </thead>
          <tbody>
            {timings.map((t) => (
              <tr key={t.action}>
                <td style={TD}>{t.action}</td>
                <td style={{ ...TD, textAlign: 'end', whiteSpace: 'nowrap' }}>{t.row}</td>
                <td style={{ ...TD, textAlign: 'end', whiteSpace: 'nowrap' }} data-timing>
                  {t.ms.toFixed(1)} ms
                </td>
                <td style={TD}>{BUDGETS[t.budget].text}</td>
                <td style={TD}>{verdict(t, shown)}</td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
      ) : null}
    </div>
  );
}
```

The tree code is a prop-gated chunk (`@salmonui/data-grid/engine/tree`
≤ 13.1 KB, the `tree` render feature with it ≤ 20.5 KB gzip); the Minimal
`DataGrid` app does not grow. Bundle size has no demo: it is
verified by `npm run bundle:check` (`tooling/checks/bundle-size.mjs`) in
`npm run release:verify`. See [Performance](https://salmonui.dev/docs/data-grid/performance).
