# Tree Components — Common API Reference

Three components share a common `TreeComponent` interface: **`ixfx-tree-list`**, **`ixfx-miller-list`**, and **`ixfx-crumb-navigation`**. This document describes the shared API, plus component-specific behaviour where noted.

`ixfx-crumb-path` uses a fundamentally different string-based model and is not covered here.

---

## Contents

1. [Data model](#data-model)
2. [Properties](#properties)
   - [Custom checkbox (`checkboxRenderer`)](#custom-checkbox-ixfx-tree-list-only--checkboxrenderer)
   - [Unselectable items (`selectable`, `alignCheckboxes`)](#unselectable-items-selectable-aligncheckboxes)
   - [Virtualisation](#virtualisation-ixfx-tree-list)
3. [Selection](#selection)
4. [Events](#events)
5. [Keyboard navigation](#keyboard-navigation)
6. [Incremental search](#incremental-search)
7. [ARIA](#aria)
8. [CSS variables](#css-variables)
9. [Controller authoring guide](#controller-authoring-guide)
10. [View state](#view-state-ixfx-tree-list)

---

## Data model

### Core types

```typescript
type TreeItem = {
  key: string;        // Unique identifier across the whole tree
  label: string;      // Display text
  isLeaf?: boolean;   // true = never expandable; undefined/false = branch
  selectable?: boolean; // false = can never be selected (and gets no checkbox in `checked` mode)
  data?: unknown;     // Arbitrary user payload
  icon?: string;      // Icon name (passed to <ixfx-icon>)
  tooltip?: string;   // Tooltip content
  value?: string;     // Optional machine-readable value
  weight?: number;    // Relative importance/magnitude; used by ixfx-hyperbolictree-list and ixfx-sunbursttree-list
};

type TreeNode = {
  item: TreeItem;
  children?: TreeNode[];  // undefined = unloaded; [] = confirmed empty
};
```

`TreeNode` is **immutable** — structural changes always produce a new root. Never mutate a node in place; use `TreeDataModel` convenience methods or replace `root` directly.

**Incremental updates.** `TreeController.sync()` re-derives children of already-materialised nodes from the source tree and patches them in place (nodes are reused by key, so expansion and selection survive). `navigateToKeyPath(keys)`, `navigateToIdentity(id)` and `lookupByKey(key)` resolve targets without searching the source tree.

**Escape hatch for in-place edits.** The component itself fills in `node.children` when lazy-loading, and `TreeController` does the same. If you must edit `node.children` or `node.item` (e.g. an icon) in place, call `el.invalidateStructure()` afterwards. It drops the cached whole-tree indexes (parent map, icon depths, filter matches, checkbox states) and re-renders. Visible rows are re-derived on every update, so ordinary expand / collapse never needs it.

---

### Static trees

Set `root` directly when the tree data is available up-front:

```typescript
el.root = {
  item: { key: 'root', label: 'My Files' },
  children: [
    { item: { key: 'docs', label: 'Documents' }, children: [] },
    { item: { key: 'img', label: 'Images', isLeaf: true } },
  ],
};
```

---

### Lazy loading via `loadChildren`

Set `loadChildren` to fetch children on demand (called when a branch is expanded):

```typescript
el.loadChildren = async ({ node, depth }, signal) => {
  const res = await fetch(`/api/children/${node.item.key}`, { signal });
  return res.json(); // TreeNode[]
};
```

The callback receives an `AbortSignal`; honour it to avoid races when the user collapses quickly. It may return `TreeNode[]`, `Promise<TreeNode[]>`, or `AsyncIterable<DataBatch<TreeNode>>` for streaming children.

---

### `TreeDataModel` — shared, cached data layer

`TreeDataModel` is an optional shared data layer that owns child-loading and caching. It is useful when:

- Multiple components display the same dataset (e.g. a tree-list and a miller-list side-by-side).
- You need programmatic tree mutation without tracking the root yourself.
- You need to invalidate (refresh) individual branches without a full re-render.

```typescript
import { TreeDataModel } from '@ixfx/components';

const model = new TreeDataModel({
  root: { item: { key: 'root', label: 'Root' }, children: undefined },
  loadChildren: async ({ node }, signal) => {
    const res = await fetch(`/api/children/${node.item.key}`, { signal });
    return res.json();
  },
});

treeEl.model = model;
millerEl.model = model;   // Both components share the same cache
```

#### Model API

| Member | Signature | Description |
|--------|-----------|-------------|
| `root` | `get root(): TreeNode` | Current immutable root snapshot |
| `setRoot` | `(root: TreeNode): void` | Replace the root; notifies all connected components |
| `getChildren` | `(node, depth, signal): Promise<TreeNode[]>` | Returns cached children or calls `loadChildren`; cache keyed by `node.item.key` |
| `invalidate` | `(nodeKey: string): void` | Clears cached children for `nodeKey`; connected components collapse that branch so the next expand triggers a fresh fetch |
| `addNode` | `(parentKey, node): TreeNode` | Appends a child; returns new root |
| `removeNode` | `(key): TreeNode` | Removes node and all descendants; returns new root |
| `updateItem` | `(key, patch): TreeNode` | Merges `patch` into the item at `key`; returns new root |
| `moveNode` | `(key, newParentKey): TreeNode` | Moves a node under a new parent; returns new root |
| `_subscribe` | `(cb): () => void` | Internal subscription used by components; returns unsubscribe |

#### How caching works

`getChildren()` stores results in a `Map<string, TreeNode[]>` keyed by `node.item.key`. A cache hit returns the stored array synchronously (wrapped in a resolved `Promise`). `invalidate(key)` deletes the cache entry and emits an `invalidate` event; connected components collapse the branch so the next expand triggers a fresh load.

Mutator methods (`addNode`, `removeNode`, `updateItem`, `moveNode`) apply pure transformations to produce a new immutable root, then emit a `root` event so all connected components re-render.

#### Model vs `loadChildren`

When both `model` and `loadChildren` are set, `model` takes precedence. `loadChildren` remains available for simple cases that do not need sharing or programmatic mutation.

---

## Properties

These properties are present on all three components (`ixfx-tree-list`, `ixfx-miller-list`, `ixfx-crumb-navigation`).

| Property / Attribute | Type | Default | Description |
|----------------------|------|---------|-------------|
| `root` | `TreeNode \| undefined` | `undefined` | Root node of the tree. Replacing it keeps expansion for every `item.key` still present (see [Replacing `root`](#replacing-root)); selection and focus are reset |
| `model` | `TreeDataModel \| undefined` | `undefined` | Shared data model; takes precedence over `loadChildren` |
| `loadChildren` | `LoadChildrenCallback \| undefined` | `undefined` | Callback for lazy child loading |
| `selectedNode` | `TreeNode \| undefined` | `undefined` | Primary (most recent) selected node |
| `selectedNodes` | `ReadonlySet<TreeNode>` | `{}` | Full selection set (read-only) |
| `interactionMode` | `TreeInteractionMode` | `'standard'` | How gestures map to selection changes (`ixfx-tree-list` / `ixfx-miller-list` only) |
| `selectionFilter` | `'none' \| 'leaf' \| 'branch'` | `'leaf'` | Which node kinds can be selected (reflected attribute) |
| `alignCheckboxes` (`align-checkboxes`) | `boolean` | `false` | In `checked` mode, unselectable rows keep the space their checkbox would take so they line up with selectable siblings (`ixfx-tree-list` only). See [Unselectable items](#unselectable-items-selectable-aligncheckboxes) |
| `filterPredicate` | `TreeFilterPredicate \| undefined` | `undefined` | Filter; only matching nodes and their ancestors are rendered (non-matching rows are not in the DOM; keyboard navigation, `selectAll`/`deselectAll` and Shift-range skip them) |
| `exclusivity` | `'none' \| 'depth' \| 'global'` | `'none'` | Expansion exclusivity (reflected attribute) |
| `stickyHeaders` (`sticky-headers`) | `boolean` | `true` | VS Code-style sticky headers; set `sticky-headers="false"` to opt out (`ixfx-tree-list` only) |
| `virtualize` | `'auto' \| 'on' \| 'off'` | `'auto'` | Render only the rows near the viewport; `auto` switches on above `virtualizeThreshold` visible rows (`ixfx-tree-list` only). See [Virtualisation](#virtualisation-ixfx-tree-list) |
| `virtualizeThreshold` (`virtualize-threshold`) | `number` | `200` | Visible-row count above which `virtualize="auto"` windows the list |
| `scrollHoverTickle` (`scroll-hover-tickle`) | `boolean` | `false` | Let the hover cursor follow rows that scroll beneath a stationary pointer. Off by default: during a scroll gesture row `pointerenter` is ignored (host carries `data-scroll-hover-suppress`), so the hover highlight and `tickle` hold still instead of trailing the content. Hover resumes on the next real pointer movement or when the pointer leaves |
| `animation` | `'auto' \| 'always' \| 'never'` | `'auto'` | Controls row enter/leave animations. `'auto'` respects `prefers-reduced-motion`; `'always'` always animates; `'never'` skips all animations. Can be overridden per-call on `expandAll`, `collapseAll`, `navigateTo`, `revealKey`, and `navigateToNode` |

### Replacing `root`

Because `TreeNode` is immutable, any structural change means assigning a new `root`. When you do:

- **Expansion is kept** for every branch whose `item.key` still exists in the new root, and dropped for keys that are gone. A key that disappears and later returns comes back collapsed. Call `collapseAll()` if you want a fresh tree.
- **Selection, focus and any pending lazy load are reset**, since they may refer to nodes that no longer exist.
- The reconciliation happens before the render, so assigning `root` and then calling `expandAll()` (or `navigateTo()`) synchronously works as you'd expect:

```ts
tree.root = rebuild();
tree.expandAll(); // stays expanded after the update
```

### `interactionMode` (`ixfx-tree-list` / `ixfx-miller-list`)

Controls how pointer and keyboard gestures translate to selection changes.

| Value | Behaviour |
|-------|-----------|
| `'implicit'` | Single selection follows every click; click also toggles expand/collapse |
| `'standard'` | Plain click selects + toggles expand; Ctrl/Cmd+click toggles item; Shift+click range-selects. Moving the cursor with the keyboard selects the item under it; Shift+move grows the range from the anchor |
| `'manual'` | Component never auto-selects; use `select()` / `deselect()` / `clearSelection()` to drive state |
| `'checked'` | Checkboxes on every row; clicking the checkbox recursively selects/deselects loaded descendants; any other click on the row (caret, label, icon, whitespace) only expands/collapses |
| `'vscode'` | Like `standard` for clicks; plain cursor moves leave the selection alone; Shift+Up/Down uses snapshot-based toggle-range (VS Code file-explorer style) |

Switching `interactionMode` clears the current selection.

### Custom checkbox (`ixfx-tree-list` only) — `checkboxRenderer`

In `checked` mode every checkable row gets a checkbox before its caret/icon/label. By default that's a native `<input type="checkbox">`, with `.indeterminate` set when a branch has some but not all descendants selected.

Set `checkboxRenderer` on `ixfx-tree-list` to replace it with your own template. The function receives the row's current tri-state — `'checked' | 'unchecked' | 'indeterminate'` — so a branch with a partial selection can render distinctly (a dash, a dimmer mark, etc.) rather than collapsing to just checked/unchecked:

```typescript
import { html } from 'lit';
import type { TreeListElement } from '@ixfx/components';

const tree = document.querySelector<TreeListElement>('#my-tree')!;
tree.interactionMode = 'checked';

tree.checkboxRenderer = (state) => state === `unchecked`
  ? html``
  : html`<svg viewBox="0 0 16 16" width="14" height="14"
        fill="none" stroke="currentColor" stroke-width="2"
        stroke-linecap="round" stroke-linejoin="round"
        style="opacity:${state === `indeterminate` ? 0.35 : 0.7}">
      <polyline points="3,8 7,12 13,4" />
    </svg>`;
```

When `checkboxRenderer` is set, the checkbox becomes a `<span class="tree-checkbox" role="checkbox" part="checkbox">` holding your template, with `aria-checked` set to `"true"`, `"false"`, or `"mixed"` to match the tri-state. The span owns the click (same as the native input), so clicking anywhere in it — including empty space when you render nothing for `unchecked` — toggles the row.

In `checked` mode **only the checkbox toggles the checked state**: the native input, or the custom renderer's `.tree-checkbox-custom` area when `checkboxRenderer` is set. Clicks anywhere else on the row, including the caret, label, icon and surrounding whitespace, only expand/collapse a branch and never change the selection. If your custom checkbox is small, enlarge the target with `--tree-checkbox-size`.

Both the native input and the custom span expose the `checkbox` CSS part for external styling:

```css
ixfx-tree-list::part(checkbox) {
  width: 18px;
  margin-right: 6px;
}
```

### Unselectable items (`ixfx-tree-list`) — `selectable`, `alignCheckboxes`

Set `selectable: false` on a `TreeItem` to stop that one node being selected, independent of `selectionFilter` and of the interaction mode. Selection APIs (`selectNode`, `selectAll`, `Shift`-range, search "select" mode) skip it.

```typescript
const root: TreeNode = {
  item: { key: 'root', label: 'root' },
  children: [
    {
      item: { key: 'fruit', label: 'Fruit', selectable: false },   // heading only
      children: [
        { item: { key: 'apple', label: 'Apple', isLeaf: true } },  // selectable
        { item: { key: 'pear', label: 'Pear', isLeaf: true } },
      ],
    },
  ],
};
```

In `checked` mode:

- An unselectable row is drawn **without a checkbox**, and there is nothing on the row that toggles selection; clicks expand/collapse it like a normal row.
- Its selectable descendants behave as normal. Unselectable leaves are ignored when working out a parent's `checked` / `indeterminate` state, so a branch whose only selectable children are all checked shows as checked.
- Only the item's own flag decides whether a checkbox is drawn. A branch that `selectionFilter="leaf"` stops being selected itself still gets a checkbox, because that checkbox toggles its descendants.

**Alignment.** By default an unselectable row reserves no space where the checkbox would be, so its caret and label sit further left than its selectable siblings. Set the `align-checkboxes` attribute (or `alignCheckboxes = true`) to keep that space:

```html
<ixfx-tree-list interaction-mode="checked" align-checkboxes></ixfx-tree-list>
```

The reserved space is an empty `<span class="tree-checkbox-spacer" aria-hidden="true">` the same size as a checkbox (`--tree-checkbox-size`, default `14px`, plus a `--space-xs` right margin). The native checkbox uses the same size, so rows line up exactly.

`alignCheckboxes` has no effect outside `checked` mode. `selectable: false` is honoured by the other tree components for selection, but only `ixfx-tree-list` draws checkboxes. See the "Unselectable items" section of `demo/tree-list.html` for a live example with a toggle.

### `selectionFilter`

| Value | Behaviour |
|-------|-----------|
| `'none'` | No nodes can be selected |
| `'leaf'` | Only leaf nodes can be selected: `isLeaf: true`, or a loaded node with `children: []` (unless `isLeaf: false`). A node whose `children` are not loaded yet is not a leaf |
| `'branch'` | Only branch nodes can be selected |

### `exclusivity`

Controls how expansion of one branch affects others.

| Value | Behaviour |
|-------|-----------|
| `'none'` | Any number of branches can be open simultaneously |
| `'depth'` | Opening a branch collapses its siblings at the same depth (accordion) |
| `'global'` | Opening any branch collapses all other open branches in the tree |

`exclusivity="depth"` replaces the old `accordion` boolean attribute. To migrate: `accordion` → `exclusivity="depth"`.

### Sticky headers (`ixfx-tree-list`)

On by default: while scrolling vertically, the ancestors of the top-visible row stick to the top of the list (VS Code-style sticky scroll), showing the full chain. Set `sticky-headers="false"` to opt out.

- Clicking a stuck header selects that ancestor and scrolls its real row into view; clicking its caret toggles expansion. Keyboard interaction stays in the real list.
- An ancestor that is itself still visible is never duplicated in the header.
- Style via `--tree-sticky-bg`, `--tree-sticky-border`, `--tree-sticky-shadow`, and the `sticky-headers` / `sticky-header` parts.

### Animation control

Row enter/leave animations are controlled by the `animation` property:

| Value | Behaviour |
|-------|-----------|
| `'auto'` (default) | Animate normally, respecting `prefers-reduced-motion` and the `MAX_ANIMATED_ROWS` (50) threshold |
| `'always'` | Always animate, even when many rows change at once |
| `'never'` | Skip all row enter/leave animations |

```html
<ixfx-tree-list animation="never"></ixfx-tree-list>
```

**Per-call override**: Methods that change the tree structure accept an optional `animate` parameter to override the property for that single call:

```typescript
// Expand with animation (default)
tree.expandAll();

// Expand without animation
tree.expandAll(undefined, false);

// Collapse without animation
tree.collapseAll(0, false);

// Navigate with animation
tree.navigateTo(['root', 'child']);

// Navigate without animation
tree.navigateTo(['root', 'child'], { animate: false });

// Reveal without animation
tree.revealKey('some-key', false);
```

This is useful when populating a tree initially or when performance matters more than visual polish.

### Virtualisation (`ixfx-tree-list`)

A node with 10,000 children needs only about 25 `<li>` elements in the DOM. When
the number of visible rows (expanded rows, after any filter) exceeds
`virtualize-threshold` (default 200), `ixfx-tree-list` renders only the rows
near the viewport, plus 5 rows of overscan either side. Two spacer `<li>`s
hold the scroll height for the rest. Force it with `virtualize="on"` or disable
it with `virtualize="off"`; `data-virtual` is set on the host while the list is
windowed.

```html
<ixfx-tree-list virtualize="on" style="--tree-item-height: 28px"></ixfx-tree-list>
```

Everything is keyed by node, not by DOM element, so these behave exactly as
they do without windowing and cover rows that are not rendered:

- **Cursor, selection, `selectAll`, Shift-range** and **checkbox states**.
- **Keyboard**: arrows move across the whole list, and Home / End / PageUp / PageDown
  jump by index. The cursor row is scrolled into view in the same frame, so it
  is never missing.
- **Incremental search**: `navigate`, `select` and `filter` modes search the whole tree.
  Match highlights are repainted as the window moves.
- **`navigateTo` / `revealKey`**: expand ancestors and scroll to the row. `navigateTo(keys, { reveal: 'center-if-hidden' })` centres the row only when it is off screen (arithmetic, no DOM measuring); `{ silent: true }` suppresses the `select` event. Otherwise `select` detail carries `origin: 'user' | 'programmatic'`.
- **Drag and drop**: drop targets are computed from the layout, so auto-scroll while dragging works.
- **Sticky headers**: found by arithmetic, with no per-row measuring.

Constraints while windowed:

- Every row must render at the same height. The list measures a rendered row's
  box (which includes its padding and border, so it is taller than
  `--tree-item-height` alone) and its top margin, and places rows by that stride.
  Keep labels single-line (they truncate with an ellipsis) and custom row content within the row.
- **Expand / collapse and insert / remove rows do not animate.** The
  fading "ghost" rows need variable heights. Below the threshold, or with
  `virtualize="off"`, animation works as before.
- The sticky-header overlay is taken out of the layout flow so it cannot shift row positions.
- Rows outside the window do not exist in the DOM. Use the component's API
  (`getNodes()`, `selectedNodes`, `revealKey()`) rather than `querySelector` to find a node.

**Real-browser benchmark** — `pnpm bench:tree-list` (needs the dev server, `pnpm start`) drives
`demo/tree-list.html` in headless Chrome with 100k nodes in three shapes (flat, folders, deep) and
reports main-thread ms per scroll frame / arrow key / hover / select, `setRoot` and `expandAll`
time, bulk collapse+expand, and retained JS heap. Use `--out` / `--compare` around a change.
Reference (100k, Chrome): arrow ≈ 2 ms script, select ≈ 1.5 ms, hover ≈ 0.3 ms, scroll ≈ 1 ms/frame,
deep `expandAll` ≈ 25 ms, ≈ 16 MB heap.

**100k-row reference (happy-dom, JS only)** — scroll frame ≈ 2.5 ms (happy-dom DOM work for
the rendered rows), select ≈ 0.5 ms, hover ≈ 0.3 ms, keyboard step ≈ 1 ms, `expandAll` ≈ 10–30 ms
(also for deep trees), ≈ 22 MB retained (flat rows ≈ 7 MB, key index ≈ 4 MB, parent index ≈ 3.5 MB).
Updates that only change selection, the cursor, scroll or sticky headers reuse the row model;
anything else (expansion, filter, `root`, any other property, or an external `requestUpdate()`)
rebuilds it, which is O(visible rows). After mutating `node.children` in place, call
`invalidateStructure()` (or `requestUpdate()`) as before.

Every row gets `aria-level`, `aria-setsize` and `aria-posinset`, counted over
**all** siblings (those matching the filter), so assistive technology
reports "5,000 of 10,000" even though most siblings are not in the DOM. The list
also exposes `aria-rowcount`.

---

## Selection

### Programmatic selection

```typescript
// Select a node (respects selectionFilter; always replaces selection)
el.select(node);

// Remove a specific node from the selection
el.deselect(node);

// Clear the entire selection
el.clearSelection();

// Select all visible items
el.selectAll();

// Deselect all items
el.deselectAll();
```

`selectAll()` selects every selectable node in the tree, including nodes inside collapsed branches (unloaded lazy children are not included). `deselectAll()` deselects the same set. Pass `{ visibleOnly: true }` to act only on the rows that are showing; Ctrl+A and the `select-all` command do this.

| Mode | `selectAll()` | `selectAll({ visibleOnly: true })` |
|------|---------------|-----------------|
| `checked` | Checks every selectable node | Same: checking a row checks its descendants |
| All other modes | Adds every selectable node to the selection | Adds the showing selectable rows |

While a `filterPredicate` is active, `selectAll()` / `deselectAll()` cover only the matching nodes (and their matching ancestors), and Shift-range selection covers only the rows that are shown (as in `ixfx-vertical-list`). `deselectAll()` leaves selected nodes the filter hides alone.

Both methods dispatch a single `select` event with the full old and new selection sets. `selectAll` respects `selectionFilter` — only nodes that pass the filter are selected.

### Reading the selection

```typescript
// Primary (most-recent) selected node
console.log(el.selectedNode?.item.label);

// Full selection set (for multi-select)
for (const node of el.selectedNodes) {
  console.log(node.item.label);
}
```

### Listening for selection changes

```typescript
el.addEventListener('select', ({ detail }) => {
  const { selected, previous } = detail;
  console.log('Selected:', [...selected].map(n => n.item.label));
  console.log('Previously:', [...previous].map(n => n.item.label));
});
```

---

### Selection intents and partial rows (`ixfx-tree-list`)

A cancelable `list-select-intent` fires before a click, Space, Enter, Shift+Arrow, Ctrl/Cmd+A, a checkbox or `selectAll()` changes the selection (in every interaction mode, including `manual`); `preventDefault()` means "I'll apply it". Expansion and the cursor still behave normally. Checking a branch in `checked` mode is one `toggle` intent with `descendants: true` and `checked` (the state it is being set to): `keys` lists the loaded selectable nodes under it, but the caller can express it as a rule ("this folder and everything under it"). `list-select` `{ selectedKeys, previousKeys, previous }` fires next to `select`.

`partialKeys` marks nodes as partially selected: in `checked` mode the checkbox is indeterminate if either the loaded descendants or `partialKeys` say so (selected wins over partial); otherwise `data-partial` and an accessible description. Incremental search in `select` mode fires a `match` intent first (see below). See [Selection intents, partial rows, unloaded keys](./user-selection-intents.md).

## Expansion

### Programmatic expansion

```typescript
// Expand every already-loaded branch
el.expandAll();

// Expand down to depth 1: top-level branches open, so their children
// (depth 1) are visible (root's children are depth 0)
el.expandAll(1);

// Collapse everything
el.collapseAll();

// Collapse branches at depth 1 and deeper — top-level branches stay open,
// so the tree remains open down to depth 0
el.collapseAll(1);
```

Notes:

- Both methods apply in a single update — one re-render for the whole tree.
- Only **already-loaded** branches are expanded; lazily loaded children are not
  fetched. Call `expandAll()` again after children load to expand further.
- Bulk expansion ignores `exclusivity` — it is an explicit "open everything"
  command.
- One `expand` / `collapse` event fires per branch whose state actually changes;
  branches already in the target state (including those opened by filter
  auto-expansion) stay silent.

---

## View state (`ixfx-tree-list`)

Snapshot and restore selection, expansion, keyboard cursor and scroll
separately from the data — see [`docs/infra-view-state.md`](./infra-view-state.md)
for the shared contract. `kind: 'tree-list'`; fields `selected`, `expanded`,
`focus`, `scroll`, all keyed by `item.key`.

```typescript
import { bindViewState } from '@ixfx/components';

bindViewState(tree, {
  load: () => JSON.parse(localStorage.getItem(`tree`) ?? `null`),
  save: s => localStorage.setItem(`tree`, JSON.stringify(s)),
});
tree.root = initialRoot; // any time, before or after
```

- **Keys, not nodes.** Replacing `root` keeps selection, expansion and cursor
  for every key the new root still has. State for keys that disappear is kept
  *pending* and comes back if they reappear — expand `C`, swap in a root
  without it, swap back, and `C` is open again.
- **Built up over time.** `setViewState({ expanded: { A: true, B: true, C: true } })`
  then grow the tree (new `root`, or mutate `children` + `invalidateStructure()`):
  each branch opens as it arrives.
- **Lazy trees.** With `restoreLoads` (default `true`) saved-open branches that
  aren't loaded are fetched through `loadChildren` / `model`, one at a time, so
  a saved path cascades open. `el.restoreLoads = false` to only open branches
  the host loads itself.
- **Selection.** A restored key fires the normal `select` event
  (`origin: 'programmatic'`). Any explicit selection change — click, key,
  `select()`, `clearSelection()` — drops a saved selection that hasn't matched yet.
- **Scroll** is saved as the first visible row's key plus an offset, and is
  applied once that row exists. The user's own scroll cancels it.
- `focus` is recorded only for a keyboard-moved cursor, not mouse hover.

---

## Events

All events **bubble** and are **composed** (cross shadow-DOM boundaries).

| Event | Detail type | When fired |
|-------|-------------|------------|
| `select` | `TreeSelectDetail` | Selection set changes by any means (click, keyboard, programmatic) |
| `tickle` | `TreeTickleDetail` | An item enters cursor focus: pointer hover OR keyboard navigation cursor |
| `activate` | `TreeActivateDetail` | User explicitly activates an item (Enter key or double-click) |
| `item-click` | `{ node: TreeNode; depth: number }` | Raw pointer click on any item (not fired for the second click of a double-click) |
| `item-dblclick` | `TreeItemDblClickDetail` | User double-clicks an item. The second click is swallowed, so a branch is never toggled open/closed by a double-click. `activate` also fires. |
| `expand` | `{ node: TreeNode; depth: number }` | A branch expands |
| `collapse` | `{ node: TreeNode; depth: number }` | A branch collapses |
| `list-native-drag-start` | `ListNativeDragStartDetail<TreeNode>` | A drag begins on a draggable row (see drag & drop below). Cancelable. |
| `tree-drag-start` | `TreeDragContext` — `{ nodes, keys }` | A drag of tree nodes has begun (fires just after a non-cancelled `list-native-drag-start`). |
| `tree-drag-over` | `TreeDropContext` | Every `dragover` where a drop target resolved. `preventDefault()` rejects the drop (same as `canDrop` returning `false`). Cancelable. |
| `tree-drop` | `TreeDropDetail` | A validated drop occurred. `preventDefault()` stops the component applying it (you handle it). Cancelable. |
| `tree-drag-end` | `{ dropped: boolean }` | A drag ended. `dropped` is `true` only for a drop that landed on this tree. |

## Drag & drop

`ixfx-tree-list` can let its rows be dragged — to **reparent** or **reorder**
nodes within the tree, and/or **out** of the element entirely (native
file/OS drag-out, like `ixfx-grid-list`). It can also be a **drop target** for
nodes from another `ixfx-tree-list` or from an arbitrary external source.

Opt in with the single **`item-dnd`** attribute:

| `item-dnd` | Rows draggable | Internal reparent/reorder | Native drag-out | Accepts drops |
|------------|:--:|:--:|:--:|:--:|
| `none` *(default)* | – | – | – | – |
| `internal` | ✓ | ✓ | – | ✓ (from any `ixfx-tree-list`) |
| `external` | ✓ | – | ✓ | ✓ (foreign payloads via `parseExternalDrop`) |
| `both` | ✓ | ✓ | ✓ | both |

### Properties

| Property | Attribute | Type | Default | Purpose |
|----------|-----------|------|---------|---------|
| `itemDnd` | `item-dnd` | `'none' \| 'internal' \| 'external' \| 'both'` | `'none'` | Opt in (table above). |
| `acceptDropTypes` | `accept-drop-types` | `string` | – | Space-separated MIME list; an external `dragenter` is only honoured when `dataTransfer.types` intersects it. |
| `dndExpandHoverMs` | `dnd-expand-hover-ms` | `number` | `500` | Hover-to-open delay: hovering a collapsed branch this long during a drag expands it (spring-loaded folders). |
| `reorderable` | `reorderable` | `boolean` | `true` | When `false` (`reorderable="false"`), a drag that only reorders siblings — or drops a node back into its current parent — is rejected: no drop indicator, no `tree-drop`. Use for models with no meaningful child order (a filesystem). Reparenting, including via the x-position ancestor walk, is unaffected. |
| `dragPreviewRenderer` | – | `ListDragPreviewRenderer<TreeNode>` | – | Custom drag image (same contract as `ixfx-grid-list`); unset ⇒ built-in row preview: a compact pill with the dragged row's icon and label (taken from the node's `item.icon` / `item.label` / `item.iconColor`), plus a count badge when several rows are dragged. |
| `canDrag` | – | `(ctx) => boolean` | – | Per-row gate at `dragstart`. Return `false` for every row (with `item-dnd` still set) for a **drop-target-only** tree. |
| `canDrop` | – | `(ctx: TreeDropContext) => boolean` | – | Sync gate on every `dragover`; controls the valid indicator and whether the drop is allowed. |
| `parseExternalDrop` | – | `(dt: DataTransfer) => TreeNode[] \| undefined` | – | Turn a foreign payload into nodes to insert (`external` / `both`). |
| `applyInternalDrop` | – | `boolean` | `true` when `model` is set | When `true`, the component performs an accepted internal drop itself via `model.applyDrop()`. Set `false` to mutate `root`/`model` yourself in the `tree-drop` handler. |

### Drop targeting (VS Code Explorer style)

While dragging over the tree:

- **Vertical position** in a row picks `before` / `inside` (reparent) / `after`.
  `inside` a leaf falls back to `after`; `after` an expanded branch lands as its
  first child.
- **Horizontal position** on a `before`/`after` line walks the target *up* the
  ancestor chain — drag left across a deeply-indented row to drop as a sibling of
  one of its ancestors without scrolling. The insertion line and its nub move to
  that depth.
- Hovering a collapsed branch for `dndExpandHoverMs` springs it open.
- With `reorderable="false"`, `before`/`after` between current siblings gives no
  feedback — only reparenting drops resolve a target.
- Dragging into the top or bottom edge zone auto-scrolls the list (see below).
- Dropping a node onto itself or into its own subtree is rejected (no indicator).

### Edge auto-scroll while dragging

When the list is scrollable, holding a drag in the top or bottom trigger zone scrolls that way so you can reach rows that are off-screen:

- **Zone:** 20% of the list's height at each edge, clamped to 24–64px (never more than half the list).
- **Accelerates the longer you hold.** Speed starts gentle (about 120px/s) and ramps quadratically to about 3200px/s over roughly 2.5s of holding, so a brief pass through the zone barely moves the list but a deliberate hold covers long distances quickly. Moving closer to the very edge scales the speed further (35% just inside the zone, 100% at the edge).
- **Resets** when the pointer leaves the zone or switches to the opposite edge, and stops when the drag leaves the list or drops.
- **The drop indicator keeps up:** after each scroll the target is re-resolved for the unmoved pointer, so the highlighted row/line always matches what is under it, even if the browser isn't sending `dragover` events.
- Spring-loaded expansion still works while scrolling: hovering a collapsed branch long enough opens it, and the list keeps scrolling past it.

The constants live in [edge-scroll.ts](edge-scroll.ts).

### Applying drops without a model

```ts
import { applyTreeDrop } from '@ixfx/components';

tree.addEventListener('tree-drop', (e) => {
  e.preventDefault();               // we'll apply it ourselves
  root = applyTreeDrop(root, e.detail); // pure, returns a new root
  tree.root = root;
});
```

`TreeDataModel` also gains `moveNode(key, parentKey, index?)`,
`moveNodeRelative(key, refKey, 'before'|'after')`, `insertNode(...)` and
`applyDrop(ctx)` — all off-by-one-safe and no-ops for invalid moves.

### Detail types

```typescript
type TreeSelectDetail = {
  readonly selected: ReadonlySet<TreeNode>;   // Current full selection
  readonly previous: ReadonlySet<TreeNode>;   // Selection before this change
};

type TreeTickleDetail = {
  readonly node: TreeNode;
  readonly depth: number;
};

type TreeActivateDetail = {
  readonly node: TreeNode;
  readonly depth: number;
};
```

### Usage example

```typescript
el.addEventListener('select', ({ detail }) => {
  // Works for both single and multi-select
  const first = [...detail.selected][0];
  if (first) console.log('Primary selection:', first.item.label);
});

el.addEventListener('tickle', ({ detail }) => {
  // Show a preview pane as the user hovers
  preview.setNode(detail.node);
});

el.addEventListener('activate', ({ detail }) => {
  // Open the item (e.g. navigate to a route)
  router.navigate(detail.node.item.key);
});
```

### Migration from old event shapes

| Old | New |
|-----|-----|
| `select` → `{ selected: TreeNode, previous: TreeNode \| undefined }` | `select` → `TreeSelectDetail` (set-based) |
| `change` (Miller) | `select` (set-based) |
| Miller `select` (Enter key) | `activate` |
| no tickle event | `tickle` |

---

## Keyboard navigation

The element must be focused (click it or tab to it) before keyboard navigation works.

### `ixfx-tree-list`

| Key | Action |
|-----|--------|
| `Arrow Up` | Move cursor to previous visible item |
| `Arrow Down` | Move cursor to next visible item |
| `Arrow Right` (on collapsed branch) | Expand and move into first child |
| `Arrow Right` (on expanded branch) | Move into first child |
| `Arrow Right` (on leaf) | No-op |
| `Arrow Left` (on expanded branch) | Collapse branch |
| `Arrow Left` (on leaf or collapsed branch) | Move to parent |
| `Home` / `End` | Move cursor to the first / last visible item |
| `Page Up` / `Page Down` | Move cursor up / down by about one viewport |
| `Enter` | Select and activate focused item |
| `Escape` | Cancel in-flight lazy load |

Holding `Shift` with any movement key extends the range selection (in `standard` / `vscode` modes).
Moving the cursor fires a `tickle` event. Pressing Enter fires `select` then `activate`.

### `ixfx-miller-list`

| Key | Action |
|-----|--------|
| `Arrow Up / Down` | Move within the active column |
| `Arrow Right` | Expand (open next column for) highlighted branch |
| `Arrow Left` | Go back to the parent column |
| `Enter` | Activate the highlighted item (`activate` event) |
| `Escape` | Cancel pending operations |

### `ixfx-crumb-navigation`

Keyboard navigation follows the crumb path. Arrow keys move between breadcrumb segments; clicking or Enter expands the next level.

---

## Incremental search

`ixfx-tree-list` and `ixfx-miller-list` have a **built-in type-ahead popover**
with three modes:

- **navigate** — expands the match's ancestors and moves the cursor to it; ↑/↓
  cycle between matches; Enter activates and closes.
- **select** — the selection becomes the set of matching nodes.
- **filter** — non-matching nodes (and branches with no matching descendant) are
  hidden; branches with a match auto-expand so the match is visible.

No default shortcut — open it via a command on `el.registry`:

```typescript
el.registry.invoke('list.search.navigate'); // or .select / .filter
```

Limit the offered modes with the `search-modes` attribute
(`search-modes="navigate filter"`). Full model: [`docs/infra-incremental.md`](./infra-incremental.md).

### Deprecated: `IncrSearchTreeController`

The external-`<input>` filter-only controller still works but is superseded by
the built-in popover.

```typescript
import { IncrSearchTreeController } from '@ixfx/components';

const ctrl = new IncrSearchTreeController(el, {
  selector: item => item.node.item.label,   // Text to search against
  input: document.querySelector('#search'), // Optional: auto-wires input/keydown
});
ctrl.connect();

// Clean up when done
ctrl.disconnect();
```

### Options

```typescript
type IncrSearchTreeOptions = {
  /** How to extract searchable text from each node */
  selector: (item: { node: TreeNode; depth: number }) => string;

  /**
   * CSS selector for label elements inside the shadow root.
   * Default: '.tree-label' (ixfx-tree-list)
   * Use '.label' for ixfx-miller-list
   */
  labelSelector?: string;

  /** Input element to auto-wire. Esc clears the query. */
  input?: HTMLInputElement;

  /** fzf matching options */
  fzf?: Partial<FzfOptions<{ node: TreeNode; depth: number }>>;
};
```

### Manual control

```typescript
await ctrl.setQuery('search text');
await ctrl.clearQuery();
```

### Using with miller-list

```typescript
const ctrl = new IncrSearchTreeController(millerEl, {
  selector: item => item.node.item.label,
  labelSelector: '.label',   // Miller uses .label, not .tree-label
  input: searchInput,
});
ctrl.connect();
```

### How it works

1. `connect()` calls `el.getNodes()` to snapshot the full item list.
2. On each query change the controller runs fzf fuzzy matching and sets `el.filterPredicate` to a function that returns `true` only for matching nodes.
3. Matched label text is highlighted in the shadow DOM using the CSS Highlight API via `applyHighlights()`.
4. `disconnect()` clears `filterPredicate` and all highlights.

---

## ARIA

Each tree-like component must implement the following. These are enforced by the shared `TreeComponent` interface and implemented in `TreeBaseElement` / `MillerBaseElement` / `CrumbNavigationElement`.

**Container element**

- [ ] `role="tree"` on the outermost interactive container
- [ ] `aria-label` or `aria-labelledby` to name the tree

`ixfx-tree-list` sets all of the item attributes below, including `aria-setsize` / `aria-posinset` (see [Virtualisation](#virtualisation-ixfx-tree-list)); the checklist is still outstanding for the other tree components.

**Each item element**

- [ ] `role="treeitem"`
- [ ] `aria-level` (1-based depth)
- [ ] `aria-setsize` (total siblings in the same group)
- [ ] `aria-posinset` (1-based position among siblings)
- [ ] `aria-selected="true|false"`

**Expandable items**

- [ ] `aria-expanded="true"` when open, `"false"` when closed
- [ ] Omit `aria-expanded` on leaf nodes

**Child groups**

- [ ] Wrap children in `<ul role="group">` (or equivalent `role="group"` container)

**Miller columns specifically**

Each column is a separate `role="listbox"` with `aria-label` showing the parent node label. Items use `role="option"` and `aria-selected`.

---

## Row animation

Rows that appear — a branch expanded, a node added to `root` / the model —
collapse + fade in, and the rows below slide down to make room. Rows that
disappear — a branch collapsed, a node removed — are kept as fading "ghost" rows
until they've collapsed out, so the gap closes smoothly. Above ~50 rows changing
at once the animation is skipped, as it is entirely under
`prefers-reduced-motion: reduce`. Duration: `--ixfx-list-item-move-duration`
(default `200ms`).

Typing in a filter search does not animate, and neither does a windowed
(virtualised) list: see [Virtualisation](#virtualisation-ixfx-tree-list).

---

## CSS variables

### Shared / themed

These are set by the global theme and inherited by all tree components.

| Variable | Description |
|----------|-------------|
| `--accent` | Selected item background |
| `--accent-text` | Selected item text |
| `--surface-3` | Panel background |
| `--surface-3-text` | Default item text |
| `--surface-muted-text` | Muted text (carets, secondary info) |
| `--surface-h` | Hover background |
| `--radius-s` | Small border radius |
| `--transition` | Default transition timing |
| `--space-xs` | Extra-small spacing |
| `--space-s` | Small spacing |
| `--space-m` | Medium spacing |
| `--font-family` | Font family |
| `--text-m` | Base text size |
| `--text-l` | Large text size |

### `ixfx-tree-list` specific

| Variable | Default | Description |
|----------|---------|-------------|
| `--tree-indent` | `20px` | Indentation per depth level |
| `--tree-item-height` | `30px` | Content height of each row (padding and border add to the rendered box) |
| `--tree-item-gap` | `1px` | Margin above each row |
| `--tree-caret-size` | `30px` | Expand/collapse caret size |
| `--ixfx-list-item-move-duration` | `200ms` | Row enter / leave animation duration |
| `--tree-drop-line` | `var(--accent)` | Colour of the before/after insertion line + nub |
| `--tree-drop-nub-size` | `5px` | Diameter of the insertion-line nub |
| `--tree-drop-into-outline` | `2px solid var(--accent)` | Outline of a row that is a reparent (`inside`) drop target |
| `--tree-drop-into-bg` | `color-mix(...)` | Background tint of a reparent drop target |
| `--tree-sticky-bg` | `var(--tree-bg)` | Sticky header background (opaque so rows slide underneath) |
| `--tree-sticky-border` | `var(--border, transparent)` | Bottom border of the sticky header stack |
| `--tree-sticky-shadow` | `0 2px 6px rgba(0,0,0,0.25)` | Shadow under the sticky header stack |

`part`s: `drop-target` (the highlighted row), `drop-indicator` (the
before/after line).

### `ixfx-miller-list` specific

| Variable | Default | Description |
|----------|---------|-------------|
| `--miller-column-width` | `180px` | Width of each column |
| `--miller-column-max-height` | `320px` | Maximum column height before scroll |
| `--item-hover-bg` | `var(--surface-h)` | Hover background |
| `--item-selected-bg` | `var(--accent)` | Selected item background |
| `--item-selected-text` | `#fff` | Selected item text |
| `--item-open-bg` | (theme) | Background for items on the open path |
| `--icon-size` | `1em` | Icon dimensions |
| `--icon-spacing` | `0px` | Gap between icon and label |

---

## Controller authoring guide

A controller operates against the `TreeComponent` interface. This means the same controller works with any of the three components.

### Minimal controller

```typescript
import type { TreeComponent, TreeNode } from '@ixfx/components';

export class MyController {
  #el: TreeComponent;
  #unsub?: () => void;

  constructor(el: TreeComponent) {
    this.#el = el;
  }

  connect(): void {
    this.disconnect();
    this.#el.addEventListener('select', this.#onSelect);
    this.#el.addEventListener('tickle', this.#onTickle);
  }

  disconnect(): void {
    this.#el.removeEventListener('select', this.#onSelect);
    this.#el.removeEventListener('tickle', this.#onTickle);
    this.#unsub?.();
    this.#unsub = undefined;
  }

  #onSelect = (e: CustomEvent) => {
    const { selected } = e.detail;
    for (const node of selected as ReadonlySet<TreeNode>) {
      console.log('selected:', node.item.label);
    }
  };

  #onTickle = (e: CustomEvent) => {
    const { node, depth } = e.detail;
    console.log('tickled:', node.item.label, 'at depth', depth);
  };
}
```

### Querying all nodes

```typescript
// Snapshot of all visible nodes with their depth
const nodes = el.getNodes(); // ReadonlyArray<{ node: TreeNode; depth: number }>
```

### Filtering

```typescript
// Only show nodes matching a predicate
el.filterPredicate = (node, depth) => node.item.label.startsWith('A');

// Clear filter
el.filterPredicate = undefined;
```

### Selecting programmatically

```typescript
// Honour selectionMode and selectionFilter automatically
el.select(someNode);

// Or navigate to a node by key path and select it
el.navigateTo(['root', 'documents', 'readme.md']);
```

### Using `TreeSearchHost` for shadow-DOM access

Controllers that need to touch the shadow DOM (e.g. for highlight injection) should type the host as `TreeSearchHost` rather than `TreeComponent`:

```typescript
import type { TreeSearchHost } from '@ixfx/components';

export class HighlightController {
  #el: TreeSearchHost;

  constructor(el: TreeSearchHost) {
    this.#el = el;
  }

  async highlight(selector: string): Promise<void> {
    await this.#el.updateComplete;
    const labels = this.#el.shadowRoot?.querySelectorAll(selector);
    // ...
  }
}
```

---

## Types reference

```typescript
type LoadChildrenCallback = (
  query: { node: TreeNode; depth: number },
  signal: AbortSignal
) => TreeNode[] | Promise<TreeNode[]> | AsyncIterable<DataBatch<TreeNode>>;

type TreeFilterPredicate = (node: TreeNode, depth: number) => boolean;

type TreeExclusivity = 'none' | 'depth' | 'global';
type TreeSelectionFilter = 'none' | 'leaf' | 'branch';
type TreeInteractionMode = 'implicit' | 'standard' | 'manual' | 'checked' | 'vscode';

// ixfx-tree-list only
type TreeCheckboxState = 'checked' | 'unchecked' | 'indeterminate';

interface TreeComponent extends EventTarget {
  root: TreeNode | undefined;
  model: TreeDataModel | undefined;
  loadChildren: LoadChildrenCallback | undefined;
  selectedNode: TreeNode | undefined;
  readonly selectedNodes: ReadonlySet<TreeNode>;
  selectionFilter: TreeSelectionFilter;
  filterPredicate: TreeFilterPredicate | undefined;
  exclusivity: TreeExclusivity;
  select(node: TreeNode): void;
  deselect(node: TreeNode): void;
  clearSelection(): void;
  navigateTo(keys: readonly string[], options?: { reveal?: 'edge' | 'center-if-hidden'; silent?: boolean }): boolean;
  navigateToNode(predicate: (node: TreeNode) => boolean): boolean;
  getNodes(): ReadonlyArray<{ node: TreeNode; depth: number }>;
}

interface TreeSearchHost extends TreeComponent {
  readonly shadowRoot: ShadowRoot | null;
  readonly updateComplete: Promise<boolean>;
}
```
