---
title: Tree collection
description: 'A flat node list as a tree: parents, levels, positions, the rows an expanded set shows, and cascading checked state.'
order: 15
---

import { HelperResults } from '@/components/primitive-example/helper-results';
import {
	createTreeCollection,
	toggleTreeChecked,
	treeCheckedStates,
	treeFromNested,
} from '@ecopages/radiant-ui/helpers';

export const files = createTreeCollection([
	{ key: 'src' },
	{ key: 'app.ts', parent: 'src' },
	{ key: 'lib', parent: 'src' },
	{ key: 'math.ts', parent: 'lib' },
	{ key: 'README.md' },
	{ key: 'docs', branch: true },
]);

export const nested = treeFromNested([
	{ id: 'fruit', children: [{ id: 'apple' }, { id: 'pear' }] },
	{ id: 'nuts', children: [] },
]);

export const food = createTreeCollection([
	{ key: 'fruit' },
	{ key: 'apple', parent: 'fruit' },
	{ key: 'pear', parent: 'fruit' },
	{ key: 'nuts' },
	{ key: 'almond', parent: 'nuts' },
]);

# Tree collection

<p class="docs-lede">
	A flat node list as a tree: parents, levels, positions, the rows an expanded set shows, and cascading checked
	state.
</p>

Reach for them for a tree or treegrid view that renders from data, or for tree checkboxes. [RuiTree](/docs/data-display/tree) and [RuiTreegrid](/docs/data-display/treegrid) build their rows with `treeFromNested`. The helpers are pure: no DOM at import time or in the call path, so they run on the server and in tests. Each result below is computed when the page is built, by running the call shown.

## Import

```ts
import {
	createTreeCollection,
	toggleTreeChecked,
	treeCheckedStates,
	treeFromNested,
	type NestedTreeItem,
	type NestedTreeNode,
	type ToggleTreeCheckedOptions,
	type TreeCheckedState,
	type TreeCheckedStrategy,
	type TreeCollection,
	type TreeNode,
	type TreePosition,
} from '@ecopages/radiant-ui/helpers';
```

## Collection

`createTreeCollection(nodes)` builds a `TreeCollection` from a flat list of `TreeNode`s: `{ key, parent, branch }`. A `parent` that is `null`, absent or not in the list makes a node top-level, and `branch: true` marks an empty or lazily loaded folder. Keys can be strings, elements or any other value a `Map` takes, except `null` and `undefined`, which a `parent` uses for the top level, as `children(null)` does. They must be unique; a later duplicate replaces the earlier node. Children keep the order they are listed in, and a parent cycle is broken by making one node of it top-level.

The calls below use this collection:

```ts
const files = createTreeCollection([
	{ key: 'src' },
	{ key: 'app.ts', parent: 'src' },
	{ key: 'lib', parent: 'src' },
	{ key: 'math.ts', parent: 'lib' },
	{ key: 'README.md' },
	{ key: 'docs', branch: true },
]);
```

`keys()` walks the tree depth first, so a parent comes before its children even when it is listed after them. `level` is 1 for a top-level node and `position` is `{ index, size }` among the siblings, both 1-based: what `aria-level`, `aria-posinset` and `aria-setsize` take. `visible(expanded)` is the rows a tree view shows: the keys whose ancestors are all in `expanded`, in tree order. A key that is not in the collection throws.

<HelperResults
	rows={[
		{ code: 'files.size', result: files.size },
		{ code: 'files.keys()', result: files.keys() },
		{ code: "files.parent('math.ts')", result: files.parent('math.ts') },
		{ code: "files.level('math.ts')", result: files.level('math.ts') },
		{ code: "files.position('lib')", result: files.position('lib') },
		{ code: "files.isBranch('docs')", result: files.isBranch('docs') },
		{ code: 'files.children(null)', result: files.children(null) },
		{ code: "files.descendants('src')", result: files.descendants('src') },
		{ code: "files.ancestors('math.ts')", result: files.ancestors('math.ts') },
		{ code: 'files.visible([])', result: files.visible([]) },
		{ code: "files.visible(['src'])", result: files.visible(['src']) },
		{ code: "files.visible(['src', 'lib'])", result: files.visible(['src', 'lib']) },
	]}
/>

`has(key)` tells whether a key is in the collection, and `node(key)` returns the node it was created from.

## Nested data

`treeFromNested(items)` is a collection over nested `{ id, children }` items, such as the `nodes` of `RuiTree` or the `rows` of `RuiTreegrid`, keyed by `id`. Each node is a `NestedTreeNode`: `{ key, parent, branch, item }`, with the original item at `node(key).item`. An item with a non-empty `children` array is a branch, as the views render it.

