# Skill Tree

A talent tree: skills on a grid, lines for prerequisites, points to spend. Nodes show their state at a glance (locked with a padlock, available with a soft glow, learned in the branch colour, maxed with a gold ring), multi-rank nodes show "2/3", and picking a node opens its details in a side panel (a bottom sheet on phones). Your game owns the ranks and the point balance; the tree tells you what changed. Big trees scale to the box and can be dragged and zoomed.

Docs: https://cozy-ui.solo.engineer/docs/components/skill-tree/

Install: `npx shadcn@latest add @cozy/skill-tree`

### Usage

```tsx
import { SkillTree, canLearn, canRefund, spentPoints, type SkillNode } from "@/components/ui/skill-tree"

const nodes: SkillNode[] = [
  { id: "till", name: "Tilling", x: 1, y: 0, maxRank: 3, branch: "fields", rankText: (r) => `+${r * 10}% speed` },
  { id: "irrigation", name: "Irrigation", x: 0, y: 1, requires: ["till"], kind: "notable", branch: "fields" },
]

const [ranks, setRanks] = useState({})
const points = totalPoints - spentPoints(ranks, nodes)

<SkillTree
  nodes={nodes}
  branches={{ fields: { label: "Fields", color: "#8DB84A" } }}
  ranks={ranks}
  onRanksChange={(next, change) => setRanks(next)}
  points={points}
  allowRefund
  onReset={() => setRanks({})}
/>
```

### Props

| Prop | Type | Default | Description |
|---|---|---|---|
| nodes | `SkillNode<T>[]` | – | { id, name, label?, icon?, description?, x, y, requires?, requiresAny?, maxRank?, cost?, kind?, branch?, rankText?, requiresLevel?, data? }. x and y are grid cells (column, row); the tree is cropped to the cells in use. |
| requires / requiresAny | `string[]` | – | Node ids. `requires`: all must be learned (rank 1 or more). `requiresAny`: at least one. Both can be used on one node. |
| maxRank / cost | `number / number \| number[]` | `1 / 1` | Ranks, and points per rank: one number, or one entry per rank (the last repeats), e.g. [1, 1, 2]. |
| kind | `"small" \| "notable" \| "keystone"` | `"small"` | Circle, rounded square, big diamond. |
| rankText | `(rank) => ReactNode` | – | Effect at a rank. The details show it for the current and the next rank. |
| branches / legend | `Record<string, { label, color?, icon? }> / boolean` | `- / true` | Colours by `node.branch` (default: a palette colour per branch). The legend shows when branches are given. |
| ranks / defaultRanks / onRanksChange | `Record<string, number>` | `{}` | Ranks per node id. `onRanksChange(next, { id, from, to, node })` fires after each learn or refund; in controlled mode apply `next`. |
| points | `number` | `unlimited` | Points the player can spend. Learning is disabled when the next rank costs more. The tree does not subtract: use `total - spentPoints(ranks, nodes)`. A number shows the counter. |
| level | `number` | – | Player level for `requiresLevel` (no level means no check). |
| allowRefund | `boolean` | `false` | Adds a Refund button to the details. Blocked while a learned node depends on the node. |
| onReset | `() => void \| boolean` | – | Shows a Reset all button (disabled with nothing learned); the game decides the cost. Uncontrolled ranks are cleared too, unless you return false. |
| selected / defaultSelected / onSelect | `string \| null / (node \| null) => void` | `none` | Selected node id and callback with the node (null when closed). |
| cellSize / height | `number / number \| string` | `88 / 480` | Pixels between cells at zoom 1, and the box height. The tree scales down to the box width, but not below 80%. |
| pannable | `boolean` | `true` | Drag to pan and zoom (buttons, Ctrl or ⌘ + wheel) when the tree is bigger than the box. False scales the whole tree to fit. |
| renderNode / renderDetails | `(node, state) => ReactNode` | – | Replace a node's icon area or the whole details panel. `state` has status, rank, maxRank, cost, learnable, refundable, learn() and refund(). |
| labels | `Partial<SkillTreeLabels>` | `English` | Every built-in text, including the aria-live announcements and "{name}", "{rank}", "{max}" placeholders. |
| canLearn(node, ranks, nodes, { points, level }) | `{ ok, reason? }` | – | Pure helper. reason is "maxed", "requires", "level" or "points" (checked in that order). |
| canRefund(node, ranks, nodes) / spentPoints(ranks, nodes) | `boolean / number` | – | Pure helpers. canRefund is false when it is the last rank and a learned node needs it. |

State: each node is locked (prerequisites or level missing), available (rank 0 and unlocked), learned (some ranks) or maxed. It is exposed as `data-state`; `data-learnable` marks nodes that can be learned right now (they pulse, except under reduced motion).

Keyboard: arrow keys move to the nearest node in that direction, Space selects, Enter selects and learns, Escape closes the details. Learning, refunding and why a learn was blocked are announced through an aria-live region.

Pan and zoom never take over the page: a plain wheel scrolls the page, Ctrl or ⌘ + wheel zooms. On touch, drags pan only along the axes where the tree overflows, so the page can still scroll.

### Example

```tsx
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { SkillTree, spentPoints } from "@/components/ui/skill-tree";
import { FARMER_BRANCHES, FARMER_NODES, TOTAL_POINTS_START } from "./skill-tree-data";

export default function SkillTreeDemo() {
  const [ranks, setRanks] = useState<Record<string, number>>({ till: 1 });
  const [total, setTotal] = useState(TOTAL_POINTS_START);
  const [level, setLevel] = useState(2);
  const points = total - spentPoints(ranks, FARMER_NODES);

  return (
    <div className="grid w-full gap-3">
      <div className="flex flex-wrap items-center gap-2">
        <Button variant="reward" size="sm" onClick={() => setTotal((t) => t + 1)}>+1 point</Button>
        <Button variant="secondary" size="sm" onClick={() => setLevel((l) => l + 1)}>Level up</Button>
        <span className="text-sm" style={{ color: "var(--cz-text-muted)" }}>Farmer level {level}</span>
      </div>
      <SkillTree
        nodes={FARMER_NODES}
        branches={FARMER_BRANCHES}
        ranks={ranks}
        onRanksChange={(next, change) => {
          setRanks(next);
          if (change.to === change.from + 1 && change.node.kind === "keystone") toast("Cloud Festival unlocked!");
        }}
        points={points}
        level={level}
        allowRefund
        onReset={() => setRanks({})}
      />
    </div>
  );
}
```

