|Kit

Tree

A standalone tree view on Ark UI's tree-view machine, for repo file trees and curriculum hierarchies. Same data as TreeSelect, children animate through Collapse.

Tree shows a hierarchy that stays on the page, like a repository's files or a curriculum's circles and projects. It takes the same data as TreeSelect and TreeMultiSelect, so an app can pass one shape to all three. Use those two when the tree is a way to pick a value in a form.

Ark's tree-view machine handles selection, expansion, focus, typeahead, the keyboard and lazy loading. The kit renders the rows itself. A branch's children open through Collapse (a CSS grid-rows transition) rather than Ark's JavaScript height measurement.

import { Tree } from '@42-central/ui-react/tree';

<Tree
  data={[
    {
      value: 'srcs',
      label: 'srcs',
      children: [
        { value: 'srcs/main.c', label: 'main.c' },
        { value: 'srcs/parser.c', label: 'parser.c' },
      ],
    },
    { value: 'Makefile', label: 'Makefile' },
  ]}
  defaultExpanded={['srcs']}
  onNodeClick={(node) => openFile(node.value)}
/>

Playground

Tree

Loading preview

Props

Code

<Tree
  size="md"
  multiple={false}
  withCheckbox={false}
  withLines
  expandOnClick
  disabled={false}
/>

Data

data is a tree of { value, label, disabled?, children?, payload?, testId? }, the shape TreeSelect uses. A node with children is a branch, and one without is a leaf. Every value must be unique across the whole tree, so for files use the path. Tree reads two more optional fields that the pickers ignore:

  • hasChildren: the node is a branch whose children aren't loaded yet. See Lazy loading.
  • icon: the node's own icon, in place of the default folder or file. Use null for no icon.

With a const array (or as const), selected, expanded and checked are typed as the tree's own values.

Selection

A click, or Enter, selects the row. By default only one row is selected at a time. With multiple, ⌘/Ctrl-click adds or removes a row, Shift-click and Shift+arrows extend the range, and ⌘A selects every row.

srcs
parsing
lexer.c
parser.c
expander.c
main.c
Makefile

onNodeClick(node, event) fires on every click on an enabled row, whether or not the selection changes. Use it to open a file or navigate. It doesn't fire for clicks on the chevron, the checkbox or the row actions.

Expanding

By default a click on a branch row expands or collapses it. With expandOnClick={false}, only the chevron and the keyboard do. Then a click on the row only selects it, as in an editor's file explorer. Children open and close through Collapse. A closed group is inert, so its rows are out of the tab order and the accessibility tree while hidden. The animation follows prefers-reduced-motion.

Controlled

selected, expanded and checked each have a default* uncontrolled form and an on*Change callback.

srcs
main.c
Makefile

Selected: nothing

Code

const [expanded, setExpanded] = useState<string[]>(['srcs']);
const [selected, setSelected] = useState<string[]>([]);

<Tree
  data={FILES}
  expanded={expanded}
  onExpandedChange={setExpanded}
  selected={selected}
  onSelectedChange={setSelected}
/>

Checkboxes

withCheckbox adds a checkbox to every row. It cascades like TreeMultiSelect's, using the same code. checked holds leaf values only. A branch is checked when all its enabled leaves are, and shows as mixed when only some are. Checking a branch checks its enabled leaves, and disabled leaves keep their state. Checking is separate from selection: a click on the box doesn't select the row. With the keyboard, Space checks the focused row and Enter selects it.

srcs
parsing
lexer.c
parser.c
expander.c
builtins
ft_cd.c
ft_export.c
main.c
Makefile

Lazy loading

Mark a node hasChildren and pass loadChildren(node, { signal }). The first time the branch expands, Tree calls it. The chevron turns into a spinner until the promise resolves, then the branch opens with what it returned. The loaded children stay loaded after the branch closes. If the promise rejects, the branch stays closed and onLoadError(node, error) fires. Expanding it again retries. signal aborts when the same branch is expanded again before the first call has finished.

A branch that was checked before it loaded counts as checked by itself. After its children load, they take its place in checked.

package.json

Code

<Tree
  data={[
    { value: 'packages', label: 'packages', hasChildren: true },
    { value: 'package.json', label: 'package.json' },
  ]}
  loadChildren={async (node, { signal }) => {
    const res = await fetch(`/api/ls?path=${node.value}`, { signal });
    return res.json();
  }}
  onLoadError={(node, error) => toast(`Couldn't list ${node.label}`)}
/>

Icons

By default a branch shows a folder (open while expanded) and a leaf shows a file. You can change them in two ways:

  • A node's own icon wins over the defaults. Use icon: null for no icon on that node.
  • icons replaces the kit's defaults for the whole tree, per instance. Its slots are chevron, folder, folderOpen, file, check, indeterminate and loading. Set folder, folderOpen or file to null for no icon.

Your icons are drawn as you pass them. Add className={iconStroke} (from @42-central/ui-react) for the kit's 1.5px line. The default chevron points down and turns a quarter towards the inline end while closed, so it already follows dir.

Curriculum
Circle 1
ft_printf882 XP
get_next_line882 XP
Born2beroot577 XP

Code

<Tree.Root data={CURRICULUM} defaultExpanded={['circle-1']}>
  <Tree.Label>Curriculum</Tree.Label>
  <Tree.List>
    {(node, state) => (
      <>
        <Tree.Indicator />
        <Tree.Icon />
        <Tree.Text />
        {state.leaf && <Badge size="xs" variant="light">{node.payload.xp} XP</Badge>}
      </>
    )}
  </Tree.List>
</Tree.Root>

Indentation guides

