# Tree Table

> A hierarchical native table with collapsible branches, inherited selection, and mixed parent checkboxes.

- Kind: ui · Category: Data display · Interactivity: script
- Install: `npx shadcn@latest add @haze/tree-table`
- File: `src/components/haze/ui/tree-table.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/tree-table

## Use when
- A file listing needs names and sizes alongside a nested hierarchy.
- Selecting a folder should include its descendant files.

## Avoid when
- The listing is flat and needs many sortable fields. Use sortable-data-table.

## Alternatives
- [file-tree](https://hazeui.com/ui/file-tree.md)
- [sortable-data-table](https://hazeui.com/ui/sortable-data-table.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique table ID. |
| caption | `string` |  | no | Visible and accessible table name. |
| nodes | `{ label: string; value?: string; children?: TreeNode[] }[]` |  | no | Hierarchical names and secondary values in display order. |
| class | `string` |  | no | Additional classes on the component wrapper. |

## Accessibility
- The native table remains fully expanded without scripts. Collapsing a branch hides its descendants while retaining their selection.
- Checkbox changes propagate downward and mixed states recompute upward. Branch controls support Arrow keys, and captions name the scrollable table.
- Key Arrow Right / Left: Expand a branch, move toward its children, collapse it or focus its parent.
- Key Arrow Up / Down: Move between visible expandable branches.

## Agent prompts

### Install and use

Install the Haze UI component "Tree Table" with `npx shadcn@latest add @haze/tree-table`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import TreeTable from "@/components/haze/ui/tree-table.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/tree-table.md

### Customize with real content

Adapt the Haze tree-table ui for our product. Replace the demo values of these props with our real content: id, caption, nodes, class. Keep the layout, the heading level rules and these accessibility details: The native table remains fully expanded without scripts. Collapsing a branch hides its descendants while retaining their selection. Checkbox changes propagate downward and mixed states recompute upward. Branch controls support Arrow keys, and captions name the scrollable table. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using tree-table, check it fits: use it when a file listing needs names and sizes alongside a nested hierarchy.; selecting a folder should include its descendant files.. Avoid it when the listing is flat and needs many sortable fields. use sortable-data-table.. Alternatives: @haze/file-tree, @haze/sortable-data-table.

## Example requests that should lead here
- Show workspace files in a nested size table with folder selection and mixed parent states.

## Source

```astro
---
import { Check, ChevronRight, Minus } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface TreeNode { label: string; value?: string; children?: TreeNode[] }
interface Props { id: string; caption?: string; nodes?: TreeNode[]; class?: string }
const { id, caption = "Workspace files", class: className, nodes = [
  { label: "Design", value: "4.2 MB", children: [{ label: "Overview.fig", value: "2.8 MB" }, { label: "Components.fig", value: "1.4 MB" }] },
  { label: "Notes", value: "12 KB", children: [{ label: "Release.md", value: "8 KB" }, { label: "Review.md", value: "4 KB" }] },
  { label: "Readme.md", value: "2 KB" },
] } = Astro.props;
const flatten = (items: TreeNode[], parent = "", level = 1): { node: TreeNode; key: string; parent: string; level: number }[] =>
  items.flatMap((node, index) => { const key = parent ? `${parent}-${index}` : String(index); return [{ node, key, parent, level }, ...flatten(node.children ?? [], key, level + 1)]; });
const rows = flatten(nodes);
---
<div data-haze-tree-table class={cn("group/tree min-w-0 overflow-hidden rounded-xl border border-border bg-card", className)}>
  <div role="region" aria-label={caption} tabindex="0" class="max-h-[30rem] min-w-0 overflow-auto focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring">
    <table id={id} class="w-full border-collapse text-left text-[0.8125rem]/5 tracking-[-0.01em]">
      <caption class="border-b border-border px-4 py-3 text-start text-[0.8125rem]/5 font-medium">{caption}</caption>
      <thead><tr class="border-b border-border text-muted-foreground"><th scope="col" class="h-11 px-4 font-medium">Name</th><th scope="col" class="h-11 px-4 text-end font-medium">Size</th></tr></thead>
      <tbody>
        {rows.map(({ node, key, parent, level }) => <tr data-tree-row data-key={key} data-parent={parent} data-level={level} class="border-t border-border first:border-t-0 hover:bg-accent has-checked:bg-muted motion-safe:transition-colors motion-safe:duration-150 motion-safe:ease-snappy [&[hidden]]:hidden">
          <th scope="row" class="h-13 px-4 font-normal">
            <div style={`padding-inline-start:${Math.min(level - 1, 12) * 14}px`} class="flex min-w-0 items-center gap-1.5">
              <span class="relative inline-grid size-4.5 shrink-0 place-items-center"><input data-tree-select type="checkbox" aria-label={`Select ${node.label}`} class="peer col-start-1 row-start-1 size-4.5 cursor-pointer appearance-none rounded-sm border border-border-strong bg-field transition-[background-color,border-color,scale] duration-150 ease-snappy hover:border-foreground active:scale-90 active:duration-75 checked:border-primary checked:hover:border-primary checked:bg-primary indeterminate:border-primary indeterminate:bg-primary focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring disabled:cursor-not-allowed forced-colors:appearance-auto" /><Check class="pointer-events-none col-start-1 row-start-1 size-3.5 scale-50 text-primary-foreground opacity-0 transition-[opacity,scale] duration-200 ease-spring forced-colors:hidden peer-checked:scale-100 peer-checked:opacity-100 peer-indeterminate:opacity-0" stroke-width={3} aria-hidden="true" /><Minus class="pointer-events-none col-start-1 row-start-1 size-3.5 scale-50 text-primary-foreground opacity-0 transition-[opacity,scale] duration-200 ease-spring forced-colors:hidden peer-indeterminate:scale-100 peer-indeterminate:opacity-100" stroke-width={3} aria-hidden="true" /></span>
              <button data-tree-toggle type="button" aria-expanded={node.children?.length ? "true" : undefined} aria-label={`${node.children?.length ? "Collapse" : "Open"} ${node.label}`} disabled={!node.children?.length}
                class="group/branch flex min-h-7 cursor-pointer items-center gap-1.5 rounded-md text-start disabled:cursor-default focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring">
                {node.children?.length ? <ChevronRight aria-hidden="true" class="size-3 shrink-0 rotate-90 text-muted-foreground motion-safe:transition-[rotate] motion-safe:duration-200 motion-safe:ease-spring group-aria-[expanded=false]/branch:rotate-0" /> : <span class="w-3 shrink-0"></span>}
                <span class="min-w-20">{node.label}</span>
              </button>
            </div>
          </th>
          <td class="px-4 text-end tabular-nums whitespace-nowrap text-muted-foreground">{node.value ?? "—"}</td>
        </tr>)}
      </tbody>
    </table>
  </div>
  <p data-tree-status role="status" class="border-t border-border px-4 py-2 text-[0.8125rem]/5 text-muted-foreground">{rows.length} files and folders</p>
</div>
<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const rows = [...root.querySelectorAll<HTMLTableRowElement>("[data-tree-row]")];
    const status = root.querySelector<HTMLElement>("[data-tree-status]")!;
    const byKey = new Map(rows.map(row => [row.dataset.key!, row]));
    const descendants = (row: HTMLTableRowElement) => rows.filter(item => item !== row && item.dataset.key!.startsWith(`${row.dataset.key}-`));
    const syncVisibility = () => rows.forEach(row => {
      let parent = byKey.get(row.dataset.parent ?? "");
      row.hidden = false;
      while (parent) {
        if (parent.querySelector("[data-tree-toggle]")?.getAttribute("aria-expanded") === "false") { row.hidden = true; break; }
        parent = byKey.get(parent.dataset.parent ?? "");
      }
    });
    rows.forEach(row => {
      const toggle = row.querySelector<HTMLButtonElement>("[data-tree-toggle]")!;
      const box = row.querySelector<HTMLInputElement>("[data-tree-select]")!;
      toggle.addEventListener("click", () => {
        const opening = toggle.getAttribute("aria-expanded") === "false";
        toggle.setAttribute("aria-expanded", String(opening));
        toggle.setAttribute("aria-label", `${opening ? "Collapse" : "Expand"} ${toggle.textContent?.trim()}`);
        syncVisibility();
        status.textContent = `${rows.filter(item => !item.hidden).length} visible files and folders`;
      });
      box.addEventListener("change", () => {
        descendants(row).forEach(child => { const input = child.querySelector<HTMLInputElement>("[data-tree-select]")!; input.checked = box.checked; input.indeterminate = false; });
        [...rows].reverse().forEach(parent => {
          const children = rows.filter(child => child.dataset.parent === parent.dataset.key);
          if (!children.length) return;
          const input = parent.querySelector<HTMLInputElement>("[data-tree-select]")!;
          const checks = children.map(child => child.querySelector<HTMLInputElement>("[data-tree-select]")!);
          input.checked = checks.every(check => check.checked);
          input.indeterminate = !input.checked && checks.some(check => check.checked || check.indeterminate);
        });
        status.textContent = `${rows.filter(item => item.querySelector<HTMLInputElement>("[data-tree-select]")!.checked).length} selected`;
      });
      row.addEventListener("keydown", event => {
        if (!(event.target instanceof HTMLButtonElement)) return;
        const visible = rows.filter(item => !item.hidden), index = visible.indexOf(row);
        const focusRow = (target?: HTMLTableRowElement) => target?.querySelector<HTMLButtonElement>("[data-tree-toggle]:not(:disabled)")?.focus();
        if (event.key === "ArrowLeft") { event.preventDefault(); if (toggle.getAttribute("aria-expanded") === "true") toggle.click(); else focusRow(byKey.get(row.dataset.parent ?? "")); }
        else if (event.key === "ArrowRight" && toggle.hasAttribute("aria-expanded")) { event.preventDefault(); if (toggle.getAttribute("aria-expanded") === "false") toggle.click(); else focusRow(visible[index + 1]); }
        else if (event.key === "ArrowDown" || event.key === "ArrowUp") {
          event.preventDefault();
          const direction = event.key === "ArrowDown" ? 1 : -1;
          const next = visible.slice(direction === 1 ? index + 1 : 0, direction === 1 ? undefined : index);
          if (direction < 0) next.reverse();
          focusRow(next.find(item => !item.querySelector<HTMLButtonElement>("[data-tree-toggle]")!.disabled));
        }
      });
    });
    root.setAttribute("data-enhanced", "");
  }
  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-tree-table]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-tree-table-listener")) {
    document.documentElement.setAttribute("data-haze-tree-table-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