```ts
const nested = treeFromNested([
	{ id: 'fruit', children: [{ id: 'apple' }, { id: 'pear' }] },
	{ id: 'nuts', children: [] },
]);
```

<HelperResults
	rows={[
		{ code: 'nested.keys()', result: nested.keys() },
		{ code: "nested.parent('apple')", result: nested.parent('apple') },
		{ code: "nested.isBranch('nuts')", result: nested.isBranch('nuts') },
		{ code: "nested.node('pear').item", result: nested.node('pear').item },
	]}
/>

## Checked state

A checked value is a list of keys, and a `TreeCheckedStrategy` says what it holds and so how checking cascades:

- `leaf`: the checked leaves. Checking a branch checks its leaves.
- `trunk`: the outermost fully checked nodes, so a checked folder stands for its contents.
- `branch`: every fully checked node, branches and leaves.
- `independent`: each checked node on its own, with no cascade and no mixed state.

In the three cascading strategies a branch in the value stands for all its leaves, so a value stays meaningful when the strategy changes or children load later.

`treeCheckedStates(tree, checked, strategy)` returns a `Map` from every key to its `TreeCheckedState`: `true`, `false`, or `'mixed'` for a branch with some of its leaves checked, as `aria-checked` takes it. Keys in `checked` that are not in the tree are ignored. `toggleTreeChecked(tree, checked, key, { strategy, checkable })` is the value after the user toggles `key`: in a cascading strategy it checks the node's editable leaves, or unchecks them when they are all checked, and returns the value in tree order in the form `strategy` stores. `checkable` returns `false` to lock a node, which keeps its state, and in a cascading strategy so does everything below it; a toggle that changes nothing returns `checked` as it was.

The calls below use this collection, and the `Map` is shown with `Object.fromEntries`:

```ts
const food = createTreeCollection([
	{ key: 'fruit' },
	{ key: 'apple', parent: 'fruit' },
	{ key: 'pear', parent: 'fruit' },
	{ key: 'nuts' },
	{ key: 'almond', parent: 'nuts' },
]);
```

<HelperResults
	rows={[
		{
			code: "treeCheckedStates(food, ['apple'], 'leaf')",
			result: Object.fromEntries(treeCheckedStates(food, ['apple'], 'leaf')),
		},
		{
			code: "treeCheckedStates(food, ['fruit'], 'trunk')",
			result: Object.fromEntries(treeCheckedStates(food, ['fruit'], 'trunk')),
		},
		{
			code: "treeCheckedStates(food, ['fruit'], 'independent')",
			result: Object.fromEntries(treeCheckedStates(food, ['fruit'], 'independent')),
		},
		{
			code: "toggleTreeChecked(food, ['apple'], 'fruit', { strategy: 'leaf' })",
			result: toggleTreeChecked(food, ['apple'], 'fruit', { strategy: 'leaf' }),
		},
		{
			code: "toggleTreeChecked(food, ['apple'], 'fruit', { strategy: 'trunk' })",
			result: toggleTreeChecked(food, ['apple'], 'fruit', { strategy: 'trunk' }),
		},
		{
			code: "toggleTreeChecked(food, ['apple'], 'fruit', { strategy: 'branch' })",
			result: toggleTreeChecked(food, ['apple'], 'fruit', { strategy: 'branch' }),
		},
		{
			code: "toggleTreeChecked(food, ['apple'], 'fruit', { strategy: 'independent' })",
			result: toggleTreeChecked(food, ['apple'], 'fruit', { strategy: 'independent' }),
		},
		{
			code: "toggleTreeChecked(food, ['apple', 'pear'], 'fruit', { strategy: 'leaf' })",
			result: toggleTreeChecked(food, ['apple', 'pear'], 'fruit', { strategy: 'leaf' }),
		},
		{
			code: "toggleTreeChecked(food, [], 'fruit', { strategy: 'leaf', checkable: (key) => key !== 'pear' })",
			result: toggleTreeChecked(food, [], 'fruit', { strategy: 'leaf', checkable: (key) => key !== 'pear' }),
		},
		{
			code: "toggleTreeChecked(food, ['apple'], 'fruit', { strategy: 'leaf', checkable: (key) => key !== 'pear' })",
			result: toggleTreeChecked(food, ['apple'], 'fruit', { strategy: 'leaf', checkable: (key) => key !== 'pear' }),
		},
	]}
/>

The last two calls lock `pear`: checking `fruit` checks only `apple`, so `fruit` stays mixed, and pressing it again unchecks `apple`.
