Tree

Slant / Navigation

A tree of nested items with roving focus, typeahead, and arrow keys that expand and collapse.

Demo

Usage

@tuttn/slant
import { Badge, Button, ContextMenu, FileIcon, FolderIcon, TrashIcon, Tree, type TreeNode } from '@tuttn/slant'

// Uniform nodes: an items array. A node with children (even []) is a parent.
const files: TreeNode[] = [
  { id: 'src', label: 'src', icon: <FolderIcon size={14} />, children: [
    { id: 'button', label: 'Button.tsx', icon: <FileIcon size={14} /> },
  ] },
  { id: 'empty', label: 'empty', icon: <FolderIcon size={14} />, children: [] },
  { id: 'lockfile', label: 'package-lock.json', disabled: true },
]

// Uncontrolled: the tree keeps its own selection and open parents.
<Tree items={files} label="Project files" defaultValue="button" defaultExpanded={['src']} />

// Controlled: you hold both. onAction fires on Enter and on a double click.
<Tree items={files} label="Project files"
  value={selected} onValueChange={setSelected}
  expanded={expanded} onExpandedChange={setExpanded}
  onAction={openFile} />

// Children on demand: hasChildren marks a parent whose children aren't loaded.
// loadChildren runs the first time it opens, however it opens; supply the
// children by updating items. A rejected promise shows a row that retries.
const [nodes, setNodes] = useState<TreeNode[]>([
  { id: 'src', label: 'src', hasChildren: true },
  { id: 'readme', label: 'README.md' },
])
<Tree items={nodes} label="Project files" loadChildren={async id => {
  const children = await listFolder(id)
  setNodes(current => withChildren(current, id, children))
}} />

// A status after the label (part of the item's name), and actions at the
// row's end, shown on hover and focus. The actions are a pointer shortcut, out
// of the tab order: give the same actions a keyboard path, such as a
// ContextMenu around the tree (Shift+F10, the menu key, or a right-click).
const row = useRef<string>()
// Each treeitem carries its node's id as data-value.
const aim = (event: SyntheticEvent) => {
  row.current = (event.target as Element).closest<HTMLElement>('[role="treeitem"]')?.dataset.value
}
<ContextMenu label="File actions" items={[{ id: 'rename', label: 'Rename' }, { id: 'delete', label: 'Delete' }]}
  onSelect={action => run(action, row.current)} onContextMenu={aim} onKeyDown={aim}>
  <Tree label="Project files" items={[
    { id: 'button', label: 'Button.tsx', status: <Badge mono tone="warning">M</Badge>,
      actions: <Button size="sm" variant="ghost" icon aria-label="Delete" onClick={() => run('delete', 'button')}>
        <TrashIcon size={14} />
      </Button> },
  ]} />
</ContextMenu>

// Rich rows: the compound form. Nested items make a parent; parent marks an
// empty one, or, with loadChildren, one whose nested items come later.
<Tree label="Project files" defaultExpanded={['src']} loadChildren={loadFolder}>
  <Tree.Item id="src" label="src" icon={<FolderIcon size={14} />}>
    <Tree.Item id="button" label={<>Button.tsx <Badge mono>M</Badge></>} textValue="Button.tsx" />
  </Tree.Item>
  <Tree.Item id="assets" label="assets" parent status="3 files">
    {assets?.map(asset => <Tree.Item key={asset.id} id={asset.id} label={asset.name} />)}
  </Tree.Item>
</Tree>

Props

