# Tree view

> The sidebar of pages, folders or files: carry a row up, down and sideways to nest it, and folders open as you hold them.

Most tree views pop children in, and their drag and drop shows a blue line that never says whether you are dropping inside a folder or beside it, so rows land one level off. Here a row's children slide out from under it while the rows below make room, and closing folds them back. Pick a row up (with everything inside it) and a copy follows you while the original dims in place, so nothing under the pointer moves. Up and down picks the gap; sideways picks the depth, one level per indent, and the line marking the gap starts exactly where the row will sit. The middle of a row means inside it: the row takes a ring, and a closed one opens itself if you hold it there. A rule can refuse a place: the line turns amber and the reason shows under what you carry. Let go and the row glides from your hand into its slot; a save that fails takes it back. F2 renames in place, + adds a row inside, Delete removes it with Undo, and Alt with the arrows moves a row by keyboard.

## Install

```bash
npx shadcn@latest add @hairline/tree-view
```

Needs React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

- npm: `lucide-react`
- Hairline UI components it needs (the CLI installs them too): none
- Docs and live preview: https://hairlineui.com/ui/tree-view
- Registry item (source): https://hairlineui.com/r/tree-view.json

## Usage

```tsx
import { TreeView, type TreeNode } from "@/components/tree-view";

const [nodes, setNodes] = useState<TreeNode[]>([
  { id: "docs", parent: null, title: "Docs" },
  { id: "intro", parent: "docs", title: "Introduction" },
  { id: "readme", parent: null, title: "README.md", leaf: true },
]);

<TreeView nodes={nodes} onNodesChange={setNodes} defaultExpanded={["docs"]} onSelect={(n) => router.push(`/p/${n.id}`)} />
```

## A workspace sidebar that saves every change

Nodes are rows of a pages table: { id, parent, title } in sibling order. Each callback saves one change and throws to undo it; onCreate returns the stored page so it takes its real id. canDrop keeps the rules your server keeps.

