Command palette

@yasinsensoy/web

Web · Components

TreeView

Tree view: for nested data like a file explorer, category tree, org chart, permission list.

38 exports

Live example

Preview

app
(site)
page.tsx
layout.tsxM
globals.css
components
ui
button.tsxButton
dialog.tsx2
city-picker.tsx
tree-view.tsx
header.tsx
footer.tsxLocked
package.json

Code

import { TreeNode, TreeView } from "@yasinsensoy/web";

const [items, setItems] = useState<TreeNode[]>(files);

<TreeView
  label="Project files"
  items={items}
  className="h-96" selectionMode="multiple" search draggable stickyParents
  onItemsChange={setItems}
  onRename={(node, name) => setItems((i) => updateNode(i, node.id, { label: name }))}
  onDelete={(nodes) => setItems((i) => removeNodes(i, nodes.map((n) => n.id)))}
  onAction={(node) => open(node)}
  contextMenu={(node, api) => [
    { label: "Rename", shortcut: "F2", onSelect: () => api.rename(node.id) },
    { label: "Delete", tone: "danger", shortcut: "Delete", onSelect: () => remove(node) },
  ]}
/>

Events

  1. Events appear here when you interact with the preview.

Checkboxes: a three-state permission tree, submitted in a form

Sales
View orders
Create orders
Issue refundsNeeds approval
Catalog
Products
View
Edit
DeleteAdmins only
Pricing
Reports

2 permissions selected (leaves only)

Lazy loading: folders from the server, error and retry

100k nodes: virtualization, sticky parent nodes, search

Region 1
Branch 1.1
Record 1.1.1
Record 1.1.2
Record 1.1.3
Record 1.1.4
Record 1.1.5
Record 1.1.6
Record 1.1.7
Record 1.1.8
Record 1.1.9
Record 1.1.10
Record 1.1.11
Record 1.1.12
Record 1.1.13
Record 1.1.14
Record 1.1.15
Record 1.1.16
Record 1.1.17
Record 1.1.18
Record 1.1.19
Record 1.1.20
Record 1.1.21
Record 1.1.22
Record 1.1.23
Record 1.1.24
Record 1.1.25
Record 1.1.26
Record 1.1.27
Record 1.1.28
Record 1.1.29

101,100 nodes, all expanded.

Import

import {
  TreeView,
  nodeText,
  canHaveChildren,
  indexTree,
  ancestorsOf,
  descendantIds,
  flattenTree,
  foldText,
  matchRanges,
  filterTree,
  computeCheckStates,
  checkedOutput,
  toggleCheck,
  updateNode,
  removeNodes,
  insertNodes,
  moveNodes,
  materializeTree,
} from "@yasinsensoy/web";

TreeView

componentClient component

Tree view: for nested data like a file explorer, category tree, org chart, permission list. Works with a single items array.

  • Expand/collapse: Chevron, clicking the row (expandOnClick), double-click, keyboard. Expanded child rows slide in. With storageKey expansion survives page reloads.
  • Selection: Single or multiple (Ctrl/⌘, Shift range, Ctrl/⌘+A).
  • Checkboxes: Tri-state, parent-child linked or independent; with checkOutput all/leaf/top nodes; submitted in a form with name.
  • Lazy loading: hasChildren + loadChildren; loading and error (Try again) rows.
  • Search: A built-in box or query; insensitive to locale-specific letters/accents, matches highlighted and their paths expanded; filtering or highlight only.
  • Drag and drop: Before/after/inside drop indicator, multi-move, auto-scroll at the edge, expand on hover, cancel with Esc, keyboard moving (Alt+arrows). On touch from the handle.
  • Rename: F2; Enter saves, Esc cancels; shows errors.
  • Row content: Icon (a different icon when expanded), description, badge, action buttons appearing on hover, tooltip, link (href).
  • Context menu: contextMenu; Shift+F10, long press on touch or the ⋯ button.
  • Keyboard (WAI-ARIA tree): ↑/↓, →/← (expand/collapse, go to child/parent), Home/End, PageUp/PageDown, * (expand siblings), type-ahead, Enter (onAction), Space (select/check), F2, Delete. In right-to-left languages →/← swap.
  • Performance: Smooth even with hundreds of thousands of nodes: rows are virtualized and the tree is flattened once; with stickyParents parent nodes stay stuck.
  • Accessibility: role="tree", aria-level/setsize/posinset, aria-activedescendant, operations are announced via a live region.

Uses a fixed row height (for virtualization); descriptions fit on a single line. Give the tree a height: className="h-96".

