# Tree (/docs/tree)





`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`](/docs/tree-select) and [`TreeMultiSelect`](/docs/tree-multi-select), 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`](/docs/collapse) (a CSS grid-rows transition) rather than Ark's JavaScript height measurement.

```tsx
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 [#playground]

<story.Playground />

## Data [#data]

`data` is a tree of `{ value, label, disabled?, children?, payload?, testId? }`, the shape [`TreeSelect`](/docs/tree-select) 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](#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 [#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.

<story.Preview variant="Multiple" />

`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 [#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 [#controlled]

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

<Preview align="center" code="&#x22;const [expanded, setExpanded] = useState<string[]>(['srcs']);\nconst [selected, setSelected] = useState<string[]>([]);\n\n<Tree\n  data={FILES}\n  expanded={expanded}\n  onExpandedChange={setExpanded}\n  selected={selected}\n  onSelectedChange={setSelected}\n/>&#x22;">
  <TreeControlledDemo />
</Preview>

## Checkboxes [#checkboxes]

`withCheckbox` adds a checkbox to every row. It cascades like [`TreeMultiSelect`](/docs/tree-multi-select)'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.

<story.Preview variant="Checkboxes" />

## Lazy loading [#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`.

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

## Icons [#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`.

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

## Indentation guides [#indentation-guides]

Each level indents by 16px. The guides are the lines [`TreeSelect`](/docs/tree-select) 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.

<story.Preview variant="Without lines" />

## Row actions [#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.

<Preview align="center" code="&#x22;<Tree\n  data={FILES}\n  actions={(node) => (\n    <>\n      <ActionIcon size=\&#x22;xs\&#x22; variant=\&#x22;subtle\&#x22; aria-label={`Rename ${node.label}`} onClick={() => rename(node)}>\n        <Pencil className={iconStroke} />\n      </ActionIcon>\n      <ActionIcon size=\&#x22;xs\&#x22; variant=\&#x22;subtle\&#x22; aria-label={`Delete ${node.label}`} onClick={() => remove(node)}>\n        <Trash2 className={iconStroke} />\n      </ActionIcon>\n    </>\n  )}\n/>&#x22;">
  <TreeActionsDemo />
</Preview>

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 [#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](https://www.w3.org/WAI/ARIA/apg/patterns/treeview/) asks. `disabled` on `Tree` disables every node. In the examples above, `obj` is disabled.

## Right to left [#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`](/docs/intl) with an RTL locale. `dir="rtl"` on the page alone isn't enough.

<Preview align="center" code="&#x22;<IntlProvider locale=\&#x22;ar\&#x22;>\n  <Tree data={FILES} withCheckbox />\n</IntlProvider>&#x22;">
  <TreeRtlDemo />
</Preview>

## Anatomy [#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](/docs/testing).

```tsx
'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 [#api]

<TypeTable
  type="{
  data: {
    type: 'TreeNodeData[]',
    description: 'The hierarchy: { value, label, disabled?, children?, hasChildren?, icon?, payload?, testId? }.',
  },
  multiple: {
    type: 'boolean',
    default: 'false',
    description: 'Let several rows be selected: ⌘/Ctrl-click toggles, Shift extends, ⌘A takes all.',
  },
  selected: { type: 'string[]', description: 'Controlled selected values.' },
  defaultSelected: { type: 'string[]', default: '[]', description: 'Uncontrolled initial selected values.' },
  onSelectedChange: { type: '(selected: string[]) => void', description: 'Fires with the next selected values.' },
  expanded: { type: 'string[]', description: 'Controlled expanded branch values.' },
  defaultExpanded: { type: 'string[]', default: '[]', description: 'Uncontrolled initial expanded branch values.' },
  onExpandedChange: { type: '(expanded: string[]) => void', description: 'Fires with the next expanded branch values.' },
  withCheckbox: {
    type: 'boolean',
    default: 'false',
    description: 'A checkbox on every row. Checking a branch cascades to its enabled leaves.',
  },
  checked: { type: 'string[]', description: 'Controlled checked leaf values. A branch is derived.' },
  defaultChecked: { type: 'string[]', default: '[]', description: 'Uncontrolled initial checked leaf values.' },
  onCheckedChange: { type: '(checked: string[]) => void', description: 'Fires with the next checked leaf values.' },
  loadChildren: {
    type: '(node, { signal }) => Promise<TreeNodeData[]>',
    description: &#x22;Loads a hasChildren branch's children on its first expand.&#x22;,
  },
  onLoadError: { type: '(node, error: unknown) => void', description: 'Fires when loadChildren rejects. The branch stays closed.' },
  onNodeClick: {
    type: '(node, event: MouseEvent) => void',
    description: 'Fires on a click on an enabled row, not on its chevron, checkbox or actions.',
  },
  expandOnClick: {
    type: 'boolean',
    default: 'true',
    description: 'Clicking a branch row toggles it. With false, only the chevron and the keyboard do.',
  },
  typeahead: { type: 'boolean', default: 'true', description: &#x22;Typing a row's first letters focuses it.&#x22; },
  disabled: { type: 'boolean', description: 'Disables every node.' },
  withLines: { type: 'boolean', default: 'true', description: 'Draw the indentation guides.' },
  size: { type: '&#x22;xs&#x22; | &#x22;sm&#x22; | &#x22;md&#x22; | &#x22;lg&#x22; | &#x22;xl&#x22;', default: '&#x22;md&#x22;', description: 'Row height, text and icon size.' },
  color: { type: 'Color', description: 'The palette of the checkboxes and the focus ring.' },
  renderItem: {
    type: '(node, state) => ReactNode',
    description: 'Fill each row yourself, from the parts. Replaces the default row and actions.',
  },
  actions: { type: '(node, state) => ReactNode', description: &#x22;Buttons at a row's end, shown on hover or focus.&#x22; },
  icons: {
    type: '{ chevron?, folder?, folderOpen?, file?, check?, indeterminate?, loading? }',
    description: &#x22;Replaces the default icons. folder, folderOpen and file accept null. A node's own icon wins.&#x22;,
  },
  translations: { type: '{ treeLabel?: string }', description: 'The tree\'s accessible name when no Tree.Label names it. Default &#x22;Tree&#x22;.' },
  classNames: {
    type: '{ tree?, node?, group?, indicator?, checkbox?, icon?, label?, actions? }',
    description: 'Classes per part. className goes on the root.',
  },
  testId: { type: 'string', description: 'data-testid on the root. Rows use the node testId, see Anatomy.' },
}"
/>

## Accessibility [#accessibility]

* It follows the [WAI-ARIA tree view pattern](https://www.w3.org/WAI/ARIA/apg/patterns/treeview/) 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.
