---
title: "Data Tree"
description: "Data Tree component - a windowed ARIA tree over hundreds of thousands of flat records: expand and collapse, filter with the path to every match kept, sort siblings, keyboard per the APG tree pattern; the query is the tree's store, kept for the session (or longer, per instance)."
slug: "data-tree"
---

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, ApiSection } from "../../lib/components/index";

<DocPage meta={meta}>

<PageHeader slug="data-tree" title="Data Tree" component="data-tree">
  A tree too big to write as markup. The records are one flat array - each names its parent - and <a class="link" href="https://www.npmjs.com/package/defuss-dataview">defuss-dataview</a> turns them into what is visible: open branches, sorted siblings, and for a filter every match with the path that leads to it. Only the items on screen exist in the DOM; focus stays on the tree and screen readers still hear "level 3, 42 of 100". For a small tree written as markup, use <a class="link" href="tree-view.html">Tree View</a>; for columns, the <a class="link" href="tree-grid.html">Tree Grid</a>.
</PageHeader>

<SkillPanel component="data-tree">
  <SkillField label="Native basis">
<SkillText>A focusable scroll container with <code>role="tree"</code>: a sizer gives the scrollbar the length of every visible node, a pool of recycled <code>treeitem</code>s rides inside it, <code>aria-activedescendant</code> names the active one. <code>df$.shadcn.dataTree.setSource(el, records)</code> hands it the data.</SkillText>
  </SkillField>

  <SkillField label="Web Platform APIs">
<SkillRow>
    <ApiPill href="https://www.w3.org/WAI/ARIA/apg/patterns/treeview/" title="levels, set sizes, positions on recycled items"><code>ARIA tree</code></ApiPill>
    <ApiPill href="https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-anchor" title="the runtime owns the scroll position"><code>overflow-anchor: none</code></ApiPill>
    <ApiPill href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-activedescendant" title="focus stays on the tree"><code>aria-activedescendant</code></ApiPill>
    <ApiPill href="https://developer.mozilla.org/en-US/docs/Web/CSS/contain" title="paint and layout stay inside"><code>contain: strict</code></ApiPill>
    <ApiPill href="https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver" title="the window follows the height"><code>ResizeObserver</code></ApiPill>
  </SkillRow>
  </SkillField>

  <SkillField label="Classes">
<SkillRow>
    <code>.data-tree</code>
    <code>.data-tree-sizer</code>
    <code>.data-tree-items</code>
    <code>.data-tree-item</code>
    <code>.data-tree-toggle</code>
    <code>.data-tree-label</code>
    <code>.data-tree-meta</code>
  </SkillRow>
  </SkillField>

  <SkillField label="Data attributes">
<SkillText><code>data-label-field</code>, <code>data-id-field</code>, <code>data-parent-field</code>, <code>data-persist</code> / <code>data-persist-prefix</code> / <code>data-persist-key</code>, <code>data-empty-text</code>, <code>data-drag</code> / <code>data-drop</code> (<code>move</code> · <code>copy</code>); <code>data-tree-filter="tree-id"</code> on any input; <code>--data-tree-row-height</code>, <code>--data-tree-indent</code>.</SkillText>
  </SkillField>
</SkillPanel>