```tsx
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { TreeView, type TreeNode } from "@/components/tree-view";

type Page = TreeNode & { readOnly?: boolean };

export function PagesSidebar({ initial, current }: { initial: Page[]; current: string }) {
  const router = useRouter();
  const [pages, setPages] = useState(initial);

  const send = async (url: string, method: string, body?: unknown) => {
    const res = await fetch(url, { method, headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
    if (!res.ok) throw new Error(await res.text());
    return res.status === 204 ? undefined : res.json();
  };

  return (
    <TreeView<Page>
      className="h-full"
      label="Pages"
      nodes={pages}
      onNodesChange={setPages}
      selected={current}
      onSelect={(page) => router.push(`/p/${page.id}`)}
      canDrop={(page, parent) => (parent?.readOnly ? `${parent.title} is read-only` : null)}
      onMove={(page, parent, index) => send(`/api/pages/${page.id}/move`, "POST", { parent: parent?.id ?? null, index })}
      onRename={(page, title) => send(`/api/pages/${page.id}`, "PATCH", { title })}
      onCreate={(parent, title) => send("/api/pages", "POST", { parent: parent?.id ?? null, title })}
      onDelete={(page) => send(`/api/pages/${page.id}`, "DELETE")}
    />
  );
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `nodes / defaultNodes` | `T extends { id, parent, title, leaf? }[]` | – | Every node, flat; parent is null at the top level. Siblings stand in the order they appear. leaf rows can't hold others. |
| `onNodesChange` | `(nodes: T[]) => void` | – | The new list after every move, rename, add, delete and undo. |
| `expanded / defaultExpanded / onExpandedChange` | `string[]` | – | Ids of the open rows. |
| `selected / defaultSelected` | `string \| null` | – | The chosen row. |
| `onSelect` | `(node: T) => void` | – | A row chosen by click, Enter or Space, e.g. to open its page. |
| `icon` | `(node, { expanded, hasChildren }) => ReactNode` | – | The row's icon. Defaults to a folder (open or closed), or a file for leaves. |
| `canDrop` | `(node, parent: T \| null) => string \| null` | – | A reason parent won't take node; null is the top level. Moving a row into itself or into a leaf is refused for you. |
| `onMove` | `(node, parent, index) => Promise<void>` | – | Saves a move (node already has its new parent). Throw to put it back. |
| `onRename` | `(node, title) => Promise<void>` | – | Turns on renaming (F2, double-click). Throw to put the old title back. |
| `onCreate` | `(parent, title) => T \| Promise<T>` | – | Turns on + (inside rows, and New … at the foot). Return the stored node. |
| `onDelete` | `(node) => Promise<void>` | – | Turns on delete. Called once the chance to undo is over; throw to bring the row back. |
| `addLabel` | `string` | `"page"` | The noun in "New …". |
| `undoFor` | `number` | `5000` | How long Undo is offered after a delete, ms. |
| `indent` | `number` | `14` | Pixels per level. |
| `label` | `string` | `"Pages"` | Accessible name of the tree. |

## States

- **open**: Opening a row turns its chevron (260ms) while its children fade in through a 4px blur where they land and the rows below glide down (480ms). Closing folds the children away where they stood while the rows below glide up. An open row with nothing inside says so.
- **lift**: After 4px (or a 300ms hold on touch, with a short vibration where supported) a copy of the row lifts: a hairline ring and a "+3" count of what's inside it. The row and everything under it dim to 40% in place.
- **slot**: The gap under the pointer gets a 2px line in the ring colour with a hollow dot at its start; the start is the depth the row will land at (90ms per change). Sideways movement changes the depth one indent at a time, inside the depths that gap allows.
- **into**: Over the middle half of a row that holds others, a ring and a light wash surround it: the row will go inside, at the end. Held there 650ms, a closed row with rows inside opens; rows opened this way close again if nothing was dropped in them.
- **refuse**: When canDrop returns a reason, the line or ring turns amber and the reason appears under the carried copy. Let go and the copy springs home (300ms, slight overshoot); the reason stays a moment under the tree.
- **land**: The moved row glides from where the copy was let go into its slot (480ms), its parent opening if it was closed; rows that changed depth slide sideways into their new indent. If onMove throws, everything glides back, the row shakes, and the line under the tree says so.
- **edit**: F2 or a double-click turns the title into a field in place. + on a row grows a new row inside it with a field; Enter keeps it, Escape folds it away. Delete folds the row and everything inside it away and holds "Deleted … · Undo" over a draining hairline (paused on hover) before calling onDelete.

## What it handles

Most tree views pop children in, and their drag and drop shows a line that never says whether you are dropping inside a folder or beside it. This makes the place and the depth of a drop clear before you let go.

- **Folders open and close smoothly**: Children slide out from under their row while the rows below make room, and closing folds them back.
- **Drag to a gap and a depth**: Up and down picks the gap, sideways picks the depth, and the line starts exactly where the row will sit.
- **Drop inside a folder**: Hold a row over the middle of another and it takes a ring. A closed folder opens itself after a moment.
- **Rules can refuse a place**: canDrop returns a reason, the line turns amber and the reason shows under what you carry.
- **Rename, add and delete**: F2 renames in place, + adds a row inside, and Delete removes it with an Undo before your function is called.
- **Keyboard and safe saving**: Arrow keys navigate, Alt with the arrows moves a row, and a failed save takes the row back.

## Replaces

a tree component, drag and drop nesting, drop depth logic, inline rename, add and delete with Undo, tree keyboard navigation

## Where it fits

- **Workspace sidebars**: The pages and folders of a Notion-style workspace.
- **File explorers**: Folders and files that people can reorganise.
- **CMS and menu managers**: Nested categories or navigation items in an admin.
- **Documentation and knowledge bases**: A tree of articles with rules about what can go where.

## Notes

- A tree of treeitems with their level, position and open state. One row is in the tab order: ↑ ↓ move, → opens a row or steps into it, ← closes it or steps out to its parent, Home and End jump, typing a title's first letters jumps to it, Enter or Space chooses.
- Alt with ↑ or ↓ moves a row among its siblings, Alt+→ moves it into the row above, Alt+← moves it out after its parent. F2 renames and Delete deletes. Every move is announced with where it went.
- Carrying writes transforms only, to the copy, the line and the ring; rows are measured once when the carry starts (and again only when a row opens under it), and nothing re-renders until the drop. Rows are memoised, so opening a folder re-renders only the rows it changes.
- On touch the list scrolls as usual; holding a row for 300ms picks it up, and only then does the page stop scrolling. A chosen row shows its + and delete buttons, since there's no hover. Near the top or bottom of the tree (or the window) it scrolls.
- Reduced motion opens, closes and moves rows in place; the line, the ring, the amber refusal and the announcements still say what happens.

License: MIT (https://hairlineui.com/license#components)
