# Tree

- Entry point: `@koobiq/components/tree`
- NgModule: `KbqTreeModule`
- API: https://koobiq.io/api/tree.md
- Component tokens: https://koobiq.io/tokens/tree.md
- Page: https://koobiq.io/en/components/tree/overview

## Overview

A hierarchical list (tree) is a tree-structured catalog for working with large amounts of data.

[**Example: Tree** (`tree-overview`)](https://koobiq.io/examples/tree-overview.md)

### When to use

When you need to provide the user with convenient access to a large amount of data (hundreds of items). Either the user can organize this data into a tree-structured catalog, or the data already arrives in this form from the system. If these conditions are not met, it is better to use a [regular list](https://koobiq.io/en/components/list.md).

### Component structure

- Name
- Item icons _(optional)_
- Additional action button for the item _(optional)_
- Expand and Collapse buttons
- Checkbox _(optional)_
- Search through items _(optional)_

### How it works

#### List with tree and text search

If a search query is entered, only the following items are shown in the tree:

- items that match the search query;
- items that are parents of items found by the search query.

Text matching the search query in the item name is highlighted in bold.

[**Example: Tree filtering** (`tree-filtering`)](https://koobiq.io/examples/tree-filtering.md)

#### List with tree and filtering of selected items

[**Example: Tree checked filtering** (`tree-checked-filtering`)](https://koobiq.io/examples/tree-checked-filtering.md)

#### List with tree and multiple item selection

Either single or multiple selection is possible (limited at the tree level).

An item can be selected by clicking on it (in any area except the Expand/Collapse icon and the additional action button). To select multiple items with the mouse, use the Ctrl or Shift keys; to select multiple items with the keyboard, use the Space key.

Non-leaf items can be expanded and collapsed by clicking the arrow icon.

[**Example: Tree multiple keyboard** (`tree-multiple-keyboard`)](https://koobiq.io/examples/tree-multiple-keyboard.md)

If checkboxes are enabled in the tree list, selecting multiple items is possible by clicking the checkbox.

[**Example: Tree multiple checkbox** (`tree-multiple-checkbox`)](https://koobiq.io/examples/tree-multiple-checkbox.md)

The mode is set by `multiple`: `checkbox` or `keyboard` for multiple selection. Single selection is the
default, so the way to ask for it is to leave the attribute off entirely. It is a normal input, so `[multiple]` can be bound and changed at any time. Narrowing a
tree that has several nodes selected keeps the first selected one and reports the shortened value; the
reported value is a bare value in single selection and an array in multiple selection, so a change of mode
changes the shape the form control holds. A tree rendered inside a `kbq-tree-select` shares its selection
model with the select, so the select decides how many nodes may be selected — switching the tree between
single and multiple selection there throws, while switching between `checkbox` and `keyboard` is allowed.

Note that this applies to `kbq-tree-selection` and `kbq-list-selection` only. On
[Select](https://koobiq.io/en/components/select.md) and `kbq-tree-select`, `multiple` still cannot be changed after
initialization and throws if you try.

#### Additional action button

Sometimes an additional action button may be present for an item.

[**Example: Tree action button** (`tree-action-button`)](https://koobiq.io/examples/tree-action-button.md)

#### Caption in options

[**Example: tree-select-two-line-option** (`tree-select-two-line-option`)](https://koobiq.io/examples/tree-select-two-line-option.md)

### Multiple selection variants

There are several variants for multiple item selection. [See in examples](https://koobiq.io/en/components/tree.md).

### State Saving

The tree remembers which nodes were expanded and restores the state after a page reload. On by default — use `[useStateSaving]="false"` to turn it off on a specific component.

[**Example: Tree state saving** (`tree-state-saving`)](https://koobiq.io/examples/tree-state-saving.md)

Selection is not persisted: it belongs to the form control the tree is bound to.

Expansion is persisted by the value `getValue` returns for a node, so that value has to be a string, stable across reloads and unique within the tree. A tree on a `NestedTreeControl` has no `getValue` and persists nothing, and neither does one rendered into an overlay — `kbq-tree-select` among them.

Expansion the application performs itself — `treeControl.expandAll()`, or writing to `expansionModel` directly — is not persisted until `saveState()` is called. `clearSavedState()` removes what is stored.

Keys, storage and expiry work the same for every component that persists — see [Saving component state](https://koobiq.io/en/components/core.md#saving-component-state).

### Focus and keyboard navigation

| Key                   | Action                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Tab                   | If focus is on the component preceding the tree in tab order → Move to the first tree row or the selected row If focus is on any tree item and it has no additional actions → Move to the next component in tab order after the tree If focus is on any tree item and it has additional actions → Move to the first additional action If focus is on an item's additional action → Move to the next additional action (if one exists), otherwise move to the next component in tab order after the tree |
| Shift + Tab           | If focus is on any tree item → Move to the previous component in tab order before the tree If focus is on the component following the tree in tab order → Move to the first tree row or the selected row                                                                                                                                                                                                                                                                                                |
| →                     | If focus is on a collapsed non-leaf item → Expand the nested items of that item If focus is on an expanded non-leaf item → Move to its first nested item If focus is on a leaf item → Nothing happens                                                                                                                                                                                                                                                                                                   |
| ←                     | If focus is on an expanded non-leaf item → Collapse the nested items of that item If focus is on a collapsed non-leaf item → Move to its parent item If focus is on a leaf item → Move to its parent item If focus is on a top-level item → Nothing happens                                                                                                                                                                                                                                             |
| ↵                     | If focus is on a tree item → Trigger the primary action of that item If focus is on a tree item with a checkbox → Nothing happens If focus is on an additional action → Apply that additional action                                                                                                                                                                                                                                                                                                    |
| Space                 | If focus is on a tree item with a checkbox → Select that tree item (and all nested items, if any) If focus is on a tree item → Nothing happens If focus is on an additional action → Apply that additional action                                                                                                                                                                                                                                                                                       |
| ↑ ↓                   | If focus is on a tree item → Move to the next (if it is the last item — nothing happens) / previous tree item (if it is the first item — nothing happens)                                                                                                                                                                                                                                                                                                                                               |
| PgUp                  | Move focus to the lowest visible item If the current item is the lowest visible → Scroll the tree down If the current item is the last in the tree → Nothing happens                                                                                                                                                                                                                                                                                                                                    |
| PgDn                  | Move focus to the topmost visible item If the current item is the topmost visible → Scroll the tree up If the current item is the topmost in the tree → Nothing happens                                                                                                                                                                                                                                                                                                                                 |
| Home                  | Move focus to the first tree item                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| End                   | Move focus to the last loaded tree item                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| Ctrl + click          | Clicking tree items — multiple row selection Clicking a selected item — the item is deselected                                                                                                                                                                                                                                                                                                                                                                                                          |
| Shift + ↓   Shift + ↑ | If focus is on a tree item → Multiple selection of the next / previous tree items (if the row is the first or last — nothing happens)                                                                                                                                                                                                                                                                                                                                                                   |
| Ctrl + C              | If focus is on tree items → Copy the content of the items By default, item names are copied. The separator between items is a line break                                                                                                                                                                                                                                                                                                                                                                |
| Ctrl + A              | If focus is on any tree item → Select all tree items (including unloaded ones)                                                                                                                                                                                                                                                                                                                                                                                                                          |
| Printable characters  | Move focus to the next item whose name starts with the typed characters. Typing several characters in quick succession matches them as one word                                                                                                                                                                                                                                                                                                                                                         |

### Accessibility

The tree exposes the structure it renders to assistive technology, so a screen reader announces an
item's nesting depth and whether it is expanded, selected or checked.

- The tree is a `role="tree"`, each row a `role="treeitem"`.
- The tab stop stays on the tree itself and the rows stay at `tabindex="-1"`, but the row the arrow
  keys land on does take real focus, and is advertised through `aria-activedescendant` on top of that.
- Branch rows carry `aria-expanded` — including while a filter is active, which disables the chevrons
  without turning the branches into leaves — and every row carries `aria-level`.
- Rows with a checkbox report `aria-checked`, including `mixed` for a partially selected branch; rows
  without one report `aria-selected`.
- Expand/collapse chevrons are hidden from assistive technology: their state is already on the row, and
  the ← and → keys drive them.
- The tree has no visible label of its own, so give it an accessible name with `aria-label`, or point
  `aria-labelledby` at the element that labels it. A tree inside a `kbq-tree-select` is labelled by the
  select and needs neither.

### Rendering

Every expanded item is rendered, with no windowing — a collapsed branch costs nothing, an expanded one
costs a DOM row per item. A tree that shows thousands of rows at once should keep its branches
collapsed or narrow the data with the search field.

Nodes are tracked by identity by default, so a data source that rebuilds its node objects on every
emission — a flattener among them — rebuilds every row, and a rebuilt node comes back collapsed.
Give the tree control a `trackBy` that returns a stable key of a node: the node is then expanded by that
key, and the tree re-uses the row of the same key across data updates. Set it before anything is
expanded, as a property or in the options, the last argument of `FlatTreeControl` and
`NestedTreeControl`:

[**Example: Tree track by** (`tree-track-by`)](https://koobiq.io/examples/tree-track-by.md)

`expansionModel` then holds the keys rather than the nodes, and the types of the tree, its events and
its data source take the key type as one more parameter: `KbqTreeSelection<FileFlatNode, string>`,
`KbqTreeFlatDataSource<FileNode, FileFlatNode, string>`.

The tree's own `trackBy` input, a `TrackByFunction` of the index and the node, overrides the key the rows
are re-used by; it does not change the expansion. Without a control `trackBy` it is the only way to
re-use the rows.

## Examples

### Search

The search results include matches and all of their parents:

- the tree collapses down to the matches and the path to them: the found items and the chain of their parents are visible
- the path to a match is expanded, while the items nested inside it are hidden;
- matched branches can be expanded and collapsed to view their contents;
- the matched fragment is highlighted.

[**Example: Tree custom filtering** (`tree-custom-filtering`)](https://koobiq.io/examples/tree-custom-filtering.md)

### Filtering with search + selected

[**Example: Tree checked filtering** (`tree-checked-filtering`)](https://koobiq.io/examples/tree-checked-filtering.md)

### Multiple selection variants

These behaviors are also available for [tree select](https://koobiq.io/en/components/tree-select.md).

#### Child subcategories

**When to use**

Used when nested items are a subset of their parents.

For example, in a hierarchical product category filter. When we search in coffee makers and toasters, we are actually searching within small kitchen appliances, which is itself a subcategory of home appliances in general.

**How it works**

The algorithm for this tree-select is the familiar 3-state checkbox behavior:

- If all N-level children are selected, their parent (N-1) becomes selected.
- If no N-level items are selected, their parent (N-1) becomes deselected.
- If some N-level items are selected and some are not, their parent (N-1) becomes selected.

**How to save to the model and select matcher**

Ideal: Display in the select matcher and save to the model the minimum set of items — N-level items if not all are selected. And one N-1 level item if all N-level items are selected.

Acceptable: When selecting an N-1 level item, save all N-level items (all children) to the model. If N+1 level items exist, save those too.

An extension of this case is the folder/group access rights scenario (variant 3).

[**Example: Tree descendants subcategories** (`tree-descendants-subcategories`)](https://koobiq.io/examples/tree-descendants-subcategories.md)

#### Independent items

The second tree behavior algorithm — levels that are independent of each other.

**When to use**

All items are independent of each other, simply visually grouped in a tree.

For example, in a system where users can assign tags, and these tags can be organized into folders and subfolders. Assigning a child tag to an object does not mean the folder object should also be assigned. And conversely, assigning a folder tag has no effect on assigning a child tag.

**How it works**

No checkboxes affect each other.

**How to save to the model and select matcher**

Checked checkboxes are saved.

[**Example: Tree multiple checkbox** (`tree-multiple-checkbox`)](https://koobiq.io/examples/tree-multiple-checkbox.md)

#### Access rights

The third tree behavior variant is an extension of the "Child subcategories" variant.

**When to use**

When you need to assign access rights to a tree of objects. Both rules apply:

1. Granting access rights to a parent object also grants rights to child items.
2. It is important to preserve the explicit selection of child items, even when parents are selected. For example, rights to `group 1.1` were granted first, then rights to group 1 were granted. If the system requires that the rights to 1.1 be preserved, this algorithm should be applied.

**How it works**

Similar to the "Child subcategories" variant, but with one restriction.
When a parent is selected, child items are not just checked — they are also disabled.
Only what is explicitly checked is saved.

In addition, if an item was selected and then its parent was selected, the siblings of that item will be selected and disabled, while the explicitly selected item remains enabled. This indicates that a specific rule is set on it.
If the checkbox on such an item is unchecked, it becomes disabled. To restore its explicit assignment, the parent's checkbox must be unchecked.

- Single non-expandable node
  - On selection:
    - Highlighted in blue; the node is not blocked.
  - On deselection:
    - If no parent is selected, simply deselected.
    - If any parent node is selected, selection and disabling occurs (becomes gray).
- Expandable node
  - On selection:
    - All child nodes that are not selected become selected and disabled (become gray).
    - If a child is already selected, nothing happens.
  - On deselection:
    - If any parent node is selected, selection and disabling occurs (becomes gray).
    - If a child node was explicitly selected and highlighted in blue, it remains untouched, while other child nodes are deselected (note that some disabled nodes may be inside selected nodes).
    - If N+1 level child nodes are disabled, deselection and node activation occur.
    - If an N+1 level child node is expandable, it is recursively checked.
- **Difference from "Child subcategories":** If all child nodes are selected, this does not mean the parent node is automatically selected.

**How to save to the model and select matcher**

Only explicitly checked items are saved. Disabled items are not saved.

[**Example: Tree access rights** (`tree-access-rights`)](https://koobiq.io/examples/tree-access-rights.md)

### Selection and marking

Clicking an item selects it and updates the information in the right panel. Clicking the checkbox marks the item, but the information in the right panel does not change.

The list can also be navigated with the keyboard. Enter selects an item and updates the text in the right panel, while Space marks it. The selected item changes along with navigation.

[**Example: tree-select-and-mark** (`tree-select-and-mark`)](https://koobiq.io/examples/tree-select-and-mark.md)

### Selection separate from focus

When navigating the list, the selected item does not change along with the focus position. An item can be selected by clicking or pressing Enter.

[**Example: tree-selection-separate-from-focus** (`tree-selection-separate-from-focus`)](https://koobiq.io/examples/tree-selection-separate-from-focus.md)

### Expanding a branch on click

Clicking an element expands the first level of child nodes, only leaf elements can be selected. Selection is disabled with the `selectable` attribute of `kbq-tree-option`: with `[selectable]="false"` the option remains focusable, navigable and expandable, but cannot be selected.

[**Example: tree-select-and-mark** (`tree-toggle-on-click`)](https://koobiq.io/examples/tree-toggle-on-click.md)