```html example label="Custom labels and a kept view" schema="none" hint="render(label, record, meta) fills each label - an icon, the name, a size. The open branches, the filters, the sort and the selection are kept: in session storage by default, here in local storage under its own key (data-persist='local', data-persist-key) - on your page they survive a reload and the next visit (this sandboxed example has no storage)."
<div
  class="data-tree"
  id="dt-files"
  aria-label="Project files"
  data-persist="local"
  data-persist-key="docs:project-files"
  style="height: 16rem; max-width: 26rem; --data-tree-row-height: 30px"
></div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const files = [
      { id: 'src', parentId: null, name: 'src' },
      { id: 'src/components', parentId: 'src', name: 'components' },
      { id: 'src/shared', parentId: 'src', name: 'shared' },
      { id: 'docs', parentId: null, name: 'docs' },
      { id: 'package.json', parentId: null, name: 'package.json', size: 2.1 },
    ];
    ['accordion', 'data-grid', 'data-tree', 'dialog', 'toast', 'virtual-list'].forEach((n, i) =>
      files.push({ id: 'src/components/' + n, parentId: 'src/components', name: n + '.ts', size: 4 + i * 3.5 }),
    );
    ['store.ts', 'dataview.ts', 'virtual.ts'].forEach((n, i) =>
      files.push({ id: 'src/shared/' + n, parentId: 'src/shared', name: n, size: 3 + i * 2 }),
    );
    ['index.html', 'data-grid.html'].forEach((n, i) =>
      files.push({ id: 'docs/' + n, parentId: 'docs', name: n, size: 40 + i * 12 }),
    );
    df$.shadcn.dataTree.setSource(document.getElementById('dt-files'), files, {
      render: (label, file, meta) => {
        const icon = document.createElement('i');
        icon.dataset.lucide = meta.hasChildren ? (meta.isExpanded ? 'folder-open' : 'folder') : 'file';
        icon.style.width = '1rem';
        icon.style.height = '1rem';
        const name = document.createElement('span');
        name.textContent = file.name;
        label.append(icon, name);
        if (file.size) {
          const size = document.createElement('span');
          size.className = 'data-tree-meta';
          size.textContent = file.size.toFixed(1) + ' KB';
          label.append(size);
        }
        globalThis.lucide?.createIcons({ root: label });
      },
    });
  });
</script>
```

```html example label="Custom editors" schema="none" hint="getEditorFn(field, value, ctx) hands the tree any editor: an element, or { el, getValue, validate?, focus?, immediate?, patch? }. Here a label edits as its name and its colour together - an Input and a row of colour swatches (radio buttons) in one editor; getValue() returns the name, patch() the colour, and both are written in one edit. render() draws the colour dot. Return false to keep an item from editing: the system labels Inbox and Sent stay as they are."
<div
  class="data-tree"
  id="dt-labels"
  aria-label="Labels"
  data-editable
  data-required
  style="height: 15rem; max-width: 26rem"
></div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const colors = {
      slate: 'oklch(0.55 0.03 260)',
      blue: 'oklch(0.6 0.16 250)',
      green: 'oklch(0.62 0.15 150)',
      amber: 'oklch(0.75 0.15 75)',
      red: 'oklch(0.6 0.2 25)',
    };
    const labels = [
      { id: 'inbox', parentId: null, name: 'Inbox', color: 'slate', system: true },
      { id: 'sent', parentId: null, name: 'Sent', color: 'slate', system: true },
      { id: 'work', parentId: null, name: 'Work', color: 'blue' },
      { id: 'work/clients', parentId: 'work', name: 'Clients', color: 'green' },
      { id: 'work/invoices', parentId: 'work', name: 'Invoices', color: 'amber' },
      { id: 'home', parentId: null, name: 'Home', color: 'red' },
      { id: 'home/travel', parentId: 'home', name: 'Travel', color: 'green' },
    ];
    // a record's editor: the name in an Input, the colour as radio swatches
    const labelEditor = (record) => {
      const el = document.createElement('span');
      el.style.cssText = 'display: flex; align-items: center; gap: 0.375rem; flex: 1; min-width: 0';
      const input = document.createElement('input');
      input.className = 'input';
      input.dataset.size = 'xs';
      input.value = record.name;
      input.setAttribute('aria-label', 'Label name');
      const swatches = document.createElement('span');
      swatches.setAttribute('role', 'radiogroup');
      swatches.setAttribute('aria-label', 'Colour');
      swatches.style.cssText = 'display: flex; gap: 0.25rem';
      const name = 'color-' + record.id.replace(/\W/g, '');
      for (const [key, value] of Object.entries(colors)) {
        const radio = document.createElement('input');
        radio.type = 'radio';
        radio.name = name;
        radio.value = key;
        radio.checked = key === record.color;
        radio.setAttribute('aria-label', key);
        radio.style.cssText =
          'appearance: none; margin: 0; width: 1rem; height: 1rem; border-radius: 50%; cursor: pointer; background: ' +
          value +
          '; outline-offset: 1px';
        radio.addEventListener('change', () => input.focus());
        swatches.append(radio);
      }
      const mark = () =>
        swatches
          .querySelectorAll('input')
          .forEach((r) => (r.style.outline = r.checked ? '2px solid var(--ring)' : 'none'));
      swatches.addEventListener('change', mark);
      mark();
      el.append(input, swatches);
      return {
        el,
        getValue: () => input.value.trim(),
        patch: () => ({ color: swatches.querySelector('input:checked')?.value ?? record.color }),
        focus: () => input.focus(),
      };
    };
    df$.shadcn.dataTree.setSource(document.getElementById('dt-labels'), labels, {
      query: { expanded: ['work', 'home'] },
      render: (label, record) => {
        const dot = document.createElement('span');
        dot.style.cssText =
          'width: 0.625rem; height: 0.625rem; border-radius: 50%; flex: none; background: ' + colors[record.color];
        const name = document.createElement('span');
        name.textContent = record.name;
        label.append(dot, name);
      },
      getEditorFn: (field, value, ctx) => (ctx.record.system ? false : labelEditor(ctx.record)),
    });
  });
</script>
```

