Blocks / Tree

Tree

A tree for any node (pages, folders, teams): arrows, selection, lazy children, drag to reorder, Alt + arrows, F2 rename.

import { Tree, structureMove, structureShift } from "@forgeron/ui";
/01 → Default
  • Home
    • Welcome
    • Handbook3
      • Leave policy
      • Expenses
      • Security
  • Inbox12
  • LegalRead-only
import { Briefcase01Icon, Home01Icon } from "@forgeron/icons";
import { Tree, type TreeNode } from "@forgeron/ui";

const pages: TreeNode[] = [
  {
    id: "home",
    label: "Home",
    icon: Home01Icon,
    children: [
      { id: "welcome", label: "Welcome" },
      {
        id: "handbook",
        label: "Handbook",
        count: 3,
        children: [
          { id: "leave", label: "Leave policy" },
          { id: "expenses", label: "Expenses" },
          { id: "security", label: "Security" },
        ],
      },
    ],
  },
  {
    id: "projects",
    label: "Projects",
    icon: Briefcase01Icon,
    children: [{ id: "launch", label: "Launch plan" }],
  },
  { id: "inbox", label: "Inbox", count: 12 },
  { id: "locked", label: "Legal", readOnly: true },
];

export default function Default() {
  return (
    <div style={{ width: 260 }}>
      <Tree
        items={pages}
        label="Pages"
        defaultExpanded={["home", "handbook"]}
        defaultSelected={["leave"]}
      />
    </div>
  );
}
/02 → Reorder and rename
  • Notes
    • Monday sync
    • Tuesday review
    • Wednesday planning
  • Ideas
Drag a row, or use Alt + arrows, or press F2.
// Drag a row onto another (a line before or after, a dashed box inside), or press Alt + arrows
// on the focused row; F2 renames it. The tree gives the new items: this page keeps them.
import { Tree, structureFind, type TreeNode } from "@forgeron/ui";
import { useState } from "react";

const start: TreeNode[] = [
  {
    id: "notes",
    label: "Notes",
    children: [
      { id: "mon", label: "Monday sync" },
      { id: "tue", label: "Tuesday review" },
      { id: "wed", label: "Wednesday planning" },
    ],
  },
  { id: "ideas", label: "Ideas" },
  { id: "archive", label: "Archive", children: [{ id: "old", label: "Old notes" }] },
];

const rename = (nodes: TreeNode[], id: string, label: string): TreeNode[] =>
  nodes.map((n) =>
    n.id === id
      ? { ...n, label }
      : n.children
        ? { ...n, children: rename([...n.children] as TreeNode[], id, label) }
        : n,
  );

export default function ReorderAndRename() {
  const [items, setItems] = useState(start);
  const [log, setLog] = useState("Drag a row, or use Alt + arrows, or press F2.");
  return (
    <div style={{ display: "grid", gap: 8, width: 280 }}>
      <Tree
        items={items}
        label="Notes"
        defaultExpanded={["notes"]}
        onMove={(m) => {
          setItems(m.items);
          const to = m.parentId ? structureFind(m.items, m.parentId)?.label : "the top";
          setLog(`Moved ${m.ids.join(", ")} into ${to}, place ${m.index + 1}`);
        }}
        onRename={(id, label) => {
          setItems((all) => rename(all, id, label));
          setLog(`Renamed to ${label}`);
        }}
      />
      <span style={{ color: "var(--ink-dim)", font: "400 11px/16px var(--font-mono)" }}>{log}</span>
    </div>
  );
}
/03 → Lazy search menu
Right-click a row
// A search that keeps what matches, children loaded when a node opens, several rows selected,
// and a right-click menu on the selection.
import { Input, Tree, type ActionMenuEntry, type TreeNode } from "@forgeron/ui";
import { useState } from "react";

const wait = (ms: number) => new Promise((done) => setTimeout(done, ms));

const menu = (): ActionMenuEntry[] => [
  { id: "open", label: "Open" },
  { id: "copy", label: "Copy link" },
  { separator: true },
  { id: "remove", label: "Remove", danger: true },
];

export default function LazySearchMenu() {
  const [items, setItems] = useState<TreeNode[]>([
    { id: "eu", label: "Europe", hasChildren: true },
    { id: "am", label: "Americas", hasChildren: true },
    {
      id: "as",
      label: "Asia",
      children: [
        { id: "jp", label: "Japan" },
        { id: "sg", label: "Singapore" },
      ],
    },
  ]);
  const [query, setQuery] = useState("");
  const [log, setLog] = useState("Right-click a row");

  const load = async (id: string) => {
    await wait(700);
    const kids: Record<string, TreeNode[]> = {
      eu: [
        { id: "fr", label: "France", count: 4 },
        { id: "de", label: "Germany", count: 2 },
      ],
      am: [
        { id: "us", label: "United States", count: 6 },
        { id: "br", label: "Brazil" },
      ],
    };
    setItems((all) => all.map((n) => (n.id === id ? { ...n, children: kids[id] ?? [] } : n)));
  };

  return (
    <div style={{ display: "grid", gap: 8, width: 280 }}>
      <Input
        type="search"
        aria-label="Filter regions"
        placeholder="Filter"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />
      <Tree
        items={items}
        label="Regions"
        selectionMode="multiple"
        filter={query}
        empty="No region matches"
        onLoadChildren={load}
        menu={menu}
        onAction={(id, ids) => setLog(`${id}: ${ids.join(", ")}`)}
      />
      <span style={{ color: "var(--ink-dim)", font: "400 11px/16px var(--font-mono)" }}>{log}</span>
    </div>
  );
}
API → Props
PropTypeDefaultDescription
itemsTreeNode<D>[]—{ id, label, icon?, count?, badge?, children?, hasChildren?, disabled?, readOnly?, data? }. hasChildren without children: loaded on first opening.
expanded / defaultExpanded / onExpandedChangestring[]—The open nodes.
selected / defaultSelected / onSelectedChangestring[]—The selection. ⌘ click toggles, ⇧ click and ⇧ arrows extend, Space toggles.
selectionMode"single" | "multiple" | "none""single"none: focus only.
onActivate(id) => void—Enter or a double click.
onLoadChildren(id) => void | Promise—First opening of a node with hasChildren and no children; a promise shows the wait.
renderItem(node, state) => ReactNode—What a row shows in place of its label: state is { level, expanded, selected, focused, query }. The icon, count and rename stay.
onMove(move) => void—{ ids, parentId, index, items }: a drag or Alt + arrows moved nodes. It turns both on; keep items from the move. The drop line shows before, inside (dashed) or after; a closed node opens after 700 ms under the pointer.
canDrop(ids, targetId, zone) => boolean—Refuses a drop. A node is never dropped into itself.
onRename / renaming / onRenamingChange(id, label) => void; string | null—F2 edits the label in place: Enter commits, Escape cancels. Set renaming from a menu action.
menu / onAction(ids) => ActionMenuEntry[]; (actionId, ids) => void—The actions of the selection behind a right click. Give useActions(…).menu.
filterstring—Keeps the nodes whose label holds the text, marks it and opens the way to them.
emptyReactNode—Shown when nothing is left.
labelstring"Tree"Names the tree.
classNamestring—Extra classes.