Skip to content

@viamrobotics/prime-tree

@viamrobotics/prime-tree renders a tree of your own nodes and is headless. The package owns behavior and accessibility, including keyboard navigation, roving focus, selection, and expansion. You own the markup of every row through the node snippet, so the tree draws nothing of its own.

src
main.ts
legacy.ts
package.json
README.md

Expanded: src

Selected: none

  • Keyboard navigation, type-ahead, and roving focus from the WAI-ARIA tree pattern, built on Zag.
  • Single or multiple selection and expansion, each a bindable array of node values.
  • A node snippet that renders every row, so indentation, icons, and hover styles are yours.
  • Row arrangement hooks for virtual lists and empty-branch placeholders.
  1. Install the package and its peers. The svelte peer is ^5.29.0. @viamrobotics/tailwind-config comes with the package as a dependency, and installing it directly as well gives your own classes the same tokens.

    Terminal window
    pnpm add @viamrobotics/prime-tree @viamrobotics/tailwind-config @zag-js/tree-view @zag-js/svelte
  2. Import the package stylesheet once, after Tailwind. Tailwind skips node_modules when it scans for classes, so this file points it at the package’s compiled components and pulls in the @viamrobotics/tailwind-config tokens.

    @import "tailwindcss";
    @import "@viamrobotics/prime-tree/styles.css";
