Installation
Run this in a project set up with shadcn/ui:
$ pnpm dlx shadcn@latest add https://uxelith.com/r/tree-view.jsonIt adds these packages for you:
clsxtailwind-mergeThe source lands in your components folder as
tree-view.tsx. It's yours: change anything.
Usage
import { TreeView } from "@/components/tree-view"
export function Files() {
return (
<TreeView
label="Project files"
draggable
defaultExpanded={["src"]}
defaultItems={[
{
id: "src",
label: "src",
children: [
{ id: "app", label: "app.tsx", meta: "3 KB" },
{ id: "index", label: "index.ts", meta: "120 B" },
],
},
{ id: "readme", label: "README.md" },
]}
/>
)
}Source
One file, 376 lines, nothing hidden. Read it before you install it.
"use client";
import * as React from "react";
import { cn } from "@/lib/utils";
export interface TreeNode {
/** Stable and unique across the whole tree. */
id: string;
/** Plain text: it is also what filtering and screen readers use. */
label: string;
/** Present (even if empty) makes this a folder. */
children?: TreeNode[];
/** Replaces the default file or folder icon. */
icon?: React.ReactNode;
/** Quiet text on the right, like a file size. */
meta?: string;
}
export type TreeDrop = { id: string; target: string; position: "before" | "after" | "inside" };
export interface TreeViewProps extends Omit<React.ComponentProps<"div">, "children" | "onSelect"> {
/** The tree, when you keep it yourself. Pair with `onItemsChange`. */
items?: TreeNode[];
/** The starting tree, when the component keeps it. */
defaultItems?: TreeNode[];
onItemsChange?: (items: TreeNode[], drop: TreeDrop) => void;
/** Accessible name, e.g. "Project files". */
label: string;
/** Folders open at the start. */
defaultExpanded?: string[];
/** The selected item. */
selected?: string | null;
defaultSelected?: string | null;
onSelect?: (id: string) => void;
/** Show only items matching this text, with their folders opened. */
filter?: string;
/** Let people drag items, and move them with Alt + ↑/↓. */
draggable?: boolean;
/** Veto a move, for example to keep something at the top level. */
canDrop?: (drop: TreeDrop) => boolean;
}
/** The node with this id, and the list it lives in. */
function locate(list: TreeNode[], id: string, parent: TreeNode | null = null): { node: TreeNode; siblings: TreeNode[]; parent: TreeNode | null } | null {
for (const node of list) {
if (node.id === id) return { node, siblings: list, parent };
const found = node.children && locate(node.children, id, node);
if (found) return found;
}
return null;
}
const holds = (node: TreeNode, id: string): boolean => node.id === id || (node.children ?? []).some((child) => holds(child, id));
/** Returns a new tree with the move applied, or the same tree if the move makes no sense. */
export function moveTreeNode(items: TreeNode[], { id, target, position }: TreeDrop): TreeNode[] {
const from = locate(items, id);
if (!from || id === target || holds(from.node, target)) return items;
const remove = (list: TreeNode[]): TreeNode[] =>
list.filter((n) => n.id !== id).map((n) => (n.children ? { ...n, children: remove(n.children) } : n));
const insert = (list: TreeNode[]): TreeNode[] =>
list.flatMap((n) => {
if (n.id !== target) return [n.children ? { ...n, children: insert(n.children) } : n];
if (position === "inside") return [{ ...n, children: [...(n.children ?? []), from.node] }];
return position === "before" ? [from.node, n] : [n, from.node];
});
return insert(remove(items));
}
function Chevron({ open }: { open: boolean }) {
return (
<svg viewBox="0 0 16 16" aria-hidden="true" fill="none" className={cn("size-3.5 shrink-0 text-muted-foreground transition-transform duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none", open && "rotate-90")}>
<path d="m6 3.5 4.5 4.5L6 12.5" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" />
</svg>
);
}
const FolderIcon = () => (
<svg viewBox="0 0 16 16" aria-hidden="true" fill="none" className="size-4 shrink-0 text-muted-foreground">
<path d="M1.8 4.4c0-.8.6-1.4 1.4-1.4h3l1.5 1.8h5.1c.8 0 1.4.6 1.4 1.4v6.2c0 .8-.6 1.4-1.4 1.4H3.2c-.8 0-1.4-.6-1.4-1.4V4.4Z" stroke="currentColor" strokeWidth="1.4" />
</svg>
);
const FileIcon = () => (
<svg viewBox="0 0 16 16" aria-hidden="true" fill="none" className="size-4 shrink-0 text-muted-foreground">
<path d="M4 1.8h5l3 3v9.4H4V1.8Z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round" />
</svg>
);
/**
* A tree of folders and files that opens smoothly, filters as you type and
* rearranges by drag and drop. Plain data in, plain data out.
*
* - Drop on a folder to put something inside it, or between rows to place it
* there; a line shows where it will land. Nothing can land inside itself.
* - Keyboard follows the tree pattern: ↑/↓ move, → opens, ← closes or goes to
* the parent, Home and End jump, Enter selects. Alt + ↑/↓ moves the current
* item, so nothing needs a mouse, and each move is announced.
* - On touch, press and hold a row to pick it up; a normal swipe still scrolls.
* - `filter` opens the folders on the way to each match and marks the text.
* - Under reduced motion folders open at once.
*/
export function TreeView({
items: itemsProp,
defaultItems = [],
onItemsChange,
label,
defaultExpanded = [],
selected: selectedProp,
defaultSelected = null,
onSelect,
filter = "",
draggable = false,
canDrop,
className,
...props
}: TreeViewProps) {
const [ownItems, setOwnItems] = React.useState(defaultItems);
const items = itemsProp ?? ownItems;
const [expanded, setExpanded] = React.useState(() => new Set(defaultExpanded));
const [ownSelected, setOwnSelected] = React.useState(defaultSelected);
const selected = selectedProp !== undefined ? selectedProp : ownSelected;
const [current, setCurrent] = React.useState<string | null>(null);
const [drop, setDrop] = React.useState<TreeDrop | null>(null);
const [dragging, setDragging] = React.useState<string | null>(null);
const [message, setMessage] = React.useState("");
const rootRef = React.useRef<HTMLUListElement>(null);
const ghostRef = React.useRef<HTMLDivElement>(null);
const focusAfter = React.useRef(false);
const justDragged = React.useRef(false);
const query = filter.trim().toLowerCase();
const matches = (n: TreeNode) => n.label.toLowerCase().includes(query);
const keep = (n: TreeNode): boolean => !query || matches(n) || (n.children ?? []).some(keep);
const isOpen = (n: TreeNode) => !!n.children && (query ? n.children.some(keep) : expanded.has(n.id));
const visible = React.useMemo(() => {
const out: TreeNode[] = [];
const walk = (list: TreeNode[]) =>
list.filter(keep).forEach((n) => {
out.push(n);
if (isOpen(n)) walk(n.children!);
});
walk(items);
return out;
// eslint-disable-next-line react-hooks/exhaustive-deps -- keep and isOpen only read these
}, [items, expanded, query]);
const focusId = current && visible.some((n) => n.id === current) ? current : (selected && visible.some((n) => n.id === selected) ? selected : visible[0]?.id);
React.useEffect(() => {
if (!focusAfter.current) return;
focusAfter.current = false;
rootRef.current?.querySelector<HTMLElement>('[role="treeitem"][tabindex="0"]')?.focus();
});
const setOpen = (id: string, open: boolean) =>
setExpanded((set) => {
const next = new Set(set);
if (open) next.add(id);
else next.delete(id);
return next;
});
const moveTo = (id: string) => {
setCurrent(id);
focusAfter.current = true;
};
const select = (id: string) => {
if (selectedProp === undefined) setOwnSelected(id);
onSelect?.(id);
};
const apply = (move: TreeDrop) => {
if (canDrop && !canDrop(move)) return;
const next = moveTreeNode(items, move);
if (next === items) return;
if (itemsProp === undefined) setOwnItems(next);
onItemsChange?.(next, move);
if (move.position === "inside") setOpen(move.target, true);
const name = (id: string) => locate(items, id)?.node.label ?? id;
setMessage(`${name(move.id)} moved ${move.position === "inside" ? "into" : move.position} ${name(move.target)}`);
};
const onKeyDown = (event: React.KeyboardEvent) => {
const i = visible.findIndex((n) => n.id === focusId);
const node = visible[i];
if (!node) return;
if (draggable && event.altKey && (event.key === "ArrowUp" || event.key === "ArrowDown")) {
event.preventDefault();
const { siblings } = locate(items, node.id)!;
const at = siblings.indexOf(node);
const near = siblings[at + (event.key === "ArrowUp" ? -1 : 1)];
if (near) {
apply({ id: node.id, target: near.id, position: event.key === "ArrowUp" ? "before" : "after" });
moveTo(node.id);
}
return;
}
if (event.key === "ArrowDown" && visible[i + 1]) moveTo(visible[i + 1]!.id);
else if (event.key === "ArrowUp" && visible[i - 1]) moveTo(visible[i - 1]!.id);
else if (event.key === "Home") moveTo(visible[0]!.id);
else if (event.key === "End") moveTo(visible.at(-1)!.id);
else if (event.key === "ArrowRight" && node.children) {
if (isOpen(node)) {
if (visible[i + 1]) moveTo(visible[i + 1]!.id);
} else {
setOpen(node.id, true);
moveTo(node.id);
}
} else if (event.key === "ArrowLeft") {
if (isOpen(node) && !query) {
setOpen(node.id, false);
moveTo(node.id);
} else {
const parent = locate(items, node.id)?.parent;
if (parent) moveTo(parent.id);
}
} else if (event.key === "Enter" || event.key === " ") {
select(node.id);
if (node.children && !query) setOpen(node.id, !expanded.has(node.id));
} else return;
event.preventDefault();
};
// Where a pointer over a row would land: the edges are "between", a folder's middle is "inside".
const dropAt = (x: number, y: number, id: string): TreeDrop | null => {
const row = document.elementFromPoint(x, y)?.closest<HTMLElement>("[data-tree-row]");
if (!row || !rootRef.current?.contains(row)) return null;
const target = locate(items, row.dataset.treeRow!)?.node;
const moving = locate(items, id)?.node;
if (!target || !moving || holds(moving, target.id)) return null;
const box = row.getBoundingClientRect();
const at = (y - box.top) / box.height;
const position = target.children ? (at < 0.25 ? "before" : at > 0.75 ? "after" : "inside") : at < 0.5 ? "before" : "after";
const move: TreeDrop = { id, target: target.id, position };
return !canDrop || canDrop(move) ? move : null;
};
const onPointerDown = (event: React.PointerEvent, node: TreeNode) => {
if (!draggable || event.button !== 0) return;
const start = { x: event.clientX, y: event.clientY };
const touch = event.pointerType === "touch";
let live = false;
let last: TreeDrop | null = null;
let hold: ReturnType<typeof setTimeout> | undefined;
const begin = () => {
live = true;
setDragging(node.id);
};
const place = (x: number, y: number) => {
if (ghostRef.current) ghostRef.current.style.transform = `translate(${x + 12}px, ${y + 10}px) rotate(-2deg)`;
};
const stopScroll = (e: TouchEvent) => live && e.preventDefault();
const onMove = (e: PointerEvent) => {
const far = Math.hypot(e.clientX - start.x, e.clientY - start.y);
if (!live) {
if (touch) {
if (far > 8) finish(); // a swipe: leave it to the page
return;
}
if (far < 5) return;
begin();
}
place(e.clientX, e.clientY);
last = dropAt(e.clientX, e.clientY, node.id);
setDrop(last);
};
const finish = () => {
clearTimeout(hold);
removeEventListener("pointermove", onMove);
removeEventListener("pointerup", end);
removeEventListener("pointercancel", finish);
removeEventListener("touchmove", stopScroll);
setDragging(null);
setDrop(null);
};
const end = () => {
if (live) {
justDragged.current = true;
setTimeout(() => (justDragged.current = false), 0);
if (last) apply(last);
}
finish();
};
if (touch) hold = setTimeout(begin, 280);
addEventListener("pointermove", onMove);
addEventListener("pointerup", end);
addEventListener("pointercancel", finish);
addEventListener("touchmove", stopScroll, { passive: false });
};
const text = (value: string) => {
const at = query ? value.toLowerCase().indexOf(query) : -1;
if (at < 0) return value;
return (
<>
{value.slice(0, at)}
<mark className="rounded-[3px] bg-[color-mix(in_oklab,var(--tree-accent,var(--primary))_30%,transparent)] text-inherit">{value.slice(at, at + query.length)}</mark>
{value.slice(at + query.length)}
</>
);
};
const render = (list: TreeNode[]): React.ReactNode =>
list.filter(keep).map((node) => {
const open = isOpen(node);
const hit = drop?.target === node.id;
return (
<li
key={node.id}
role="treeitem"
aria-selected={node.id === selected}
aria-expanded={node.children ? open : undefined}
tabIndex={node.id === focusId ? 0 : -1}
className="rounded-lg outline-none [&:focus-visible>[data-tree-row]]:ring-2 [&:focus-visible>[data-tree-row]]:ring-inset [&:focus-visible>[data-tree-row]]:ring-ring"
onFocus={(event) => {
if (event.target === event.currentTarget) setCurrent(node.id);
}}
>
<div
data-tree-row={node.id}
onPointerDown={(event) => onPointerDown(event, node)}
onClick={(event) => {
event.stopPropagation();
if (justDragged.current) return;
setCurrent(node.id);
select(node.id);
if (node.children && !query) setOpen(node.id, !expanded.has(node.id));
}}
className={cn(
"relative flex h-8 cursor-pointer select-none items-center gap-1.5 rounded-lg px-2 text-sm transition-colors duration-150 motion-reduce:transition-none",
node.id === selected ? "bg-[color-mix(in_oklab,var(--tree-accent,var(--primary))_15%,transparent)] font-medium" : "hover:bg-accent",
node.id === dragging && "opacity-45",
hit && drop.position === "inside" && "bg-[color-mix(in_oklab,var(--tree-accent,var(--primary))_12%,transparent)] ring-2 ring-inset ring-[var(--tree-accent,var(--primary))]",
)}
>
{hit && drop.position !== "inside" && (
<span aria-hidden="true" className={cn("absolute inset-x-1 z-10 h-0.5 rounded-full bg-[var(--tree-accent,var(--primary))]", drop.position === "before" ? "-top-px" : "-bottom-px")} />
)}
{node.children ? <Chevron open={open} /> : <span aria-hidden="true" className="w-3.5 shrink-0" />}
{node.icon ?? (node.children ? <FolderIcon /> : <FileIcon />)}
<span className="min-w-0 truncate">{text(node.label)}</span>
{node.meta && <span className={cn("ml-auto shrink-0 pl-3 font-mono text-xs", node.id === selected ? "text-foreground/80" : "text-muted-foreground")}>{node.meta}</span>}
</div>
{node.children && (
<div className={cn("grid transition-[grid-template-rows,visibility] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none", open ? "visible grid-rows-[1fr]" : "invisible grid-rows-[0fr]")}>
<ul role="group" className="ml-[0.9rem] min-h-0 overflow-hidden border-l border-border pl-2">
{render(node.children)}
</ul>
</div>
)}
</li>
);
});
return (
<div className={cn("w-full [--tree-accent:var(--primary)]", className)} {...props}>
<ul ref={rootRef} role="tree" aria-label={label} onKeyDown={onKeyDown}>
{render(items)}
</ul>
{query && visible.length === 0 && <p className="px-2 py-3 text-sm text-muted-foreground">Nothing matches “{filter.trim()}”.</p>}
{dragging && (
<div ref={ghostRef} aria-hidden="true" className="pointer-events-none fixed left-0 top-0 z-50 rounded-lg bg-foreground px-2.5 py-1 text-sm text-background shadow-lg" style={{ transform: "translate(-999px, -999px)" }}>
{locate(items, dragging)?.node.label}
</div>
)}
<p role="status" className="sr-only">
{message}
</p>
</div>
);
}Props
| Prop | Type | Default | Description |
|---|---|---|---|
| items / defaultItems | TreeNode[] | [] | The tree, kept by you or by the component. |
| onItemsChange | (items, drop) => void | — | Called with the new tree after a move. |
| label | string | — | Accessible name. |
| defaultExpanded | string[] | [] | Folders open at the start. |
| selected / defaultSelected | string | null | null | The selected item. |
| onSelect | (id: string) => void | — | Called when an item is chosen. |
| filter | string | "" | Shows only matches, with their folders opened. |
| draggable | boolean | false | Allow moving items by drag, or Alt + arrow keys. |
| canDrop | (drop) => boolean | — | Veto a move. |
Accessibility
- Follows the ARIA tree pattern: arrow keys, Home and End move, Right opens, Left closes or goes to the parent, Enter selects.
- Alt + Up and Alt + Down move the current item, so dragging is never required, and every move is announced.
- On touch, press and hold picks a row up; swiping still scrolls.
- Folders open at once under prefers-reduced-motion.
Changelog
- v1.0.0Latest
First release.