---
title: "Tree Grid"
description: "Tree Grid - the Data Grid with parents: every row may have a parent, so it pages, filters, multisorts and locks columns like a grid and opens and closes like a tree. 111,000 rows, ARIA treegrid, keyboard, store-driven."
slug: "tree-grid"
---

import { DocPage, PageHeader, SkillPanel, SourceFiles, SourceNote, StatesSection, CodeBlock, Demo, DemoCode, ChangelogEntries, ArchBody, StatsClaim, StatsCards, PageOverlay, DocText, DocLink, H2, SkillField, SkillText, SkillRow, SkillGrid, Variant, ApiPill, Dim, CodeCard, TableCard } from "../../lib/components/index";

<DocPage meta={meta}>

<PageHeader slug="tree-grid" title="Tree Grid" component="data-grid">
  A <a class="link" href="data-grid.html">Data Grid</a> whose rows may have a parent. Name the parent field with <code>data-parent-field</code> and the grid becomes an ARIA <code>treegrid</code>: the first column indents by depth and opens and closes branches, while everything a grid does still works on the visible rows - multisort orders siblings, a column filter keeps the ancestors of every match and opens the way to it, pages and infinite loading walk the tree, columns lock. The records stay one flat array; <a class="link" href="https://www.npmjs.com/package/defuss-dataview">defuss-dataview</a> builds the hierarchy.
</PageHeader>

```html example label="111,110 nodes" schema="none" hint="Ten regions × ten countries × a hundred cities × ten districts - one flat array of records with a parentId. Open a branch with its chevron or Right Arrow / Left Arrow on the first column. Filter 'district 4.2.17' to see a match with its whole path opened; sort Population (Shift+click Name to break ties). Expand all opens 11,110 branches at once. The columns arrange like the Data Grid's: the arrow at a header's end opens its menu (sort, lock, show or hide columns), a header drags to another place, its end edge resizes it - the toggle stays in the first shown column."
<div class="flex flex-col gap-3">
  <div class="flex flex-wrap gap-2">
    <button class="btn" data-variant="outline" data-size="sm" type="button" id="tg-open">Expand all</button>
    <button class="btn" data-variant="outline" data-size="sm" type="button" id="tg-close">Collapse all</button>
  </div>
  <div
    class="data-grid"
    id="tg-geo"
    aria-label="Regions"
    data-parent-field="parentId"
    data-select="single"
    data-empty-text="No place matches."
    style="height: 26rem"
  >
    <div class="data-grid-viewport">
      <div class="data-grid-head">
        <div class="data-grid-row">
          <div class="data-grid-header" data-field="name" data-width="18rem" data-filter="text" data-locked>Name</div>
          <div
            class="data-grid-header"
            data-field="kind"
            data-width="7rem"
            data-filter="select"
            data-options="region,country,city,district"
            >Kind</div
          >
          <div
            class="data-grid-header"
            data-field="population"
            data-type="number"
            data-width="9rem"
            data-filter="number"
            >Population</div
          >
          <div class="data-grid-header" data-field="area" data-type="number" data-width="8rem">Area km²</div>
          <div class="data-grid-header" data-field="growth" data-type="number" data-format="percent" data-width="7rem"
            >Growth</div
          >
        </div>
      </div>
      <div class="data-grid-body"></div>
    </div>
  </div>
</div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    // one flat array: every record names its parent
    const rows = [];
    let id = 0;
    const node = (parentId, name, kind, i) => {
      rows.push({
        id: ++id,
        parentId,
        name,
        kind,
        population: 1000 + ((id * 7919) % 900_000),
        area: 10 + ((id * 131) % 5000),
        growth: (((id * 37) % 60) - 20) / 1000,
      });
      return id;
    };
    for (let a = 1; a <= 10; a++) {
      const region = node(null, 'Region ' + a, 'region');
      for (let b = 1; b <= 10; b++) {
        const country = node(region, 'Country ' + a + '.' + b, 'country');
        for (let c = 1; c <= 100; c++) {
          const city = node(country, 'City ' + a + '.' + b + '.' + c, 'city');
          for (let d = 1; d <= 10; d++) node(city, 'District ' + a + '.' + b + '.' + c + '.' + d, 'district');
        }
      }
    }
    const grid = document.getElementById('tg-geo');
    const { dataGrid } = df$.shadcn;
    dataGrid.setSource(grid, rows);
    document.getElementById('tg-open').addEventListener('click', () => dataGrid.expandAll(grid));
    document.getElementById('tg-close').addEventListener('click', () => dataGrid.collapseAll(grid));
  });
</script>
```

