---
title: Tree
description: Render hierarchical data with createTree, with expansion,
  selection, cascading checkboxes, lazy loading, and virtualization.
package: moraine
version: 0.11.0
repository: https://github.com/subframe7536/moraine
---

# Tree

> Render hierarchical data with createTree, with expansion, selection, cascading checkboxes, lazy loading, and virtualization.

## Anatomy

```text
tree.Tree [component; slot=root; <ul>]
└── tree.Item [part; slot=item; <li>]
    ├── row [slot; <div>]
    │   ├── guides [internal; <span>]
    │   │   └── guide [slot; <span>]
    │   ├── tree.ItemTrigger [part; slot=trigger; <span>]
    │   ├── tree.ItemCheckbox [part; slot=checkbox; <button>]
    │   │   └── icon [internal]
    │   ├── tree.ItemIcon [part; slot=icon]
    │   ├── tree.ItemLabel [part; slot=label; <span>]
    │   └── tree.ItemAction [part; slot=action; <div>]
    └── content [slot; <div>]
        └── group [internal; <ul>]
            └── tree.Item [part]
```

`tree.Tree` is the `tree` root. Each item is a `tree.Item` (`treeitem`) that holds a `row` and,
when it has children, a `content` wrapper around a nested `group`. With `virtualizer`, there
are no nested groups: every visible item is a flat row inside the root, which is also the scroll
container.

## Usage