### Source (components/ui/skill-tree.tsx)

```tsx
import * as React from "react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { GameIcon } from "@/components/ui/game-core";

/* Skill tree: a talent tree on a grid. Nodes are learned with points the game hands out,
   lines show prerequisites. Data in, events out: the game owns ranks and points, or lets the
   tree keep the ranks itself. Wide boxes get a side panel for details, narrow ones a bottom sheet. */

export type SkillNodeKind = "small" | "notable" | "keystone";

export type SkillBranch = {
  /** Plain-text name, shown in the legend and the details. */
  label: string;
  /** Any CSS colour for the nodes and lines of this branch. Default: a palette colour per branch, in order. */
  color?: string;
  /** Small icon for the legend. */
  icon?: React.ReactNode;
};

export type SkillNode<T = unknown> = {
  /** Stable id. Other nodes name it in `requires`. */
  id: string;
  /** Display name. */
  name: React.ReactNode;
  /** Plain-text name for aria and announcements. Falls back to `name` when it is a string, else the id. */
  label?: string;
  /** A React node (SVG, sprite) or an image URL. Default: a star. */
  icon?: React.ReactNode;
  /** Longer text in the details. */
  description?: React.ReactNode;
  /** Grid column. Whole numbers; the tree is cropped to the cells in use. */
  x: number;
  /** Grid row, 0 at the top. */
  y: number;
  /** Ids that must ALL be learned (rank 1 or more) first. */
  requires?: string[];
  /** Ids of which AT LEAST ONE must be learned first. */
  requiresAny?: string[];
  /** Number of ranks. Default 1. */
  maxRank?: number;
  /** Points per rank: one number for every rank, or one entry per rank (the last repeats). Default 1. */
  cost?: number | number[];
  /** Size and shape: small circle, notable rounded square, keystone diamond. Default "small". */
  kind?: SkillNodeKind;
  /** Key into `branches`, for the colour. */
  branch?: string;
  /** Effect at a rank, e.g. `(rank) => \`+${rank * 10}% yield\``. Shown as "Now" and "Next rank". */
  rankText?: (rank: number) => React.ReactNode;
  /** Player level needed to learn the first rank (checked against the `level` prop). */
  requiresLevel?: number;
  /** Your own object; comes back in callbacks. */
  data?: T;
};

export type SkillNodeStatus = "locked" | "available" | "learned" | "maxed";
export type SkillBlockReason = "maxed" | "points" | "requires" | "level";
export type CanLearnResult = {
  /** True when the next rank can be learned now. */
  ok: boolean;
  /** Why not. Checked in this order: maxed, requires, level, points. */
  reason?: SkillBlockReason;
};

export type SkillTreeChange<T = unknown> = {
  /** Id of the node whose rank changed. */
  id: string;
  /** Rank before. */
  from: number;
  /** Rank after: one more than `from` when learning, one less when refunding. */
  to: number;
  /** The node itself. */
  node: SkillNode<T>;
};

/** What the tree knows about one node; passed to `renderNode` and `renderDetails`. */
export type SkillNodeState = {
  /** locked: prerequisites or level missing. available: rank 0 and unlocked. learned: some ranks. maxed: all ranks. */
  status: SkillNodeStatus;
  /** Current rank. */
  rank: number;
  /** Highest rank. */
  maxRank: number;
  /** This node is the selected one. */
  selected: boolean;
  /** Points the next rank costs; undefined when maxed. */
  cost?: number;
  /** Result of `canLearn` for the next rank. */
  learnable: CanLearnResult;
  /** `allowRefund` is on and `canRefund` says yes. */
  refundable: boolean;
  /** The branch of the node, if any. */
  branch?: SkillBranch;
  /** Learn the next rank (announces why when `learnable.ok` is false). */
  learn: () => void;
  /** Give one rank back (does nothing when `refundable` is false). */
  refund: () => void;
};

/** Texts of the tree. `{name}`, `{rank}`, `{max}` and `{n}` are filled in. */
export type SkillTreeLabels = Partial<{
  /** Header counter. Default "Points". */
  points: string;
  /** Default "point". */
  pointOne: string;
  /** Default "points". */
  pointMany: string;
  /** Default "Learn". */
  learn: string;
  /** Learn button for a node that already has a rank. Default "Rank up". */
  rankUp: string;
  /** Default "Maxed". */
  maxed: string;
  /** Default "Refund". */
  refund: string;
  /** Default "Reset all". */
  resetAll: string;
  /** Default "Locked". */
  statusLocked: string;
  /** Default "Available". */
  statusAvailable: string;
  /** Default "Learned". */
  statusLearned: string;
  /** Default "Maxed". */
  statusMaxed: string;
  /** Details heading for the current rank's effect. Default "Now". */
  now: string;
  /** Default "Next rank". */
  nextRank: string;
  /** Default "Cost". */
  cost: string;
  /** Default "Requires". */
  requires: string;
  /** Default "One of". */
  requiresAny: string;
  /** Default "Level {n}". */
  level: string;
  /** Spoken after a met requirement. Default "done". */
  reqMet: string;
  /** Spoken after a missing requirement. Default "missing". */
  reqMissing: string;
  /** Default "Notable". */
  kindNotable: string;
  /** Default "Keystone". */
  kindKeystone: string;
  /** Default "Already at the highest rank." */
  reasonMaxed: string;
  /** Default "Not enough points." */
  reasonPoints: string;
  /** Default "Learn the requirements first." */
  reasonRequires: string;
  /** Default "Needs level {n}." */
  reasonLevel: string;
  /** aria-live text. Default "Learned {name}, rank {rank} of {max}". */
  announceLearned: string;
  /** aria-live text. Default "Refunded {name}, rank {rank} of {max}". */
  announceRefunded: string;
  /** Empty side panel text. Default "Select a skill to see what it does." */
  selectHint: string;
  /** Default "Close". */
  close: string;
  /** Default "Zoom in". */
  zoomIn: string;
  /** Default "Zoom out". */
  zoomOut: string;
  /** Default "Fit to view". */
  fit: string;
  /** Default "Branches". */
  legend: string;
  /** Accessible name of the side panel. Default "Skill details". */
  details: string;
  /** Shown when `nodes` is empty. Default "No skills yet." */
  empty: string;
}>;