```html example label="Inline editing" schema="none" hint="data-editable lets a reader rename an item in place: double-click it, or press F2 on the active item. The editor is the library's Input (data-editor picks another: enum with data-options, number ...); Enter or leaving it writes the name, Escape keeps the old one. data-required, data-max-length and data-pattern refuse a value with a message; validateFn(field, value, ctx) refuses across records - here a name its siblings already use. Every edit replaces the record and runs the query again, so the siblings sort by name (data-sort) and a renamed folder moves among them. The line below listens to data-tree-edit."
<div
  class="data-tree"
  id="dt-rename"
  aria-label="Folders"
  data-editable
  data-required
  data-max-length="40"
  data-pattern="[^/]+"
  data-message="A name without slashes, 1 to 40 characters"
  style="height: 16rem; max-width: 26rem"
></div>
<p class="text-sm" style="margin-block-start: 0.5rem"
  ><output id="dt-rename-log">Double-click a folder, or press F2.</output></p
>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const rows = [];
    let id = 0;
    for (let a = 0; a < 40; a++) {
      const top = ++id;
      rows.push({ id: top, parentId: null, name: 'Project ' + String(a + 1).padStart(2, '0') });
      for (let b = 0; b < 25; b++) {
        const sub = ++id;
        rows.push({
          id: sub,
          parentId: top,
          name: ['Design', 'Docs', 'Research', 'Release', 'Tests'][b % 5] + ' ' + (Math.floor(b / 5) + 1),
        });
        for (let c = 0; c < 10; c++) rows.push({ id: ++id, parentId: sub, name: 'Note ' + (c + 1) });
      }
    }
    const tree = document.getElementById('dt-rename');
    df$.shadcn.dataTree.setSource(tree, rows, {
      query: { sorters: [{ field: 'name', direction: 'asc' }], expanded: [1] },
      validateFn: (field, value, ctx) => {
        const siblings = df$.shadcn.dataTree
          .source(tree)
          .rows.filter((r) => r.parentId === ctx.record.parentId && r.id !== ctx.record.id);
        if (siblings.some((r) => r.name.toLowerCase() === String(value).toLowerCase()))
          return 'Another item here is called ' + value;
      },
    });
    tree.addEventListener('data-tree-edit', (e) => {
      document.getElementById('dt-rename-log').textContent = e.detail.oldValue + ' is now ' + e.detail.value;
    });
  });
</script>
```