```html example label="Checkbox selection" schema="none" hint="With data-select-model='checkbox' a tree grid gets a checkbox in front of every row - before the indentation, so the boxes line up at every depth - and one in the head. A box selects its own row only: a phase's box leaves its tasks as they are. Shift+click on a box selects the range of shown rows from the last one; the head's box selects every row the open branches show, or none. Open and close branches with the chevrons - the ticks stay. The line below follows config.selected."
<div
  class="data-grid"
  id="tg-checks"
  aria-label="Project plan"
  data-parent-field="parentId"
  data-select="multiple"
  data-select-model="checkbox"
  data-persist="none"
  style="height: 20rem"
>
  <div class="data-grid-viewport">
    <div class="data-grid-head">
      <div class="data-grid-row">
        <div class="data-grid-header" data-field="name" data-width="minmax(11rem, 1fr)">Task</div>
        <div class="data-grid-header" data-field="owner" data-width="7rem">Owner</div>
        <div class="data-grid-header" data-field="days" data-type="number" data-format="" data-width="5rem">Days</div>
      </div>
    </div>
    <div class="data-grid-body"></div>
  </div>
</div>
<p class="text-sm" style="margin-block-start: 0.5rem"><output id="tg-checks-log">Nothing is selected.</output></p>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const plan = {
      Discovery: ['Interviews', 'Survey', 'Competitor review'],
      Design: ['Wireframes', 'Visual design', 'Prototype', 'Usability test'],
      Build: ['API', 'Web app', 'Mobile app', 'Payments', 'Search'],
      Launch: ['Beta', 'Docs', 'Announcement'],
    };
    const owners = ['Ada', 'Ken', 'Grace', 'Linus', 'Hedy'];
    const rows = [];
    let id = 0;
    for (const [phase, tasks] of Object.entries(plan)) {
      const top = ++id;
      rows.push({ id: top, parentId: null, name: phase, owner: owners[top % 5], days: null });
      for (const task of tasks)
        rows.push({ id: ++id, parentId: top, name: task, owner: owners[id % 5], days: 2 + ((id * 5) % 9) });
    }
    const grid = document.getElementById('tg-checks');
    const log = document.getElementById('tg-checks-log');
    df$.shadcn.dataGrid.setSource(grid, rows, { query: { expanded: [1, 5] } });
    grid.store.subscribe(({ config }) => {
      const picked = df$.shadcn.dataGrid.selected(grid);
      log.textContent = picked.length
        ? picked.length + ' selected: ' + picked.map((r) => r.name).join(', ')
        : 'Nothing is selected.';
    });
  });
</script>
```

```html example label="Checkboxes and drag into a branch" schema="none" hint="data-select-model='checkbox' puts a checkbox in front of every row - before the indentation - and one in the head for every row of the query (mixed while some are ticked). Tick a few files, then drag one of them: the ticked rows go together. With data-drag and data-drop rows move between branches: the middle of a row drops into it (it opens), its top or bottom edge before or after it; a folder brings everything under it, and never goes into its own subtree. Drag a row out to the Data Tree beside it - the Archive takes it with its subtree. Alt (Option) or Ctrl copies."
<div class="grid gap-3" style="grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr))">
  <div
    class="data-grid"
    id="tg-files"
    aria-label="Files"
    data-parent-field="parentId"
    data-select="multiple"
    data-select-model="checkbox"
    data-drag
    data-drop
    data-persist="none"
    style="height: 20rem"
  >
    <div class="data-grid-viewport">
      <div class="data-grid-head">
        <div class="data-grid-row">
          <div class="data-grid-header" data-field="name" data-width="minmax(10rem, 1fr)">Name</div>
          <div class="data-grid-header" data-field="size" data-type="number" data-width="5.5rem">KB</div>
        </div>
      </div>
      <div class="data-grid-body"></div>
    </div>
  </div>
  <div
    class="data-tree"
    id="tg-archive"
    aria-label="Archive"
    data-drag
    data-drop
    data-persist="none"
    style="height: 20rem"
  ></div>
</div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const rows = [];
    let id = 0;
    for (const folder of ['Design', 'Research', 'Release']) {
      const top = ++id;
      rows.push({ id: top, parentId: null, name: folder, size: null });
      for (let n = 1; n <= 4; n++)
        rows.push({
          id: ++id,
          parentId: top,
          name: folder.toLowerCase() + '-' + n + '.md',
          size: ((id * 37) % 90) + 4,
        });
    }
    df$.shadcn.dataGrid.setSource(document.getElementById('tg-files'), rows, { query: { expanded: [1, 6] } });
    df$.shadcn.dataTree.setSource(document.getElementById('tg-archive'), [
      { id: 'a2025', parentId: null, name: '2025' },
      { id: 'a2026', parentId: null, name: '2026' },
    ]);
  });
</script>
```

