Tree

Navigate a hierarchy without confusing focus, selection, expansion or activation.
Download runnable sandbox
import { createSignal, For } from "solid-js";
import { Tree } from "@wsagency/radix2solid-primitives";
import styles from "./styles.module.css";
const files = [
{ value: "source-readme", label: "Readme" },
{ value: "source-config", label: "Configuration" },
];
export default function TreeDemo() {
const [value, setValue] = createSignal<string | null>(null);
const [expanded, setExpanded] = createSignal<readonly string[]>(["shared"]);
const [acceptExpansion, setAcceptExpansion] = createSignal(true);
const [acceptSelection, setAcceptSelection] = createSignal(true);
const [reversed, setReversed] = createSignal(false);
const [rtl, setRtl] = createSignal(false);
const [count, setCount] = createSignal(0);
const [focused, setFocused] = createSignal("none");
const activate = (event: Event, key: string) => {
if (key === "protected") event.preventDefault();
if (!event.defaultPrevented) setCount(current => current + 1);
};
return <div class={styles.Demo}>
<Tree.Root class={styles.Tree} aria-label="Project explorer" dir={rtl() ? "rtl" : "ltr"} value={value()} onValueChange={next => { if (acceptSelection()) setValue(next); }} expandedValues={expanded()} onExpandedValuesChange={next => { if (acceptExpansion()) setExpanded(next); }}>
<Tree.Item class={styles.Item} value="source" textValue="Source" hasChildren onFocus={() => setFocused("source")} onActivate={event => activate(event, "source")}>
<span class={styles.Row}><Tree.ExpandTrigger class={styles.Toggle} aria-label="Toggle Source">▸</Tree.ExpandTrigger><Tree.ItemText>Source</Tree.ItemText><Tree.ItemIndicator class={styles.Indicator}> •</Tree.ItemIndicator></span>
<Tree.ItemGroup class={styles.Group}>
<For each={reversed() ? [...files].reverse() : files}>{file =>
<Tree.Item class={styles.Item} value={file.value} textValue={file.label} onFocus={event => { event.stopPropagation(); setFocused(file.value); }} onActivate={event => activate(event, file.value)}>
<span class={styles.Row}><Tree.ItemText>{file.label}</Tree.ItemText><Tree.ItemIndicator class={styles.Indicator}> •</Tree.ItemIndicator></span>
</Tree.Item>}
</For>
</Tree.ItemGroup>
</Tree.Item>
<Tree.Item class={styles.Item} value="docs-readme" textValue="Readme" onFocus={() => setFocused("docs-readme")} onActivate={event => activate(event, "docs-readme")}>
<span class={styles.Row}><Tree.ItemText>Readme</Tree.ItemText><Tree.ItemIndicator class={styles.Indicator}> •</Tree.ItemIndicator></span>
</Tree.Item>
<Tree.Item class={styles.Item} value="shared" textValue="Shared (disabled parent)" hasChildren disabled>
<span class={styles.Row}><Tree.ItemText>Shared (disabled parent)</Tree.ItemText></span>
<Tree.ItemGroup class={styles.Group}>
<Tree.Item class={styles.Item} value="shared-guide" textValue="Enabled guide" onFocus={() => setFocused("shared-guide")} onActivate={event => activate(event, "shared-guide")}>
<span class={styles.Row}><Tree.ItemText>Enabled guide</Tree.ItemText><Tree.ItemIndicator class={styles.Indicator}> •</Tree.ItemIndicator></span>
</Tree.Item>
</Tree.ItemGroup>
</Tree.Item>
<Tree.Item class={styles.Item} value="protected" textValue="Protected action" onFocus={() => setFocused("protected")} onActivate={event => activate(event, "protected")}>
<span class={styles.Row}><Tree.ItemText>Protected action</Tree.ItemText></span>
</Tree.Item>
</Tree.Root>
<label><input type="checkbox" checked={acceptExpansion()} onChange={event => setAcceptExpansion(event.currentTarget.checked)} /> Accept expansion proposals</label>
<label><input type="checkbox" checked={acceptSelection()} onChange={event => setAcceptSelection(event.currentTarget.checked)} /> Accept selection proposals</label>
<label><input type="checkbox" checked={rtl()} onChange={event => setRtl(event.currentTarget.checked)} /> Right-to-left tree</label>
<button class={styles.Button} type="button" onClick={() => setReversed(current => !current)}>Reverse source children</button>
<button class={styles.Button} type="button" onClick={() => setExpanded(current => current.filter(key => key !== "source"))}>Collapse source externally</button>
<output aria-label="Tree focused key">Focused: {focused()}</output>
<output aria-label="Tree selected key">Selected: {value() ?? "none"}</output>
<output aria-label="Tree expanded keys">Expanded: {expanded().join(", ") || "none"}</output>
<output aria-label="Tree activations">Activations: {count()}</output>
</div>;
}

Introduced in published 0.1.0-rc.3 and included in the current Primitives 0.1.0-rc.4 release. The earlier rc.2 does not include Tree. Primitives is published on npm as 0.1.0-rc.4; use the exact-version installation instructions. Styled explorer recipe.

Imports and anatomy