```html example label="Drag and drop between trees" schema="none" hint="data-drag lets items drag out - each with everything under it - and data-drop lets records drop in. Within the Library, drag a song onto another genre: the middle of an item drops into it (it opens), its top or bottom edge before or after it. Drag a genre or a song into the Playlist: the Playlist takes copies only (data-drop='copy'), so the Library keeps it and the copies get ids of their own. From the Playlist back into the Library a drag moves; hold Alt (Option) or Ctrl to copy. A move into its own subtree goes nowhere. The line below follows data-tree-drop."
<div class="grid gap-3" style="grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr))">
  <div
    class="data-tree"
    id="dt-library"
    aria-label="Library"
    data-drag
    data-drop
    data-persist="none"
    style="height: 16rem"
  ></div>
  <div
    class="data-tree"
    id="dt-playlist"
    aria-label="Playlist"
    data-drag
    data-drop="copy"
    data-persist="none"
    style="height: 16rem"
  ></div>
</div>
<p class="text-sm" style="margin-block-start: 0.5rem"
  ><output id="dt-dnd-log">Drag an item into the other tree.</output></p
>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const { dataTree } = df$.shadcn;
    const genres = {
      Rock: ['Thunder Road', 'Glass Hearts', 'Neon Rain'],
      Jazz: ['Blue Hour', 'Late Train', 'Brass Moon'],
      Folk: ['River Song', 'Old Pines'],
      Electronic: ['Pulse', 'Afterglow', 'Night Drive'],
    };
    const rows = [];
    for (const [genre, songs] of Object.entries(genres)) {
      rows.push({ id: genre, parentId: null, name: genre });
      for (const song of songs) rows.push({ id: genre + '/' + song, parentId: genre, name: song });
    }
    const library = document.getElementById('dt-library');
    const playlist = document.getElementById('dt-playlist');
    dataTree.setSource(library, rows, { query: { expanded: ['Rock', 'Jazz'] } });
    dataTree.setSource(
      playlist,
      [
        { id: 'focus', parentId: null, name: 'Focus' },
        { id: 'focus/Blue Hour', parentId: 'focus', name: 'Blue Hour' },
        { id: 'road', parentId: null, name: 'Road trip' },
      ],
      { query: { expanded: ['focus'] } },
    );
    for (const tree of [library, playlist])
      tree.addEventListener('data-tree-drop', (e) => {
        const { records, effect, at } = e.detail;
        const name = records[0].name + (records.length > 1 ? ' (+' + (records.length - 1) + ')' : '');
        const where = at.place === 'into' ? ' into ' + dataTree.source(tree).rows.find((r) => r.id === at.id).name : '';
        log(effect === 'copy' ? 'Copied ' : 'Moved ', name, where, tree);
      });
    function log(verb, name, where, tree) {
      document.getElementById('dt-dnd-log').textContent =
        verb + name + where + ' (' + tree.getAttribute('aria-label') + ').';
    }
  });
</script>
```

```html example label="111,110 nodes" hint="Ten regions × ten countries × a hundred cities × ten districts. Open branches with the chevrons or the keyboard (↑ ↓ → ← Home End, Enter selects, * opens every sibling). The input is bound by data-tree-filter: type 'district 7.3.4' - every match shows with the path to it opened, the first match becomes active. The line below subscribes to the tree's store."
<div class="flex flex-col gap-2" style="max-width: 26rem">
  <input class="input" data-tree-filter="dt-geo" aria-label="Filter places" placeholder="Filter places…" />
  <div
    class="data-tree"
    id="dt-geo"
    aria-label="Places"
    data-empty-text="No place matches."
    style="height: 20rem"
  ></div>
  <p class="text-sm text-muted-foreground m-0" id="dt-geo-line" aria-live="polite"></p>
</div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    // one flat array: every record names its parent (null = a root)
    const rows = [];
    let id = 0;
    for (let a = 1; a <= 10; a++) {
      const region = ++id;
      rows.push({ id: region, parentId: null, name: 'Region ' + a });
      for (let b = 1; b <= 10; b++) {
        const country = ++id;
        rows.push({ id: country, parentId: region, name: 'Country ' + a + '.' + b });
        for (let c = 1; c <= 100; c++) {
          const city = ++id;
          rows.push({ id: city, parentId: country, name: 'City ' + a + '.' + b + '.' + c });
          for (let d = 1; d <= 10; d++)
            rows.push({ id: ++id, parentId: city, name: 'District ' + a + '.' + b + '.' + c + '.' + d });
        }
      }
    }
    const tree = document.getElementById('dt-geo');
    df$.shadcn.dataTree.setSource(tree, rows);
    const line = document.getElementById('dt-geo-line');
    tree.store.subscribe(
      ({ config }) => {
        const picked = df$.shadcn.dataTree.selected(tree);
        line.textContent =
          config.expanded.length + ' open · ' + (picked ? 'selected: ' + picked.name : 'nothing selected');
      },
      { immediate: true },
    );
  });
</script>
```

