# Tree View

> TreeView renders hierarchical data as a virtualized WAI-ARIA tree with nested or flat data, single or multiple selection, reactive expanded and selected ids, the full APG keyboard model, RTL, a ref API and server rendering of the first window.

Canonical: https://salmonui.dev/docs/navigation/tree-view

```tsx
import { TreeView } from '@salmonui/navigation/tree-view';
import '@salmonui/navigation/tree-view/styles.css';

<TreeView
  aria-label="Folders"
  data={folders}
  getItemId={(f) => f.id}
  getItemLabel={(f) => f.name}
  getChildren={(f) => f.children}
  height={400}
/>
```

`@salmonui/navigation/tree-view` is self-contained: it loads neither the Data
Grid nor another component family. Its stylesheet needs nothing besides
`@salmonui/core/styles.css`, which every app imports once.

### Live demo: Tree View basics

Live demo: https://salmonui.dev/demos/navigation/tree-view-basics

A file tree with reactive expanded and selected ids, multiple selection with Ctrl/Cmd and Shift, a disabled folder and the APG keyboard model.

`Demo.tsx`:

```tsx
'use client';
import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { TreeView, type TreeViewKey } from '@salmonui/navigation/tree-view';

interface Folder {
  id: string;
  name: string;
  children?: Folder[];
  locked?: boolean;
}

const folders: Folder[] = [
  {
    id: 'src',
    name: 'src',
    children: [
      { id: 'components', name: 'components', children: [{ id: 'button', name: 'Button.tsx' }, { id: 'tree', name: 'TreeView.tsx' }] },
      { id: 'index', name: 'index.ts' },
    ],
  },
  { id: 'docs', name: 'docs', children: [{ id: 'readme', name: 'README.md' }, { id: 'guide', name: 'guide.md' }] },
  { id: 'secrets', name: 'secrets', locked: true, children: [{ id: 'env', name: '.env' }] },
  { id: 'package', name: 'package.json' },
];

const getItemId = (f: Folder) => f.id;
const getItemLabel = (f: Folder) => f.name;
const getChildren = (f: Folder) => f.children;
const isItemDisabled = (f: Folder) => f.locked === true;

export default function TreeViewBasicsDemo() {
  const [expanded, setExpanded] = useState<readonly TreeViewKey[]>(['src']);
  const [selected, setSelected] = useState<readonly TreeViewKey[]>([]);
  const [multiple, setMultiple] = useState(true);
  const [last, setLast] = useState('nothing yet');
  return (
    <div style={{ display: 'grid', gap: 12, maxWidth: 420 }}>
      <Checkbox checked={multiple} onCheckedChange={(checked) => setMultiple(checked)}>
        Multiple selection
      </Checkbox>
      <TreeView
        aria-label="Project files"
        data={folders}
        getItemId={getItemId}
        getItemLabel={getItemLabel}
        getChildren={getChildren}
        isItemDisabled={isItemDisabled}
        selection={multiple ? 'multiple' : 'single'}
        expanded={expanded}
        onExpandedChange={(e) => {
          setExpanded(e.expanded);
          setLast(`${e.id ?? 'several'} ${e.expanded.includes(e.id ?? '') ? 'expanded' : 'collapsed'} (${e.source})`);
        }}
        selected={selected}
        onSelectedChange={(e) => {
          setSelected(e.selected);
          setLast(`selected ${e.selected.join(', ') || 'nothing'} (${e.source})`);
        }}
        height={280}
      />
      <p>
        Last change: <output>{last}</output>
      </p>
    </div>
  );
}
```

## Data

`data` is application owned; the tree never copies or changes it. Two shapes
are supported:

- **Nested**: `getChildren(item)` returns the children of an
  item.
- **Flat, self-referential**: `getParentId(item)`
  returns the parent id; `null`, `undefined` or an unknown id makes a root.
  The parent index is built once per `data` identity, in O(n).

`getItemId(item)` returns a stable, unique id (`string | number`).
Every piece of state (expanded, selected, checked, focus) is kept by id, so
it survives a new `data` array. A duplicate id logs one development
warning. `getItemLabel(item)` is the accessible name, the typeahead text and
the sort key (default: `String(id)`).

Accessors are read again whenever `data` changes; passing new inline
functions with the same `data` does not rebuild the model.