<Tree>
{#snippet node(item, state)}
<Tree.Branch>
<Tree.BranchControl>
<Tree.BranchTrigger>
<Tree.Indicator />
</Tree.BranchTrigger>
</Tree.BranchControl>
<Tree.BranchContent>
<Tree.IndentGuide />
<Tree.Row />
</Tree.BranchContent>
</Tree.Branch>
<Tree.Item />
{/snippet}
</Tree>

nodes holds the root nodes and is the single source of truth. A later change to it flows into the tree without a remount. The accessors tell the tree how to read your node type: nodeToValue returns a unique id, nodeToString returns the label used for type-ahead, and nodeToChildren returns the children. nodeToChildrenCount and isNodeDisabled are optional. Return a number from nodeToChildrenCount for a branch that may be empty, such as an empty folder, so it still renders as a branch, and undefined for a leaf. Any number, including 0, makes the node a branch.

The node snippet receives the node and its TreeNodeState. It runs once per visible node. Return a Tree.Branch for a branch or a Tree.Item for a leaf. Inside a branch, Tree.BranchControl holds the row you see, and Tree.BranchContent renders the children.

A collapsed branch never calls the snippet for its children, and indentation is yours: see Styling for --depth.

package.json
Code
Basic.svelte
<script lang="ts">
import { Tree } from "@viamrobotics/prime-tree";
interface FileNode {
path: string;
name: string;
children?: FileNode[];
}
const files: FileNode[] = [
{
path: "src",
name: "src",
children: [
{ path: "src/index.ts", name: "index.ts" },
{ path: "src/app.svelte", name: "app.svelte" },
],
},
{ path: "package.json", name: "package.json" },
];
</script>
<div class="not-content">
<Tree
nodes={files}
nodeToValue={(file) => file.path}
nodeToString={(file) => file.name}
nodeToChildren={(file) => file.children}
aria-label="Files"
>
{#snippet node(file, state)}
{#if state.isBranch}
<Tree.Branch>
<Tree.BranchControl
class="focus-ring rounded-sm py-1 text-sm"
style="padding-inline-start: calc(var(--depth) * 1rem)"
>
<Tree.BranchTrigger aria-label={state.expanded ? "Collapse" : "Expand"}>
<Tree.Indicator>{state.expanded ? "▾" : "▸"}</Tree.Indicator>
</Tree.BranchTrigger>
{file.name}
</Tree.BranchControl>
<Tree.BranchContent />
</Tree.Branch>
{:else}
<Tree.Item
class="focus-ring rounded-sm py-1 text-sm"
style="padding-inline-start: calc(var(--depth) * 1rem)"
>
{file.name}
</Tree.Item>
{/if}
{/snippet}
</Tree>
</div>

The second argument of the node snippet is a TreeNodeState.

The second argument of the node snippet is a TreeNodeState.

Field Type Meaning
value string The node’s value from nodeToValue, the key expanded and selected hold
isBranch boolean The node has children, or nodeToChildrenCount says it may
expanded boolean The branch is open and its children render. Always false on a leaf
selected boolean The node is in selected
focused boolean The node holds the roving focus, whether or not the tree has DOM focus
disabled boolean isNodeDisabled returned true. A disabled node cannot be selected or expanded
depth number Nesting depth, starting at 1 for a root node. Matches aria-level and --depth
indexPath readonly number[] The index of the node and of each ancestor within its siblings, root first

Indentation is yours. Use depth as in the recipe above, or read the --depth custom property that each row carries.

bind:expanded and bind:selected hold arrays of node values. selectionMode is 'single' by default and 'multiple' allows several selected rows. expandOnClick defaults to true, so a click on a branch row toggles it.

src
index.ts
app.svelte
package.json

expanded: src

selected: none

Code
TwoWay.svelte
<script lang="ts">
import { Tree } from "@viamrobotics/prime-tree";
interface FileNode {
path: string;
name: string;
children?: FileNode[];
}
const files: FileNode[] = [
{
path: "src",
name: "src",
children: [
{ path: "src/index.ts", name: "index.ts" },
{ path: "src/app.svelte", name: "app.svelte" },
],
},
{ path: "package.json", name: "package.json" },
];
let expanded = $state<string[]>(["src"]);
let selected = $state<string[]>([]);
</script>
<div class="not-content flex flex-col gap-3">
<Tree
nodes={files}
nodeToValue={(file) => file.path}
nodeToString={(file) => file.name}
nodeToChildren={(file) => file.children}
selectionMode="multiple"
bind:expanded
bind:selected
aria-label="Files"
>
{#snippet node(file, state)}
{#if state.isBranch}
<Tree.Branch>
<Tree.BranchControl
class="focus-ring rounded-sm py-1 text-sm data-[selected]:bg-medium"
style="padding-inline-start: calc(var(--depth) * 1rem)"
>
<Tree.BranchTrigger aria-label={state.expanded ? "Collapse" : "Expand"}>
<Tree.Indicator>{state.expanded ? "▾" : "▸"}</Tree.Indicator>
</Tree.BranchTrigger>
{file.name}
</Tree.BranchControl>
<Tree.BranchContent />
</Tree.Branch>
{:else}
<Tree.Item
class="focus-ring rounded-sm py-1 text-sm data-[selected]:bg-medium"
style="padding-inline-start: calc(var(--depth) * 1rem)"
>
{file.name}
</Tree.Item>
{/if}
{/snippet}
</Tree>
<p class="text-sm text-subtle-2">expanded: <code>{expanded.join(", ") || "none"}</code></p>
<p class="text-sm text-subtle-2">selected: <code>{selected.join(", ") || "none"}</code></p>
</div>

Both props also take a function binding. The setter runs on each change and can refuse it by not assigning. This tree keeps the locked folder from closing.

src
src/index.ts
locked
locked/secret.ts

expanded: src, locked

Code
Controlled.svelte
<script lang="ts">
import { Tree } from "@viamrobotics/prime-tree";
interface FolderNode {
id: string;
children?: FolderNode[];
}
const folders: FolderNode[] = [
{ id: "src", children: [{ id: "src/index.ts" }] },
{ id: "locked", children: [{ id: "locked/secret.ts" }] },
];
let expanded = $state<string[]>(["src", "locked"]);
</script>
<div class="not-content flex flex-col gap-3">
<Tree
nodes={folders}
nodeToValue={(folder) => folder.id}
nodeToString={(folder) => folder.id}
nodeToChildren={(folder) => folder.children}
bind:expanded={
() => expanded,
(next) => {
if (!next.includes("locked")) return;
expanded = next;
}
}
aria-label="Folders"
>
{#snippet node(folder, state)}
{#if state.isBranch}
<Tree.Branch>
<Tree.BranchControl
class="focus-ring rounded-sm py-1 text-sm"
style="padding-inline-start: calc(var(--depth) * 1rem)"
>
<Tree.BranchTrigger aria-label={state.expanded ? "Collapse" : "Expand"}>
<Tree.Indicator>{state.expanded ? "▾" : "▸"}</Tree.Indicator>
</Tree.BranchTrigger>
{folder.id}
</Tree.BranchControl>
<Tree.BranchContent />
</Tree.Branch>
{:else}
<Tree.Item
class="focus-ring rounded-sm py-1 text-sm"
style="padding-inline-start: calc(var(--depth) * 1rem)"
>
{folder.id}
</Tree.Item>
{/if}
{/snippet}
</Tree>
<p class="text-sm text-subtle-2">expanded: <code>{expanded.join(", ")}</code></p>
</div>

To arrange the rows yourself, pass a children snippet to Tree or to Tree.BranchContent. It receives the nodes at that level, and you render one Tree.Row per node you want shown, with the node’s index among those nodes. That is how a branch with hundreds of children goes through a virtual list, or how an empty branch shows a placeholder. Tree.IndentGuide is a hook for a vertical guide line.

The nodes a children snippet receives are typed unknown, since a part cannot see the root’s node type. Narrow them once with a helper or a cast.

src
lib
index.ts
tree.ts
main.ts
package.json
Code
CustomRows.svelte
<script lang="ts">
import { Tree } from "@viamrobotics/prime-tree";
interface FileNode {
path: string;
name: string;
children?: FileNode[];
}
const files: FileNode[] = [
{
path: "src",
name: "src",
children: [
{
path: "src/lib",
name: "lib",
children: [
{ path: "src/lib/index.ts", name: "index.ts" },
{ path: "src/lib/tree.ts", name: "tree.ts" },
],
},
{ path: "src/main.ts", name: "main.ts" },
],
},
{ path: "package.json", name: "package.json" },
];
let expanded = $state<string[]>(["src", "src/lib"]);
const nodeToValue = (file: FileNode) => file.path;
</script>
<div class="not-content">
<Tree
nodes={files}
{nodeToValue}
nodeToString={(file) => file.name}
nodeToChildren={(file) => file.children}
bind:expanded
aria-label="Files"
>
{#snippet node(file, state)}
{#if state.isBranch}
<Tree.Branch>
<Tree.BranchControl
class="focus-ring flex items-center gap-1 rounded-sm py-1 text-sm hover:bg-light"
style="padding-inline-start: calc(var(--depth) * 1rem)"
>
<Tree.BranchTrigger
class="flex items-center"
aria-label={state.expanded ? "Collapse" : "Expand"}
>
<Tree.Indicator class="inline-block transition-transform data-[state=open]:rotate-90">
&gt;
</Tree.Indicator>
</Tree.BranchTrigger>
{file.name}
</Tree.BranchControl>
<Tree.BranchContent class="relative">
{#snippet children(rows)}
<Tree.IndentGuide
class="absolute inset-y-0 w-px bg-medium"
style="inset-inline-start: calc(var(--depth) * 1rem + 0.5rem)"
/>
{#each rows as row, index (nodeToValue(row as FileNode))}
<Tree.Row node={row} {index} />
{/each}
{/snippet}
</Tree.BranchContent>
</Tree.Branch>
{:else}
<Tree.Item
class="focus-ring rounded-sm py-1 text-sm hover:bg-light"
style="padding-inline-start: calc(var(--depth) * 1rem + 1rem)"
>
{file.name}
</Tree.Item>
{/if}
{/snippet}
</Tree>
</div>

branchClick decides what a click, Enter, or Space on a branch row does: 'toggle-and-select' (the default) opens or closes the branch and selects it, 'select' only selects it and leaves opening to the trigger, and 'toggle' only opens or closes it, for a tree whose branches are folders rather than choices. The trigger always toggles.

selected: none

Code
Branches.svelte
<script lang="ts">
import type { TreeBranchClick } from "@viamrobotics/prime-tree";
import { Tree } from "@viamrobotics/prime-tree";
interface FileNode {
path: string;
name: string;
children?: FileNode[];
}
const files: FileNode[] = [
{
path: "src",
name: "src",
children: [{ path: "src/index.ts", name: "index.ts" }],
},
{
path: "docs",
name: "docs",
children: [{ path: "docs/intro.md", name: "intro.md" }],
},
];
const modes: TreeBranchClick[] = ["toggle-and-select", "select", "toggle"];
let branchClick = $state<TreeBranchClick>("toggle");
let selected = $state<string[]>([]);
</script>
<div class="not-content flex flex-col gap-3">
<label class="flex items-center gap-2 text-sm">
branchClick
<select class="input" bind:value={branchClick}>
{#each modes as mode (mode)}
<option value={mode}>{mode}</option>
{/each}
</select>
</label>
<Tree
nodes={files}
nodeToValue={(file) => file.path}
nodeToString={(file) => file.name}
nodeToChildren={(file) => file.children}
{branchClick}
bind:selected
aria-label="Files"
>
{#snippet node(file, state)}
{#if state.isBranch}
<Tree.Branch>
<Tree.BranchControl
class="focus-ring rounded-sm py-1 text-sm data-[selected]:bg-medium"
style="padding-inline-start: calc(var(--depth) * 1rem)"
>
<Tree.BranchTrigger aria-label={state.expanded ? "Collapse" : "Expand"}>
<Tree.Indicator>{state.expanded ? "▾" : "▸"}</Tree.Indicator>
</Tree.BranchTrigger>
{file.name}
</Tree.BranchControl>
<Tree.BranchContent />
</Tree.Branch>
{:else}
<Tree.Item
class="focus-ring rounded-sm py-1 text-sm data-[selected]:bg-medium"
style="padding-inline-start: calc(var(--depth) * 1rem + 1rem)"
>
{file.name}
</Tree.Item>
{/if}
{/snippet}
</Tree>
<p class="text-sm text-subtle-2">selected: <code>{selected.join(", ") || "none"}</code></p>
</div>

A row reads its state from the node snippet’s second argument, and the same state is on the row as data attributes.

expanded
child
selected
disabled

The root renders one element, role="tree", with tabindex="-1". class and every other attribute land on it, so size it with a class and make it the scroll container with overflow-auto when the tree is taller than its box. To reach the element itself, pass an attachment through the rest props.

Each part spreads the attributes you pass over its own, so class, style, and event handlers all work on every part. Each renders children, except that Tree.BranchContent treats children as the row renderer and Tree.Row renders no element of its own. Tree.Item leaves aria-current to you. The package renders only what the snippet returns, so it adds no wrappers or default styles.

The package sets a --depth custom property on Tree.Branch and Tree.Item, and a branch’s control inherits it. Use it in a style attribute for indentation, as the recipes do. state.depth is the script-side equivalent. For the utility classes the recipes wear, such as focus-ring, see the component classes.

Zag sets these data attributes, so Tailwind variants like data-[selected]:bg-medium work without a wrapper.

Attribute Parts Value
data-part every part The part name, such as branch-control
data-value Branch, BranchControl, BranchTrigger, Item The node’s value
data-depth Branch, BranchControl, Item, IndentGuide Nesting depth, starting at 1
data-state Branch, BranchControl, BranchTrigger, Indicator open or closed
data-selected Branch, BranchControl, Item, Indicator present when selected
data-focus BranchControl, Item, Indicator present on the row holding the roving focus
data-disabled Branch, BranchControl, BranchTrigger, Item, Indicator present when disabled

Focus is roving. One row has tabindex="0" and the rest are reachable by the arrow keys, so the tree is a single tab stop. Rows carry aria-expanded, aria-selected, aria-level, aria-setsize, and aria-posinset. A branch row shows expansion with a visual icon, and Tree.Indicator is aria-hidden, so the label inside the row must name the node. Name the tree itself with aria-label or aria-labelledby.

KeyAction
ArrowDown / ArrowUpMove focus to the next or previous visible row
ArrowRightExpand a collapsed branch, or move into an expanded one
ArrowLeftCollapse an expanded branch, or move to the parent
Home / EndMove focus to the first or last visible row
Enter / SpaceSelect the focused row. On a branch, do what branchClick sets
Shift + ArrowUp / ArrowDownExtend a multiple selection
*Expand every sibling of the focused row
Printable charactersType-ahead by nodeToString
PropTypeDefaultDescription
nodesreadonly TNode[]The root nodes, the single source of truth for what the tree renders.
bind:expandedstring[][]The values of the expanded branches. Bind it, or pass a function binding to veto a change.
bind:selectedstring[][]The values of the selected nodes. Bind it, or pass a function binding to veto a change.
selectionMode'single' | 'multiple''single'Whether one node or several can be selected at a time.
branchClickTreeBranchClick'toggle-and-select'What a click, Enter, or Space on a branch row does. The trigger always toggles.
nodeSnippet<[TNode, TreeNodeState]>Renders one node. Compose it from the Tree parts.
childrenSnippet<[readonly TNode[]]>Renders the root rows in place of the default, one Tree.Row per node, so a consumer can window or otherwise arrange them. Receives the root nodes.

Plus everything in TreeAccessors<TNode>, Omit<HTMLAttributes<HTMLDivElement>, 'children'>, spread onto the element.

Tree.Branch

Takes Props as its props.

Tree.BranchContent

PropTypeDefaultDescription
childrenSnippet<[readonly unknown[]]>

Plus everything in Omit<HTMLAttributes<HTMLDivElement>, 'children'>, spread onto the element.

Tree.BranchControl

Takes Props as its props.

Tree.BranchTrigger

Takes Props as its props.

Tree.IndentGuide

Takes Props as its props.

Tree.Indicator

Takes Props as its props.

Tree.Item

Takes Props as its props.

Tree.Row

PropTypeDefaultDescription
nodeTNode
indexnumber