```html example label="Selection drives a detail pane" schema="none" hint="Selecting (click, Enter, Space) dispatches data-tree-select with the record - here a detail pane follows it. Sorting orders siblings: the select writes config.sorters."
<div class="flex flex-wrap gap-4">
  <div class="flex flex-col gap-2" style="flex: 1; min-width: 14rem">
    <select class="select" aria-label="Sort" id="dt-org-sort">
      <option value="">Org chart order</option>
      <option value="name:asc">Name A–Z</option>
      <option value="reports:desc">Most reports first</option>
    </select>
    <div class="data-tree" id="dt-org" aria-label="Organization" style="height: 16rem"></div>
  </div>
  <div class="card" style="flex: 1; min-width: 12rem">
    <div class="card-header"
      ><h3 class="card-title" id="dt-org-name">Pick someone</h3
      ><p class="card-description" id="dt-org-role">Their role shows here.</p></div
    >
  </div>
</div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const titles = ['VP', 'Director', 'Manager', 'Engineer'];
    const people = [];
    let id = 0;
    const add = (parentId, level) => {
      const me = ++id;
      people.push({ id: me, parentId, name: 'Person ' + me, title: titles[level], reports: 0 });
      if (level < 3) for (let i = 0; i < 4; i++) (people[me - 1].reports++, add(me, level + 1));
    };
    add(null, 0);
    const tree = document.getElementById('dt-org');
    df$.shadcn.dataTree.setSource(tree, people, {
      render: (label, person) => {
        const name = document.createElement('span');
        name.textContent = person.name;
        const title = document.createElement('span');
        title.className = 'data-tree-meta';
        title.textContent = person.title;
        label.append(name, title);
      },
    });
    df$.shadcn.dataTree.query(tree, { expanded: [1] });
    tree.addEventListener('data-tree-select', (e) => {
      document.getElementById('dt-org-name').textContent = e.detail.record.name;
      document.getElementById('dt-org-role').textContent =
        e.detail.record.title + ' · ' + e.detail.record.reports + ' direct reports';
    });
    document.getElementById('dt-org-sort').addEventListener('change', (e) => {
      const [field, direction] = e.target.value.split(':');
      df$.shadcn.dataTree.query(tree, { sorters: field ? [{ field, direction }] : [] });
    });
  });
</script>
```

```html example label="One open way" schema="none" hint="data-exclusive keeps one way open: open Region 3, then Region 5 - Region 3 closes with everything below it. The field picks a district somewhere else; reveal() opens only the way to it, selects it and scrolls it into view."
<div class="flex flex-col gap-2" style="max-width: 26rem">
  <form class="flex gap-2" id="dt-way-form">
    <input class="input" id="dt-way-input" aria-label="A district" value="District 7.4.61.3" />
    <button class="btn" data-variant="outline" type="submit">Reveal</button>
  </form>
  <div
    class="data-tree"
    id="dt-way"
    aria-label="Places, one way open"
    data-exclusive
    data-persist="none"
    style="height: 16rem"
  ></div>
  <p class="text-sm text-muted-foreground m-0" id="dt-way-line" aria-live="polite"></p>
</div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const rows = [];
    let id = 0;
    for (let a = 1; a <= 10; a++) {
      const region = ++id;
      rows.push({ id: region, parentId: null, name: 'Region ' + a });
      for (let b = 1; b <= 10; b++) {
        const country = ++id;
        rows.push({ id: country, parentId: region, name: 'Country ' + a + '.' + b });
        for (let c = 1; c <= 100; c++) {
          const city = ++id;
          rows.push({ id: city, parentId: country, name: 'City ' + a + '.' + b + '.' + c });
          for (let d = 1; d <= 10; d++)
            rows.push({ id: ++id, parentId: city, name: 'District ' + a + '.' + b + '.' + c + '.' + d });
        }
      }
    }
    const tree = document.getElementById('dt-way');
    df$.shadcn.dataTree.setSource(tree, rows);
    const line = document.getElementById('dt-way-line');
    tree.store.subscribe(({ config }) => (line.textContent = config.expanded.length + ' branches open'), {
      immediate: true,
    });
    document.getElementById('dt-way-form').addEventListener('submit', (e) => {
      e.preventDefault();
      const name = document.getElementById('dt-way-input').value.trim();
      const row = rows.find((r) => r.name === name);
      if (!row || !df$.shadcn.dataTree.reveal(tree, row.id)) line.textContent = 'No place is called ' + name;
    });
  });
</script>
```