PropTypeDefaultDescription
itemsTreeNode[]—The nodes as data, for a uniform tree. Leave it out and compose `Tree.Item`s as children instead.
childrenReactNode—The compound form, used when there are no `items`: `Tree.Item`s, nested for children.
labelstring—The tree's accessible name. Required, unless `aria-labelledby` names the tree instead.
valuestring | null—The selected node's id, or `null` for none. Pass it with onValueChange to control the selection.
defaultValuestring | nullnullThe node selected at first, when uncontrolled.
onValueChange(id: string) => void—Called with a node's id when the user selects it: a click, Enter, Space, or a move with `selectionFollowsFocus`.
expandedstring[]—The ids of the open parents. Pass it with onExpandedChange to control which are open.
defaultExpandedstring[][]The parents open at first, when uncontrolled.
onExpandedChange(ids: string[]) => void—Called with the ids of every open parent whenever one opens or closes.
selectionFollowsFocusbooleanfalseThe arrow keys, Home, End and typeahead select the item they move to, as well as focusing it.
onAction(id: string) => void—Called with a node's id on Enter or a double click: open a file, say. Enter also selects the node.
loadChildren(id: string) => Promise<unknown> | void—Fetches a parent's children the first time it opens, by any path: a click, Right, `*`, or an `expanded` that lists it at mount. It waits on data nodes with `hasChildren` and no `children`, and on `Tree.Item`s marked `parent` with no nested items. Supply the children by updating `items` (or the nested items). Return a promise to show the parent busy until it settles and, if it rejects, a row that retries; a function that returns nothing is done at once. The tree never asks twice for an id that loaded.
size'sm' | 'md''sm'The row height, on the control scale. `sm` is the dense row of a desktop sidebar.
Tree.Item idstring—The node's id, unique in the tree: what the tree's value, expanded and callbacks carry.
Tree.Item labelReactNode—The row's visible content.
Tree.Item iconReactNode—A leading glyph, such as a folder or a file. Decorative: the label names the item.
Tree.Item statusReactNode—A short status after the label, such as a badge, a count or a state word. It is part of the item's name.
Tree.Item actionsReactNode—Controls at the row's inline end, shown while the row is hovered or the item has focus. A pointer shortcut: out of the tab order and hidden from screen readers, so give the same actions a keyboard path too.
Tree.Item disabledboolean—Skipped by the arrow keys and typeahead, and can't be selected, opened or acted on. It stays visible.
Tree.Item textValuestring—The text typeahead matches, when the label is not plain text.
Tree.Item parentboolean—Makes the item a parent without children, such as an empty folder. Nested items make it a parent anyway. With the tree's loadChildren, a parent with no nested items is one whose children are still to load.
Tree.Item childrenReactNode—Nested Tree.Items, rendered only while the item is open.
…restHTMLAttributes—className, style, other attributes and the ref go on the tree's role="tree" list, and on each Tree.Item's role="treeitem" li.

Keyboard

↓ / ↑moves to the next or previous visible item, skipping disabled ones, without wrapping
Home / Endmoves to the first or last visible item
→opens a closed parent, loading its children the first time with loadChildren; on an open parent, moves to its first child (or the retry row). ← under right-to-left
←closes an open parent; otherwise moves to the item's parent. → under right-to-left
*opens every parent among the focused item's siblings, loading any that aren't loaded
Enterselects the item and calls onAction; on the retry row, loads the children again
Spaceselects the item; on the retry row, loads the children again
Lettersmove to the next visible item whose text starts with the letters typed
Tableaves the tree: one item is a tab stop, and the rows' actions are none

Accessibility

  • The list is a tree named by label (or aria-labelledby); each item is a treeitem with aria-level, aria-selected, and aria-expanded on parents. Open children sit in a group inside their parent, which browsers leave out of the parent's name.
  • An item is named from its row: the label, then the status. The icon, the chevron and the actions are aria-hidden.
  • While a parent's children load, the parent is aria-busy="true" and the spinner where they will appear is hidden. A failed load is announced politely, and the parent gets one child treeitem reading "Couldn’t load" and "Retry", which the arrow keys reach like any child.
  • The actions are a pointer shortcut: Tree sets tabIndex={-1} on every control inside them after each render, and they show only while the row is hovered or the item has focus. Anyone on a keyboard or a screen reader needs the same actions another way: a ContextMenu around the tree, onAction, or a toolbar acting on the selected item.
  • Disabled items keep aria-disabled="true", stay in the reading order, and are skipped by the keys.

Nodes

A node is { id, label, children?, hasChildren?, icon?, status?, actions?, disabled?, textValue? }. Children of a closed parent are not rendered, so the keys, typeahead and the page's find only see what is shown. Selection is single: value is an id or null. Each treeitem carries its node's id as data-value, which tells a ContextMenu around the tree which row it opened on.

Focus and selection

A click on a row selects and focuses it; a click on the chevron opens or closes without selecting. One item is in the tab order: the focused one, else the selected one while it is shown, else the first. When a parent closes over the focused item, focus moves to that parent. Disabled items stay visible but are skipped and can't be selected. With selectionFollowsFocus, every move selects too.

Children on demand

With loadChildren, a parent can open before its children exist: a data node with hasChildren and no children, or a Tree.Item marked parent with no nested items (children: [] is a loaded, empty parent). The first time it opens, by a click, Right, * or an expanded that lists it at mount, the tree calls loadChildren(id); you add the children to items (or render the nested items), and the tree never asks again for an id that loaded. While the promise is pending, the parent is busy and shows a spinner where its children will go. If it rejects, the parent shows one child row reading the failure and Retry: Enter, Space or a click asks again. A function that returns nothing counts as loaded at once. The tree remembers each id's state only while it is mounted.

Status and actions

status sits after the label and is read with it: a git letter, a count, "Running". actions sit at the row's inline end, keep their place while hidden so the text never moves, and show while the row is hovered or the item has focus. A click on them never selects, opens or acts on the row, and their controls are kept out of the tab order, so the tree stays one tab stop. That makes them a pointer shortcut only: offer the same actions from the keyboard, as the demo does with a ContextMenu (Shift+F10 or the menu key on the focused item).