Use Tree for hierarchical data that users expand, select, or check, such as files, categories, or
permissions. Use [List](https://moraine.subf.dev/components/list.md) for flat data, [Accordion](https://moraine.subf.dev/components/accordion.md) to
disclose sections of content, and [Sidebar](https://moraine.subf.dev/components/sidebar.md) or
[NavigationMenu](https://moraine.subf.dev/components/navigation-menu.md) for site navigation.

Tree has no static component. Call `createTree(options)` inside a component, then render the
bound `tree.Tree`. The instance owns all state, so each call creates an independent tree.

```tsx
import { createTree } from 'moraine'

interface FileNode {
  id: string
  name: string
  children?: FileNode[]
}

export function Files(props: { files: FileNode[] }) {
  const tree = createTree<FileNode>({
    items: () => props.files,
    getKey: (node) => node.id,
    getChildren: (node) => node.children,
    getLabel: (node) => node.name,
  })

  return <tree.Tree aria-label="Project files" />
}
```

Always name the tree with `aria-label` or `aria-labelledby` on `tree.Tree`.

### Options and props

Behavior is configured on `createTree`; presentation is configured on `tree.Tree`. The generated
API reference below lists `tree.Tree` and part props. `createTree` options are listed here.

| Concern    | `createTree` options                                                                                                              |
| ---------- | --------------------------------------------------------------------------------------------------------------------------------- |
| Data       | `items` (accessor), `getKey`, `getChildren`, `getLabel`, `isDisabled`, `isLeaf`                                                   |
| Expansion  | `expandedKeys`, `defaultExpandedKeys`, `onExpandedKeysChange`, `expandOnClick` (`true`), `trigger` (`true`)                       |
| Selection  | `selectionMode` (`'single'` by default, `'multiple'`, or `'none'`), `selectedKeys`, `defaultSelectedKeys`, `onSelectedKeysChange` |
| Checking   | `checkable` (`false`), `checkCascade` (`true`), `checkedKeys`, `defaultCheckedKeys`, `onCheckedKeysChange`                        |
| Lazy loads | `loadChildren`, `onLoadChildrenComplete`, `onLoadChildrenError`                                                                   |
| Other      | `getIcon` (default item icon), `typeahead` (`true`), `onAction` (<kbd>Enter</kbd>)                                                |

| Concern      | `tree.Tree` props                                                                 |
| ------------ | --------------------------------------------------------------------------------- |
| Rendering    | `itemRender`, `actionRender`, `virtualizer`                                       |
| Icons        | `expandIcon` (`'icon-chevron-right'`), `loadingIcon` (`'icon-loading'`)           |
| Presentation | `size`, `variant`, `indentGuide`, `transition`, `forceMount`, `classes`, `styles` |

`createTree` reads options reactively. Pass changing or controlled values as getters, for example
`get selectedKeys() { return selected() }`; a plain value is read once.

Keys are strings returned by `getKey` and must be unique across the whole tree. If a key repeats,
the first occurrence wins. `getLabel` provides the accessible name and the typeahead text; it
defaults to the item itself for strings and to the key otherwise.

### Instance

`createTree` returns one object with reactive state, methods, and bound parts. Read state in JSX or
effects like any signal.

| Member                                                                               | Description                                                                         |
| ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |
| `expandedKeys`, `selectedKeys`, `checkedKeys`, `loadingKeys`                         | Current keys, read-only.                                                            |
| `focusedKey`                                                                         | Key of the item that holds focus while focus is inside the tree.                    |
| `flattenedItems`                                                                     | Visible items in display order.                                                     |
| `expand`, `collapse`, `toggle`, `expandAll`, `collapseAll`                           | Change expansion by key. Disabled branches are skipped.                             |
| `expandTo(key)`                                                                      | Expands every ancestor so the item becomes visible.                                 |
| `select`, `deselect`, `toggleSelect`, `selectAll`, `clearSelection`                  | Change selection by key. `selectAll` only works in `'multiple'` mode.               |
| `check`, `uncheck`, `toggleCheck`                                                    | Change the check state by key, cascading when `checkCascade` is on.                 |
| `focus(key)`                                                                         | Expands collapsed ancestors, scrolls the item into view, and moves DOM focus to it. |
| `getItem(key)`, `isLoading(key)`                                                     | Read one item handle or its loading state.                                          |
| `Tree`, `Item`, `ItemTrigger`, `ItemCheckbox`, `ItemIcon`, `ItemLabel`, `ItemAction` | Components bound to this instance.                                                  |

`getItem(key)` returns a stable item handle (`TreeT.ItemInstance<T>`), and `itemRender`,
`actionRender`, `getIcon`, and `onAction` receive the same handle. Its fields are reactive, and it
carries per-item actions:

- Data: `key`, `raw`, `label`, `parentKey`, `children`.
- Position: `level` (one-based), `posInSet`, `setSize`, `isLastChild`, `hasChildren`, `isLeaf`.
- State: `isExpanded`, `isSelected`, `isFocused`, `isLoading`, `isDisabled`, `checkedState`
  (`'checked'`, `'unchecked'`, or `'indeterminate'`).
- Actions: `expand()`, `collapse()`, `toggle()`, `select()`, `toggleSelect()`, `toggleCheck()`,
  `focus()`.

Disabled items are skipped by keyboard navigation and cannot be focused, selected, expanded, or
checked.

### Expansion

Use `defaultExpandedKeys` for uncontrolled expansion, or `expandedKeys` with `onExpandedKeysChange` to
own it.

```tsx
const [expanded, setExpanded] = createSignal(['src'])

const tree = createTree({
  items,
  getKey,
  getChildren,
  get expandedKeys() {
    return expanded()
  },
  onExpandedKeysChange: setExpanded,
})
```

Clicking a branch row toggles it, and the trigger chevron always toggles. Set `expandOnClick: false`
so row clicks only select. Set `trigger: false` to render no chevron; rows then always toggle,
whatever `expandOnClick` says.

Branch height animates by default; set `transition={false}` on `tree.Tree` to turn it off.
Collapsed branches unmount their children unless `forceMount`. Neither prop applies
with `virtualizer`, which has no nested groups.

### Selection

`selectionMode` defaults to `'single'`.

- `'single'`: clicking a row selects only that row.
- `'multiple'`: <kbd>Ctrl</kbd> or <kbd>Cmd</kbd> click toggles a row, <kbd>Shift</kbd> click
  selects a range of visible rows, and <kbd>Ctrl</kbd>+<kbd>A</kbd> selects every enabled item,
  including items inside collapsed branches.
- `'none'`: rows cannot be selected, and `aria-selected` is omitted.

Control selection with `selectedKeys` and `onSelectedKeysChange`.

### Checkboxes

Set `checkable: true` to give every item a check state. The default item then renders a
`tree.ItemCheckbox` in each row, and each `treeitem` exposes `aria-checked`.

With `checkCascade` on (the default), checking a branch checks its enabled descendants, and a
branch whose descendants are partly checked becomes `indeterminate`. Set `checkCascade: false` to
check each item independently.

`checkedKeys` and `onCheckedKeysChange` use the same keys, including keys of items that have not
loaded yet. A checked key under a lazy branch applies once its item loads. With `checkCascade` on,
children loaded under a checked branch start checked.

In a custom `itemRender`, place `tree.ItemCheckbox` yourself. It follows the tree `size` and the
item's check state. It is hidden from assistive technology and removed from the tab order because
the `treeitem` carries `aria-checked`; <kbd>Space</kbd> on the item toggles it. Change its glyphs
with `checkedIcon` and `indeterminateIcon`.

```tsx
<tree.Tree
  aria-label="Permissions"
  itemRender={(item) => (
    <tree.Item item={item}>
      <tree.ItemTrigger />
      <tree.ItemCheckbox />
      <tree.ItemLabel />
    </tree.Item>
  )}
/>
```

### Lazy children

Provide `loadChildren` to fetch children on demand. An item becomes a lazy branch when
`getChildren` returns `undefined` for it and `isLeaf` does not return `true`. Return an empty
array from `getChildren`, or mark the item with `isLeaf`, when it can never have children.

Expanding a lazy branch waits for the promise. While it loads, the trigger shows `loadingIcon`,
the item sets `aria-busy`, and its key appears in `loadingKeys`. On success the branch expands and
`onLoadChildrenComplete` runs. On failure `onLoadChildrenError` runs and the branch stays
collapsed, so expanding it again retries. Lazy keys in `defaultExpandedKeys` or `expandedKeys` load
the same way.

Loaded children are cached per key while `items()` keeps returning the same item object for that
key. Returning a new object for a key drops its cached children and loads them again: right away
when the branch is expanded, otherwise on its next expansion.

### Virtualization

Pass a `virtualizer` from `createListVirtualizer` to render only the rows near the viewport. The
`tree.Tree` root becomes the scroll container, so give it a bounded height and `overflow-auto`.
Keyboard focus and `tree.focus(key)` scroll through the virtualizer, so they reach rows outside the
window.

```tsx
import { createTree } from 'moraine'
import type { TreeT } from 'moraine'
import { createListVirtualizer } from 'moraine/virtualizer'

const tree = createTree<FileNode>({ items, getKey, getChildren })
const virtualizer = createListVirtualizer<TreeT.ItemInstance<FileNode>>({
  estimateSize: () => 32,
  getItemKey: (item) => item.key,
})

<tree.Tree
  aria-label="Files"
  virtualizer={virtualizer}
  class="h-80 overflow-auto"
/>
```

Expanded branches are flattened into one list. Every row keeps `aria-level`, `aria-posinset`, and
`aria-setsize`, so assistive technology still reads the full hierarchy.

### Drag to move items

`createTreeSortable` from `moraine/dnd` (needs `@dnd-kit/dom`) moves items by dragging. Wrap
`tree.Tree` in `sortable.Provider`, call `sortable.useNode(item)` in `itemRender`, and spread its
`props` onto `tree.Item`. `onMove` reports the new `parentKey` and sibling `index`;
`moveTreeNode` applies it to `children`-shaped data.

```tsx
import { createTreeSortable, moveTreeNode } from 'moraine/dnd'

const sortable = createTreeSortable(tree, {
  canNest: (item) => item.raw.children !== undefined,
  onMove: (event) => setFiles((files) => moveTreeNode(files, event, access)),
})

<sortable.Provider>
  <tree.Tree
    itemRender={(item) => {
      const node = sortable.useNode(item)
      return (
        <tree.Item item={item} {...node.props}>
          <tree.ItemTrigger />
          <tree.ItemLabel />
          <button ref={node.handleRef} aria-label={`Move ${item.label}`}>⋮⋮</button>
        </tree.Item>
      )
    }}
  />
</sortable.Provider>
```

- The top and bottom quarters of a row drop before and after it; the middle drops inside, as the
  last child, when `canNest` allows it. Dropping after an expanded item with children makes the
  source its first child, which is where the indicator line sits.
- Moves into the dragged item or its descendants are rejected. Pass `canDrop` for other rules.
- Hovering inside a collapsed item for 600 ms expands it, which also loads lazy children. Set
  `expandDelay` to change or disable it.
- The tree styles the drag: a copy stays in place while the dragged item follows the pointer at 60%
  opacity, the row under the pointer keeps its hover background, `before` and `after` draw a
  straight line from the label start, and `inside` rings the row. These styles follow
  `data-dnd-dragging` and `data-drop-position` on `tree.Item`; override them through the `row` slot.
- After the drop, the moved item slides from where it was released into its new place. A drop
  inside a collapsed item expands it first. Set `dropAnimation: false` to place it at once.
- Keyboard dragging starts only from `node.handleRef`, so <kbd>Space</kbd> and <kbd>Enter</kbd> on
  an item keep selecting and activating it. Arrow keys move along the visible rows.
- With a `virtualizer`, pass `rangeExtractor: sortable.rangeExtractor` to `createListVirtualizer`
  so the dragged row stays mounted while it is scrolled out of view.
- `moveTreeNode` only moves nodes that are in your data. Children from `loadChildren` live in the
  tree's cache, and a moved ancestor gets a new object, so merge loaded children into your data
  before moving them.

### Custom items

`itemRender` renders one visible item and receives its item handle. Return a `tree.Item` with
`item={item}` as the root, then compose the bound parts inside it in this order: `tree.ItemTrigger`,
`tree.ItemCheckbox`, `tree.ItemIcon`, `tree.ItemLabel`, your own content, and `tree.ItemAction` last.

Without `itemRender`, the default item renders the trigger, the checkbox when `checkable`, the icon
from `getIcon`, the label, and the `actionRender` actions.

- `tree.ItemTrigger` toggles the branch and is hidden from assistive technology. Pass `icon` to
  change the chevron for one item, or `children` to replace it.
- `tree.ItemLabel` shows `label`. Pass `children` to render other content.
- `tree.ItemIcon` renders the `icon` you pass. Use `getIcon` instead when you keep the default item.

### Icons

`getIcon` returns the prefix icon of the default item. It receives the item handle, so the icon
can follow `hasChildren`, `isExpanded`, or `isLoading`. Return `undefined` for no icon.

```tsx
const tree = createTree({
  items,
  getKey,
  getChildren,
  getIcon: (item) => {
    if (!item.hasChildren) {
      return 'i-lucide:file'
    }
    return item.isExpanded ? 'i-lucide:folder-open' : 'i-lucide:folder'
  },
})
```

On `tree.Tree`, `expandIcon` replaces the chevron of every item and `loadingIcon` replaces the
glyph shown while a branch loads.

### Row actions

`actionRender` adds trailing controls to every row of the default item, inside `tree.ItemAction`.
Clicks inside the actions never select or expand the item. Actions are always visible; to reveal
them on hover, style the `action` slot with the `group/tree-row` group that every row sets.

The tree keeps a single tab stop and does not manage focus inside actions. Set
`tabIndex={item.isFocused ? 0 : -1}` on each control so <kbd>Tab</kbd> from the focused item
reaches only that row's actions.

```tsx
<tree.Tree
  aria-label="Files"
  classes={{
    action: 'opacity-0 group-hover/tree-row:opacity-100 focus-within:opacity-100',
  }}
  actionRender={(item) => (
    <Button
      variant="ghost"
      size="icon-xs"
      leading="i-lucide:trash-2"
      tabIndex={item.isFocused ? 0 : -1}
      aria-label={`Delete ${item.label}`}
    />
  )}
/>
```

### Indentation and guides

Each row indents by its depth times `--mo-tree-indent`. Set the geometry variables in the
`tree.Tree` `style`; every item reads them from the root.

| Variable           | Default        | Description                                       |
| ------------------ | -------------- | ------------------------------------------------- |
| `--mo-tree-indent` | `1.25rem`      | Indentation added per nesting level.              |
| `--mo-tree-gap`    | Size dependent | Gap between the trigger, icon, and label.         |
| `--mo-tree-gutter` | `0.25rem`      | Horizontal margin between rows and the tree edge. |
| `--mo-tree-pad`    | `0.5rem`       | Row start padding before indentation.             |

```tsx
<tree.Tree
  aria-label="Files"
  style={{
    '--mo-tree-indent': '1.5rem',
    '--mo-tree-gap': '0.25rem',
  }}
/>
```

Indent guides are on by default. Each row renders one `guide` element per ancestor level inside an
`aria-hidden` wrapper, in nested and virtual mode alike. Guides follow right-to-left layouts and
stay visible in forced-colors mode. Restyle them with `classes.guide`, or set `indentGuide={false}`
to render none.

### Keyboard interaction

Only one item is in the tab order at a time. Arrow keys move focus between visible items and skip
disabled ones. In right-to-left layouts, <kbd>ArrowLeft</kbd> and <kbd>ArrowRight</kbd> swap.

| Key                                                        | Action                                                                                                                 |
| ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| <kbd>ArrowDown</kbd> / <kbd>ArrowUp</kbd>                  | Moves focus to the next or previous visible item.                                                                      |
| <kbd>ArrowRight</kbd>                                      | Expands a collapsed branch; on an expanded branch, moves focus to its first child.                                     |
| <kbd>ArrowLeft</kbd>                                       | Collapses an expanded branch; otherwise moves focus to the parent.                                                     |
| <kbd>Home</kbd> / <kbd>End</kbd>                           | Moves focus to the first or last visible item.                                                                         |
| <kbd>Enter</kbd>                                           | Selects the item, or toggles the branch when `selectionMode` is `'none'`. Then calls `onAction` when provided.         |
| <kbd>Space</kbd>                                           | Toggles the check state when `checkable`; toggles selection in `'multiple'` mode; selects the item in `'single'` mode. |
| <kbd>Shift</kbd> + arrows, <kbd>Home</kbd>, <kbd>End</kbd> | Moves focus and extends the selection in `'multiple'` mode.                                                            |
| <kbd>Ctrl</kbd>+<kbd>A</kbd> / <kbd>Cmd</kbd>+<kbd>A</kbd> | Selects every enabled item in `'multiple'` mode.                                                                       |
| <kbd>\*</kbd>                                              | Expands every enabled sibling of the focused item.                                                                     |
| Printable characters                                       | Moves focus to the next item whose text starts with the typed text. Turn off with `typeahead: false`.                  |

## Examples

### Browse project files

Describe nested data with `getKey` and `getChildren`, then render `tree.Tree`. Clicking a branch
row or its chevron toggles it.

```tsx
import { createTree } from 'moraine'

interface FileNode {
  id: string
  name: string
  children?: FileNode[]
}

const FILES: FileNode[] = [
  {
    id: 'src',
    name: 'src',
    children: [
      {
        id: 'components',
        name: 'components',
        children: [
          { id: 'button', name: 'button.tsx' },
          { id: 'input', name: 'input.tsx' },
        ],
      },
      { id: 'index', name: 'index.ts' },
    ],
  },
  { id: 'package', name: 'package.json' },
  { id: 'readme', name: 'README.md' },
]

export function Basic() {
  const tree = createTree<FileNode>({
    items: () => FILES,
    getKey: (node) => node.id,
    getChildren: (node) => node.children,
    getLabel: (node) => node.name,
    defaultExpandedKeys: ['src'],
  })

  return (
    <div class="max-w-sm w-full">
      <tree.Tree aria-label="Project files" />
    </div>
  )
}
```

### Drive expansion from page state

Control `expandedKeys` with `onExpandedKeysChange`, and call `expandAll`, `collapseAll`, or `expandTo`
from toolbar buttons.

```tsx
import { Button, createTree } from 'moraine'
import { createSignal } from 'solid-js'

interface Section {
  id: string
  title: string
  children?: Section[]
}

const SECTIONS: Section[] = [
  {
    id: 'guides',
    title: 'Guides',
    children: [
      { id: 'install', title: 'Installation' },
      { id: 'theming', title: 'Theming' },
    ],
  },
  {
    id: 'components',
    title: 'Components',
    children: [
      {
        id: 'forms',
        title: 'Forms',
        children: [
          { id: 'input', title: 'Input' },
          { id: 'select', title: 'Select' },
        ],
      },
      { id: 'overlay', title: 'Overlay' },
    ],
  },
]

export function Expanded() {
  const [expanded, setExpanded] = createSignal<string[]>(['components'])
  const tree = createTree<Section>({
    items: () => SECTIONS,
    getKey: (node) => node.id,
    getChildren: (node) => node.children,
    getLabel: (node) => node.title,
    get expandedKeys() {
      return expanded()
    },
    onExpandedKeysChange: setExpanded,
  })

  return (
    <div class="max-w-sm w-full space-y-3">
      <div class="flex flex-wrap gap-2">
        <Button size="sm" variant="outline" onClick={() => tree.expandAll()}>
          Expand all
        </Button>
        <Button size="sm" variant="outline" onClick={() => tree.collapseAll()}>
          Collapse all
        </Button>
        <Button size="sm" variant="outline" onClick={() => tree.expandTo('select')}>
          Reveal Select
        </Button>
      </div>
      <tree.Tree aria-label="Documentation outline" />
      <p class="text-xs text-muted-foreground">
        Expanded: <span class="text-foreground font-medium">{expanded().join(', ') || 'none'}</span>
      </p>
    </div>
  )
}
```

### Expand only from the chevron

Set `expandOnClick: false` so clicking a row selects it and only the chevron expands or collapses
it.

```tsx
import { createTree } from 'moraine'

interface FileNode {
  id: string
  name: string
  children?: FileNode[]
}

const FILES: FileNode[] = [
  {
    id: 'src',
    name: 'src',
    children: [
      {
        id: 'components',
        name: 'components',
        children: [
          { id: 'button', name: 'button.tsx' },
          { id: 'input', name: 'input.tsx' },
        ],
      },
      { id: 'index', name: 'index.ts' },
    ],
  },
  { id: 'package', name: 'package.json' },
  { id: 'readme', name: 'README.md' },
]

export function TriggerExpand() {
  const tree = createTree<FileNode>({
    items: () => FILES,
    getKey: (node) => node.id,
    getChildren: (node) => node.children,
    getLabel: (node) => node.name,
    defaultExpandedKeys: ['src'],
    expandOnClick: false,
  })

  return (
    <div class="max-w-sm w-full space-y-2">
      <tree.Tree
        aria-label="Project files"
        itemRender={(item) => (
          <tree.Item item={item}>
            <tree.ItemTrigger />
            <tree.ItemIcon icon={item.hasChildren ? 'icon-folder' : 'icon-file'} />
            <tree.ItemLabel />
          </tree.Item>
        )}
      />
      <p class="text-xs text-muted-foreground">
        Click the chevron to expand or collapse a folder. Clicking the row only selects it.
      </p>
    </div>
  )
}
```

### Select several folders

Set `selectionMode: 'multiple'` and `expandOnClick: false` so row clicks only change the
selection. Use <kbd>Ctrl</kbd>, <kbd>Cmd</kbd>, or <kbd>Shift</kbd> clicks to select more.

```tsx
import { createTree } from 'moraine'
import { createSignal } from 'solid-js'

interface Folder {
  id: string
  name: string
  children?: Folder[]
}

const FOLDERS: Folder[] = [
  {
    id: 'inbox',
    name: 'Inbox',
    children: [
      { id: 'invoices', name: 'Invoices' },
      { id: 'receipts', name: 'Receipts' },
    ],
  },
  {
    id: 'projects',
    name: 'Projects',
    children: [
      { id: 'moraine', name: 'Moraine' },
      { id: 'atlas', name: 'Atlas' },
    ],
  },
  { id: 'archive', name: 'Archive' },
]

export function Selection() {
  const [selected, setSelected] = createSignal<string[]>(['moraine'])
  const tree = createTree<Folder>({
    items: () => FOLDERS,
    getKey: (node) => node.id,
    getChildren: (node) => node.children,
    getLabel: (node) => node.name,
    defaultExpandedKeys: ['inbox', 'projects'],
    selectionMode: 'multiple',
    expandOnClick: false,
    get selectedKeys() {
      return selected()
    },
    onSelectedKeysChange: setSelected,
  })

  return (
    <div class="max-w-sm w-full space-y-3">
      <tree.Tree aria-label="Mail folders" variant="solid" />
      <p class="text-xs text-muted-foreground">
        Click to select, hold <kbd>Ctrl</kbd> to toggle, and hold <kbd>Shift</kbd> to select a
        range. Selected:{' '}
        <span class="text-foreground font-medium">{selected().join(', ') || 'none'}</span>
      </p>
    </div>
  )
}
```

### Grant permissions with cascading checkboxes

Set `checkable: true` and `selectionMode: 'none'`. Checking a group checks everything inside it,
and partly checked groups show an indeterminate state.

```tsx
import { createTree } from 'moraine'
import { createSignal } from 'solid-js'

interface Permission {
  id: string
  label: string
  children?: Permission[]
}

const PERMISSIONS: Permission[] = [
  {
    id: 'billing',
    label: 'Billing',
    children: [
      { id: 'billing-read', label: 'View invoices' },
      { id: 'billing-write', label: 'Manage payment methods' },
    ],
  },
  {
    id: 'members',
    label: 'Members',
    children: [
      { id: 'members-read', label: 'View members' },
      { id: 'members-invite', label: 'Invite members' },
      { id: 'members-remove', label: 'Remove members' },
    ],
  },
]

export function Checkable() {
  const [checked, setChecked] = createSignal<string[]>(['members-read'])
  const tree = createTree<Permission>({
    items: () => PERMISSIONS,
    getKey: (node) => node.id,
    getChildren: (node) => node.children,
    getLabel: (node) => node.label,
    defaultExpandedKeys: ['billing', 'members'],
    checkable: true,
    selectionMode: 'none',
    get checkedKeys() {
      return checked()
    },
    onCheckedKeysChange: setChecked,
  })

  return (
    <div class="max-w-sm w-full space-y-3">
      <tree.Tree aria-label="Role permissions" />
      <p class="text-xs text-muted-foreground">
        Checked leaves and branches:{' '}
        <span class="text-foreground font-medium">{checked().join(', ') || 'none'}</span>
      </p>
    </div>
  )
}
```

### Load folders on demand

Provide `loadChildren` and mark files with `isLeaf`. Each folder loads the first time it expands
and shows a loading icon until its children arrive.

```tsx
import { createTree } from 'moraine'

interface Directory {
  id: string
  name: string
  hasChildren?: boolean
  children?: Directory[]
}

const REMOTE: Record<string, Directory[]> = {
  root: [
    { id: 'design', name: 'Design', hasChildren: true },
    { id: 'engineering', name: 'Engineering', hasChildren: true },
    { id: 'notes', name: 'notes.txt' },
  ],
  design: [
    { id: 'brand', name: 'Brand', hasChildren: true },
    { id: 'wireframes', name: 'wireframes.fig' },
  ],
  engineering: [
    { id: 'api', name: 'api.md' },
    { id: 'infra', name: 'infra.md' },
  ],
  brand: [{ id: 'logo', name: 'logo.svg' }],
}

function fetchChildren(id: string): Promise<Directory[]> {
  return new Promise((resolve) => setTimeout(() => resolve(REMOTE[id] ?? []), 900))
}

export function AsyncLoad() {
  const tree = createTree<Directory>({
    items: () => REMOTE.root!,
    getKey: (node) => node.id,
    getChildren: (node) => node.children,
    getLabel: (node) => node.name,
    isLeaf: (node) => !node.hasChildren,
    loadChildren: (node) => fetchChildren(node.id),
  })

  return (
    <div class="max-w-sm w-full">
      <tree.Tree aria-label="Remote files" />
    </div>
  )
}
```

### Render ten thousand rows

Pass a `virtualizer` from `createListVirtualizer`, and give the tree a bounded
height. Expanded branches join the same virtual list.

```tsx
import { createTree } from 'moraine'
import type { TreeT } from 'moraine'
import { createListVirtualizer } from 'moraine/virtualizer'

interface Row {
  id: string
  name: string
  children?: Row[]
}

const GROUPS: Row[] = Array.from({ length: 200 }, (_, group) => ({
  id: `group-${group}`,
  name: `Group ${group + 1}`,
  children: Array.from({ length: 50 }, (_, index) => ({
    id: `group-${group}-item-${index}`,
    name: `Item ${group + 1}.${index + 1}`,
  })),
}))

export function Virtual() {
  const tree = createTree<Row>({
    items: () => GROUPS,
    getKey: (node) => node.id,
    getChildren: (node) => node.children,
    getLabel: (node) => node.name,
    defaultExpandedKeys: ['group-0'],
  })
  const virtualizer = createListVirtualizer<TreeT.ItemInstance<Row>>({
    estimateSize: () => 32,
    getItemKey: (entry) => entry.key,
  })

  return (
    <div class="max-w-sm w-full space-y-2">
      <tree.Tree
        aria-label="Ten thousand rows"
        virtualizer={virtualizer}
        class="p-1 border border-border rounded-lg h-[280px] overflow-auto"
      />
      <p class="text-xs text-muted-foreground">
        Expand a group to flatten its 50 items into the same virtualized list.
      </p>
    </div>
  )
}
```

### Move files and folders by dragging

Drag a grip, or Tab to it and press Space, then the arrow keys. Only folders accept drops inside,
and hovering over the collapsed `docs` folder opens it.

```tsx
import { Icon, createTree } from 'moraine'
import { createTreeSortable, moveTreeNode } from 'moraine/dnd'
import { createSignal } from 'solid-js'

interface FileNode {
  id: string
  name: string
  children?: FileNode[]
}

const FILES: FileNode[] = [
  {
    id: 'src',
    name: 'src',
    children: [
      { id: 'app', name: 'app.tsx' },
      { id: 'routes', name: 'routes', children: [{ id: 'home', name: 'home.tsx' }] },
    ],
  },
  { id: 'docs', name: 'docs', children: [{ id: 'guide', name: 'guide.md' }] },
  { id: 'readme', name: 'README.md' },
  { id: 'license', name: 'LICENSE' },
]

const ACCESS = {
  getKey: (node: FileNode) => node.id,
  getChildren: (node: FileNode) => node.children,
  withChildren: (node: FileNode, children: FileNode[]) => ({ ...node, children }),
}

export function Sortable() {
  const [files, setFiles] = createSignal(FILES)

  const tree = createTree<FileNode>({
    items: files,
    getKey: (node) => node.id,
    getChildren: (node) => node.children,
    getLabel: (node) => node.name,
    defaultExpandedKeys: ['src'],
  })
  const sortable = createTreeSortable(tree, {
    // Only folders accept children; files take drops before or after them.
    canNest: (item) => item.raw.children !== undefined,
    onMove: (event) => setFiles((current) => moveTreeNode(current, event, ACCESS)),
  })

  return (
    <div class="max-w-sm w-full">
      <sortable.Provider>
        <tree.Tree
          aria-label="Project files"
          itemRender={(item) => {
            const node = sortable.useNode(item)
            return (
              <tree.Item item={item} {...node.props}>
                <tree.ItemTrigger />
                <tree.ItemIcon icon={item.raw.children ? 'i-lucide:folder' : 'i-lucide:file'} />
                <tree.ItemLabel />
                <button
                  ref={node.handleRef}
                  type="button"
                  aria-label={`Move ${item.raw.name}`}
                  class="text-muted-foreground ms-auto rounded-sm flex size-6 cursor-grab items-center justify-center hover:bg-accent"
                >
                  <Icon name="i-lucide:grip-vertical" />
                </button>
              </tree.Item>
            )
          }}
        />
      </sortable.Provider>
    </div>
  )
}
```

### Add counts and custom icons

Return a `tree.Item` from `itemRender` and compose the bound parts with your own content, such as a
`Badge` with a count and a `tree.ItemIcon` per item.

```tsx
import { Badge, createTree } from 'moraine'
import { Show } from 'solid-js'

interface Workspace {
  id: string
  name: string
  count?: number
  children?: Workspace[]
}

const WORKSPACES: Workspace[] = [
  {
    id: 'acme',
    name: 'Acme',
    children: [
      { id: 'web', name: 'Web app', count: 12 },
      { id: 'mobile', name: 'Mobile app', count: 4 },
    ],
  },
  { id: 'personal', name: 'Personal', count: 2 },
]

export function CustomItem() {
  const tree = createTree<Workspace>({
    items: () => WORKSPACES,
    getKey: (node) => node.id,
    getChildren: (node) => node.children,
    getLabel: (node) => node.name,
    defaultExpandedKeys: ['acme'],
  })

  return (
    <div class="max-w-sm w-full">
      <tree.Tree
        aria-label="Workspaces"
        itemRender={(item) => (
          <tree.Item item={item}>
            <tree.ItemTrigger />
            <tree.ItemIcon
              icon={item.hasChildren ? 'i-lucide:building-2' : 'i-lucide:layout-dashboard'}
            />
            <tree.ItemLabel />
            <Show when={item.raw.count}>
              {(count) => (
                <Badge variant="soft" size="sm">
                  {count()}
                </Badge>
              )}
            </Show>
          </tree.Item>
        )}
      />
    </div>
  )
}
```

### Add row actions

Pass `actionRender` to add a button and a dropdown menu to each row. The `action` slot hides them
until the row is hovered, focused, or its menu is open. Each control sets
`tabIndex={item.isFocused ? 0 : -1}`, so <kbd>Tab</kbd> from an item reaches only its actions.

```tsx
import { Button, DropdownMenu, createTree } from 'moraine'
import { Show, createSignal } from 'solid-js'

interface FileNode {
  id: string
  name: string
  children?: FileNode[]
}

const FILES: FileNode[] = [
  {
    id: 'src',
    name: 'src',
    children: [
      {
        id: 'components',
        name: 'components',
        children: [
          { id: 'button', name: 'button.tsx' },
          { id: 'input', name: 'input.tsx' },
        ],
      },
      { id: 'index', name: 'index.ts' },
    ],
  },
  { id: 'docs', name: 'docs', children: [{ id: 'guide', name: 'guide.md' }] },
  { id: 'package', name: 'package.json' },
  { id: 'readme', name: 'README.md' },
]

export function ItemAction() {
  const [status, setStatus] = createSignal('Hover a row to show its actions.')
  const tree = createTree<FileNode>({
    items: () => FILES,
    getKey: (node) => node.id,
    getChildren: (node) => node.children,
    getLabel: (node) => node.name,
    getIcon: (item) => (item.hasChildren ? 'i-lucide:folder' : 'i-lucide:file'),
    defaultExpandedKeys: ['src', 'components'],
  })

  return (
    <div class="max-w-sm w-full space-y-2">
      <tree.Tree
        aria-label="Files"
        classes={{
          action:
            'opacity-0 transition-opacity group-hover/tree-row:opacity-100 focus-within:opacity-100 has-[[aria-expanded=true]]:opacity-100 [@media(hover:none)]:opacity-100',
        }}
        actionRender={(item) => (
          <>
            <Show when={item.hasChildren}>
              <Button
                variant="ghost"
                size="icon-xs"
                leading="i-lucide:file-plus"
                tabIndex={item.isFocused ? 0 : -1}
                aria-label={`New file in ${item.label}`}
                onClick={() => setStatus(`New file in ${item.label}`)}
              />
            </Show>
            <DropdownMenu>
              <DropdownMenu.Trigger
                as={Button}
                variant="ghost"
                size="icon-xs"
                leading="i-lucide:ellipsis"
                tabIndex={item.isFocused ? 0 : -1}
                aria-label={`More actions for ${item.label}`}
              />
              <DropdownMenu.Content
                items={[
                  {
                    label: 'Rename',
                    icon: 'i-lucide:pencil',
                    onSelect: () => setStatus(`Rename ${item.label}`),
                  },
                  {
                    label: 'Delete',
                    icon: 'i-lucide:trash-2',
                    onSelect: () => setStatus(`Delete ${item.label}`),
                  },
                ]}
              />
            </DropdownMenu>
          </>
        )}
      />
      <p role="status" class="text-xs text-muted-foreground">
        {status()}
      </p>
    </div>
  )
}
```

## API Reference

### Attributes

| Attributes | Slot | Description |
| --- | --- | --- |
| `data-checked` | `tree-item`, `tree-checkbox` | Present when the item or toggle is checked. |
| `data-disabled` | `tree-item`, `tree-row`, `tree-checkbox` | Present when the component, slot, or item is disabled. |
| `data-expanded` | `tree-item`, `tree-row`, `tree-trigger`, `tree-icon`, `tree-content` | Present when the panel, accordion, or menu is expanded. |
| `data-indeterminate` | `tree-item`, `tree-checkbox` | Present when the checkbox or progress state is indeterminate. |
| `data-leaf` | `tree-item`, `tree-row`, `tree-trigger`, `tree-icon` | Present when the tree item has no children. |
| `data-loading` | `tree-item`, `tree-trigger` | Present when the component or async operation is loading. |
| `data-selected` | `tree-item`, `tree-row` | Present when the item or tab is selected. |
| `data-unchecked` | `tree-checkbox` | Present when the checkbox, radio item, or switch is unchecked. |
| `data-closed` | `tree-content` | Present when disclosure or transition content is closed. |
| `data-transition` | `tree-content` | Present while a target participates in a visibility transition. |
| `data-transitioning` | `tree-content` | Present while a resizable panel is transitioning between sizes. |

### Props

#### tree.Tree

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| actionRender | Component<ItemRenderProps<T>> \| undefined | — | Renders trailing actions for each item in the default item, inside `tree.ItemAction`.<br>Receives the item instance. Ignored when `itemRender` is set; custom item content composes<br>`tree.ItemAction` directly. |
| expandIcon | IconT.Name \| undefined | 'icon-chevron-right' | Icon of the expand trigger, used when `tree.ItemTrigger` has no `icon` or children of its<br>own. The recipe rotates it as the branch expands. |
| forceMount | boolean \| undefined | false | Whether collapsed branches keep their children mounted. When `false`, children mount on<br>first expansion and unmount once the branch collapses; when `true`, children mount even<br>before the first expansion. |
| indentGuide | boolean \| undefined | true | Whether nested items draw vertical guide lines for their ancestor levels. |
| itemRender | Component<ItemRenderProps<T>> \| undefined | — | Renders one visible item. Defaults to trigger, check box when checkable, the icon<br>returned by `getIcon`, label, and `actionRender` actions. Receives the item instance.<br>Use `tree.Item` as the root of the rendered content; it also renders the nested children<br>of expanded branches when the tree is not virtualized. |
| loadingIcon | IconT.Name \| undefined | 'icon-loading' | Icon shown in the trigger instead of the expand icon while a lazy branch loads its children. |
| size | 'sm' \| 'md' \| 'lg' \| undefined | 'md' | Visual size of the component. |
| transition | boolean \| undefined | true | Whether expanding and collapsing nested content animates its height. |
| variant | 'subtle' \| 'solid' \| undefined | 'subtle' | How the selected row is highlighted. |
| virtualizer | Virtualizer<T> \| undefined | — | Renders only the visible items of the flattened tree instead of nesting them. Create it<br>with `createListVirtualizer()` from `moraine/virtualizer`. The tree root is the scroll<br>container, so give it a bounded height, and keyboard focus scrolls through the virtualizer.<br>The row wiring is applied by `tree.Item`, so no extra props need spreading. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| classes | Classes \| undefined | — | Family slot class defaults for this instance. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |
| styles | Styles \| undefined | — | Family slot style defaults for this instance. |

**`actionRender` example**

```tsx
import { Button, createTree } from 'moraine'

const tree = createTree<string>({ items: () => ['Docs', 'Src'], getKey: (name) => name })

<tree.Tree
  actionRender={(item) => (
    <Button size="icon-sm" variant="ghost" leading="i-lucide:plus" aria-label={`Add to ${item.label}`} />
  )}
/>
```

**`itemRender` example**

```tsx
import { createTree } from 'moraine'

const tree = createTree<string>({ items: () => ['Docs', 'Src'], getKey: (name) => name })

<tree.Tree
  itemRender={(item) => (
    <tree.Item item={item}>
      <tree.ItemTrigger />
      <tree.ItemLabel>{item.raw.toUpperCase()}</tree.ItemLabel>
    </tree.Item>
  )}
/>
```

**`virtualizer` example**

```tsx
import { createTree } from 'moraine'
import type { TreeT } from 'moraine'
import { createListVirtualizer } from 'moraine/virtualizer'

const names = Array.from({ length: 10_000 }, (_, index) => `Item ${index}`)
const tree = createTree<string>({ items: () => names, getKey: (name) => name })
const virtualizer = createListVirtualizer<TreeT.ItemInstance<string>>({ estimateSize: () => 28 })

<tree.Tree class="h-80 overflow-auto" virtualizer={virtualizer} />
```

#### tree.Item

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| item* | ItemInstance<T> | — | Item this node renders; pass the instance that `itemRender` receives. Drives the<br>`treeitem` ARIA attributes (level, position, expanded, selected, checked) and its click and<br>keyboard handling. |
| children | JSX.Element \| undefined | — | Row content, usually trigger and label. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |

#### tree.ItemTrigger

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| icon | IconT.Name \| undefined | — | Overrides the expand icon of this trigger (otherwise the tree's `expandIcon`). The loading<br>icon still replaces it while the branch loads. |
| as | T \| undefined | 'span' | Element or component to render as. |
| children | JSX.Element \| undefined | — | Replaces the icon entirely, including the loading icon. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |

#### tree.ItemCheckbox

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| checkedIcon | IconT.Name \| undefined | 'icon-check' | Icon shown when the item is checked. |
| indeterminateIcon | IconT.Name \| undefined | 'icon-minus' | Icon shown when the item is indeterminate. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |

#### tree.ItemIcon

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| icon* | IconT.Name | — | Icon to render. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |

#### tree.ItemLabel

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| as | T \| undefined | 'span' | Element or component to render as. |
| children | JSX.Element \| undefined | — | Replaces the item's text value. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |

#### tree.ItemAction

Host props of the action container; children are the action controls.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| children | JSX.Element \| undefined | — | Content rendered inside the element. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |
