# Tree data

> Show hierarchical records such as an org chart, a bill of materials or a file system, built from paths or parent ids.

Tree data displays rows that already form a hierarchy: managers and their reports, product categories and SKUs, cost centres and accounts. Unlike [row grouping](https://docs.birchui.com/grid-pro/row-grouping.md), which invents group rows from shared values, tree data shows your own rows at every level, and every row can be a parent.

> **Grid Pro: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md**
>
> Tree data requires `TreeDataModule` from `@birchui/grid-pro`. Add `AggregationModule` to roll values up to parent rows.

**Live demo: Tree data: cost centres** (runs on the HTML version of this page). Source of `demos/tree-data.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createGrid, type ColumnDef } from '@birchui/core';
import { AggregationModule, TreeDataModule } from '@birchui/grid-pro';
import { button, currency, docsTheme, field, layout, onDocsThemeChange } from './_shared';

export const meta = { title: 'Tree data: cost centres', height: 480 };

interface CostCentre {
  path: string[];
  owner: string;
  headcount?: number;
  budget?: number;
  spent?: number;
}

const rows: CostCentre[] = [
  { path: ['Operations'], owner: 'Grace Lin' },
  { path: ['Operations', 'Field service'], owner: 'Marcus Reid' },
  {
    path: ['Operations', 'Field service', 'North crew'],
    owner: 'Ivy Okafor',
    headcount: 14,
    budget: 820000,
    spent: 611400,
  },
  {
    path: ['Operations', 'Field service', 'South crew'],
    owner: 'Tomás Ortega',
    headcount: 11,
    budget: 690000,
    spent: 702300,
  },
  { path: ['Operations', 'Warehousing'], owner: 'Elena Petrova', headcount: 22, budget: 1150000, spent: 948250 },
  { path: ['Operations', 'Fleet'], owner: 'Ken Watanabe', headcount: 6, budget: 540000, spent: 497800 },
  { path: ['Sales'], owner: 'Amelia Hart' },
  { path: ['Sales', 'Enterprise'], owner: 'Jonas Becker', headcount: 9, budget: 1340000, spent: 1012000 },
  { path: ['Sales', 'Mid-market'], owner: 'Priya Natarajan', headcount: 12, budget: 980000, spent: 1003400 },
  { path: ['Sales', 'Partner channel'], owner: 'Diego Alvarez', headcount: 5, budget: 410000, spent: 288900 },
  { path: ['Engineering'], owner: 'Hana Sato' },
  { path: ['Engineering', 'Platform'], owner: 'Ruth Adeyemi', headcount: 18, budget: 2260000, spent: 1904100 },
  { path: ['Engineering', 'Mobile apps'], owner: 'Lukas Novak', headcount: 8, budget: 1120000, spent: 1187600 },
  { path: ['Engineering', 'Data'], owner: 'Sofia Rossi', headcount: 7, budget: 960000, spent: 702050 },
];

const money = (value: unknown) => (typeof value === 'number' ? currency.format(value) : '');

const columns: ColumnDef<CostCentre>[] = [
  { field: 'owner', header: 'Owner', width: 170 },
  { field: 'headcount', header: 'Headcount', type: 'number', width: 120, aggFunc: 'sum' },
  { field: 'budget', header: 'Budget', type: 'number', width: 140, format: money, aggFunc: 'sum' },
  { field: 'spent', header: 'Spent', type: 'number', width: 140, format: money, aggFunc: 'sum' },
  {
    id: 'remaining',
    header: 'Remaining',
    type: 'number',
    width: 140,
    valueGetter: (row) => (row.budget ?? 0) - (row.spent ?? 0),
    format: money,
    aggFunc: 'sum',
    cellClass: ({ value }) => (typeof value === 'number' && value < 0 ? 'demo-over-budget' : undefined),
  },
];

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  const search = document.createElement('input');
  search.type = 'search';
  search.placeholder = 'Filter, e.g. crew';
  const grid = createGrid<CostCentre>(body, {
    columns,
    rows,
    treeData: true,
    getDataPath: (row) => row.path,
    getRowId: (row) => row.path.join('/'),
    groupColumn: { header: 'Cost centre', width: 260 },
    groupDefaultExpanded: -1,
    modules: [TreeDataModule, AggregationModule],
    theme: docsTheme(),
    ariaLabel: 'Cost centres',
  });
  const onInput = () => grid.setQuickFilter(search.value);
  search.addEventListener('input', onInput);
  toolbar.append(
    button('Expand all', () => grid.expandAll()),
    button('Collapse all', () => grid.collapseAll()),
    field('Quick filter', search),
  );
  status.textContent = 'Filtering keeps the ancestors of matching rows so every match stays in context.';
  const stopTheme = onDocsThemeChange((theme) => grid.update({ theme }));
  return () => {
    search.removeEventListener('input', onInput);
    stopTheme();
    grid.destroy();
  };
}
```

## Two ways to describe the hierarchy

Set `treeData: true` and tell the grid how rows relate, with either `getDataPath` or `getParentId`.

### Paths: `getDataPath`

Return the row's position in the tree as a list of keys, ending with the row itself. This suits data that comes with a path, such as file systems, account codes or category breadcrumbs.

```ts title="cost-centres.ts"
import { createGrid, type ColumnDef } from '@birchui/core';
import { TreeDataModule, AggregationModule } from '@birchui/grid-pro';

interface Account {
  path: string[];
  owner: string;
  budget: number;
  actual: number;
}

const accounts: Account[] = [
  { path: ['Operations'], owner: 'Priya Raman', budget: 0, actual: 0 },
  { path: ['Operations', 'Field service'], owner: 'Tomás Herrera', budget: 0, actual: 0 },
  { path: ['Operations', 'Field service', 'Vehicles'], owner: 'Tomás Herrera', budget: 182000, actual: 176450 },
  { path: ['Operations', 'Field service', 'Tools and parts'], owner: 'Grace Okafor', budget: 64000, actual: 71210 },
  { path: ['Operations', 'Warehousing', 'Rotterdam DC'], owner: 'Daan de Vries', budget: 240000, actual: 231900 },
  { path: ['Sales', 'EMEA', 'Trade shows'], owner: 'Lena Fischer', budget: 90000, actual: 88400 },
  { path: ['Sales', 'North America', 'Partner programme'], owner: 'Maya Singh', budget: 120000, actual: 134250 },
];

const columns: ColumnDef<Account>[] = [
  { field: 'owner' },
  { field: 'budget', type: 'number', aggFunc: 'sum' },
  { field: 'actual', type: 'number', aggFunc: 'sum' },
];

createGrid(container, {
  columns,
  rows: accounts,
  getRowId: (row) => row.path.join('/'),
  modules: [TreeDataModule, AggregationModule],
  treeData: true,
  getDataPath: (row) => row.path,
  groupColumn: { header: 'Account', width: 260 },
  groupDefaultExpanded: 1,
});
```

Missing ancestors are filled in for you. In the example there is no row for `Operations › Warehousing` or for `Sales`, so the grid creates placeholder parent rows labelled with those path segments and no data. When the array does contain a row for a path, that row is used, even if it comes after its children.

### Parent ids: `getParentId`

Return the id of the row's parent, or `null` for top-level rows. This suits data from a database table with a `parent_id` column, such as an organisation chart.

```ts title="org-chart.ts"
interface Employee {
  id: string;
  managerId: string | null;
  name: string;
  title: string;
  location: string;
  salary: number;
}

const staff: Employee[] = [
  { id: 'E100', managerId: null, name: 'Amara Osei', title: 'Chief Operating Officer', location: 'London', salary: 245000 },
  { id: 'E210', managerId: 'E100', name: 'Jonas Berg', title: 'Head of Field Service', location: 'Stockholm', salary: 152000 },
  { id: 'E211', managerId: 'E210', name: 'Sofia Rossi', title: 'Service Technician', location: 'Milan', salary: 61000 },
  { id: 'E212', managerId: 'E210', name: 'Kwame Mensah', title: 'Service Technician', location: 'Accra', salary: 48000 },
  { id: 'E220', managerId: 'E100', name: 'Hannah Wright', title: 'Logistics Manager', location: 'Manchester', salary: 98000 },
];

createGrid(container, {
  columns: [
    { field: 'name', header: 'Employee', width: 280 },
    { field: 'title' },
    { field: 'location' },
    { field: 'salary', type: 'number', aggFunc: 'sum' },
  ],
  rows: staff,
  getRowId: (row) => row.id,
  modules: [TreeDataModule, AggregationModule],
  treeData: true,
  getParentId: (row) => row.managerId,
});
```

`getParentId` must return ids in the same form as [`getRowId`](https://docs.birchui.com/grid/rows.md). Rows are linked in one pass, so parents can appear before or after their children in the array.

The grid is forgiving with imperfect data:

- A row whose parent id does not match any row becomes a top-level row.
- Rows that form a cycle, such as two rows that name each other as parent, are shown at the top level instead of disappearing.
- Duplicate ids are made unique, so every row is still displayed.

If both functions are given, `getDataPath` wins. If `treeData` is `true` but neither function is set, the grid shows a flat list and logs one console warning.

## The tree column

The hierarchy is drawn in one column, with an expand toggle and indentation by depth. Which column that is depends on `groupColumn`:

- **Without `groupColumn`**, the first visible column becomes the tree column. Its own values and cell renderer are kept; the toggle and indentation are added around them. The org chart above uses this to show employee names as the tree.
- **With `groupColumn`**, the grid adds a separate group column at the left, configured like the [row grouping](https://docs.birchui.com/grid-pro/row-grouping.md#the-group-column) column. With `getDataPath` and no `field` or `valueGetter` in `groupColumn`, it shows the last path segment of each row, as in the cost-centre example.

Placeholder parents have no data, so they show their path segment in the tree column and aggregates, if any, in the other columns.

## Expanding and collapsing

Users click the toggle, or press `Enter` or `Space` in the tree column. `Arrow Right` expands the focused row, and `Arrow Left` collapses it or moves focus to its parent. Tree rows use the same expansion API as group rows:

```ts
api.setExpanded('E210', true);
api.setExpanded(['E100', 'E220'], true);
api.expandAll();
api.collapseAll();

api.on('rowExpanded', ({ rowId, expanded }) => {
  console.log(rowId, expanded);
});
```

`setExpanded()` takes one id or an array, and fires `rowExpanded` for every row that changes. `isExpanded(id, { ignoreExpandAll: true })` tells you whether a row was toggled on its own, ignoring a previous `expandAll()`.

`groupDefaultExpanded` sets how many levels start open: `0` (the default) collapses everything, `-1` opens every level. Row ids in a tree are your own ids from `getRowId`, so you can expand a known record directly. Placeholder parents created from paths get ids derived from their path.

## Filtering keeps ancestors

When a filter or the quick filter matches a row deep in the tree, the grid keeps that row's ancestors visible so the match stays in context. Parents that do not match are shown only as the path to matching rows. Placeholder parents never match on their own.

```ts
api.setQuickFilter('technician');
```

With the org chart above, this shows Amara Osei and Jonas Berg as ancestors, plus the two technicians beneath them.

## Sorting

Sorting reorders siblings within each parent; children never move to another parent. Columns with an `aggFunc` sort parents by their aggregate, other columns by the parent's own value. Siblings that compare equal keep their order from the source array.

## Aggregating up the tree

With `AggregationModule` installed, parent rows show aggregates of the leaf rows below them, using each column's `aggFunc`. In the cost-centre example, `Operations` shows the total budget and actual spend of its vehicles, tools and Rotterdam accounts.

For columns with an `aggFunc`, a parent row displays the aggregate in place of its own value, and its own value is not added to the total. That avoids counting a subtotal twice when your data already stores one on the parent. Columns without an `aggFunc` show the parent's own values as usual.

`groupTotals: true` adds a grand total row below the tree.

See [Aggregation](https://docs.birchui.com/grid-pro/aggregation.md) for the full list of functions.

## Updating tree data

Update rows with `setRows()` or `applyTransaction()` as usual. The hierarchy is rebuilt from `getDataPath` or `getParentId`, so moving an employee to another manager is a normal update:

```ts
api.applyTransaction({ update: [{ ...staff[3], managerId: 'E220' }] });
```

Expanded state is kept by row id across updates.

## Reference

**`GridOptions`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface GridOptions<TRow = RowData> extends GridFeatureOptions<TRow>
```

| Property | Type | Description |
| --- | --- | --- |
| `groupDefaultExpanded?` | `number` |  |
| `groupColumn?` | `Partial<ColumnDef<TRow>>` |  |
| `treeData?` | `boolean` |  |
| `getDataPath?` | `(row: TRow) => string[]` |  |
| `getParentId?` | `(row: TRow) => string \| null \| undefined` |  |