TreeView({ items, label, size: sizeProp, indent, guides, expanded: expandedProp, defaultExpanded, onExpandedChange, storageKey, expandOnClick, selectionMode, selected: selectedProp, defaultSelected, onSelectedChange, selectionFollowsFocus, onAction, checkboxes, checked: checkedProp, defaultChecked, onCheckedChange, checkMode, checkOutput, name, loadChildren, query: queryProp, defaultQuery, onQueryChange, search, filterMode, filter, draggable, canDrop, onMove, onItemsChange, onRename, onDelete, contextMenu, renderLabel, empty, stickyParents, virtualize, apiRef, className, style, effect, ...props }: TreeViewProps<T>): JSX.Element

Examples

const [items, setItems] = useState<TreeNode[]>(files);

<TreeView
  label="Files"
  items={items}
  className="h-96"
  search
  draggable
  onItemsChange={setItems}
  onRename={(node, name) => setItems((i) => updateNode(i, node.id, { label: name }))}
  onAction={(node) => open(node.id)}
  contextMenu={(node, api) => [
    { label: "Rename", shortcut: "F2", onSelect: () => api.rename(node.id) },
    { label: "Delete", tone: "danger", shortcut: "Delete", onSelect: () => remove(node) },
  ]}
/>

// Checkboxes, lazy loading
<TreeView
  label="Permissions"
  items={[{ id: "root", label: "Server", hasChildren: true }]}
  loadChildren={(node) => fetch(`/api/tree/${node.id}`).then((r) => r.json())}
  checkboxes
  checkOutput="leaves"
  name="permissions"
  selectionMode="none"
/>

nodeText

function

Plain text of a node used for search and type-ahead.

nodeText(node: N): string

Can the node have children (loaded or to be loaded)?

canHaveChildren(node: N, getChildren?: GetChildren<N>): boolean

indexTree

function

Indexes all known nodes (including loaded children) by id. Walks with a stack; no stack overflow on deep trees.

indexTree(roots: readonly N[], getChildren?: GetChildren<N>): TreeIndex<N>

ancestorsOf

function

Ancestor ids of a node from the root down (excluding itself, starting at the root).

ancestorsOf(id: string, parentOf: ReadonlyMap<string, string | null>): string[]

The node itself and all its (known) descendants.

descendantIds(node: N, getChildren?: GetChildren<N>, includeSelf?: boolean): string[]

flattenTree

function

Converts the tree into an array of visible rows: children of expanded nodes come right after their parent. Virtualization and keyboard navigation work on this array. Walks with a stack; fast even at 100k rows.

flattenTree(roots: readonly N[], { isExpanded, getChildren, statusOf, filter, reveal, showEmpty }: FlattenOptions<N>): FlatRow<N>[]

foldText

function

Folds text for search: Turkish lowercase, without accents (see matchRanges).

foldText(text: string): string

matchRanges

function

Returns where the query occurs in the text, with indices of the original text. Turkish case and accent differences are ignored ("sehir" → "Şehir").

matchRanges(text: string, query: string): [number, number][]

filterTree

function

Finds the nodes matching a query and the path to them. Searches only known (loaded) nodes.

filterTree(roots: readonly N[], query: string, getChildren?: GetChildren<N>, match?: (node: N, query: string) => boolean): TreeFilterResult

Computes each node's state from the checked set. In connected (cascade) mode a node with children takes its state from them: checked when all are checked, mixed when some are. A parent in the set counts all its descendants as checked.

computeCheckStates(roots: readonly N[], checked: ReadonlySet<string>, getChildren?: GetChildren<N>, cascade?: boolean): Map<string, Exclude<CheckState, "unchecked">>

Produces the checked value from a state map. See CheckOutput.

checkedOutput(states: ReadonlyMap<string, Exclude<CheckState, "unchecked">>, index: TreeIndex<N>, output: CheckOutput, getChildren?: GetChildren<N>): string[]

toggleCheck

function

Returns the new checked set when a node's checkbox is pressed. In connected mode the node and all its descendants are checked or unchecked together (disabled ones and those with checkable: false don't change); the parents' entries in the set are removed and their state comes from their children.

toggleCheck(node: N, checked: ReadonlySet<string>, states: ReadonlyMap<string, Exclude<CheckState, "unchecked">>, index: TreeIndex<N>, getChildren?: GetChildren<N>, cascade?: boolean): Set<string>

updateNode

function

Changes a node. Returns a new tree; only nodes along the path are copied.

updateNode(roots: readonly N[], id: string, patch: Partial<N> | ((node: N) => N)): N[]

Examples

setItems((items) => updateNode(items, "src", { label: "source" }));