```html example label="Paged tree" schema="none" hint="data-paging='pages' pages the VISIBLE rows: open a branch and the pages after it shift; a filter opens the paths to its matches and pages through them."
<div
  class="data-grid"
  id="tg-pages"
  aria-label="Departments"
  data-parent-field="parentId"
  data-paging="pages"
  data-page-size="15"
  style="height: 24rem; max-width: 40rem"
>
  <div class="data-grid-viewport">
    <div class="data-grid-head">
      <div class="data-grid-row">
        <div class="data-grid-header" data-field="name" data-width="minmax(14rem, 1fr)" data-filter="text">Team</div>
        <div class="data-grid-header" data-field="headcount" data-type="number" data-width="7rem">People</div>
        <div
          class="data-grid-header"
          data-field="budget"
          data-type="number"
          data-format="currency:EUR"
          data-width="9rem"
          >Budget</div
        >
      </div>
    </div>
    <div class="data-grid-body"></div>
  </div>
</div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const areas = ['Engineering', 'Design', 'Sales', 'Support', 'Finance', 'People'];
    const rows = [];
    let id = 0;
    areas.forEach((area) => {
      const top = ++id;
      rows.push({ id: top, parentId: null, name: area, headcount: 0, budget: 0 });
      for (let t = 1; t <= 12; t++) {
        const team = ++id;
        rows.push({ id: team, parentId: top, name: area + ' team ' + t, headcount: 0, budget: 0 });
        for (let p = 1; p <= 8; p++)
          rows.push({
            id: ++id,
            parentId: team,
            name: area + ' ' + t + '.' + p,
            headcount: 1,
            budget: 40_000 + ((id * 7919) % 90_000),
          });
      }
    });
    df$.shadcn.dataGrid.setSource(document.getElementById('tg-pages'), rows);
  });
</script>
```