Children are flattened into the visible order only while their parent is
expanded (load on demand, always on). `hasChildren(item)`
shows the expand twisty before any child is known; with `loadChildren` the
first expand loads them ([Lazy loading](https://salmonui.dev/docs/navigation/tree-view-loading)).

Items carry no state fields: expanded, selected and checked state are id
lists the application derives from its data:

```tsx
const expandedIds = useMemo(() => flatten(folders).filter((f) => f.open).map((f) => f.id), [folders]);
<TreeView expanded={expandedIds} /* ... */ />
```

## Expansion

`expanded` is a reactive id list: the tree applies it whenever the array
identity changes, and keeps its own changes when the prop does not follow.
`onBeforeExpandedChange({ id, item, expanded, source })` runs first
and `event.preventDefault()` cancels; `onExpandedChange({ expanded, id, item,
source })` reports every expanded id afterwards:

```tsx
const [expanded, setExpanded] = useState<readonly TreeViewKey[]>(['docs']);
<TreeView expanded={expanded} onExpandedChange={(e) => setExpanded(e.expanded)} /* ... */ />
```

`expanded` and `selected` are reactive rather than strictly controlled:
without the prop the tree keeps its own state (starting empty), with the
prop the tree starts from it and re-applies it whenever you pass a new
array. There is no `defaultExpanded` or `defaultSelected`; pass the initial
array once and update it from the change event when you need to read it.

`expandOn` picks what toggles a parent besides its twisty:
`'auto'` (default: double-click with a mouse, a tap on touch), `'click'`,
`'doubleClick'` or `'none'` (twisty and keyboard only). Collapsing a parent
that contains the focused item moves focus to the parent.

`api.expandAll({ ids, level })` and `api.collapseAll({ ids, level })`
 change many items with one store update and one flatten; `level`
is 1-based (`expandAll({ level: 2 })` opens the first two levels,
`collapseAll({ level: 2 })` closes level 2 and deeper).

## Selection

`selection` is `'single'` (default), `'multiple'` or `'none'`.
`selected` is a reactive id list; `onBeforeSelectedChange({ selected, id,
item, source })` is cancellable and `onSelectedChange` reports the new list.

| Input | Single | Multiple |
| --- | --- | --- |
| Click, Enter | select the item | select only the item |
| Ctrl/Cmd+click, Space | select | toggle the item |
| Shift+click, Shift+Space | select | range from the anchor |
| Shift+ArrowUp/Down | move | move and extend the range |
| Ctrl/Cmd+Shift+Home/End | move | range to the first / last item |
| Ctrl/Cmd+A | — | select every enabled item |

Disabled items (`isItemDisabled`) stay focusable with
`aria-disabled="true"` but cannot be selected, checked, expanded, renamed
or dragged; `disabled` disables the whole tree.

`rowHighlight` is `'full'` (default, full-row selection): the
whole row shows hover and selection; `'label'` highlights the label
only.

`onItemClick({ id, item, source })` fires on a click or Enter.

## Keyboard

The WAI-ARIA APG Tree View keys. Focus is tracked by id, not by DOM
position, so it survives scrolling, expansion and new data.

| Key | Action |
| --- | --- |
| ArrowDown / ArrowUp | next / previous visible item |
| ArrowRight | expand a collapsed parent; on an expanded parent, move to its first child |
| ArrowLeft | collapse an expanded parent; otherwise move to the parent |
| Home / End | first / last visible item |
| `*` | expand every sibling of the focused item |
| a printable character | typeahead on `getItemLabel` (case and accents ignored) |
| Enter | select, `onItemClick`, follow the item's link |
| Space | check (with `checkable`) or select / toggle |
| F2 | rename (with `renamable`) |
| Alt+arrows | move the item (with `draggable`, see [Drag and drop](https://salmonui.dev/docs/navigation/tree-view-drag-drop)) |

Under `dir="rtl"` (inherited from any ancestor) ArrowRight and ArrowLeft are
mirrored and the twisty points the other way.

A native `onKeyDown` on the tree runs before the built-in keys;
calling `event.preventDefault()` skips the built-in
behavior for that key.

## Accessibility

The DOM is a flat list of `role="treeitem"` rows inside `role="tree"`:
under virtualization the `group` containers cannot be rendered,
so every row carries `aria-level`, `aria-setsize` and `aria-posinset`.
Parents carry `aria-expanded`, selectable rows `aria-selected`, checkable
rows `aria-checked` (`"mixed"` for partially checked parents), the tree
`aria-multiselectable` with multiple selection and `aria-busy` while a lazy
load runs. Give the tree a name with `aria-label` or `aria-labelledby`.

The tree has exactly one tab stop (roving `tabindex`). The focused row stays
rendered when it scrolls out of the window, so focus never falls to
`<body>`; `aria-activedescendant` is not used.

## API

`ref` receives a `TreeViewApi` with the commands props cannot express:

```tsx
const tree = useRef<TreeViewApi<Folder>>(null);
tree.current?.scrollToItem('2026-receipts'); // expands the ancestors, scrolls the virtual list
tree.current?.focusItem('cv');
tree.current?.getItem('cv'); // { item, id, level, parentId, expanded, selected, checked, disabled, visible }
tree.current?.expandAll({ level: 1 });
tree.current?.getCheckedIds();
tree.current?.startRename('cv');
```

There is no method that returns the tree data: the full data stays with
the application, which already holds it.
Every method and type is listed in the
[`@salmonui/navigation/tree-view` reference](https://salmonui.dev/docs/reference/navigation/tree-view)
(`TreeView`, `TreeViewApi`, `TreeViewProps`, the event types,
`TREE_VIEW_DEFAULT_LOCALE_TEXT` and the `moveTreeItems` helper).

## Virtualization and layout

The list is virtualized by default: only the rows in view plus an
overscan are rendered, over fixed 32 px rows. Give the tree a `height`
(number of px or a CSS length) or size it with CSS. `virtualize={false}`
renders every visible item, for short trees that must be searchable with
the browser's find.

`textWrap` lets labels wrap; row heights are then measured after
each render and kept per id.

`sort` orders siblings by `getItemLabel` with the locale's
`Intl.Collator` (`'asc'`, `'desc'`, or `null` for data order); `locale`
picks the collator.

### Live demo: Tree View with 100,000 items

Live demo: https://salmonui.dev/demos/navigation/tree-view-large

A virtualized tree of 100,010 nodes with checkboxes and multiple selection; expandAll, collapseAll and focusItem through the ref API.

`Demo.tsx`:

```tsx
'use client';
import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { TreeView, type TreeViewApi } from '@salmonui/navigation/tree-view';

interface Node {
  id: string;
  name: string;
  children?: Node[];
}

/** 10 regions × 100 stores × 99 products: 100,010 nodes. */
function generate(): Node[] {
  const roots: Node[] = [];
  for (let r = 0; r < 10; r++) {
    const stores: Node[] = [];
    for (let s = 0; s < 100; s++) {
      const products: Node[] = [];
      for (let p = 0; p < 99; p++) products.push({ id: `${r}.${s}.${p}`, name: `Product ${r}.${s}.${p}` });
      stores.push({ id: `${r}.${s}`, name: `Store ${r}.${s}`, children: products });
    }
    roots.push({ id: `${r}`, name: `Region ${r}`, children: stores });
  }
  return roots;
}

const getItemId = (n: Node) => n.id;
const getItemLabel = (n: Node) => n.name;
const getChildren = (n: Node) => n.children;

export default function TreeViewLargeDemo() {
  const [data] = useState(generate);
  const tree = useRef<TreeViewApi<Node>>(null);
  return (
    <div style={{ display: 'grid', gap: 12, maxWidth: 420 }}>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => tree.current?.expandAll()}>
          Expand all
        </Button>
        <Button variant="outline" onClick={() => tree.current?.collapseAll()}>
          Collapse all
        </Button>
        <Button variant="outline" onClick={() => tree.current?.focusItem('7.42.77')}>
          Go to Product 7.42.77
        </Button>
      </div>
      <TreeView ref={tree} aria-label="Catalog" data={data} getItemId={getItemId} getItemLabel={getItemLabel} getChildren={getChildren} selection="multiple" checkable height={360} />
    </div>
  );
}
```

## Server rendering

The server renders the first window of visible items (by a numeric
`height`, else 20 rows) with the correct `aria-setsize` / `aria-posinset`,
and the client hydrates the same window without warnings. Lazy loads of
initially expanded items start after mount, never on the server.

## Localization

`localeText` overrides `TREE_VIEW_DEFAULT_LOCALE_TEXT` (`loading`,
`loadError`, `retry`, `rename`, `moved`).

## Performance

Budgets: the subpath's
initial JavaScript is ≤ 12 KB gzip (rename ≤ 2 KB and drag and drop ≤ 5 KB
load on first use), CSS ≤ 2.5 KB; mounting 100,000 nodes ≤ 50 ms to the
first painted window, expanding 10,000 children ≤ 16 ms of work,
`expandAll` over 100,000 nodes ≤ 100 ms to painted, a cascade check of
100,000 descendants ≤ 16 ms of work and a typeahead keystroke ≤ 8 ms.
Expanding splices the new rows into the visible order; a cascade check
updates counts along the ancestor path and resolves the subtree lazily.

### Live demo: Tree View flat data

Live demo: https://salmonui.dev/demos/navigation/tree-view-flat-data

A team tree built from flat self-referential rows with getParentId, its expanded, selected and checked ids derived from per-row state fields, and siblings sorted with the English or Swedish collator.

`Demo.tsx`:

```tsx
'use client';
import { useState } from 'react';
import { Select } from '@salmonui/dropdowns/select';
import { TreeView, type TreeViewKey } from '@salmonui/navigation/tree-view';

// Flat, self-referential rows as a database returns them: each row names its parent.
// `open`, `current` and `onboarded` are per-row state fields
// (expanded, selected, checked); the application turns them into id lists.
interface Person {
  id: string;
  name: string;
  managerId: string | null;
  open?: boolean;
  current?: boolean;
  onboarded?: boolean;
}

const people: Person[] = [
  { id: 'p1', name: 'Örjan Lind', managerId: null, open: true },
  { id: 'p2', name: 'Zoe Park', managerId: 'p1', open: true, onboarded: true },
  { id: 'p3', name: 'Åsa Berg', managerId: 'p1', open: true },
  { id: 'p4', name: 'Adam Ek', managerId: 'p1', onboarded: true },
  { id: 'p5', name: 'Ärla Holm', managerId: 'p2', current: true, onboarded: true },
  { id: 'p6', name: 'Bo Ström', managerId: 'p2' },
  { id: 'p7', name: 'Olle Nyberg', managerId: 'p3', onboarded: true },
  { id: 'p8', name: 'Ylva Sund', managerId: 'p3' },
];

const SORTS = [
  { value: 'asc', label: 'asc' },
  { value: 'desc', label: 'desc' },
  { value: 'none', label: 'data order' },
];
const LOCALES = [
  { value: 'en', label: 'English (en)' },
  { value: 'sv', label: 'Swedish (sv)' },
];

const ids = (pick: (p: Person) => boolean | undefined): TreeViewKey[] => people.filter(pick).map((p) => p.id);

export default function TreeViewFlatDataDemo() {
  const [expanded, setExpanded] = useState<readonly TreeViewKey[]>(() => ids((p) => p.open));
  const [selected, setSelected] = useState<readonly TreeViewKey[]>(() => ids((p) => p.current));
  const [checked, setChecked] = useState<readonly TreeViewKey[]>(() => ids((p) => p.onboarded));
  const [sort, setSort] = useState<'asc' | 'desc' | 'none'>('asc');
  const [locale, setLocale] = useState('en');
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      <div className="demo-toolbar" style={{ marginBlockEnd: 0 }}>
        <label>
          Sort{' '}
          <Select aria-label="Sort" data={SORTS} value={sort} onValueChange={(value) => value != null && setSort(value as 'asc' | 'desc' | 'none')} />
        </label>
        <label>
          Locale{' '}
          <Select aria-label="Locale" data={LOCALES} value={locale} onValueChange={(value) => value != null && setLocale(String(value))} />
        </label>
      </div>
      <TreeView
        aria-label="Team"
        data={people}
        getItemId={(p) => p.id}
        getItemLabel={(p) => p.name}
        getParentId={(p) => p.managerId}
        sort={sort === 'none' ? null : sort}
        locale={locale}
        checkPropagation="none"
        checkable
        expanded={expanded}
        onExpandedChange={(e) => setExpanded(e.expanded)}
        selected={selected}
        onSelectedChange={(e) => setSelected(e.selected)}
        checked={checked}
        onCheckedChange={(e) => setChecked(e.checked)}
        height={300}
        style={{ maxInlineSize: 420 }}
      />
      <p style={{ margin: 0 }}>
        Expanded: <output>{expanded.join(', ') || 'none'}</output>
        <br />
        Selected: <output>{selected.join(', ') || 'none'}</output>
        <br />
        Onboarded (checked): <output>{checked.join(', ') || 'none'}</output>
      </p>
    </div>
  );
}
```

### Live demo: Tree View interaction

Live demo: https://salmonui.dev/demos/navigation/tree-view-interaction

A handbook tree with long wrapping labels, a switch for what expands a parent, full-row or label-only highlight, an onItemClick log and a native onKeyDown that can skip the built-in keys.

`Demo.tsx`:

```tsx
'use client';
import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Select } from '@salmonui/dropdowns/select';
import { TreeView } from '@salmonui/navigation/tree-view';

interface Topic {
  id: string;
  title: string;
  children?: Topic[];
}

const topics: Topic[] = [
  {
    id: 'onboarding',
    title: 'Onboarding checklist for new team members joining in the first quarter',
    children: [
      { id: 'laptop', title: 'Request a laptop, a security key and access to the shared drives before the first day' },
      { id: 'buddy', title: 'Pick a buddy' },
    ],
  },
  {
    id: 'policies',
    title: 'Policies',
    children: [
      { id: 'travel', title: 'Travel and expenses, including per diem rates for international trips' },
      { id: 'leave', title: 'Leave' },
    ],
  },
  { id: 'contacts', title: 'Contacts' },
];

type ExpandOn = 'auto' | 'click' | 'doubleClick' | 'none';

const EXPAND_ON = [
  { value: 'auto', label: 'auto' },
  { value: 'click', label: 'click' },
  { value: 'doubleClick', label: 'doubleClick' },
  { value: 'none', label: 'none (twisty only)' },
];
const ROW_HIGHLIGHTS = ['full', 'label'];

export default function TreeViewInteractionDemo() {
  const [expandOn, setExpandOn] = useState<ExpandOn>('auto');
  const [rowHighlight, setRowHighlight] = useState<'full' | 'label'>('full');
  const [textWrap, setTextWrap] = useState(true);
  const [skipEnter, setSkipEnter] = useState(false);
  const [log, setLog] = useState<readonly string[]>([]);
  const add = (entry: string) => setLog((list) => [entry, ...list].slice(0, 6));
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      <div className="demo-toolbar" style={{ marginBlockEnd: 0 }}>
        <label>
          Expand on{' '}
          <Select aria-label="Expand on" data={EXPAND_ON} value={expandOn} onValueChange={(value) => value != null && setExpandOn(value as ExpandOn)} />
        </label>
        <label>
          Row highlight{' '}
          <Select aria-label="Row highlight" data={ROW_HIGHLIGHTS} value={rowHighlight} onValueChange={(value) => value != null && setRowHighlight(value as 'full' | 'label')} />
        </label>
        <Checkbox checked={textWrap} onCheckedChange={(checked) => setTextWrap(checked)}>
          Wrap text
        </Checkbox>
        <Checkbox checked={skipEnter} onCheckedChange={(checked) => setSkipEnter(checked)}>
          Skip built-in Enter
        </Checkbox>
      </div>
      <TreeView
        aria-label="Handbook"
        data={topics}
        getItemId={(t) => t.id}
        getItemLabel={(t) => t.title}
        getChildren={(t) => t.children}
        expandOn={expandOn}
        rowHighlight={rowHighlight}
        textWrap={textWrap}
        onItemClick={(event) => add(`onItemClick ${event.id} (${event.source})`)}
        onKeyDown={(event) => {
          if (event.key === 'Enter' && skipEnter) {
            // preventDefault() skips the built-in Enter (select and activate).
            event.preventDefault();
            add('onKeyDown Enter: preventDefault(), built-in Enter skipped');
            return;
          }
          add(`onKeyDown ${event.key}`);
        }}
        height={260}
        style={{ maxInlineSize: 440 }}
      />
      <div className="demo-log" aria-live="polite" style={{ marginBlockStart: 0, maxInlineSize: 440, boxSizing: 'border-box' }}>
        {log.length === 0 ? (
          <span style={{ color: 'var(--salmon-text-secondary)' }}>No events yet.</span>
        ) : (
          <ol>
            {log.map((entry, index) => (
              <li key={`${index}-${entry}`}>{entry}</li>
            ))}
          </ol>
        )}
      </div>
    </div>
  );
}
```