const DEFAULT_LABELS: Required<SkillTreeLabels> = {
  points: "Points", pointOne: "point", pointMany: "points",
  learn: "Learn", rankUp: "Rank up", maxed: "Maxed", refund: "Refund", resetAll: "Reset all",
  statusLocked: "Locked", statusAvailable: "Available", statusLearned: "Learned", statusMaxed: "Maxed",
  now: "Now", nextRank: "Next rank", cost: "Cost", requires: "Requires", requiresAny: "One of", level: "Level {n}",
  reqMet: "done", reqMissing: "missing", kindNotable: "Notable", kindKeystone: "Keystone",
  reasonMaxed: "Already at the highest rank.", reasonPoints: "Not enough points.", reasonRequires: "Learn the requirements first.", reasonLevel: "Needs level {n}.",
  announceLearned: "Learned {name}, rank {rank} of {max}", announceRefunded: "Refunded {name}, rank {rank} of {max}",
  selectHint: "Select a skill to see what it does.", close: "Close", zoomIn: "Zoom in", zoomOut: "Zoom out", fit: "Fit to view",
  legend: "Branches", details: "Skill details", empty: "No skills yet.",
};

/* ---------- pure helpers ---------- */

/** Highest rank of a node (default 1). */
export function maxRankOf(node: Pick<SkillNode, "maxRank">): number {
  return Math.max(1, Math.floor(node.maxRank ?? 1));
}

/** Points the next rank costs when the node is at rank `from` (`from` 0 gives the cost of rank 1). */
export function rankCost(node: Pick<SkillNode, "cost">, from: number): number {
  const c = node.cost;
  if (c == null) return 1;
  if (Array.isArray(c)) return c.length ? c[Math.min(from, c.length - 1)] : 1;
  return c;
}

/** Whether the prerequisites (`requires` and `requiresAny`) of a node are met. */
export function prerequisitesMet(node: SkillNode<any>, ranks: Record<string, number>): boolean {
  const all = (node.requires ?? []).every((id) => (ranks[id] ?? 0) >= 1);
  const any = !node.requiresAny?.length || node.requiresAny.some((id) => (ranks[id] ?? 0) >= 1);
  return all && any;
}

/** Can the next rank of `node` be learned? `points` undefined means unlimited; `level` undefined skips the level check. */
export function canLearn(
  node: SkillNode<any>,
  ranks: Record<string, number>,
  _nodes: SkillNode<any>[],
  opts: { points?: number; level?: number } = {},
): CanLearnResult {
  const rank = ranks[node.id] ?? 0;
  if (rank >= maxRankOf(node)) return { ok: false, reason: "maxed" };
  if (!prerequisitesMet(node, ranks)) return { ok: false, reason: "requires" };
  if (node.requiresLevel != null && opts.level != null && opts.level < node.requiresLevel) return { ok: false, reason: "level" };
  if (opts.points != null && opts.points < rankCost(node, rank)) return { ok: false, reason: "points" };
  return { ok: true };
}

/** Can one rank of `node` be given back? False when it is the last rank and another learned node depends on it. */
export function canRefund(node: SkillNode<any>, ranks: Record<string, number>, nodes: SkillNode<any>[]): boolean {
  const rank = ranks[node.id] ?? 0;
  if (rank <= 0) return false;
  if (rank > 1) return true;
  return !nodes.some((d) => {
    if (d.id === node.id || (ranks[d.id] ?? 0) < 1) return false;
    if (d.requires?.includes(node.id)) return true;
    if (d.requiresAny?.includes(node.id)) return !d.requiresAny.some((id) => id !== node.id && (ranks[id] ?? 0) >= 1);
    return false;
  });
}

/** Total points spent on the learned ranks. */
export function spentPoints(ranks: Record<string, number>, nodes: SkillNode<any>[]): number {
  let sum = 0;
  for (const n of nodes) {
    const r = Math.min(ranks[n.id] ?? 0, maxRankOf(n));
    for (let i = 0; i < r; i++) sum += rankCost(n, i);
  }
  return sum;
}

/* ---------- internals ---------- */

const useIsoLayoutEffect = typeof window !== "undefined" ? React.useLayoutEffect : React.useEffect;
const BRANCH_COLORS = ["var(--cz-primary)", "var(--cz-success)", "var(--cz-info)", "var(--cz-secondary)"];
const WIDE_AT = 720;
const MIN_FIT = 0.8;
const MIN_ZOOM = 0.6;
const MAX_ZOOM = 2.5;
const EDGE_PAD = 24;
const DRAG_START = 6;

const nodeText = (n: SkillNode<any>) => n.label ?? (typeof n.name === "string" ? n.name : n.id);
const fmt = (s: string, v: Record<string, string | number>) => s.replace(/\{(\w+)\}/g, (_, k) => String(v[k] ?? ""));
const sizeFactor = (k?: SkillNodeKind) => (k === "keystone" ? 0.86 : k === "notable" ? 0.68 : 0.58);
const clamp = (v: number, a: number, b: number) => Math.min(b, Math.max(a, v));
const clampAxis = (p: number, content: number, view: number) => (content <= view ? (view - content) / 2 : clamp(p, view - content - EDGE_PAD, EDGE_PAD));