```html example label="Totals per branch: an aggregated tree" schema="none" hint="200,000 sales become a tree with three aggregate plans that differ only in their groupBy - region, region + country, region + country + channel - run on one source. Every branch carries the totals of everything below it: orders, units, revenue, the average order and the returns (a count with a where). Pick a year: the plans run again with a where and the open branches stay open. Sorting sorts siblings."
<div class="flex flex-col gap-2" style="max-width: 48rem">
  <div class="flex flex-wrap items-center gap-2">
    <label class="label" for="tg-sales-year">Year</label>
    <select class="select w-auto" id="tg-sales-year">
      <option value="" selected>All years</option>
      <option value="2024">2024</option>
      <option value="2025">2025</option>
    </select>
    <output class="text-sm text-muted-foreground" id="tg-sales-line" aria-live="polite"
      >Aggregating 200,000 sales…</output
    >
  </div>
  <div class="data-grid" id="tg-sales" aria-label="Sales by region" data-parent-field="parentId" style="height: 22rem">
    <div class="data-grid-viewport">
      <div class="data-grid-head">
        <div class="data-grid-row">
          <div class="data-grid-header" data-field="name" data-width="minmax(12rem, 1fr)" data-filter="text"
            >Market</div
          >
          <div class="data-grid-header" data-field="orders" data-type="number" data-width="6rem">Orders</div>
          <div class="data-grid-header" data-field="units" data-type="number" data-width="6rem">Units</div>
          <div
            class="data-grid-header"
            data-field="revenue"
            data-type="number"
            data-format="currency:EUR"
            data-width="9rem"
            data-sort="desc"
            >Revenue</div
          >
          <div
            class="data-grid-header"
            data-field="average"
            data-type="number"
            data-format="currency:EUR"
            data-width="7rem"
            >Avg order</div
          >
          <div class="data-grid-header" data-field="returns" data-type="number" data-width="6rem">Returns</div>
        </div>
      </div>
      <div class="data-grid-body"></div>
    </div>
  </div>
</div>
<script type="module">
  import {
    forRows,
    createImmutableArraySource,
  } from 'https://cdn.jsdelivr.net/npm/defuss-dataview@0.10.0/dist/browser-compute.mjs';

  addEventListener('DOMContentLoaded', () => {
    const markets = {
      Europe: ['Germany', 'France', 'Spain', 'Poland'],
      Americas: ['United States', 'Brazil', 'Canada'],
      'Asia Pacific': ['Japan', 'India', 'Australia'],
      Africa: ['Nigeria', 'Kenya'],
    };
    const places = Object.entries(markets).flatMap(([region, list]) => list.map((country) => ({ region, country })));
    const channels = ['Online', 'Retail', 'Partner'];
    // a deterministic pseudo-random number in [0, n) for row i and a salt: row i always reads the same
    const pick = (i, salt, n) => {
      let h = Math.imul(i + 1, 0x9e3779b1) ^ Math.imul(salt + 1, 0x85ebca6b);
      h = Math.imul(h ^ (h >>> 15), 0x2c1b3c6d);
      h = Math.imul(h ^ (h >>> 12), 0x297a2d39);
      return ((h ^ (h >>> 15)) >>> 0) % n;
    };
    // synthetic sales: the larger markets sell more, partners in bulk, online returns more
    const sales = Array.from({ length: 200_000 }, (_, i) => {
      const place = places[Math.min(pick(i, 1, places.length), pick(i, 2, places.length))];
      const channel = channels[pick(i, 3, 3)];
      const units = 1 + pick(i, 4, channel === 'Partner' ? 12 : 4);
      return {
        ...place,
        channel,
        year: 2024 + pick(i, 5, 2),
        units,
        revenue: Math.round(units * (9 + pick(i, 6, 12_000) / 100) * 100) / 100,
        returned: pick(i, 7, channel === 'Online' ? 12 : 30) === 0,
      };
    });
    const source = createImmutableArraySource(sales);

    // the measures every level shares; the levels differ in their groupBy only
    const q = forRows();
    const measures = {
      orders: q.count(),
      units: q.sum(q.field('units')),
      revenue: q.sum(q.field('revenue')),
      average: q.avg(q.field('revenue')),
      returns: q.count(undefined, { where: q.field('returned') }),
    };
    const levels = [['region'], ['region', 'country'], ['region', 'country', 'channel']];
    const plansFor = (year) =>
      levels.map((keys) =>
        q.aggregate({
          ...(year ? { where: q.eq(q.field('year'), q.literal(Number(year))) } : {}),
          groupBy: Object.fromEntries(keys.map((k) => [k, q.field(k)])),
          measures,
        }),
      );

    const grid = document.getElementById('tg-sales');
    const year = document.getElementById('tg-sales-year');
    const line = document.getElementById('tg-sales-line');
    let run = 0;
    const update = async () => {
      const mine = ++run;
      const started = performance.now();
      const results = await Promise.all(plansFor(year.value).map((plan) => plan.evaluate(source)));
      if (mine !== run) return;
      // a group's path is its id, the path without its last key its parent: the tree links itself
      const rows = results.flatMap(({ rows }, depth) =>
        rows.map((group) => {
          const path = levels[depth].map((k) => group[k]);
          return {
            id: path.join('/'),
            parentId: depth ? path.slice(0, -1).join('/') : null,
            name: path[depth],
            orders: group.orders,
            units: group.units,
            revenue: group.revenue,
            average: group.average,
            returns: group.returns,
          };
        }),
      );
      df$.shadcn.dataGrid.setSource(grid, rows);
      const total = results[0].rows.reduce((n, r) => n + r.orders, 0);
      line.textContent =
        rows.length +
        ' groups from ' +
        total.toLocaleString('en') +
        ' sales · ' +
        Math.round(performance.now() - started) +
        ' ms';
    };
    year.addEventListener('change', update);
    update();
  });
</script>
```