removeNodes

function

Removes nodes (and their descendants) from the tree.

removeNodes(roots: readonly N[], ids: Iterable<string>): N[]

insertNodes

function

Inserts nodes at a given position. With parentId null they are added to the root; at the end when index is omitted.

insertNodes(roots: readonly N[], nodes: readonly N[], { parentId, index }: { parentId: string | null; index?: number; }): N[]

moveNodes

function

Moves nodes to a new position (the result of drag and drop). The target position is given relative to the tree before the move; the shift when moving down within the same list is corrected automatically. A node can't be moved under itself; such a request returns the tree unchanged.

moveNodes(roots: readonly N[], ids: readonly string[], target: TreeLocation): N[]

Examples

// Move "a.ts" and "b.ts" to the start of the "lib" folder
setItems((items) => moveNodes(items, ["a.ts", "b.ts"], { parentId: "lib", index: 0 }));

Writes loaded children (loadChildren results) into the tree, so the tree can be stored or passed around as a single piece of data.

materializeTree(roots: readonly N[], loaded: ReadonlyMap<string, readonly N[]>): N[]

TreeNodeBase

interface

Node fields used by tree math (platform nodes extend this).

NameTypeDescription
idstringUnique id within the tree.
label?unknownDisplay name; when it is text it is used for search and type-ahead.
textValue?stringPlain text for search when the name isn't text.
children?readonly TreeNodeBase[]Child nodes.
hasChildren?booleanChildren will be loaded later.
disabled?booleanDisabled node.
selectable?booleanSelectable?
checkable?booleanCheckable?

TreeAction

interface

Small action button at the end of a TreeNode row.

NameTypeDefaultDescription
iconIconPropIcon of the button: name or element.
labelstringName of the button; it is the tooltip and screen reader text.
onSelect(node: TreeNode<T>) => voidCalled with the node when clicked.
tone?"neutral" | "danger""neutral"Color.

TreeNode

interface

A node inside TreeView. Only id and label are required.

Extends: TreeNodeBase

NameTypeDefaultDescription
idstringUnique key across the whole tree. Selection, expansion and moving use it.
labelReactNodeName shown in the row. Text is recommended for search and type-ahead.
textValue?stringPlain text used in search, type-ahead and the drag preview if label isn't text.
icon?IconPropIcon before the name: name or element.
expandedIcon?IconPropIcon shown while the node is expanded (e.g. an open folder).
description?ReactNodeShort faded description next to the name (single line).
badge?ReactNodeBadge at the end of the row: a number or short text. 0 isn't shown, "" draws a dot.
badgeTone?Tone"neutral"Badge color.
children?readonly TreeNode<T>[]Child nodes. An empty array means "can have children but has none" (e.g. an empty folder).
hasChildren?booleanChild nodes aren't loaded yet but exist. When expanded, TreeView requests them with loadChildren.
disabled?booleanCan't be selected, checked or dragged; can still be expanded and collapsed.
selectable?booleantrueWhether this node can be selected.
checkable?booleantrueWhether this node shows a checkbox (while the tree has checkboxes on).
draggable?booleantrueWhether this node can be dragged (while the tree has draggable on).
droppable?booleanCan items be dropped into it? Default: nodes that can have children (children or hasChildren given) accept, leaves don't.
editable?booleantrueWhether it can be renamed (if the tree has onRename).
href?stringLink: if given, clicking the name goes to this address (with the UIProvider link).
tooltip?TooltipPropTooltip of the row. See TooltipProp.
actions?readonly TreeAction<T>[]Action buttons at the end of the row that appear on hover.
menu?readonly MenuEntry[]Context menu of this node only; replaces the tree's contextMenu.
className?stringClasses added to the row.
data?TYour own data; it comes with the node in callbacks.

Examples

const items: TreeNode[] = [
  {
    id: "src",
    label: "src",
    icon: "folder",
    children: [
      { id: "src/index.ts", label: "index.ts", icon: "file", badge: "M" },
    ],
  },
  { id: "remote", label: "Server", hasChildren: true }, // children come via loadChildren
];

FlatStatusRow

interface

Status row for children being loaded or failing to load.

NameTypeDescription
kind"loading" | "error" | "empty"Row kind: children loading, failed to load, or empty.
idstringId of the row (generated from the parent).
parentIdstringId of the parent whose status is shown.
levelnumberDepth; one below the parent.

Function returning the children of a node (given or loaded).

type GetChildren = Core.GetChildren<TreeNode<T>>

Index of the tree by id.

type TreeIndex = Core.TreeIndex<TreeNode<T>>