function Glyph({ d, size = 18 }: { d: string; size?: number }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor" strokeWidth={3} strokeLinecap="round" strokeLinejoin="round" aria-hidden>
      <path d={d} />
    </svg>
  );
}
const LockIcon = () => (
  <svg viewBox="0 0 24 24" width="12" height="12" aria-hidden fill="currentColor"><path d="M7 10V8a5 5 0 0 1 10 0v2h1a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1v-9a1 1 0 0 1 1-1h1Zm2.5 0h5V8a2.5 2.5 0 0 0-5 0v2Z" /></svg>
);
const StarIcon = () => (
  <svg viewBox="0 0 24 24" aria-hidden fill="currentColor" stroke="currentColor" strokeWidth={1.5} strokeLinejoin="round"><path d="m12 3 2.6 5.6 6.1.7-4.5 4.2 1.2 6L12 16.5 6.6 19.5l1.2-6L3.3 9.3l6.1-.7L12 3Z" /></svg>
);

function useControlled<V>(value: V | undefined, defaultValue: V): [V, (v: V) => void, boolean] {
  const [inner, setInner] = React.useState(defaultValue);
  const controlled = value !== undefined;
  return [controlled ? (value as V) : inner, setInner, controlled];
}

export type SkillTreeProps<T = unknown> = Omit<React.ComponentProps<"div">, "onSelect" | "children" | "defaultValue"> & {
  /** The skills. Positions are grid cells; the tree is sized to the cells in use. */
  nodes: SkillNode<T>[];
  /** Branch names and colours, keyed by `node.branch`. Also fills the legend. */
  branches?: Record<string, SkillBranch>;
  /** Show the branch legend above the tree. Default true when `branches` is given. */
  legend?: boolean;
  /** Ranks per node id (controlled). Missing ids are rank 0. */
  ranks?: Record<string, number>;
  /** Initial ranks when uncontrolled. Default none. */
  defaultRanks?: Record<string, number>;
  /** Called after a rank went up or down, with the whole next map. In controlled mode apply it to `ranks`. */
  onRanksChange?: (next: Record<string, number>, change: SkillTreeChange<T>) => void;
  /** Points available to spend. The tree never lets learning go below 0 but does not subtract them: derive it as `total - spentPoints(ranks, nodes)`. Default undefined: unlimited, and no counter is shown. */
  points?: number;
  /** Player level for `requiresLevel`. Default undefined: the level check is skipped. */
  level?: number;
  /** Show a Refund button in the details (blocked while another learned node needs the node). Default false. */
  allowRefund?: boolean;
  /** Shows a "Reset all" button (disabled with nothing learned). The game decides what it costs. In uncontrolled mode the ranks are cleared too, unless this returns false. */
  onReset?: () => void | boolean;
  /** Selected node id (controlled); null for none. */
  selected?: string | null;
  /** Initially selected id when uncontrolled. Default none. */
  defaultSelected?: string | null;
  /** Called when the selection changes; null when the details close. */
  onSelect?: (node: SkillNode<T> | null) => void;
  /** Pixels between grid cells at zoom 1. Default 88. */
  cellSize?: number;
  /** Height of the box, a number of px or any CSS length. Default 480. */
  height?: number | string;
  /** Drag to pan and zoom (buttons, Ctrl/⌘ + wheel) when the tree is larger than the box. When false the tree is scaled down to fit entirely. Default true. */
  pannable?: boolean;
  /** Replace the inside of a node (the icon area). The badges, padlock and ring stay. */
  renderNode?: (node: SkillNode<T>, state: SkillNodeState) => React.ReactNode;
  /** Replace the whole content of the details panel. */
  renderDetails?: (node: SkillNode<T>, state: SkillNodeState) => React.ReactNode;
  /** Replace built-in texts, for localisation. */
  labels?: SkillTreeLabels;
  /** Accessible name of the tree. Default "Skill tree". */
  label?: string;
};

