# TreeSelect

> TreeSelect from @salmonui/dropdowns/tree-select - a select-only combobox with a tree popup, nested or flat data, lazy children, search that keeps ancestors, templates and forms.

Canonical: https://salmonui.dev/docs/dropdowns/tree-select

`TreeSelect` is a dropdown tree, the
[Select](https://salmonui.dev/docs/dropdowns/select) trigger with a tree popup: a native
`<button type="button" role="combobox" aria-haspopup="tree">` owns focus
and the keyboard, and the popup is a WAI-ARIA `role="tree"` driven through
`aria-activedescendant`, so focus never leaves the trigger (or the popup
search field). The tree model (expansion, lazy loading, selection and
tri-state checks) is the one [TreeView](https://salmonui.dev/docs/navigation/tree-view) uses.

```tsx
import { TreeSelect } from '@salmonui/dropdowns/tree-select';
import '@salmonui/dropdowns/tree-select/styles.css';

<label id="office-label">Office</label>
<TreeSelect aria-labelledby="office-label" data={offices} defaultValue="osa" placeholder="Pick an office" />
```

The server renders the trigger, the value and (with `name`) the hidden
form `<select>` only; the popup is a lazy chunk loaded after hydration and rendered only
while open, so nothing in it can cause a hydration mismatch. Every prop is listed in the
[API reference](https://salmonui.dev/docs/reference/dropdowns/tree-select).

### Live demo: TreeSelect basics

Live demo: https://salmonui.dev/demos/dropdowns/tree-select-basics

A controlled single TreeSelect where only leaves are selectable, a searchable flat-data TreeSelect whose matches keep their ancestors, and a required form field.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { TreeSelect, type TreeSelectValue } from '@salmonui/dropdowns/tree-select';

interface Office {
  id: string;
  name: string;
  children?: Office[];
  closed?: boolean;
}

// Nested data: regions hold countries, countries hold offices.
const OFFICES: Office[] = [
  {
    id: 'emea',
    name: 'Europe',
    children: [
      { id: 'de', name: 'Germany', children: [{ id: 'ber', name: 'Berlin' }, { id: 'muc', name: 'Munich' }] },
      { id: 'fr', name: 'France', children: [{ id: 'par', name: 'Paris' }, { id: 'lyo', name: 'Lyon', closed: true }] },
    ],
  },
  {
    id: 'apac',
    name: 'Asia Pacific',
    children: [
      { id: 'jp', name: 'Japan', children: [{ id: 'tyo', name: 'Tokyo' }, { id: 'osa', name: 'Osaka' }] },
      { id: 'sg', name: 'Singapore', children: [{ id: 'sin', name: 'Singapore City' }] },
    ],
  },
  { id: 'amer', name: 'Americas', children: [{ id: 'us', name: 'United States', children: [{ id: 'nyc', name: 'New York' }, { id: 'sfo', name: 'San Francisco' }] }] },
];

interface Department {
  value: number;
  text: string;
  parent: number | null;
}

// Flat (self-referential) data: each row names its parent.
const DEPARTMENTS: Department[] = [
  { value: 1, text: 'Engineering', parent: null },
  { value: 2, text: 'Platform', parent: 1 },
  { value: 3, text: 'Developer tools', parent: 2 },
  { value: 4, text: 'Design systems', parent: 1 },
  { value: 5, text: 'Sales', parent: null },
  { value: 6, text: 'Partner sales', parent: 5 },
  { value: 7, text: 'Support', parent: null },
  { value: 8, text: 'Developer relations', parent: 7 },
];

const getOfficeValue = (o: Office) => o.id;
const getOfficeLabel = (o: Office) => o.name;
const isLeaf = (o: Office) => o.children === undefined;
const isClosed = (o: Office) => o.closed === true;
const getOfficeProps = (o: Office) => (o.closed ? { title: 'Closed for renovation', 'data-closed': '' } : undefined);
const getDepartmentParent = (d: Department) => d.parent;

// A single TreeSelect with leaf-only selection, a searchable flat-data
// TreeSelect, and a form field with a hidden native select.
export default function TreeSelectBasicsDemo() {
  const [office, setOffice] = useState<TreeSelectValue | null>('osa');
  const [lastKey, setLastKey] = useState('none');
  return (
    <div style={{ display: 'grid', gap: 16, maxWidth: 320 }}>
      <div style={{ display: 'grid', gap: 4 }}>
        <span id="demo-office-label">Office</span>
        <TreeSelect
          aria-labelledby="demo-office-label"
          data={OFFICES}
          getItemValue={getOfficeValue}
          getItemLabel={getOfficeLabel}
          isItemSelectable={isLeaf}
          isItemDisabled={isClosed}
          getItemProps={getOfficeProps}
          value={office}
          onValueChange={setOffice}
          onKeyDown={(event) => setLastKey(event.key)}
          clearable
          placeholder="Pick an office"
        />
      </div>
      <output>
        Value: {String(office)} · last key: {lastKey}
      </output>
      <div style={{ display: 'grid', gap: 4 }}>
        <span id="demo-department-label">Department</span>
        <TreeSelect
          aria-labelledby="demo-department-label"
          data={DEPARTMENTS}
          getParentId={getDepartmentParent}
          defaultExpanded={[1]}
          searchable
          searchOperator="contains"
          highlightMatches
          searchPlaceholder="Search departments"
          placeholder="Any department"
        />
      </div>
      <form
        onSubmit={(event) => {
          event.preventDefault();
          alert(JSON.stringify([...new FormData(event.currentTarget)]));
        }}
        style={{ display: 'grid', gap: 8 }}
      >
        <span id="demo-home-label">Home office (required)</span>
        <TreeSelect aria-labelledby="demo-home-label" name="office" required data={OFFICES} getItemValue={getOfficeValue} getItemLabel={getOfficeLabel} isItemSelectable={isLeaf} placeholder="Choose an office" />
        <Button type="submit" style={{ justifySelf: 'start' }}>
          Submit
        </Button>
      </form>
    </div>
  );
}
```

## Data

Data is nested by default: `getChildren(item)` returns the children, and it
defaults to `item.children`. For self-referential flat rows pass
`getParentId(item)` instead; a row whose parent is `null` or `undefined` is
a root. The accessors read common field names by default:

- `getItemValue` (default `item.value`, else `item.id`): the node value, a
  string or a number. Values are unique across the whole tree.
- `getItemLabel` (default `item.label`, else `item.text`).
- `isItemDisabled` (default `item.disabled === true`): a disabled parent
  disables its whole subtree.
- `isItemSelectable`: nodes it rejects still expand but cannot be chosen.
The demo makes only leaves
  selectable.

```tsx
<TreeSelect data={departments} getParentId={(d) => d.parentId} getItemLabel={(d) => d.name} />
```

Selection and expansion are not read from the data: the value and the
expanded ids are props (below), so the data stays immutable.

## Value and events

`value` / `defaultValue` / `onValueChange(value, event)` is the
[components triad](https://salmonui.dev/docs/buttons/toggle-button): one node value or `null`,
or an array with `multiple` (see
[TreeSelect checkboxes](https://salmonui.dev/docs/dropdowns/tree-select-checkboxes)). The event
is the shared dropdown event `{ source, reason, previousValue, items }`.
`open` / `defaultOpen` / `onOpenChange(open, event)` control the popup, as
on Select. `ref` receives the trigger button, and `onKeyDown` with every
other DOM prop reaches it.

Items of the value that are not in the loaded `data` (children that were
never loaded) take their labels from `selectedItems`.

## Expansion

`expanded` / `defaultExpanded` / `onExpandedChange(ids, { id, item, source })`
hold the expanded node values. `expandOn` decides what a click on
a parent does:

| `expandOn` | Click on a parent row |
| --- | --- |
| `'auto'` (default) | Toggles a parent that is not selectable; selects a selectable one |
| `'click'` | Toggles any parent; Enter or Space selects it |
| `'doubleClick'` | A double-click toggles; a click selects |
| `'none'` | Only the twisty and the arrow keys expand |

When the popup opens with a value, the selected node's ancestors expand and
the node scrolls into view and becomes active. To reveal any other node, add its
ancestors to a controlled `expanded`.

## Load on demand

`hasChildren(item)` shows a twisty before the children are known;
expanding the node calls `loadChildren(item, { signal })`. A
response that arrives after the node was collapsed and reloaded, or after
`data` changed, is dropped, and `signal` aborts the stale request. A
rejected load marks the node with an error and a Retry button and calls
`onLoadError(error, item)`; `renderLoading({ item })` and
`renderError({ error, item, retry })` replace the default status texts.

### Live demo: TreeSelect lazy loading

Live demo: https://salmonui.dev/demos/dropdowns/tree-select-lazy

Folders load on first expand through loadChildren with an abort signal; one share fails first and shows a custom error row with Retry, plus header, footer and item templates.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { TreeSelect, type TreeSelectValue } from '@salmonui/dropdowns/tree-select';

interface Dir {
  id: string;
  name: string;
  lazy?: boolean;
}

const ROOTS: Dir[] = [
  { id: 'home', name: 'home', lazy: true },
  { id: 'mnt', name: 'mnt (flaky network share)', lazy: true },
  { id: 'readme', name: 'README' },
];

// Every loaded folder holds the same three subfolders; the last has no children.
const FOLDERS = ['projects', 'photos', 'archive'];

const getDirValue = (d: Dir) => d.id;
const getDirLabel = (d: Dir) => d.name;
const hasChildren = (d: Dir) => d.lazy === true;

// Load on demand: `hasChildren` shows a twisty before the children are
// known, `loadChildren` fetches them (aborted through `signal` when stale).
export default function TreeSelectLazyDemo() {
  const [failures] = useState(() => new Set(['mnt']));
  const [value, setValue] = useState<TreeSelectValue | null>(null);
  const [log, setLog] = useState<string[]>([]);
  return (
    <div style={{ display: 'grid', gap: 12, maxWidth: 360 }}>
      <div style={{ display: 'grid', gap: 4 }}>
        <span id="demo-folder-label">Folder</span>
        <TreeSelect
          aria-labelledby="demo-folder-label"
          data={ROOTS}
          getItemValue={getDirValue}
          getItemLabel={getDirLabel}
          hasChildren={hasChildren}
          loadChildren={(dir, { signal }) =>
            new Promise<Dir[]>((resolve, reject) => {
              const timer = setTimeout(() => {
                if (failures.delete(dir.id)) reject(new Error('Network share unavailable'));
                else resolve(FOLDERS.map((name, i) => ({ id: `${dir.id}/${name}`, name, lazy: i < 2 })));
              }, 700);
              signal.addEventListener('abort', () => clearTimeout(timer));
            })
          }
          onLoadError={(error, dir) => setLog((l) => [...l, `${dir.name}: ${(error as Error).message}`])}
          renderItem={({ label, level }) => (
            <span>
              <span aria-hidden="true">{level === 1 ? '🗄 ' : '📁 '}</span>
              {label}
            </span>
          )}
          renderLoading={() => <em>Loading folders…</em>}
          renderError={({ error, retry }) => (
            <span>
              {(error as Error).message}{' '}
              <Button
                variant="outline"
                tabIndex={-1}
                // Keep focus on the trigger, and keep the click off the row (it would select the share).
                onPointerDown={(event) => event.preventDefault()}
                onClick={(event) => {
                  event.stopPropagation();
                  retry();
                }}
              >
                Retry
              </Button>
            </span>
          )}
          popupHeader={<strong>Choose a folder</strong>}
          popupFooter={<small>Folders load on first expand.</small>}
          value={value}
          onValueChange={setValue}
          clearable
          placeholder="Pick a folder"
        />
      </div>
      <output>Value: {String(value)}</output>
      <p>
        Errors: <output>{log.join('; ') || 'none'}</output>
      </p>
    </div>
  );
}
```

To load children from a server, read a `@salmonui/data` source per
parent: `read({ parentRowId })` answers
tree envelopes (`TreeRowEnvelope`: `row`, `hasChildren`, ...), and
`loadChildren` unwraps them.

```tsx
import { createJsonDataSource } from '@salmonui/data';
import { EMPTY_GRID_QUERY } from '@salmonui/data-grid/engine';

const folders = createJsonDataSource<Folder>({ url: '/api/folders', key: 'id' });

<TreeSelect
  data={roots}
  hasChildren={(f) => f.hasChildren}
  loadChildren={async (folder, { signal }) => {
    const result = await folders.read({ version: 0, query: EMPTY_GRID_QUERY, parentRowId: folder.id, signal });
    return result.rows.map((envelope) => envelope.row);
  }}
/>
```

## Search

`searchable` puts a search field in the popup: DOM focus moves
into it and typing filters the tree with `searchOperator` (`'startsWith'`
by default, `'contains'`, `'endsWith'` or `(item, text) => boolean`),
`matchCase` and `ignoreAccents`. Matches keep their ancestors visible, so a
match always appears under its path. `searchPlaceholder` labels the field,
`onSearchChange(text, event)` reports the text and `highlightMatches` marks
the matched characters.

## Templates and per-node props

The [Templates](https://salmonui.dev/docs/dropdowns/dropdown-templates) render props apply:

| Part | Template |
| --- | --- |
| Node | `renderItem({ item, label, level, selected, checked, expanded, active, disabled, matches })` |
| Selected value | `renderValue({ items, labels })` |
| Popup header and footer | `popupHeader`, `popupFooter` |
| Empty tree | `renderEmpty({ reason })` (`'noData'` or `'noMatch'`) |
| Load error | `renderError({ error, item, retry })`, per node that failed to load |

Per-node icons and attributes: `getItemIcon(item)` renders an
icon before the label, and `getItemProps(item)` merges `title` (a
tooltip), `data-*`, `className` and `style` onto the `treeitem`. Both are
pure functions of the item, so the server renders the same markup.

Text is always escaped by React and no HTML strings are rendered, so
there are no HTML encoding or sanitizer options: render markup with `renderItem`.

## Popup

The popup renders after a user action only, in a portal in the top layer,
below the trigger (above when there is no room) and at least as wide.
`maxVisibleItems` (default 8) sets its height in rows; the tree is windowed
above 100 shown rows (`virtualization={false}` turns that off). `popupMode`
is `'popover'`, `'sheet'` (a full-screen dialog) or `'auto'` (the sheet on
coarse-pointer phones, decided at open time), as on Select.

The popup always unmounts when it closes (there is no option to keep
its DOM). A
closed popup must cost nothing and is never server-rendered, and a kept DOM
would leave stale ARIA ids in the document. The expanded ids and the value
persist in state, so reopening restores the view. `showTrigger` (default
`true`) shows the chevron.

## Keyboard

| Key | Closed | Open |
| --- | --- | --- |
| Arrow Down / Up | Open | Move the active node |
| Enter, Space, Alt+Down | Open | See below |
| Arrow Right | | Expand a collapsed parent, then move to its first child |
| Arrow Left | | Collapse an expanded parent, else move to the parent |
| Home / End | | First / last shown node |
| Page Down / Page Up | | Move by `maxVisibleItems` |
| Enter | | Select the active node (single closes); a non-selectable parent toggles |
| Space | | Select the node, or toggle its checkbox |
| Alt+Up | | Choose the active node and close |
| Ctrl+A / Cmd+A | | Check or select every node (`multiple`) |
| Letters | | Move to the next matching node (type-ahead) |
| Escape | | Clear the search, then close |
| Tab | | Close and move focus on |
| Delete / Backspace | Clear the value with `clearable` | |

Arrow Right and Left mirror in RTL. Disabled nodes are skipped.

## Accessibility

The popup is an APG tree: `role="tree"` (with
`aria-multiselectable` when `multiple`), rows are `role="treeitem"` with
`aria-level`, `aria-setsize`, `aria-posinset` and `aria-expanded` on
parents, `aria-selected` (or `aria-checked`, including `'mixed'`, with
checkboxes), `aria-disabled`, and `aria-busy` while children load. The
active row stays rendered when it scrolls out of the virtual window, so
`aria-activedescendant` always resolves. The trigger carries
`aria-expanded`, `aria-controls`, `aria-readonly` and `aria-required`.
Label it with `aria-labelledby` or a `<label htmlFor>`; there is no
floating label. The placeholder is hidden from assistive technology.

## Forms and appearance

With `name`, a hidden native `<select>` holds one option per value, so the
value submits with the form, appears in `FormData` and `required` uses
native validation; a form `reset` restores `defaultValue`. `form`,
`disabled`, `readOnly`, `clearable` and `placeholder` behave as on
[Select](https://salmonui.dev/docs/dropdowns/dropdown-forms).

`className` and `style` reach the root; `classNames` / `styles` reach the
parts `root`, `trigger`, `value`, `chip`, `popup`, `tree`, `item` and
`search`. Texts come from `localeText` over
`TREE_SELECT_DEFAULT_LOCALE_TEXT` (the dropdown texts plus
`loadingChildren`), and `locale` formats lists and counts.

`size` (`'sm' | 'md' | 'lg'`, default `'md'`) sets the trigger to 24, 32
or 40 px with 8, 12 or 16 px of inline padding and 14, 16 or 20 px icons,
as on [Select](https://salmonui.dev/docs/dropdowns/select#size); chips follow the size and the
tree rows keep one size.

## Data ownership

There is no method that returns the tree's data: the application already owns `data`, the value and the
expanded ids, so it reads them directly; the event's `items` hold the items
of a new value. There is no sort option either: the tree shows data order, because sorting is a data concern
(a collator sort on every `data` change would land on the open path, and a
remote source already sorts on the server). Sort each level before passing
it, or sort on the server for `loadChildren`. See
[Data, search and the popup](https://salmonui.dev/docs/dropdowns/dropdown-popup-data) for the
data model shared with the other dropdowns.