A visible node row.

type FlatNodeRow = Core.FlatNodeRow<TreeNode<T>>

A row of the flattened tree.

type FlatRow = Core.FlatRow<TreeNode<T>>

Options of flattenTree.

type FlattenOptions = Core.FlattenOptions<TreeNode<T>>

Result of filterTree.

NameTypeDescription
matchedSet<string>Nodes matching the query.
keepSet<string>Nodes that must be visible: the matches and their ancestors.
parentsSet<string>Nodes with a matching descendant; expanded automatically during search.

State of the checkbox.

type CheckState = "checked" | "unchecked" | "mixed"

Which nodes the TreeView checked value contains.

  • "all": all checked nodes (including parents).
  • "leaves": only checked leaves (e.g. selected files).
  • "top": the topmost fully checked nodes; their descendants aren't listed (the shortest list for saying "all of this folder").
type CheckOutput = "all" | "leaves" | "top"

TreeLocation

interface

A position in the tree: the parent (null for the root) and the index in its child list.

NameTypeDescription
parentIdstring | nullId of the parent (null for the root).
indexnumberIndex in the parent's child list (starts at 0).

Size of a TreeView row.

type TreeViewSize = "sm" | "md" | "lg"

TreeRowState

interface

Row state given to the TreeView renderLabel function.

NameTypeDescription
levelnumberDepth; roots are 1.
expandedbooleanIs the node expanded?
selectedbooleanIs the node selected?
focusedbooleanIs keyboard focus on this row?
checkedCheckStateState of the checkbox.
querystringThe search query ("" if empty).
highlight(text: string) => ReactNodeMarks query matches in the text with <mark>.

Selection mode of TreeView.

  • "none": Rows aren't selected (only expand/collapse, checkboxes or actions).
  • "single": A single row is selected.
  • "multiple": One by one with Ctrl/⌘, a range with Shift, all with Ctrl/⌘+A. On touch, tapping while a row is selected adds to/removes from the selection.
type TreeSelectionMode = "none" | "single" | "multiple"

Position of the drop relative to the row.

type TreeDropPosition = "before" | "after" | "inside"

TreeMoveInfo

interface

Info of TreeViewProps.canDrop and TreeViewProps.onMove.

NameTypeDescription
idsstring[]Ids of the moved nodes (in tree order).
nodesTreeNode<T>[]The moved nodes.
parentIdstring | nullNew parent (null for the root).
parentTreeNode<T> | nullNew parent (null for the root).
indexnumberIndex in the new parent's child list, relative to the tree before the move.
targetIdstring | nullThe row dropped on and the drop position relative to it (filled for keyboard moves too).
positionTreeDropPositionPosition of the drop relative to the target row: before, after or inside.

TreeViewApi

interface

Tools obtained with apiRef to control TreeView from outside.