/** A talent tree: nodes on a grid with prerequisite lines, points to spend, details panel, pan and zoom. */
function SkillTree<T = unknown>({
  nodes, branches, legend, ranks: ranksProp, defaultRanks, onRanksChange, points, level, allowRefund = false, onReset,
  selected: selectedProp, defaultSelected = null, onSelect, cellSize = 88, height = 480, pannable = true,
  renderNode, renderDetails, labels: labelsProp, label = "Skill tree", className, style, onKeyDown, ...props
}: SkillTreeProps<T>) {
  const L = { ...DEFAULT_LABELS, ...labelsProp };
  const uid = React.useId();
  const titleId = `${uid}-title`;
  const [ranks, setRanksInner, ranksControlled] = useControlled<Record<string, number>>(ranksProp, defaultRanks ?? {});
  const [selId, setSelInner, selControlled] = useControlled<string | null>(selectedProp, defaultSelected);
  const [live, setLive] = React.useState("");
  const [focusId, setFocusId] = React.useState<string | null>(null);
  const [wide, setWide] = React.useState(false);
  const [box, setBox] = React.useState({ w: 0, h: 0 });
  const [zoom, setZoom] = React.useState(1);
  const [pan, setPan] = React.useState({ x: 0, y: 0 });
  const [dragging, setDragging] = React.useState(false);
  const [sheetDy, setSheetDy] = React.useState(0);

  const rootRef = React.useRef<HTMLDivElement>(null);
  const stageRef = React.useRef<HTMLDivElement>(null);
  const sheetRef = React.useRef<HTMLDivElement>(null);
  const nodeRefs = React.useRef(new Map<string, HTMLButtonElement>());
  const drag = React.useRef<{ id: number; sx: number; sy: number; px: number; py: number; active: boolean } | null>(null);
  const sheetDrag = React.useRef<{ y: number; dy: number } | null>(null);
  const swallowClick = React.useRef(false);
  const liveFlip = React.useRef(false);

  const byId = React.useMemo(() => new Map(nodes.map((n) => [n.id, n])), [nodes]);
  const branchKeys = React.useMemo(() => Object.keys(branches ?? {}), [branches]);
  const colorOf = (n: SkillNode<any>) => {
    if (!n.branch) return BRANCH_COLORS[0];
    const i = branchKeys.indexOf(n.branch);
    return branches?.[n.branch]?.color ?? BRANCH_COLORS[(i < 0 ? 0 : i) % BRANCH_COLORS.length];
  };

  // grid bounds -> world size in px
  const cell = Math.max(40, cellSize);
  const bounds = React.useMemo(() => {
    if (!nodes.length) return { minX: 0, minY: 0, cols: 1, rows: 1 };
    const xs = nodes.map((n) => n.x), ys = nodes.map((n) => n.y);
    const minX = Math.min(...xs), minY = Math.min(...ys);
    return { minX, minY, cols: Math.max(...xs) - minX + 1, rows: Math.max(...ys) - minY + 1 };
  }, [nodes]);
  const W = bounds.cols * cell, H = bounds.rows * cell;
  const centre = (n: SkillNode<any>) => ({ x: (n.x - bounds.minX + 0.5) * cell, y: (n.y - bounds.minY + 0.5) * cell });

  // measure the box and the root
  useIsoLayoutEffect(() => {
    const st = stageRef.current, root = rootRef.current;
    if (!st || !root) return;
    const measure = () => { setBox({ w: st.clientWidth, h: st.clientHeight }); setWide(root.clientWidth >= WIDE_AT); };
    measure();
    if (typeof ResizeObserver === "undefined") return;
    const ro = new ResizeObserver(measure);
    ro.observe(st); ro.observe(root);
    return () => ro.disconnect();
  }, []);

  // scale and position (always clamped, so a resize can never leave the tree out of reach)
  const base = box.w <= 0 ? 1 : pannable ? clamp(box.w / W, MIN_FIT, 1) : Math.min(1, box.w / W, box.h > 0 ? box.h / H : 1);
  const z = pannable ? zoom : 1;
  const s = base * z;
  const pos = { x: clampAxis(pan.x, W * s, box.w), y: clampAxis(pan.y, H * s, box.h) };
  const canX = pannable && W * s > box.w + 0.5, canY = pannable && H * s > box.h + 0.5;
  const canPan = canX || canY;
  const touchAction = canX && canY ? "none" : canX ? "pan-y" : canY ? "pan-x" : "auto";

  const view = React.useRef({ s, pos, z, box });
  view.current = { s, pos, z, box };

  const setZoomAt = (factor: number, cx = view.current.box.w / 2, cy = view.current.box.h / 2) => {
    const v = view.current;
    const nz = clamp(v.z * factor, MIN_ZOOM, MAX_ZOOM);
    if (nz === v.z) return;
    const ns = (v.s / v.z) * nz;
    const wx = (cx - v.pos.x) / v.s, wy = (cy - v.pos.y) / v.s;
    setZoom(nz);
    setPan({ x: cx - wx * ns, y: cy - wy * ns });
  };
  const fit = () => { setZoom(1); setPan({ x: 0, y: 0 }); };

  // Ctrl/⌘ + wheel zooms; a plain wheel is left to the page
  React.useEffect(() => {
    const st = stageRef.current;
    if (!st || !pannable) return;
    const onWheel = (e: WheelEvent) => {
      if (!(e.ctrlKey || e.metaKey)) return;
      e.preventDefault();
      const r = st.getBoundingClientRect();
      const dy = e.deltaMode === 1 ? e.deltaY * 16 : e.deltaY;
      setZoomAt(Math.exp(-dy * 0.002), e.clientX - r.left, e.clientY - r.top);
    };
    st.addEventListener("wheel", onWheel, { passive: false });
    return () => st.removeEventListener("wheel", onWheel);
  }, [pannable]);

  // nodes -> states
  const stateOf = (n: SkillNode<T>): SkillNodeState => {
    const max = maxRankOf(n);
    const rank = Math.min(ranks[n.id] ?? 0, max);
    const learnable = canLearn(n, ranks, nodes, { points, level });
    const open = prerequisitesMet(n, ranks) && !(n.requiresLevel != null && level != null && level < n.requiresLevel);
    const status: SkillNodeStatus = rank >= max ? "maxed" : rank > 0 ? "learned" : open ? "available" : "locked";
    return {
      status, rank, maxRank: max, selected: selId === n.id, cost: rank >= max ? undefined : rankCost(n, rank), learnable,
      refundable: allowRefund && canRefund(n, ranks, nodes), branch: n.branch ? branches?.[n.branch] : undefined,
      learn: () => doLearn(n), refund: () => doRefund(n),
    };
  };

  const announce = (text: string) => { liveFlip.current = !liveFlip.current; setLive(text + (liveFlip.current ? "" : " ")); };
  const setRank = (n: SkillNode<T>, from: number, to: number) => {
    const next = { ...ranks, [n.id]: to };
    if (to <= 0) delete next[n.id];
    if (!ranksControlled) setRanksInner(next);
    onRanksChange?.(next, { id: n.id, from, to, node: n });
  };
  const reasonText = (n: SkillNode<T>, reason?: SkillBlockReason) => {
    switch (reason) {
      case "maxed": return L.reasonMaxed;
      case "points": return L.reasonPoints;
      case "level": return fmt(L.reasonLevel, { n: n.requiresLevel ?? "" });
      case "requires": return L.reasonRequires;
      default: return "";
    }
  };
  function doLearn(n: SkillNode<T>) {
    const res = canLearn(n, ranks, nodes, { points, level });
    if (!res.ok) { announce(`${nodeText(n)}: ${reasonText(n, res.reason)}`); return; }
    const from = Math.min(ranks[n.id] ?? 0, maxRankOf(n));
    setRank(n, from, from + 1);
    announce(fmt(L.announceLearned, { name: nodeText(n), rank: from + 1, max: maxRankOf(n) }));
  }
  function doRefund(n: SkillNode<T>) {
    if (!allowRefund || !canRefund(n, ranks, nodes)) return;
    const from = ranks[n.id] ?? 0;
    setRank(n, from, from - 1);
    announce(fmt(L.announceRefunded, { name: nodeText(n), rank: from - 1, max: maxRankOf(n) }));
  }

  const selNode = selId ? byId.get(selId) ?? null : null;
  const select = (n: SkillNode<T> | null) => {
    if ((n?.id ?? null) === (selNode?.id ?? null)) return;
    if (!selControlled) setSelInner(n?.id ?? null);
    onSelect?.(n);
  };

  // keep a node inside the visible part of the box
  const reveal = (id: string, bottomInset = 0) => {
    const n = byId.get(id);
    const v = view.current;
    if (!n || !canPan || v.box.w <= 0 || v.box.h <= 0) return;
    const c = centre(n);
    const r = (cell * sizeFactor(n.kind) / 2) * v.s + 12;
    const cx = v.pos.x + c.x * v.s, cy = v.pos.y + c.y * v.s;
    let { x, y } = v.pos;
    if (canX) {
      if (cx - r < 0) x -= cx - r;
      else if (cx + r > v.box.w) x -= cx + r - v.box.w;
    }
    if (canY) {
      const bottom = v.box.h - bottomInset;
      if (cy - r < 0) y -= cy - r;
      else if (cy + r + 26 > bottom) y -= cy + r + 26 - bottom;
    }
    if (x !== v.pos.x || y !== v.pos.y) setPan({ x, y });
  };
  useIsoLayoutEffect(() => {
    if (selId) reveal(selId, sheetRef.current?.offsetHeight ?? 0);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selId, wide]);

  // keyboard
  const first = React.useMemo(() => [...nodes].sort((a, b) => a.y - b.y || a.x - b.x)[0], [nodes]);
  const tabId = (focusId && byId.has(focusId) ? focusId : null) ?? selNode?.id ?? first?.id;
  const focusNode = (id: string) => { setFocusId(id); nodeRefs.current.get(id)?.focus(); };
  const onNodeKey = (e: React.KeyboardEvent, n: SkillNode<T>) => {
    if (e.key === "Enter") {
      e.preventDefault();
      select(n);
      doLearn(n);
      return;
    }
    const dir = ({ ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] } as Record<string, number[] | undefined>)[e.key];
    if (!dir) return;
    e.preventDefault();
    let best: SkillNode<T> | null = null, bestScore = Infinity;
    for (const o of nodes) {
      if (o === n) continue;
      const dx = o.x - n.x, dy = o.y - n.y;
      const along = dx * dir[0] + dy * dir[1];
      if (along <= 0) continue;
      const perp = Math.abs(dx * dir[1] + dy * dir[0]);
      const score = along + perp * 2;
      if (score < bestScore) { bestScore = score; best = o; }
    }
    if (best) focusNode(best.id);
  };
  const onRootKey = (e: React.KeyboardEvent<HTMLDivElement>) => {
    onKeyDown?.(e);
    if (e.defaultPrevented) return;
    if (e.key === "Escape" && selNode) {
      e.stopPropagation();
      const id = selNode.id;
      select(null);
      requestAnimationFrame(() => nodeRefs.current.get(id)?.focus());
    }
  };

  // pointer pan (mouse, touch, pen): starts after a few px so clicks on nodes still work
  const onPointerDown = (e: React.PointerEvent) => {
    swallowClick.current = false;
    if (!canPan || drag.current || (e.pointerType === "mouse" && e.button !== 0)) return;
    drag.current = { id: e.pointerId, sx: e.clientX, sy: e.clientY, px: pos.x, py: pos.y, active: false };
  };
  const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
    const d = drag.current;
    if (!d || d.id !== e.pointerId) return;
    const dx = e.clientX - d.sx, dy = e.clientY - d.sy;
    if (!d.active) {
      if (Math.hypot(dx, dy) < DRAG_START) return;
      d.active = true;
      setDragging(true);
      try { e.currentTarget.setPointerCapture(e.pointerId); } catch { /* ignore */ }
    }
    setPan({ x: canX ? d.px + dx : pos.x, y: canY ? d.py + dy : pos.y });
  };
  const endPointer = (e: React.PointerEvent) => {
    const d = drag.current;
    if (!d || d.id !== e.pointerId) return;
    if (d.active) {
      swallowClick.current = true;
      setTimeout(() => { swallowClick.current = false; }, 0);
      setPan(view.current.pos);
    }
    drag.current = null;
    setDragging(false);
  };

  const showLegend = (legend ?? true) && branchKeys.length > 0;
  const spent = spentPoints(ranks, nodes);
  const word = (n: number) => (n === 1 ? L.pointOne : L.pointMany);
  const statusWord = (st: SkillNodeStatus) => ({ locked: L.statusLocked, available: L.statusAvailable, learned: L.statusLearned, maxed: L.statusMaxed })[st];

  // edges: lit ones last, so they sit on top
  const edges = (() => {
    const out: { key: string; x1: number; y1: number; x2: number; y2: number; on: boolean; any: boolean; color: string }[] = [];
    for (const n of nodes) {
      const to = centre(n);
      const add = (pid: string, any: boolean) => {
        const p = byId.get(pid);
        if (!p) return;
        const from = centre(p);
        out.push({ key: `${pid}>${n.id}`, x1: from.x, y1: from.y, x2: to.x, y2: to.y, on: (ranks[pid] ?? 0) >= 1, any, color: colorOf(p.branch ? p : n) });
      };
      n.requires?.forEach((id) => add(id, false));
      n.requiresAny?.forEach((id) => add(id, true));
    }
    return out.sort((a, b) => Number(a.on) - Number(b.on));
  })();

  /* ---------- details ---------- */
  const reqItem = (id: string) => {
    const r = byId.get(id);
    const met = (ranks[id] ?? 0) >= 1;
    return (
      <li key={id} className="cz-skill__req" data-met={met || undefined}>
        <span className="cz-skill__req-mark" aria-hidden>{met ? "✓" : "•"}</span>
        <span>{r ? r.name : id}</span>
        <span className="cz-skill__sr"> ({met ? L.reqMet : L.reqMissing})</span>
      </li>
    );
  };
  const detailsBody = (n: SkillNode<T>) => {
    const st = stateOf(n);
    if (renderDetails) return renderDetails(n, st);
    const color = colorOf(n);
    const maxed = st.status === "maxed";
    const levelMet = n.requiresLevel == null || level == null || level >= n.requiresLevel;
    const hint = !st.learnable.ok && !maxed ? reasonText(n, st.learnable.reason) : "";
    const metaBits = [n.kind === "keystone" ? L.kindKeystone : n.kind === "notable" ? L.kindNotable : null, n.branch ? branches?.[n.branch]?.label : null].filter(Boolean);
    const nowText = st.rank > 0 ? n.rankText?.(st.rank) : null;
    const nextText = !maxed ? n.rankText?.(st.rank + 1) : null;
    return (
      <>
        <div className="cz-skill__head">
          <span className="cz-skill__tile" style={{ "--sk": color } as React.CSSProperties}>{n.icon != null ? <GameIcon icon={n.icon} alt="" /> : <StarIcon />}</span>
          <div className="cz-skill__title">
            <h3 id={titleId}>{n.name}</h3>
            <small>{[...metaBits, statusWord(st.status)].join(" · ")}</small>
          </div>
        </div>
        {st.maxRank > 1 && (
          <div className="cz-skill__rank" style={{ "--sk": color } as React.CSSProperties}>
            <span className="cz-skill__pips" aria-hidden>{Array.from({ length: st.maxRank }, (_, i) => <i key={i} data-on={i < st.rank || undefined} />)}</span>
            <span>{st.rank} / {st.maxRank}</span>
          </div>
        )}
        <div className="cz-skill__actions">
          <Button variant={maxed ? "secondary" : "success"} size="sm" disabled={!st.learnable.ok} onClick={() => doLearn(n)}>
            {maxed ? L.maxed : st.rank > 0 ? L.rankUp : L.learn}
            {!maxed && st.cost != null && <span className="cz-skill__btn-cost">{st.cost}</span>}
          </Button>
          {allowRefund && (
            <Button variant="outline" size="sm" disabled={!st.refundable} onClick={() => doRefund(n)}>{L.refund}</Button>
          )}
        </div>
        {hint && <p className="cz-skill__hint">{hint}</p>}
        {n.description != null && <div className="cz-skill__desc">{n.description}</div>}
        {(nowText != null || nextText != null) && (
          <dl className="cz-skill__effects">
            {nowText != null && <div><dt>{L.now}</dt><dd>{nowText}</dd></div>}
            {nextText != null && <div data-next><dt>{L.nextRank}</dt><dd>{nextText}</dd></div>}
          </dl>
        )}
        {st.cost != null && (
          <div className="cz-skill__row"><span>{L.cost}</span><strong>{st.cost} {word(st.cost)}</strong></div>
        )}
        {(n.requires?.length || n.requiresAny?.length || n.requiresLevel != null) && (
          <div className="cz-skill__reqs">
            <span className="cz-skill__reqs-title">{L.requires}</span>
            <ul>
              {n.requiresLevel != null && (
                <li className="cz-skill__req" data-met={levelMet || undefined}>
                  <span className="cz-skill__req-mark" aria-hidden>{levelMet ? "✓" : "•"}</span>
                  <span>{fmt(L.level, { n: n.requiresLevel })}</span>
                  <span className="cz-skill__sr"> ({levelMet ? L.reqMet : L.reqMissing})</span>
                </li>
              )}
              {n.requires?.map(reqItem)}
            </ul>
            {!!n.requiresAny?.length && (
              <>
                <span className="cz-skill__reqs-title">{L.requiresAny}</span>
                <ul>{n.requiresAny.map(reqItem)}</ul>
              </>
            )}
          </div>
        )}
      </>
    );
  };

  const empty = !nodes.length;
  // narrow boxes: a bottom sheet over the tree when it can be panned out of the way, else the details sit below the box
  const sheetOpen = !wide && !!selNode && canPan;
  const stacked = !wide && !!selNode && !canPan;

  return (
    <div
      ref={rootRef}
      data-slot="skill-tree"
      data-layout={wide ? "wide" : "narrow"}
      role="group"
      aria-label={label}
      className={cn("cz-skill", className)}
      style={{ "--sk-h": typeof height === "number" ? `${height}px` : height, ...style } as React.CSSProperties}
      onKeyDown={onRootKey}
      {...props}
    >
      {(points != null || showLegend || onReset) && (
        <div className="cz-skill__bar">
          {points != null && (
            <div className="cz-skill__points" data-empty={points <= 0 || undefined}>
              <span>{L.points}</span>
              <strong>{points}</strong>
            </div>
          )}
          {showLegend && (
            <ul className="cz-skill__legend" aria-label={L.legend}>
              {branchKeys.map((k, i) => {
                const b = branches![k];
                return (
                  <li key={k} style={{ "--sk": b.color ?? BRANCH_COLORS[i % BRANCH_COLORS.length] } as React.CSSProperties}>
                    <span className="cz-skill__dot" aria-hidden>{b.icon}</span>
                    {b.label}
                  </li>
                );
              })}
            </ul>
          )}
          {onReset && (
            <Button
              variant="outline"
              size="sm"
              className="cz-skill__reset"
              disabled={spent <= 0}
              onClick={() => {
                if (onReset() === false) return;
                if (!ranksControlled) setRanksInner({});
              }}
            >
              {L.resetAll}
            </Button>
          )}
        </div>
      )}
      <div className="cz-skill__body">
        <div ref={stageRef} className="cz-skill__stage">
          <div
            className="cz-skill__viewport"
            data-pannable={canPan || undefined}
            data-dragging={dragging || undefined}
            style={{ touchAction }}
            onPointerDown={onPointerDown}
            onPointerMove={onPointerMove}
            onPointerUp={endPointer}
            onPointerCancel={endPointer}
            onClickCapture={(e) => { if (swallowClick.current) { e.stopPropagation(); e.preventDefault(); swallowClick.current = false; } }}
            onClick={(e) => { const t = e.target as HTMLElement; if (t === e.currentTarget || t.classList.contains("cz-skill__world") || t.closest(".cz-skill__edges")) select(null); }}
          >
            {empty ? (
              <p className="cz-skill__empty">{L.empty}</p>
            ) : (
              <div
                className="cz-skill__world"
                style={{ width: W, height: H, transform: `translate(${pos.x}px, ${pos.y}px) scale(${s})`, "--s": s, "--cell": `${cell}px` } as React.CSSProperties}
              >
                <svg className="cz-skill__edges" width={W} height={H} viewBox={`0 0 ${W} ${H}`} aria-hidden>
                  <g className="cz-skill__edge-walls">
                    {edges.map((e) => <line key={e.key} x1={e.x1} y1={e.y1} x2={e.x2} y2={e.y2} />)}
                  </g>
                  <g>
                    {edges.map((e) => (
                      <line key={e.key} className="cz-skill__edge" data-on={e.on || undefined} data-any={e.any || undefined} style={{ "--sk": e.color } as React.CSSProperties} x1={e.x1} y1={e.y1} x2={e.x2} y2={e.y2} />
                    ))}
                  </g>
                </svg>
                {nodes.map((n) => {
                  const st = stateOf(n);
                  const c = centre(n);
                  const px = Math.round(cell * sizeFactor(n.kind));
                  const nm = nodeText(n);
                  return (
                    <button
                      key={n.id}
                      ref={(el) => { if (el) nodeRefs.current.set(n.id, el); else nodeRefs.current.delete(n.id); }}
                      type="button"
                      data-slot="skill-node"
                      data-id={n.id}
                      data-state={st.status}
                      data-kind={n.kind ?? "small"}
                      data-selected={st.selected || undefined}
                      data-learnable={st.learnable.ok || undefined}
                      data-rank={st.rank}
                      data-branch={n.branch}
                      aria-label={`${nm}, rank ${st.rank} of ${st.maxRank}, ${statusWord(st.status).toLowerCase()}`}
                      aria-pressed={st.selected}
                      tabIndex={n.id === tabId ? 0 : -1}
                      className="cz-skill__node"
                      style={{ left: c.x, top: c.y, "--sz": `${px}px`, "--sk": colorOf(n) } as React.CSSProperties}
                      onClick={() => select(n)}
                      onDoubleClick={() => { select(n); doLearn(n); }}
                      onKeyDown={(e) => onNodeKey(e, n)}
                      onFocus={() => { setFocusId(n.id); reveal(n.id, sheetOpen ? sheetRef.current?.offsetHeight ?? 0 : 0); }}
                    >
                      <span className="cz-skill__face">
                        <span className="cz-skill__icon">
                          {renderNode ? renderNode(n, st) : n.icon != null ? <GameIcon icon={n.icon} alt="" /> : <StarIcon />}
                        </span>
                      </span>
                      {st.maxRank > 1 && st.status !== "locked" && <span className="cz-skill__badge" aria-hidden>{st.rank}/{st.maxRank}</span>}
                      {st.status === "locked" && <span className="cz-skill__lock" aria-hidden><LockIcon /></span>}
                      <span className="cz-skill__name" aria-hidden>{n.name}</span>
                    </button>
                  );
                })}
              </div>
            )}
          </div>
          {pannable && !empty && (
            <div className="cz-skill__zoom" role="group" aria-label="Zoom">
              <button type="button" aria-label={L.zoomIn} disabled={z >= MAX_ZOOM} onClick={() => setZoomAt(1.25)}><Glyph d="M12 5v14M5 12h14" /></button>
              <button type="button" aria-label={L.zoomOut} disabled={z <= MIN_ZOOM} onClick={() => setZoomAt(0.8)}><Glyph d="M5 12h14" /></button>
              <button type="button" aria-label={L.fit} disabled={zoom === 1 && pan.x === 0 && pan.y === 0} onClick={fit}><Glyph d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" size={16} /></button>
            </div>
          )}
          {sheetOpen && selNode && (
            <div
              ref={sheetRef}
              className="cz-skill__panel cz-skill__sheet"
              role="region"
              aria-labelledby={titleId}
              data-slot="skill-details"
              style={sheetDy ? { translate: `0 ${sheetDy}px`, transition: "none" } : undefined}
            >
              <div
                className="cz-skill__handle"
                aria-hidden
                onPointerDown={(e) => { sheetDrag.current = { y: e.clientY, dy: 0 }; (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); }}
                onPointerMove={(e) => { if (sheetDrag.current) { sheetDrag.current.dy = Math.max(0, e.clientY - sheetDrag.current.y); setSheetDy(sheetDrag.current.dy); } }}
                onPointerUp={() => { const d = sheetDrag.current?.dy ?? 0; sheetDrag.current = null; setSheetDy(0); if (d > 70) select(null); }}
                onPointerCancel={() => { sheetDrag.current = null; setSheetDy(0); }}
              ><span /></div>
              <button type="button" className="cz-skill__close" aria-label={L.close} onClick={() => select(null)}>×</button>
              {detailsBody(selNode)}
            </div>
          )}
        </div>
        {stacked && selNode && (
          <div className="cz-skill__panel cz-skill__stack" role="region" aria-labelledby={titleId} data-slot="skill-details">
            <button type="button" className="cz-skill__close" aria-label={L.close} onClick={() => select(null)}>×</button>
            {detailsBody(selNode)}
          </div>
        )}
        {wide && (
          <aside className="cz-skill__panel cz-skill__side" data-slot="skill-details" data-empty={!selNode || undefined} role="region" aria-label={selNode ? undefined : L.details} aria-labelledby={selNode ? titleId : undefined}>
            {selNode ? (
              <>
                <button type="button" className="cz-skill__close" aria-label={L.close} onClick={() => select(null)}>×</button>
                {detailsBody(selNode)}
              </>
            ) : (
              <p className="cz-skill__placeholder">{L.selectHint}</p>
            )}
          </aside>
        )}
      </div>
      <div className="cz-skill__sr" role="status" aria-live="polite" aria-atomic="true">{live}</div>
    </div>
  );
}

export { SkillTree };
```

npm: `import { SkillTree } from "@0xtrou/cozy-ui"` (after `npm install @0xtrou/cozy-ui` and `import "@0xtrou/cozy-ui/styles.css"`).