import { Tree } from "@wsagency/radix2solid-primitives";
// Alternatively: import * as Tree from "@wsagency/radix2solid-primitives/tree";
export default () => <Tree.Root aria-label="Files" defaultExpandedValues={["source"]}>
<Tree.Item value="source" textValue="Source" hasChildren>
<Tree.ExpandTrigger aria-label="Toggle Source">Expand</Tree.ExpandTrigger>
<Tree.ItemText>Source</Tree.ItemText>
<Tree.ItemIndicator>Selected or expanded</Tree.ItemIndicator>
<Tree.ItemGroup>
<Tree.Item value="readme" textValue="Readme"><Tree.ItemText>Readme</Tree.ItemText></Tree.Item>
</Tree.ItemGroup>
</Tree.Item>
</Tree.Root>;

API reference

PartProps and responsibility
RootselectionMode: "single" | "none" (default single); value/defaultValue: string | null (default null); onValueChange(value); expandedValues/defaultExpandedValues: readonly string[] (default empty); onExpandedValuesChange(values); dir; required accessible name.
ItemRequired stable value and plain-text textValue; disabled?: boolean; hasChildren?: boolean (default false); cancellable onActivate(event); native positional ARIA attributes. The treeitem itself is focusable.
ItemTextVisual label and accessible-name reference; rich children do not replace textValue for typeahead.
ItemIndicatorPresentation for selected/expanded state, not independent state.
ItemGroupNested hierarchy owned by nearest Item; descendants render only for accepted expansion, with native presence/forceMount conventions.
ExpandTriggerOptional explicitly named button with tabIndex=-1; changes expansion, not selection or activation.

Native refs, consumer cancellation and target-factory asChild apply. Keys are nonempty, unique within Root and stable across reorder. Duplicate registered keys are errors; the primitive cannot certify unrendered data without evaluating children, so authors own data-wide uniqueness.

hasChildren declares a branch even before children arrive. ItemGroup supplies explicit parent context; there is no descendant prewalk. Leaves omit aria-expanded.

Four independent operations

  • Arrows and typeahead move focus, not selection or activation.
  • Space requests selection in single mode; it never toggles a selected key off. Programmatic null clears it. In none mode Space is consumed without action.
  • Enter or primary click on the item's own row emits one cancellable activation, then requests selection if not cancelled. It does not expand. Consumer side effects already executed cannot be undone by later cancellation.
  • ExpandTrigger and branch-arrow operations expand/collapse without selecting or activating. Descendant activation does not activate ancestors.

Controlled callbacks are proposals; only accepted props change selection/expansion. No optimistic state appears on rejection. Expanded arrays contain unique keys, retaining existing order and appending new keys. No-op changes do not notify. selectionMode="none" omits aria-selected and ignores selection callbacks without erasing stored state; switching back reflects that state.

Keyboard and disabled nodes

One tab stop enters the surviving focused visible enabled item, then selected visible enabled item, then first enabled item. Root takes the tab stop when none is available. Tab leaves normally. Up/Down traverse enabled visible preorder without wrapping; Home/End reach the ends.

In LTR, Right expands a closed branch or moves into its first enabled visible descendant; Left collapses an open branch or moves to the nearest enabled ancestor. RTL reverses these logical branch keys. Leaves do not expand. ExpandTrigger events are not item-navigation events.

Plain printable characters use case-insensitive textValue prefix matching, starting after the current item and wrapping for matches. Repeated characters cycle. The buffer clears after 1000ms or on leaving the tree. Ctrl/Meta/Alt editing and composition do not activate typeahead. Consumer prevention wins.

Disabled applies only to that node, not its subtree. An expanded disabled parent can contain enabled, reachable descendants. Disabled nodes cannot focus, select, activate or expand by user input; the application can change expansion. Ancestor navigation skips disabled ancestors. There is no separate read-only prop.

Dynamic data and focus repair

Navigation follows visible DOM preorder after reorder even without re-registration; focus and selection stay keyed. Closing groups are excluded immediately, including retained exit-animation/force-mounted descendants, which cannot remain tab stops.

Accepted collapse evacuates focused descendants to the enabled branch, then enabled ancestor, next outside item, previous item, or Root. Refused collapse does not move focus. External changes never steal focus from outside the tree. Removing/disabling a focused item repairs to a surviving enabled ancestor, next/previous position, then Root; when focus is outside, only the future tab stop changes.

Hidden or absent selected keys remain selected state, without selecting a neighbor or automatically expanding. Clear permanently deleted keys explicitly. Expansion keys can similarly survive absent branches; this does not imply a cache or loader.

Partial data, SSR and boundaries

Complete nested DOM provides hierarchy positions. For partial sibling data, supply correct native aria-level, aria-posinset and aria-setsize from your data; unknown total is -1. Levels/positions are positive; known sizes are positive with position no greater than size. The primitive must not guess unseen siblings. Use hasChildren, aria-busy and supplied children for an unloaded branch boundary, not a built-in loading service.

SSR emits accepted hierarchy, labels, selection and deterministic IDs without client registration or child prewalk. Hydration preserves nodes; registration establishes focus order without rebuilding the hierarchy. Tree is not a form field: no name, required or reset contract. Serialization is application-owned.

This is not a filesystem, router, virtualizer, multi-selection engine or permission service. For ordinary navigation links or rows with arbitrary tabbable controls, prefer a Collapsible disclosure list. Visible focus and selected state need different styling. Browser/role assertions are not screen-reader certification.

Native source