```html example label="Aggregated branches: 250,000 requests" schema="none" hint="Each node is a group of request log lines - service, then endpoint, then outcome - measured by an aggregate plan per level: the requests, the average and slowest latency and the errors (a count with a where). Its label shows them, the error share computed from two measures. Turn on Only slow requests: the plans run again with a where (latency > 800 ms) and the open branches stay open."
<div class="flex flex-col gap-2" style="max-width: 34rem">
  <div class="flex flex-wrap items-center gap-3">
    <div class="switch-item flex items-center gap-2">
      <input class="switch" type="checkbox" role="switch" id="dt-requests-slow" />
      <label for="dt-requests-slow">Only slow requests</label>
    </div>
    <output class="text-sm text-muted-foreground" id="dt-requests-line" aria-live="polite"
      >Aggregating 250,000 requests…</output
    >
  </div>
  <div class="data-tree" id="dt-requests" aria-label="Requests by service" style="height: 18rem"></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 services = {
      checkout: ['POST /orders', 'GET /orders/:id', 'POST /payments', 'GET /cart'],
      catalog: ['GET /products', 'GET /products/:id', 'GET /search', 'GET /categories'],
      accounts: ['POST /login', 'GET /me', 'PUT /me', 'POST /logout'],
      shipping: ['GET /rates', 'POST /labels', 'GET /tracking/:id'],
    };
    const routes = Object.entries(services).flatMap(([service, list]) =>
      list.map((endpoint) => ({ service, endpoint })),
    );
    // 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 log lines: each endpoint with its own traffic, speed and error rate
    const requests = Array.from({ length: 250_000 }, (_, i) => {
      const r = Math.min(pick(i, 1, routes.length), pick(i, 2, routes.length));
      const roll = pick(i, 3, 20 + 9 * (r % 6));
      const outcome = roll === 0 ? 'server error' : roll < 3 ? 'client error' : 'ok';
      return {
        ...routes[r],
        outcome,
        latency: 15 + 30 * (r % 5) + pick(i, 4, 300 + 120 * (r % 4)) + (outcome === 'server error' ? 500 : 0),
      };
    });
    const source = createImmutableArraySource(requests);

    const q = forRows();
    const failed = q.neq(q.field('outcome'), q.literal('ok'));
    const levels = [['service'], ['service', 'endpoint'], ['service', 'endpoint', 'outcome']];
    const plansFor = (slow) =>
      levels.map((keys) =>
        q.aggregate({
          ...(slow ? { where: q.gt(q.field('latency'), q.literal(800)) } : {}),
          groupBy: Object.fromEntries(keys.map((k) => [k, q.field(k)])),
          measures: {
            requests: q.count(),
            latency: q.avg(q.field('latency')),
            slowest: q.max(q.field('latency')),
            errors: q.count(undefined, { where: failed }),
          },
          orderBy: [{ field: 'requests', direction: 'desc' }],
        }),
      );

    const int = new Intl.NumberFormat('en');
    const pct = new Intl.NumberFormat('en', { style: 'percent', maximumFractionDigits: 1 });
    const tree = document.getElementById('dt-requests');
    const slow = document.getElementById('dt-requests-slow');
    const line = document.getElementById('dt-requests-line');
    const render = (label, node) => {
      const name = document.createElement('span');
      name.textContent = node.name;
      const meta = document.createElement('span');
      meta.className = 'data-tree-meta';
      meta.textContent =
        int.format(node.requests) +
        ' req · ' +
        Math.round(node.latency) +
        ' ms avg · ' +
        (node.depth < 2 ? pct.format(node.errors / node.requests) + ' errors' : int.format(node.slowest) + ' ms max');
      label.append(name, meta);
    };
    let run = 0;
    const update = async () => {
      const mine = ++run;
      const started = performance.now();
      const results = await Promise.all(plansFor(slow.checked).map((plan) => plan.evaluate(source)));
      if (mine !== run) return;
      const nodes = 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],
            depth,
            ...group,
          };
        }),
      );
      df$.shadcn.dataTree.setSource(tree, nodes, { render });
      const total = results[0].rows.reduce((n, r) => n + r.requests, 0);
      line.textContent =
        int.format(total) +
        ' requests in ' +
        nodes.length +
        ' groups · ' +
        Math.round(performance.now() - started) +
        ' ms';
    };
    slow.addEventListener('change', update);
    update();
  });
</script>
```