```html example label="Driven through the store" schema="none" hint="Open branches are config.expanded - plain JSON in the grid's store. The list below subscribes to it; the buttons only write it."
<div class="flex flex-col gap-3" style="max-width: 36rem">
  <div class="flex flex-wrap gap-2">
    <button class="btn" data-variant="outline" data-size="sm" type="button" data-open="src">Open src</button>
    <button class="btn" data-variant="outline" data-size="sm" type="button" data-open="src,src/components"
      >Open src/components</button
    >
    <button class="btn" data-variant="ghost" data-size="sm" type="button" data-open="">Close all</button>
  </div>
  <div class="data-grid" id="tg-files" aria-label="Repository" data-parent-field="parentId" style="height: 16rem">
    <div class="data-grid-viewport">
      <div class="data-grid-head">
        <div class="data-grid-row">
          <div class="data-grid-header" data-field="name" data-width="minmax(12rem, 1fr)">Path</div>
          <div class="data-grid-header" data-field="size" data-type="number" data-width="7rem">Bytes</div>
        </div>
      </div>
      <div class="data-grid-body"></div>
    </div>
  </div>
  <p class="text-sm text-muted-foreground m-0" id="tg-files-open" aria-live="polite"></p>
</div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const files = [
      { id: 'src', parentId: null, name: 'src', size: 0 },
      { id: 'src/components', parentId: 'src', name: 'components', size: 0 },
      { id: 'src/shared', parentId: 'src', name: 'shared', size: 0 },
      { id: 'tests', parentId: null, name: 'tests', size: 0 },
      { id: 'README.md', parentId: null, name: 'README.md', size: 18_204 },
    ];
    ['accordion', 'button', 'data-grid', 'data-tree', 'dialog', 'virtual-list'].forEach((n, i) =>
      files.push({ id: 'src/components/' + n, parentId: 'src/components', name: n + '.ts', size: 2000 + i * 1733 }),
    );
    ['store.ts', 'dataview.ts', 'virtual.ts'].forEach((n, i) =>
      files.push({ id: 'src/shared/' + n, parentId: 'src/shared', name: n, size: 3000 + i * 911 }),
    );
    ['ui.test.ts', 'store.test.ts'].forEach((n, i) =>
      files.push({ id: 'tests/' + n, parentId: 'tests', name: n, size: 9000 + i * 4096 }),
    );
    const grid = document.getElementById('tg-files');
    const { dataGrid } = df$.shadcn;
    dataGrid.setSource(grid, files);
    document
      .querySelectorAll('[data-open]')
      .forEach((button) =>
        button.addEventListener('click', () =>
          dataGrid.query(grid, { expanded: button.dataset.open ? button.dataset.open.split(',') : [] }),
        ),
      );
    const line = document.getElementById('tg-files-open');
    grid.store.subscribe(
      ({ config }) => {
        line.textContent = 'expanded: ' + (config.expanded.length ? config.expanded.join(', ') : 'nothing');
      },
      { immediate: true },
    );
  });
</script>
```

<H2 id="how">How it works</H2>

<DocText>The tree grid IS the <a class="link" href="data-grid.html">Data Grid</a> - same component, same files, same State API (see its page for every attribute and state). <code>data-parent-field</code> (and <code>data-id-field</code>, default <code>id</code>) switch on the hierarchy:</DocText>

<ul class="text-sm text-muted-foreground mb-5 ps-5">
  <li><code>role="treegrid"</code>; each row carries <code>aria-level</code> and, with children, <code>aria-expanded</code>.</li>
  <li>The config gains <code>expanded</code> (the open branch ids) and, while a filter is active, <code>collapsed</code> (branches closed again - a filter opens every branch that holds a match).</li>
  <li>Sorting orders siblings; the hierarchy never breaks. A filter's matches keep their ancestors, and the status line counts both (<em>"12 rows shown · 10 of 11,020 match"</em>).</li>
  <li>Keyboard on the first column: Right Arrow opens a branch, Left Arrow closes it or moves to the parent. <code>df$.shadcn.dataGrid.expandAll(grid)</code> / <code>collapseAll(grid)</code> open or close everything.</li>
</ul>

<SourceFiles component="data-grid" section="css">
  <SourceNote for="css">The tree grid is the Data Grid: the same stylesheet - the first column's indentation and toggle are its <code>.data-grid-toggle</code> rules.</SourceNote>
</SourceFiles>

<SourceFiles component="data-grid" section="js" jsTitle="JS" />

</DocPage>
