Skip to main content

Tree

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

  • src
    • components
      • button.tsx
      • checkbox.tsx
      • tree.tsx
    • index.ts
  • package.json
  • LICENSE
Props
Slots

Anatomy#

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 for flat data, Accordion to disclose sections of content, and Sidebar or NavigationMenu 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.

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 (↵)
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.

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': Ctrl or Cmd click toggles a row, ⇧ click selects a range of visible rows, and Ctrl+A 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; Space on the item toggles it. Change its glyphs with checkedIcon and indeterminateIcon.

<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.

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.

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 Space and ↵ 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.

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 ⇥ from the focused item reaches only that row’s actions.

<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.
<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, ← and → swap.

Key Action
↓ / ↑ Moves focus to the next or previous visible item.
→ Expands a collapsed branch; on an expanded branch, moves focus to its first child.
← Collapses an expanded branch; otherwise moves focus to the parent.
↖ / ↘ Moves focus to the first or last visible item.
↵ Selects the item, or toggles the branch when selectionMode is 'none'. Then calls onAction when provided.
Space Toggles the check state when checkable; toggles selection in 'multiple' mode; selects the item in 'single' mode.
⇧ + arrows, ↖, ↘ Moves focus and extends the selection in 'multiple' mode.
Ctrl+A / Cmd+A Selects every enabled item in 'multiple' mode.
* 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.

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.

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.

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 Ctrl, Cmd, or ⇧ clicks to select more.

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.

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.

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.

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.

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.

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 ⇥ from an item reaches only its actions.

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

Props#

Tree#

Renders a <ul> element by default.

Prop

Item#

Renders a <li> element by default.

Prop

ItemTrigger#

Renders a <span> element by default.

Prop

ItemCheckbox#

Renders a <button> element by default.

Prop

ItemIcon#

Renders a <span> element by default.

Prop

ItemLabel#

Renders a <span> element by default.

Prop

ItemAction#

Host props of the action container; children are the action controls. Renders a <div> element by default.

Prop