Checkbox Tree
Nested checkboxes with expandable groups. A parent shows checked, unchecked or mixed from its descendants and sets them all.
pnpm dlx shadcn@latest add @haze/checkbox-tree---
import { Check, ChevronRight, Minus } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import CheckboxTree from "./checkbox-tree.astro";
export interface CheckboxTreeItem {
id: string;
label: string;
checked?: boolean;
disabled?: boolean;
expanded?: boolean;
children?: CheckboxTreeItem[];
}
interface Props {
id: string;
label?: string;
name?: string;
items?: CheckboxTreeItem[];
nested?: boolean;
class?: string;
}
const demo: CheckboxTreeItem[] = [
{
id: "workspace", label: "Workspace", children: [
{ id: "members", label: "Members", children: [{ id: "members-view", label: "View members", checked: true }, { id: "members-invite", label: "Invite members", checked: true }, { id: "members-remove", label: "Remove members" }] },
{ id: "billing", label: "Billing", expanded: false, children: [{ id: "billing-view", label: "View invoices" }, { id: "billing-edit", label: "Change plan" }] },
{ id: "audit", label: "Read the audit log" },
],
},
{ id: "projects", label: "Projects", children: [{ id: "projects-create", label: "Create projects", checked: true }, { id: "projects-delete", label: "Delete projects", disabled: true }] },
];
const { id, label = "Permissions", name = id, items = demo, nested = false, class: className } = Astro.props;
const leaves = (item: CheckboxTreeItem): CheckboxTreeItem[] => (item.children?.length ? item.children.flatMap(leaves) : [item]);
const checkedState = (item: CheckboxTreeItem) => {
const active = leaves(item).filter(leaf => !leaf.disabled);
return active.length > 0 && active.every(leaf => leaf.checked);
};
const box = "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 disabled:hover:border-border-strong disabled:active:scale-100 forced-colors:appearance-auto";
---
<div id={nested ? undefined : id} data-haze-checkbox-tree={nested ? undefined : ""} role={nested ? undefined : "group"} aria-label={nested ? undefined : label} class={nested ? "contents" : cn("grid min-w-0 max-w-full", className)}>
<ul class="grid gap-0.5">
{items.map(item => (
<li data-tree-item data-expanded={item.children?.length && item.expanded === false ? "false" : undefined}>
{item.children?.length ? (
<>
<div class="flex min-h-8 items-center gap-1">
<button type="button" data-tree-toggle hidden aria-expanded="true" aria-controls={`${id}-${item.id}-children`} aria-label={`Toggle ${item.label}`}
class="group inline-grid size-6 shrink-0 cursor-pointer place-items-center rounded-sm text-muted-foreground transition-[color,scale] duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-90 active:duration-75 [&[hidden]]:hidden">
<ChevronRight aria-hidden="true" class="size-4 transition-[rotate] duration-200 ease-snappy motion-reduce:transition-none group-aria-expanded:rotate-90" />
</button>
<span data-tree-spacer class="size-6 shrink-0 [[data-enhanced]_&]:hidden"></span>
<div class="flex min-w-0 items-center gap-2">
<span class="relative inline-grid size-4.5 shrink-0 place-items-center">
<input id={`${id}-${item.id}`} type="checkbox" data-tree-parent checked={checkedState(item)} class={box} />
<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 peer-checked:scale-100 peer-checked:opacity-100 peer-indeterminate:opacity-0 forced-colors:hidden" 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 peer-indeterminate:scale-100 peer-indeterminate:opacity-100 forced-colors:hidden" stroke-width={3} aria-hidden="true" />
</span>
<label for={`${id}-${item.id}`} class="min-w-0 cursor-pointer text-[0.8125rem]/6 font-medium text-foreground wrap-anywhere">{item.label}</label>
</div>
</div>
<div id={`${id}-${item.id}-children`} class="ms-3 border-s border-border ps-3 [&[hidden]]:hidden">
<CheckboxTree id={id} name={name} items={item.children} nested />
</div>
</>
) : (
<div class="flex min-h-8 items-center gap-1">
<span class="size-6 shrink-0"></span>
<div class="flex min-w-0 items-center gap-2 has-[:disabled]:opacity-50">
<span class="relative inline-grid size-4.5 shrink-0 place-items-center">
<input id={`${id}-${item.id}`} type="checkbox" name={name} value={item.id} data-tree-leaf checked={item.checked} disabled={item.disabled} class={box} />
<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 peer-checked:scale-100 peer-checked:opacity-100 forced-colors:hidden" stroke-width={3} aria-hidden="true" />
</span>
<label for={`${id}-${item.id}`} class="min-w-0 cursor-pointer text-[0.8125rem]/6 text-foreground wrap-anywhere">{item.label}</label>
</div>
</div>
)}
</li>
))}
</ul>
</div>
<script>
function enhance(root: HTMLElement) {
if (root.hasAttribute("data-enhanced")) return;
const leafInputs = (scope: ParentNode) => Array.from(scope.querySelectorAll<HTMLInputElement>("input[data-tree-leaf]:not(:disabled)"));
const sync = () => {
for (const parent of root.querySelectorAll<HTMLInputElement>("input[data-tree-parent]")) {
const leaves = leafInputs(parent.closest("li")!);
const on = leaves.filter(leaf => leaf.checked).length;
parent.checked = leaves.length > 0 && on === leaves.length;
parent.indeterminate = on > 0 && on < leaves.length;
parent.disabled = leaves.length === 0;
}
};
const setExpanded = (item: HTMLElement, open: boolean) => {
const toggle = item.querySelector<HTMLButtonElement>(":scope > div > [data-tree-toggle]");
const panel = item.querySelector<HTMLElement>(":scope > [id$='-children']");
if (!toggle || !panel) return;
toggle.setAttribute("aria-expanded", String(open));
panel.hidden = !open;
};
const visibleInputs = () => Array.from(root.querySelectorAll<HTMLInputElement>("input[type=checkbox]:not(:disabled)")).filter(input => !input.closest("[hidden]"));
root.addEventListener("change", event => {
const input = event.target as HTMLInputElement;
if (input.hasAttribute("data-tree-parent")) {
for (const leaf of leafInputs(input.closest("li")!)) leaf.checked = input.checked;
}
sync();
root.dispatchEvent(new CustomEvent("tree-change", { bubbles: true, detail: { checked: leafInputs(root).filter(leaf => leaf.checked).map(leaf => leaf.value) } }));
});
root.addEventListener("click", event => {
const toggle = (event.target as HTMLElement).closest<HTMLButtonElement>("[data-tree-toggle]");
if (toggle) setExpanded(toggle.closest("li")!, toggle.getAttribute("aria-expanded") !== "true");
});
root.addEventListener("keydown", event => {
const input = event.target as HTMLInputElement;
if (!input.matches?.("input[type=checkbox]")) return;
const list = visibleInputs();
const index = list.indexOf(input);
const item = input.closest("li")!;
const toggle = item.querySelector<HTMLButtonElement>(":scope > div > [data-tree-toggle]");
let target: HTMLElement | undefined;
if (event.key === "ArrowDown") target = list[index + 1];
else if (event.key === "ArrowUp") target = list[index - 1];
else if (event.key === "Home") target = list[0];
else if (event.key === "End") target = list[list.length - 1];
else if (event.key === "ArrowRight" && toggle) {
if (toggle.getAttribute("aria-expanded") === "true") target = list[index + 1];
else setExpanded(item, true);
} else if (event.key === "ArrowLeft") {
if (toggle?.getAttribute("aria-expanded") === "true") setExpanded(item, false);
else target = item.parentElement?.closest<HTMLElement>("li")?.querySelector<HTMLElement>("input[data-tree-parent]") ?? undefined;
} else return;
event.preventDefault();
target?.focus();
});
for (const item of root.querySelectorAll<HTMLElement>("li[data-tree-item]")) {
const toggle = item.querySelector<HTMLButtonElement>(":scope > div > [data-tree-toggle]");
if (!toggle) continue;
toggle.hidden = false;
setExpanded(item, item.dataset.expanded !== "false");
}
sync();
root.closest("form")?.addEventListener("reset", () => setTimeout(sync));
root.setAttribute("data-enhanced", "");
}
const init = () => document.querySelectorAll<HTMLElement>("[data-haze-checkbox-tree]").forEach(enhance);
init();
if (!document.documentElement.hasAttribute("data-haze-checkbox-tree-listener")) {
document.documentElement.setAttribute("data-haze-checkbox-tree-listener", "");
document.addEventListener("astro:page-load", init);
}
</script>When to use
- Permissions, scopes or categories that come in groups with sub-options.
- Choosing a subset of a hierarchy, for example folders to sync.
When not to use
- A flat list; use checkbox.
- Browsing items that are opened rather than selected; use file-tree.
Installation
Add the Haze registry to components.json once, then install Checkbox Tree with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/checkbox-treenpx shadcn@latest add @haze/checkbox-treeyarn dlx shadcn@latest add @haze/checkbox-treebunx --bun shadcn@latest add @haze/checkbox-treeFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique ID for the tree; input IDs derive from it. |
| label | string | Permissions | Accessible name of the group. |
| name | string | id | Form field name shared by the leaf checkboxes, whose value is the item id. Parents are not submitted. |
| items | { id, label, checked?, disabled?, expanded?, children? }[] | – | The tree, to any depth. A demo permissions tree is used when omitted. Leaves hold the checked state; a parent starts checked when all its enabled leaves are. |
| class | string | – | Classes on the wrapper. |
Keyboard interactions
- TabShiftTab
- Move between checkboxes and group toggles.
- Space
- Toggle the focused checkbox.
- Arrow DownArrow Up
- Move to the next or previous visible checkbox.
- Arrow RightArrow Left
- Open a group or enter it; close a group or move to its parent.
- HomeEnd
- First or last visible checkbox.
Accessibility
- Every box is a native checkbox. A parent in the mixed state uses the native indeterminate property, which is exposed as mixed, and shows a minus.
- Toggles are buttons with aria-expanded and aria-controls and appear once scripts run; without scripts every group stays open and leaf checkboxes still submit.
- Disabled leaves keep their state and are skipped when a parent is toggled and when its state is worked out.
- A tree-change event bubbles with the list of checked leaf values.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Checkbox Tree" with `npx shadcn@latest add @haze/checkbox-tree`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/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 CheckboxTree from "@/components/haze/ui/checkbox-tree.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: http://localhost:4329/ui/checkbox-tree.md
Customize with real content
Adapt the Haze checkbox-tree ui for our product. Replace the demo values of these props with our real content: id, label, name, items, class. Keep the layout, the heading level rules and these accessibility details: Every box is a native checkbox. A parent in the mixed state uses the native indeterminate property, which is exposed as mixed, and shows a minus. Toggles are buttons with aria-expanded and aria-controls and appear once scripts run; without scripts every group stays open and leaf checkboxes still submit. Disabled leaves keep their state and are skipped when a parent is toggled and when its state is worked out. A tree-change event bubbles with the list of checked leaf values. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using checkbox-tree, check it fits: use it when permissions, scopes or categories that come in groups with sub-options.; choosing a subset of a hierarchy, for example folders to sync.. Avoid it when a flat list; use checkbox.; browsing items that are opened rather than selected; use file-tree.. Alternatives: @haze/checkbox, @haze/file-tree, @haze/tree-table.
Dependencies
- npm: @lucide/astro
- @haze/checkbox-tree
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.