```html example label="Loading and empty" schema="none" hint="A tree without records waits in 'loading' (placeholder rows, aria-busy); a filter nothing matches lands in 'empty' with data-empty-text."
<div class="flex flex-wrap gap-4">
  <div class="data-tree" aria-label="Waiting for data" style="height: 9rem; flex: 1; min-width: 12rem"></div>
  <div
    class="data-tree"
    id="dt-none"
    aria-label="No matches"
    data-empty-text="Nothing matches 'zebra'."
    style="height: 9rem; flex: 1; min-width: 12rem"
  ></div>
</div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const tree = document.getElementById('dt-none');
    df$.shadcn.dataTree.setSource(tree, [
      { id: 1, parentId: null, name: 'Animals' },
      { id: 2, parentId: 1, name: 'Lion' },
    ]);
    df$.shadcn.dataTree.query(tree, { filters: [{ field: 'name', op: 'contains', value: 'zebra' }] });
  });
</script>
```

<StatesSection>
  <p class="text-sm text-muted-foreground m-0 mb-3">Named states via the shared State API, driven per instance through the bound <code>api</code>; the config of every state is the query (<code>filters</code>, <code>sorters</code>, <code>expanded</code>, <code>collapsed</code>, <code>selected</code>), merged on each <code>setState</code> and observable as <code>el.store</code>:</p>
  <ul class="text-sm text-muted-foreground m-0 mb-3 ps-5">
    <li><code>default</code> - the visible nodes of the query; nothing visible lands in <code>empty</code></li>
    <li><code>loading</code> - <code>aria-busy="true"</code> and placeholder rows; a tree without records starts here</li>
    <li><code>empty</code> - nothing to show: the <code>data-empty-text</code> message</li>
  </ul>
  <p class="text-sm text-muted-foreground">The first example carries <code>data-state-demo</code>; <code>bun run screenshots</code> drives it via <code>el.api.setState(name)</code> and captures <code>screenshots/\{mode\}/data-tree-\{state\}.png</code>.</p>

Machine contract - verified against <a class="link" href="../schemas/data-tree.schema.json"><code>data-tree.schema.json</code></a> by <code>bun run verify</code>:

```states
| State | Type | Values | Default | Description |
| --- | --- | --- | --- | --- |
| `loading` | `boolean` | `true`, `false` | `false` | aria-busy with placeholder rows (`setState('loading')`). |
| `empty` | `boolean` | `true`, `false` | `false` | Nothing to show - shows data-empty-text (`setState('empty')`). |
```

</StatesSection>

<ApiSection component="data-tree" />

<SourceFiles component="data-tree" section="css" />

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

</DocPage>