NameTypeDescription
expand(ids: string | readonly string[]) => voidExpands nodes.
collapse(ids: string | readonly string[]) => voidCollapses nodes.
toggle(id: string) => voidExpands or collapses a node.
expandAll() => voidExpands all known nodes (unloaded children aren't requested).
collapseAll() => voidCollapses all nodes.
reveal(id: string) => voidExpands its parents, makes the row visible and moves keyboard focus to it.
focus(id?: string) => voidFocuses the tree (that row if given).
select(ids: readonly string[]) => voidChanges the selection.
rename(id: string) => voidStarts inline rename. If the node isn't in the tree yet (e.g. just added) it starts on the first render where it appears.
reload(id: string) => voidDrops the lazily loaded children and requests them again.
getNode(id: string) => TreeNode<T> | undefinedNode by id (loaded children included).
getPath(id: string) => string[]Parent ids of the node starting from the root.
getItems() => TreeNode<T>[]The full tree with loaded children written in.

TreeViewProps

interface

Props of the TreeView component.

Extends: Omit<ComponentProps<"div">, "children" | "onSelect" | "defaultValue" | "defaultChecked" | "contextMenu">

NameTypeDefaultDescription
itemsreadonly TreeNode<T>[]Nodes. See TreeNode.
labelstringScreen reader name of the tree (e.g. "Files").
size?TreeViewSize"md"Row height and font size. If omitted, chosen from the UIProvider density setting: compact → "sm", comfortable → "lg".
indent?number16Indent of each level (px).
guides?booleantrueVertical lines showing levels. The focused node's line darkens.
expanded?readonly string[]Expanded nodes (controlled).
defaultExpanded?readonly string[] | "all"Initially expanded nodes; "all" expands all known nodes.
onExpandedChange?(ids: string[]) => voidWhen the expanded nodes change.
storageKey?stringIf given, expanded nodes are stored in the browser under this key and restored on page reload (in uncontrolled use).
expandOnClick?booleantrueWhether clicking a parent's row toggles it. If false, only the chevron, double-click and keyboard expand it.
selectionMode?TreeSelectionMode"single"Selection mode. See TreeSelectionMode.
selected?readonly string[]Selected nodes (controlled).
defaultSelected?readonly string[]Initially selected nodes. Their parents expand automatically.
onSelectedChange?(ids: string[], nodes: TreeNode<T>[]) => voidWhen the selection changes, with ids and nodes.
selectionFollowsFocus?booleanfalseIn single selection, whether the selection follows focus while navigating with arrow keys (like a file explorer).
onAction?(node: TreeNode<T>) => voidWhen a row is "activated": double-click or Enter (e.g. to open a file).
checkboxes?booleanfalseCheckboxes.
checked?readonly string[]Checked nodes (controlled). See checkOutput.
defaultChecked?readonly string[]Initially checked nodes.
onCheckedChange?(ids: string[]) => voidWhen the checks change.
checkMode?"cascade" | "independent""cascade""cascade": a parent is linked to its children (tri-state: checked, mixed, empty). "independent": each node on its own.
checkOutput?CheckOutput"all"Which nodes the checked value contains. See CheckOutput.
name?stringForm field name: a hidden field with this name is added for each checked (if checkboxes are on) or selected node; FormData.getAll(name) gives the ids.
loadChildren?(node: TreeNode<T>, context: { signal: AbortSignal; }) => Promise<readonly TreeNode<T>[] | undefined | void>Fetches the children of a node with hasChildren: true and no children when it is expanded. If you return an array the tree stores it; if you return nothing and update your own items data, that is used. If it throws, "Tekrar dene" appears on the row.
query?stringSearch text (controlled). If not empty, matches are highlighted.
defaultQuery?stringInitial search text.
onQueryChange?(query: string) => voidWhen the search text changes (from the built-in search box too).
search?boolean | stringfalseSearch box above the tree. true or placeholder text. In the box ↓ or Enter goes to the first match; Esc clears.
filterMode?"filter" | "highlight""filter"Whether non-matching branches are hidden in search ("filter") or only matches are highlighted and their paths expanded ("highlight").
filter?(node: TreeNode<T>, query: string) => booleanYour own matching rule. If omitted, the name (and textValue) is searched insensitive to locale-specific letters and accents.
draggable?booleanfalseMoving by drag and drop. Drag a row with the mouse; on touch drag from the row's handle. On the keyboard Alt+↑/↓ moves the order, Alt+→ inside, Alt+← outside. The result comes via onMove and/or onItemsChange.
canDrop?(info: TreeMoveInfo<T>) => booleanWhether the drop is allowed. In addition to the default rules (can't drop into its own child).
onMove?(info: TreeMoveInfo<T>) => voidWhen a move happens.
onItemsChange?(items: TreeNode<T>[]) => voidThe new tree after a move (loaded children included). If you keep items in state you can pass setItems directly.
onRename?(node: TreeNode<T>, label: string) => void | string | Promise<void | string>If given, nodes can be renamed: F2, apiRef.rename(id) or from a menu. If you return text (or a Promise resolves with text) it is shown as an error and the box stays open.
onDelete?(nodes: TreeNode<T>[]) => voidWhen Delete is pressed, with the selected (otherwise the focused) nodes.
contextMenu?readonly MenuEntry[] | ((node: TreeNode<T>, api: TreeViewApi<T>) => readonly MenuEntry[])Context menu (long press on touch, Shift+F10 on the keyboard). Pass a function if it varies by node. The node's own menu takes precedence. On touch screens a ⋯ button also appears on the row.
renderLabel?(node: TreeNode<T>, state: TreeRowState) => ReactNodeYour own content instead of the name.
empty?ReactNodeShown when there are no rows.
effect?EffectPropEffect or effects of node rows (also plays on the selected and focused row) (e.g. "ripple", "border"). If omitted, UIProvider appearance.defaults.treeView.effect. See BuiltinEffect.
stickyParents?booleanfalseWhile scrolling, parent nodes stay stuck at the top (like VS Code); clicking goes to that node. The background is taken from the color behind the tree; if you want a different one set the --ui-tree-surface CSS variable.
virtualize?boolean | "auto""auto"Draws only visible rows. "auto": with more than 100 rows. Give the tree a height (className="h-96").
apiRef?Ref<TreeViewApi<T>>Tree API. See TreeViewApi.