# Tree

A hierarchical list that expands and collapses: file browsers, categories, org charts. Nodes are typed and identified by key, so the selection and the expanded nodes are plain arrays of keys that you can store, put in a URL or send to a server.

- Package: [@vigdx/ui](https://www.npmjs.com/package/@vigdx/ui)
- Selectors: `vig-tree`, `ng-template[vigTreeNode]`
- Source: [libs/ui/src/lib/organisms/tree/tree.ts](https://github.com/bakyurekk/vigdx/blob/main/libs/ui/src/lib/organisms/tree/tree.ts)

```typescript title="Import"
import { Tree, TreeNodeTemplate } from '@vigdx/ui/tree';
```

## Basic

Pass the top-level `nodes`, each a `TreeNode<T>` with a unique `key`, a `label`, optional `children`, `icon`, `disabled` and typed `data`. `selectionMode="single"` makes nodes selectable (the default `none` is a navigation tree, where a click expands); `[(value)]` holds the selected keys and `[(expandedKeys)]` the open ones. `selectable: false` keeps a node out of the selection without dimming it, e.g. a folder of pickable files. `nodeActivated` fires on a click or Enter, for opening a file; `nodeExpanded`, `nodeCollapsed`, `nodeSelected` and `nodeUnselected` report the rest.

```typescript title="tree-basic.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { Tree } from '@vigdx/ui/tree';

import { FILES } from './files';

@Component({
  selector: 'app-tree-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Tree],
  template: `
    <div class="flex w-full max-w-sm flex-col gap-3">
      <vig-tree
        selectionMode="single"
        [nodes]="files"
        [(value)]="selected"
        [(expandedKeys)]="expanded"
        [labels]="{ ariaLabel: 'Project files' }"
        (nodeActivated)="opened.set($event.label)"
      />
      <p class="text-sm text-muted-foreground" aria-live="polite">
        Selected: {{ selected().join(', ') || 'none' }} · Last opened: {{ opened() ?? 'none' }}
      </p>
    </div>
  `,
})
export class TreeBasicDemo {
  protected readonly files = FILES;
  protected readonly selected = signal<readonly string[]>(['src/main.ts']);
  protected readonly expanded = signal<readonly string[]>(['src']);
  protected readonly opened = signal<string | undefined>(undefined);
}
```

## Checkboxes

`selectionMode="checkbox"` draws a checkbox per node. With `cascade` (the default) checking a folder checks its branch and a folder shows checked, unchecked or mixed from its children. Disabled and `selectable: false` nodes keep their own state: checking passes through them to their descendants, and their parent ignores them. While `filterQuery` is set, checking reaches the nodes the filter shows only. The value lists every checked key, folders included. Turn `cascade` off for independent checkboxes. `multiple` selects without checkboxes: each click toggles a node, Shift+click selects a range.

```typescript title="tree-checkbox.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { ToggleSwitch } from '@vigdx/ui/toggle-switch';
import { Tree } from '@vigdx/ui/tree';

import { FILES } from './files';

@Component({
  selector: 'app-tree-checkbox',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Tree, ToggleSwitch],
  template: `
    <div class="flex w-full max-w-sm flex-col gap-3">
      <vig-toggle-switch label="Cascade to children and parents" [(value)]="cascade" />
      <vig-tree
        selectionMode="checkbox"
        [cascade]="cascade()"
        [nodes]="files"
        [(value)]="checked"
        [expandedKeys]="['src', 'src/app', 'docs']"
        [labels]="{ ariaLabel: 'Files to deploy' }"
      />
      <p class="text-sm text-muted-foreground">{{ checked().length }} keys checked</p>
    </div>
  `,
})
export class TreeCheckboxDemo {
  protected readonly files = FILES;
  protected readonly cascade = signal(true);
  protected readonly checked = signal<readonly string[]>(['src/app/routes.ts']);
}
```

## Lazy loading

`loadChildren(node, signal)` returns a promise of the children of a node without `children`; it runs on first expand, in the browser only. The node is busy meanwhile (`aria-busy`), a rejected promise shows a row that retries, and collapsing the node aborts `signal`, so pass it on to `fetch`. Mark nodes that never have children with `leaf: true`. Loaded children are kept per key, also across new `nodes` with the same keys, and dropped for keys that leave the data or when `loadChildren` changes; call `reload(key?)` when the server's data changed.

```typescript title="tree-lazy.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Tree, type TreeLoader, type TreeNode } from '@vigdx/ui/tree';

interface Folder {
  path: string;
}

@Component({
  selector: 'app-tree-lazy',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Tree],
  template: `
    <vig-tree
      class="w-full max-w-sm"
      [nodes]="roots"
      [loadChildren]="load"
      [labels]="{ ariaLabel: 'Remote folders' }"
    />
  `,
})
export class TreeLazyDemo {
  protected readonly roots: TreeNode<Folder>[] = [
    { key: '/projects', label: 'projects', data: { path: '/projects' } },
    { key: '/archive', label: 'archive (fails once)', data: { path: '/archive' } },
    { key: '/notes.txt', label: 'notes.txt', leaf: true },
  ];
  private failed = false;

  /** Stands in for `fetch(url, { signal })`; a collapse aborts it. */
  protected readonly load: TreeLoader<Folder> = (node, signal) =>
    new Promise((resolve, reject) => {
      const timer = setTimeout(() => {
        if (node.key === '/archive' && !this.failed) {
          this.failed = true;
          reject(new Error('Network error'));
          return;
        }
        const path = node.data?.path ?? node.key;
        resolve([
          { key: `${path}/a`, label: 'reports', data: { path: `${path}/a` } },
          { key: `${path}/b.txt`, label: 'summary.txt', leaf: true },
        ]);
      }, 700);
      signal.addEventListener('abort', () => clearTimeout(timer));
    });
}
```

## Filtering and custom nodes

`filterQuery` keeps the nodes whose label contains the text (case- and accent-insensitive, in the active locale), their ancestors, which open, and their descendants. Compose it with any search field. A `vigTreeNode` template replaces the icon and label of each node; bind `[vigTreeNodeOf]` to type `let-node` and its `data`.

```typescript title="tree-filter.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { Icon } from '@vigdx/ui/icon';
import { InputField, InputPrefix } from '@vigdx/ui/input-field';
import { Tree, TreeNodeTemplate } from '@vigdx/ui/tree';

import { FILES } from './files';

@Component({
  selector: 'app-tree-filter',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Icon, InputField, InputPrefix, Tree, TreeNodeTemplate],
  template: `
    <div class="flex w-full max-w-sm flex-col gap-2">
      <vig-input label="Search files" hideLabel placeholder="Search files" [(value)]="query">
        <vig-icon vigInputPrefix name="search" />
      </vig-input>
      <vig-tree [nodes]="files" [filterQuery]="query()" [labels]="{ ariaLabel: 'Project files' }">
        <ng-template vigTreeNode [vigTreeNodeOf]="files" let-node>
          <span class="min-w-0 flex-1 truncate">{{ node.label }}</span>
          @if (node.data; as file) {
            <span class="shrink-0 text-xs text-muted-foreground">{{ file.size }}</span>
          }
        </ng-template>
      </vig-tree>
    </div>
  `,
})
export class TreeFilterDemo {
  protected readonly files = FILES;
  protected readonly query = signal('ts');
}
```

## Virtual scrolling

`virtual` renders only the rows in view, for trees of thousands of nodes. The tree then scrolls itself at `--vig-tree-height` (20rem by default) and labels stay on one line. Keyboard focus, `aria-setsize` and `aria-posinset` describe the whole tree, not the rendered window.

```typescript title="tree-virtual.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Tree, type TreeNode } from '@vigdx/ui/tree';

/** 200 folders of 100 documents: 20,200 nodes. */
function buildTree(): TreeNode[] {
  return Array.from({ length: 200 }, (_, f) => ({
    key: `f${f}`,
    label: `Folder ${f + 1}`,
    children: Array.from({ length: 100 }, (_, i) => ({
      key: `f${f}/${i}`,
      label: `Document ${f + 1}.${i + 1}`,
    })),
  }));
}

@Component({
  selector: 'app-tree-virtual',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Tree],
  template: `
    <vig-tree
      virtual
      class="w-full max-w-sm [--vig-tree-height:20rem]"
      selectionMode="multiple"
      [nodes]="nodes"
      [expandedKeys]="expanded"
      [labels]="{ ariaLabel: 'Documents' }"
    />
  `,
})
export class TreeVirtualDemo {
  protected readonly nodes = buildTree();
  protected readonly expanded = this.nodes.slice(0, 50).map((node) => node.key);
}
```

## Styling hooks

Internal elements carry a stable `data-part` and the component's `data-scope`; both are public API, so removing one is a breaking change. Select a part by both, e.g. `[data-scope="tree"][data-part="root"] { … }`: the pair stays within this component when kit components nest, and also reaches parts in overlay panels, which render outside the host. State is exposed through `aria-*` and, where listed, a `data-state`; literal values are checked by the API gate, values computed from the component's state follow its documented types. Other `data-*` attributes listed below (such as `data-opening` while an overlay animates) are API too. See [Customizing](https://vigdx.com/docs/theming.md#customizing).

Scope: `[data-scope="tree"]`

| Part | Element | data-state |
| --- | --- | --- |
| `root` | The `vig-tree` host. |   |
| `tree` | The `role="tree"` element (the one Tab stop is a row in it). |   |
| `item` | A `role="treeitem"` row (`aria-level`, `aria-expanded`, `aria-selected` or `aria-checked`, `aria-busy` while its children load). | `open, closed` |
| `toggle` | The expand chevron of a row (pointer only). |   |
| `loading` | The busy ring in place of the chevron while children load. |   |
| `checkbox` | The tri-state box of a row (`selectionMode="checkbox"`). |   |
| `icon` | The node icon. |   |
| `label` | The node text. |   |
| `content` | Wrapper of a custom `vigTreeNode` template. |   |
| `error` | The row under a node whose children failed to load. |   |
| `retry` | The retry text of that row. |   |
| `empty` | The `role="status"` region: the message without nodes or filter matches, and the announcement of a failed load. |   |
| `viewport` | The scrolling viewport of a `virtual` tree. |   |

## Accessibility

- Follows the WAI-ARIA APG treeview pattern: a `role="tree"` named by `labels.ariaLabel` (name every tree) of `role="treeitem"` rows with `aria-level`, `aria-setsize`, `aria-posinset` and `aria-expanded`. Selected rows carry `aria-selected`, checkbox rows `aria-checked` (`mixed` for a partly checked folder), and the tree is `aria-multiselectable` in `multiple` and `checkbox` modes.
- The tree is one Tab stop (a roving tab index). ArrowDown and ArrowUp move, ArrowRight opens a node or enters it, ArrowLeft closes it or goes to its parent (mirrored in right-to-left pages), Home and End jump, \* opens every sibling, and typing moves to the next node starting with the text. Enter and Space select (toggle in `multiple`, check in `checkbox`); in `multiple`, Shift+Arrow extends the selection and Ctrl+A selects every visible node.
- A node whose children load is `aria-busy` and described as loading; a failed load is announced through the tree's status region and adds a row that retries with Enter, Space or a click.
- The selected row has a bar at its inline start besides its fill, and the chevron's direction shows expansion, so neither state rests on color alone; in forced-colors mode the bar takes the system Highlight color.
- With `virtual`, when the focused row scrolls out of the DOM focus stays in the tree, and the arrow keys bring the row back; once the row renders again it takes focus back. Arrow, Home and End keys held with Alt, Ctrl or Meta are left to the browser.

## API

### Tree

Selector: `vig-tree` · Kind: component

A hierarchical list (APG treeview pattern) that expands and collapses, with optional selection: `single`, `multiple`, or tri-state `checkbox`es that check whole branches. Nodes are typed (`TreeNode<T>`) and identified by key, so `value` and `expandedKeys` are plain key arrays. Children can load on first expand (`loadChildren`, cancelled when the node collapses), `filterQuery` narrows the tree to matches and their ancestors, and `virtual` renders only the rows in view, for trees of thousands of nodes.

**Example :**

```html
<vig-tree [nodes]="files" selectionMode="single" [(value)]="picked"
  [labels]="{ ariaLabel: 'Files' }" />
```

One Tab stop (a roving tab index): ArrowUp/ArrowDown move, ArrowRight expands or enters a node, ArrowLeft collapses or goes to the parent (mirrored in RTL), Home/End jump, `*` expands the siblings, Enter and Space select, and typing jumps to the next node starting with the text.

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `cascade` | `boolean` | `true` | `checkbox` mode: checking a node checks its selectable descendants, and a parent shows checked, unchecked or mixed from them. Disabled and `selectable: false` nodes keep their own state. Off, every checkbox stands alone. While `filterQuery` is set, checking reaches the nodes the filter shows only. |
| `expandedKeys` (model) | `readonly string[]` | `[]` | Keys of the expanded nodes. |
| `filterQuery` | `string` | `''` | Narrows the tree to the nodes whose label contains the text (case- and accent-insensitive, in the active locale), their ancestors, which expand, and their descendants. Only loaded nodes are searched. |
| `labels` | `Partial<TreeLabels>` | — | Texts (i18n); locale defaults. Set `ariaLabel` to name the tree. |
| `loadChildren` | `TreeLoader<T> \| undefined` | `undefined` | Fetches the children of nodes that have none of their own; see `TreeLoader`. Another loader starts afresh: what the previous one loaded is dropped, and its pending answers are ignored. |
| `nodes` | `readonly TreeNode<T>[]` | `[]` | The top-level nodes. |
| `selectionMode` | `TreeSelectionMode` | `'none'` | How nodes are selected; `none` (navigation only) by default. |
| `size` | `FieldSize` | `'md'` | — |
| `value` (model) | `readonly string[]` | `[]` | Keys of the selected (or, in `checkbox` mode, checked) nodes, in every mode an array: `single` uses its first key only. With `cascade`, a checked branch lists its parent and every loaded selectable descendant. |
| `virtual` | `boolean` | `false` | Renders only the rows in view (CDK virtual scrolling), for large trees. The tree then scrolls itself at `--vig-tree-height` (20rem by default), and labels stay on one line. Rows don't size the tree, so give it a definite width inside shrink-to-fit parents (`inline-block`, `w-fit`). |

#### Outputs

| Name | Payload | Description |
| --- | --- | --- |
| `expandedKeysChange` | `readonly string[]` | Keys of the expanded nodes. |
| `nodeActivated` | `TreeNode<T>` | A node was clicked or got Enter: its default action, e.g. opening a file. |
| `nodeCollapsed` | `TreeNode<T>` | A node was collapsed (by the user). |
| `nodeExpanded` | `TreeNode<T>` | A node was expanded (by the user). |
| `nodeSelected` | `TreeNode<T>` | A node was selected, or became checked, by the user. |
| `nodeUnselected` | `TreeNode<T>` | A node was unselected, or became unchecked, by the user. |
| `valueChange` | `readonly string[]` | Keys of the selected (or, in `checkbox` mode, checked) nodes, in every mode an array: `single` uses its first key only. With `cascade`, a checked branch lists its parent and every loaded selectable descendant. |

#### Methods

| Signature | Description |
| --- | --- |
| `focus(): void` | Moves focus to the tree's tab stop (the active, else the first selected, row). |
| `reload(key?: string): void` | Forgets what `loadChildren` loaded for `key` (and below it), or for every node without a key, and cancels those loads: expanded nodes load again, the others on their next expand. For data that changed on the server under the same keys. |

### TreeNodeTemplate

Selector: `ng-template[vigTreeNode]` · Kind: directive

Custom content of each node of `vig-tree` (and `vig-tree-select`), replacing the default icon and label; the expand toggle and the checkbox stay. Bind the nodes to `vigTreeNodeOf` to type `let-node`:

**Example :**

```html
<vig-tree [nodes]="files">
  <ng-template vigTreeNode [vigTreeNodeOf]="files" let-node>
    {{ node.label }} <small>{{ node.data?.size }}</small>
  </ng-template>
</vig-tree>
```

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `vigTreeNodeOf` | `readonly TreeNode<T>[] \| null \| undefined` | `undefined` | Type-only: the nodes the template renders, so `let-node` is typed. Not read at runtime. |