Each level indents by 16px. The guides are the lines TreeSelect draws: a vertical line per ancestor that has more siblings below, and an elbow into each row. withLines={false} keeps the indent and drops the lines.

srcs
parsing
lexer.c
parser.c
expander.c
main.c
Makefile

Row actions

actions(node, state) puts buttons at the end of each row. They show while the row is hovered or has focus. Hidden actions use visibility: hidden, which also takes them out of the tab order. Tab from the focused row reaches only that row's actions, then leaves the tree. Clicks and keys inside the actions never select the row or move the focus.

srcs
main.c
Makefile

Hover a row, or focus one and press Tab.

Code

<Tree
  data={FILES}
  actions={(node) => (
    <>
      <ActionIcon size="xs" variant="subtle" aria-label={`Rename ${node.label}`} onClick={() => rename(node)}>
        <Pencil className={iconStroke} />
      </ActionIcon>
      <ActionIcon size="xs" variant="subtle" aria-label={`Delete ${node.label}`} onClick={() => remove(node)}>
        <Trash2 className={iconStroke} />
      </ActionIcon>
    </>
  )}
/>

Give each action an aria-label that names its node. A screen reader user reaches the actions from the row, so "Delete" alone wouldn't say which file.

Disabled

A node with disabled: true can't be selected, expanded, checked or clicked. Its whole subtree is disabled too. Keyboard navigation still passes over it, as the WAI-ARIA tree pattern asks. disabled on Tree disables every node. In the examples above, obj is disabled.

Right to left

The rails, chevron and actions use logical sides, so they mirror under rtl. Ark mirrors ← and → too, so ← expands. Ark reads the direction from the locale, so wrap the app in IntlProvider with an RTL locale. dir="rtl" on the page alone isn't enough.

srcs
parsing
lexer.c
parser.c
expander.c
main.c
Makefile

Code

<IntlProvider locale="ar">
  <Tree data={FILES} withCheckbox />
</IntlProvider>

Anatomy

The data form <Tree /> is Tree.Root with a Tree.List inside. Use the parts to build your own rows.

  • Tree.Root: owns the state (Ark's machine, loaded children, checkboxes) and renders the root <div>. It takes every prop the data form takes except renderItem and actions.
  • Tree.Label: an optional visible name. When it's there, the tree is labelled by it. Otherwise translations.treeLabel (default "Tree") names it.
  • Tree.List: the role="tree" element. It renders every node. Its children is the row renderer, (node, state) => ReactNode. The tree keeps the row itself (its treeitem role, rails, roving focus, click and keys) and the renderer fills what comes after the rails. Leave children out for the default row.
  • Tree.Indicator: a branch's chevron, or a spinner while it loads. On a leaf it renders an empty column so labels line up. Clicking it toggles the branch without selecting it.
  • Tree.Checkbox: the row's checkbox. It's decorative: the state is on the treeitem's aria-checked.
  • Tree.Icon: the node's icon, else a folder or a file. It renders nothing when that resolves to null. children replace it.
  • Tree.Text: the label, truncated to the row. children replace it.
  • Tree.Actions: buttons at the row's end, shown on hover or focus.

state holds { depth, leaf, selected, expanded, loading, checked, indeterminate, disabled, focused }. useTree() returns the tree's live API (Ark's expand, collapse, select, focus…) and useTreeNode() returns the row being rendered, for a part of your own.

Every row's data-testid is the node's testId, which defaults to `item-${value}`. A branch's children group is `${testId}-group`. The parts default to the row's id plus their name: -indicator, -checkbox, -icon, -text, -actions. Each part also takes its own testId. Tree.Root and Tree.List take one too. See Testing.

'use client';
import { Tree } from '@42-central/ui-react/tree';

<Tree.Root data={FILES} withCheckbox testId="files">
  <Tree.Label>Files</Tree.Label>
  <Tree.List>
    {(node, state) => (
      <>
        <Tree.Indicator />
        <Tree.Checkbox />
        <Tree.Icon />
        <Tree.Text>{state.leaf ? node.label : `${node.label}/`}</Tree.Text>
        <Tree.Actions>
          <DeleteButton node={node} />
        </Tree.Actions>
      </>
    )}
  </Tree.List>
</Tree.Root>

Tree.Root, Tree.Label, Tree.Text and Tree.Actions accept asChild. Tree.List, Tree.Indicator, Tree.Checkbox and Tree.Icon render their own structure, so they don't.

API

Prop

Type

Accessibility

  • It follows the WAI-ARIA tree view pattern through Ark's machine. The list is role="tree" (aria-multiselectable with multiple), each node is a treeitem with aria-level, aria-setsize, aria-posinset and aria-selected, a branch has aria-expanded, and its children sit in a role="group".
  • The tree is a single tab stop. ↓ / ↑ move between visible rows. → opens a branch, then moves into it. ← closes a branch, or moves to the parent. Home / End jump to the first and last rows. * expands every sibling. Typing a few letters focuses the next matching row.
  • Enter selects (and toggles a branch while expandOnClick is on). Space does the same, or checks the row when withCheckbox is on. A checked row has aria-checked ("mixed" for a partly checked branch).
  • A loading branch has aria-busy="true". A disabled node has aria-disabled: it's skipped by selection but still reachable, so its label is read.
  • A closed group is inert. Its rows are out of the tab order and the accessibility tree, as they would be with hidden, but the close animation still plays.
  • Row actions are reachable with Tab from the focused row. Name each one after its node.
  • Under an RTL locale the rails and chevron mirror, and ← / → swap.

Changelog

v0.30.0
  • New Tree: a tree view that stays on the page, with selection, checkboxes, lazy loading and row actions, using TreeSelect's data

    #487

On this page