# Integrate `Treemap` from Motion Garden

You are helping me add the **Treemap** component to an existing project.
Everything you need is below — full source, dependencies, props and the
behavioural contract. Read it all before writing anything.

- **Component:** Treemap
- **Category:** Power-User Systems
- **Summary:** A treemap you can walk into. Every box is a share of the whole, and a box with children is a frame with its children packed inside. Click a frame and it grows to fill the view. The cells that stay on screen slide to their new place, the new ones arrive from where they would have been, and a path at the top takes you back out. Arrow keys move between cells by where they are on screen. With live on, the values wander and the map keeps reflowing.
- **Reference:** https://motion-garden.netlify.app/components/treemap
- **Full catalog (for you, the agent):** https://motion-garden.netlify.app/llms.txt

## Stack this source assumes

- React 19 with the Next.js App Router (never the `pages/` directory)
- TypeScript, strict
- Tailwind CSS v4, CSS-first config (utilities are inline; no `tailwind.config` needed)

If my project differs, adapt the integration — but do not rewrite the animation math to suit a different stack. Ask me first.

## Dependencies

```bash
# Treemap needs no npm packages
```

## Files to create

3 files — all of them are required. Paths are as shipped; the component may live anywhere in my project, but keep every peer file at the exact path shown so the import aliases resolve.

### 1. `components/registry/treemap/treemap.tsx`

```tsx
"use client";

import {
	useEffect,
	useLayoutEffect,
	useMemo,
	useRef,
	useState,
	useSyncExternalStore,
	type KeyboardEvent as ReactKeyboardEvent,
} from "react";
import { useAnimationLoop } from "@/hooks/use-animation-loop";
import {
	layoutTree,
	type LayoutOptions,
	type Rect,
	type TreemapCell,
	type TreemapNode,
} from "./treemap-layout";

export type { TreemapNode } from "./treemap-layout";

export type TreemapColorBy = "branch" | "size" | "depth";

export interface TreemapProps {
	data: TreemapNode;
	gap?: number;
	depth?: number;
	live?: boolean;
	speed?: number;
	labels?: boolean;
	colorBy?: TreemapColorBy;
	duration?: number;
	radius?: number;
	accentColor?: string;
	baseColor?: string;
	formatValue?: (value: number) => string;
	onSelect?: (node: TreemapNode) => void;
	label?: string;
	paused?: boolean;
	reducedMotion?: boolean;
	className?: string;
}

type RGB = [number, number, number];

interface Entry {
	node: TreemapNode;
	parent: string | null;
	order: number;
	base: number;
}

interface Exit {
	cell: TreemapCell;
	to: Rect;
}

const HEADER = 20;
const BEAT = 1.6;
const EASE = "cubic-bezier(0.22, 1, 0.36, 1)";

const compact =
	typeof Intl !== "undefined"
		? new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 })
		: null;
const defaultFormat = (value: number) =>
	compact ? compact.format(value) : String(Math.round(value));

export default function Treemap({
	data,
	gap = 3,
	depth = 2,
	live = true,
	speed = 1,
	labels = true,
	colorBy = "branch",
	duration = 520,
	radius = 4,
	accentColor = "#a855f7",
	baseColor = "#16121f",
	formatValue = defaultFormat,
	onSelect,
	label = "Treemap",
	paused = false,
	reducedMotion = false,
	className = "",
}: TreemapProps) {
	const mapRef = useRef<HTMLDivElement>(null);
	const els = useRef(new Map<string, HTMLDivElement>());
	const enters = useRef<Map<string, Rect> | null>(null);
	const refocus = useRef(false);
	const calm = useRef<number | null>(null);
	const beat = useRef(0);

	const systemStill = useSyncExternalStore(
		subscribeMotion,
		readMotion,
		readMotionOnServer,
	);
	const still = reducedMotion || systemStill;

	const [size, setSize] = useState({ w: 0, h: 0 });
	const [instant, setInstant] = useState(false);
	const [factors, setFactors] = useState<Map<string, number>>(() => new Map());
	const [view, setView] = useState<{ focus: string; key: number; exits: Exit[] }>({
		focus: data.id,
		key: 0,
		exits: [],
	});
	const [active, setActive] = useState<string | null>(null);
	const [hover, setHover] = useState<string | null>(null);
	const [keyboard, setKeyboard] = useState(false);

	const index = useMemo(() => {
		const map = new Map<string, Entry>();
		let order = 0;
		const walk = (node: TreemapNode, parent: string | null): number => {
			const entry: Entry = { node, parent, order: order++, base: 0 };
			map.set(node.id, entry);
			entry.base = node.children?.length
				? node.children.reduce((sum, kid) => sum + walk(kid, node.id), 0)
				: Math.max(0, node.value ?? 0);
			return entry.base;
		};
		walk(data, null);
		return map;
	}, [data]);

	const leaves = useMemo(
		() =>
			[...index.values()]
				.filter((entry) => !entry.node.children?.length)
				.map((entry) => entry.node.id),
		[index],
	);

	const totals = useMemo(() => {
		const map = new Map<string, number>();
		const walk = (node: TreemapNode): number => {
			const value = node.children?.length
				? node.children.reduce((sum, kid) => sum + walk(kid), 0)
				: Math.max(0, node.value ?? 0) * (factors.get(node.id) ?? 1);
			map.set(node.id, value);
			return value;
		};
		walk(data);
		return map;
	}, [data, factors]);

	const levels = clamp(Math.round(depth), 1, 4);
	const space = Math.max(0, gap);
	const options = useMemo<LayoutOptions>(
		() => ({
			depth: levels,
			gap: space,
			header: HEADER,
			valueOf: (node) => totals.get(node.id) ?? 0,
			orderOf: (node) => index.get(node.id)?.base ?? 0,
		}),
		[levels, space, totals, index],
	);

	const focusId = index.has(view.focus) ? view.focus : data.id;
	const focusNode = index.get(focusId)?.node ?? data;

	const cells = useMemo(
		() =>
			size.w > 0 && size.h > 0
				? layoutTree(focusNode, size.w, size.h, options)
				: [],
		[focusNode, size, options],
	);

	useAnimationLoop({
		target: mapRef,
		halted: paused || still || !live,
		dpr: 1,
		onResize: (m) => {
			setSize((s) =>
				s.w === m.width && s.h === m.height ? s : { w: m.width, h: m.height },
			);
			setInstant(true);
			if (calm.current !== null) window.clearTimeout(calm.current);
			calm.current = window.setTimeout(() => {
				calm.current = null;
				setInstant(false);
			}, 140);
		},
		onFrame: ({ dt }) => {
			beat.current += dt * Math.max(0, speed);
			if (beat.current < BEAT) return;
			beat.current = 0;
			setFactors((prev) => wander(prev, leaves));
		},
	});

	useEffect(
		() => () => {
			if (calm.current !== null) window.clearTimeout(calm.current);
		},
		[],
	);

	const ms = still || instant ? 0 : Math.max(0, duration);
	const transition =
		ms > 0
			? `transform ${ms}ms ${EASE}, width ${ms}ms ${EASE}, height ${ms}ms ${EASE}, opacity ${ms}ms ease, background-color 240ms ease, filter 160ms ease`
			: "none";

	const navigable = cells.filter((cell) => !cell.group);
	const activeId = navigable.some((cell) => cell.id === active)
		? active
		: (navigable[0]?.id ?? null);

	const isUnder = (id: string, ancestor: string): boolean => {
		let at: string | null = id;
		while (at) {
			if (at === ancestor) return true;
			at = index.get(at)?.parent ?? null;
		}
		return false;
	};

	const zoomTo = (nextId: string) => {
		const entry = index.get(nextId);
		if (!entry || nextId === focusId || size.w <= 0 || size.h <= 0) return;
		const next = layoutTree(entry.node, size.w, size.h, options);
		const before = new Map(cells.map((cell) => [cell.id, cell]));
		const after = new Map(next.map((cell) => [cell.id, cell]));

		const full: Rect = { x: 0, y: 0, w: size.w, h: size.h };
		let from: Rect = full;
		let to: Rect = full;
		const target = before.get(nextId);
		if (target) {
			from = target;
		} else {
			let at: string | null = focusId;
			while (at) {
				const found = after.get(at);
				if (found) {
					to = found;
					break;
				}
				at = index.get(at)?.parent ?? null;
			}
		}
		const pairFor = (id: string): { old: Rect; next: Rect } => {
			let at = index.get(id)?.parent ?? null;
			while (at) {
				const old = before.get(at);
				const now = after.get(at);
				if (old && now) return { old, next: now };
				at = index.get(at)?.parent ?? null;
			}
			return { old: from, next: to };
		};

		const moving = ms > 0;
		const starts = new Map<string, Rect>();
		if (moving) {
			for (const cell of next) {
				if (before.has(cell.id)) continue;
				const pair = pairFor(cell.id);
				starts.set(cell.id, remap(cell, pair.next, pair.old));
			}
		}
		enters.current = moving ? starts : null;
		const exits: Exit[] = moving
			? cells
					.filter((cell) => !after.has(cell.id))
					.map((cell) => {
						const pair = pairFor(cell.id);
						return { cell, to: remap(cell, pair.old, pair.next) };
					})
			: [];

		const open = next.filter((cell) => !cell.group);
		const keep =
			open.find((cell) => cell.id === activeId) ??
			open.find((cell) => cell.id === focusId) ??
			open.find((cell) => isUnder(cell.id, focusId)) ??
			open[0];
		refocus.current = Boolean(mapRef.current?.contains(document.activeElement));
		beat.current = Math.min(0, BEAT - (ms / 1000) * Math.max(0, speed) - 0.1);
		setActive(keep?.id ?? null);
		setHover(null);
		setView((v) => ({ focus: nextId, key: v.key + 1, exits }));
	};

	useLayoutEffect(() => {
		const starts = enters.current;
		enters.current = null;
		if (starts && starts.size > 0) {
			const moved: [HTMLDivElement, TreemapCell][] = [];
			for (const cell of cells) {
				const start = starts.get(cell.id);
				const el = els.current.get(cell.id);
				if (!start || !el) continue;
				el.style.transition = "none";
				el.style.transform = `translate(${start.x}px, ${start.y}px)`;
				el.style.width = `${Math.max(0, start.w)}px`;
				el.style.height = `${Math.max(0, start.h)}px`;
				el.style.opacity = "0";
				moved.push([el, cell]);
			}
			if (moved.length > 0) {
				void mapRef.current?.offsetWidth;
				for (const [el, cell] of moved) {
					el.style.transition = transition;
					el.style.transform = `translate(${cell.x}px, ${cell.y}px)`;
					el.style.width = `${cell.w}px`;
					el.style.height = `${cell.h}px`;
					el.style.opacity = "1";
				}
			}
		}
		if (refocus.current) {
			refocus.current = false;
			if (activeId) els.current.get(activeId)?.focus({ preventScroll: true });
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [view.key]);

	const leaving = view.exits.length;
	useEffect(() => {
		if (leaving === 0) return;
		const key = view.key;
		const id = window.setTimeout(
			() => setView((v) => (v.key === key ? { ...v, exits: [] } : v)),
			ms + 60,
		);
		return () => window.clearTimeout(id);
	}, [view.key, leaving, ms]);

	const activate = (cell: TreemapCell) => {
		const top = index.get(cell.top)?.node;
		if (top?.children?.length) zoomTo(top.id);
		else onSelect?.(cell.node);
	};

	const up = (): boolean => {
		const parent = index.get(focusId)?.parent;
		if (!parent) return false;
		zoomTo(parent);
		return true;
	};

	const step = (from: TreemapCell, dx: number, dy: number) => {
		const cx = from.x + from.w / 2;
		const cy = from.y + from.h / 2;
		let best: TreemapCell | null = null;
		let bestScore = Infinity;
		for (const cell of navigable) {
			if (cell.id === from.id) continue;
			const ox = cell.x + cell.w / 2 - cx;
			const oy = cell.y + cell.h / 2 - cy;
			const along = ox * dx + oy * dy;
			if (along <= 1) continue;
			const across = Math.abs(ox * dy) + Math.abs(oy * dx);
			const score = along + across * 2;
			if (score < bestScore) {
				bestScore = score;
				best = cell;
			}
		}
		if (!best) return;
		setActive(best.id);
		els.current.get(best.id)?.focus({ preventScroll: true });
	};

	const onCellKey = (e: ReactKeyboardEvent<HTMLDivElement>, cell: TreemapCell) => {
		switch (e.key) {
			case "ArrowRight":
				step(cell, 1, 0);
				break;
			case "ArrowLeft":
				step(cell, -1, 0);
				break;
			case "ArrowDown":
				step(cell, 0, 1);
				break;
			case "ArrowUp":
				step(cell, 0, -1);
				break;
			case "Enter":
			case " ":
				activate(cell);
				break;
			case "Backspace":
			case "Escape":
				if (!up()) return;
				break;
			default:
				return;
		}
		e.preventDefault();
		e.stopPropagation();
	};

	const base = parseColor(baseColor) ?? [22, 18, 31];
	const accent = parseColor(accentColor) ?? [168, 85, 247];
	const ink = luma(base) > 0.55 ? "#0b0a10" : "#f4f0ff";
	let largest = 0;
	for (const cell of navigable) if (cell.value > largest) largest = cell.value;

	const fillOf = (cell: TreemapCell): RGB => {
		if (cell.group) return mix(base, accent, 0.07);
		const within =
			cell.depth > 1 && cell.siblings > 1 ? cell.rank / (cell.siblings - 1) : 0;
		if (colorBy === "size") {
			const share = largest > 0 ? cell.value / largest : 0;
			return mix(base, accent, 0.14 + 0.86 * Math.sqrt(share));
		}
		if (colorBy === "depth") {
			return mix(
				base,
				accent,
				clamp(0.26 + 0.24 * (cell.depth - 1) - 0.1 * within, 0.08, 1),
			);
		}
		const tone = cell.topCount > 1 ? cell.topIndex / (cell.topCount - 1) : 0;
		return mix(accent, base, clamp(0.1 + 0.62 * tone + 0.16 * within, 0, 0.92));
	};

	const here = new Set(cells.map((cell) => cell.id));
	const drawn: { cell: TreemapCell; exit: Rect | null }[] = [
		...cells.map((cell) => ({ cell, exit: null })),
		...view.exits
			.filter((exit) => !here.has(exit.cell.id) && index.has(exit.cell.id))
			.map((exit) => ({ cell: exit.cell, exit: exit.to })),
	];
	drawn.sort(
		(a, b) =>
			(index.get(a.cell.id)?.order ?? 0) - (index.get(b.cell.id)?.order ?? 0),
	);

	const trail: TreemapNode[] = [];
	for (let at: string | null = focusId; at; at = index.get(at)?.parent ?? null) {
		const entry = index.get(at);
		if (entry) trail.unshift(entry.node);
	}

	const shownId = hover ?? (keyboard ? activeId : null);
	const shown = shownId ? cells.find((cell) => cell.id === shownId) : undefined;
	const whole = totals.get(focusId) ?? 0;

	return (
		<div
			className={`relative flex h-full w-full flex-col overflow-hidden ${className}`.trim()}
			style={{ backgroundColor: css(base), color: ink }}
		>
			<div className="flex h-8 shrink-0 items-center gap-3 px-2.5 font-mono text-[10px] tracking-[0.12em] uppercase">
				<nav aria-label="Path" className="flex min-w-0 items-center gap-1">
					{trail.map((node, i) => {
						const last = i === trail.length - 1;
						return (
							<span key={node.id} className="flex min-w-0 items-center gap-1">
								{i > 0 ? <span className="opacity-40">/</span> : null}
								<button
									type="button"
									disabled={last}
									aria-current={last ? "location" : undefined}
									onClick={() => zoomTo(node.id)}
									className="max-w-[10rem] cursor-pointer truncate rounded-sm px-1 py-0.5 opacity-60 hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-2 focus-visible:outline-offset-1 disabled:cursor-default disabled:opacity-100"
									style={{ outlineColor: css(accent) }}
								>
									{node.label}
								</button>
							</span>
						);
					})}
				</nav>
				<span className="ml-auto min-w-0 truncate tabular-nums opacity-70">
					{shown
						? `${shown.node.label} · ${formatValue(shown.value)} · ${
								whole > 0 ? Math.round((shown.value / whole) * 100) : 0
							}%`
						: formatValue(whole)}
				</span>
			</div>

			<div
				ref={mapRef}
				role="group"
				aria-label={label}
				className="relative min-h-0 flex-1 overflow-hidden"
				onFocus={() => setKeyboard(true)}
				onBlur={() => setKeyboard(false)}
				onPointerLeave={() => setHover(null)}
			>
				{drawn.map(({ cell, exit }) => {
					const rect = exit ?? cell;
					const fill = fillOf(cell);
					const dark = luma(fill) <= 0.55;
					const gone = exit !== null;
					const roomForName = cell.w >= 46 && cell.h >= 22;
					const roomForValue = cell.h >= 42 && cell.w >= 46;
					const text = Math.round(
						clamp(Math.sqrt(cell.w * cell.h) / 11, 11, 19),
					);
					const reachable = !cell.group && !gone;
					return (
						<div
							key={cell.id}
							ref={(el) => {
								if (el) els.current.set(cell.id, el);
								else els.current.delete(cell.id);
							}}
							role={reachable ? "button" : undefined}
							tabIndex={reachable ? (cell.id === activeId ? 0 : -1) : undefined}
							aria-hidden={gone ? true : undefined}
							aria-label={
								reachable
									? `${cell.node.label}, ${formatValue(cell.value)}`
									: undefined
							}
							onClick={gone ? undefined : () => activate(cell)}
							onPointerEnter={reachable ? () => setHover(cell.id) : undefined}
							onFocus={reachable ? () => setActive(cell.id) : undefined}
							onKeyDown={reachable ? (e) => onCellKey(e, cell) : undefined}
							className={`absolute top-0 left-0 overflow-hidden outline-none select-none focus-visible:z-10 focus-visible:outline-2 focus-visible:-outline-offset-2 ${
								gone ? "pointer-events-none" : "cursor-pointer"
							}`}
							style={{
								transform: `translate(${rect.x}px, ${rect.y}px)`,
								width: Math.max(0, rect.w),
								height: Math.max(0, rect.h),
								opacity: gone ? 0 : 1,
								borderRadius: radius,
								backgroundColor: css(fill),
								color: dark ? "#f4f0ff" : "#0b0a10",
								outlineColor: dark ? "#ffffff" : "#0b0a10",
								boxShadow: cell.group
									? `inset 0 0 0 1px ${css(mix(base, accent, 0.26))}`
									: undefined,
								filter:
									reachable && cell.id === hover ? "brightness(1.18)" : undefined,
								transition,
							}}
						>
							{cell.group ? (
								<div
									className="flex items-center gap-2 px-1.5 font-mono text-[9px] tracking-[0.14em] uppercase"
									style={{ height: HEADER }}
								>
									<span className="min-w-0 truncate opacity-80">
										{cell.node.label}
									</span>
									<span className="ml-auto shrink-0 tabular-nums opacity-50">
										{formatValue(cell.value)}
									</span>
								</div>
							) : labels && roomForName ? (
								<div className="flex h-full flex-col justify-between p-1.5">
									<span
										className="truncate leading-tight font-medium"
										style={{ fontSize: text }}
									>
										{cell.node.label}
									</span>
									{roomForValue ? (
										<span className="truncate font-mono text-[10px] tabular-nums opacity-70">
											{formatValue(cell.value)}
										</span>
									) : null}
								</div>
							) : null}
						</div>
					);
				})}
			</div>
		</div>
	);
}

function remap(r: Rect, a: Rect, b: Rect): Rect {
	const sx = b.w / (a.w || 1);
	const sy = b.h / (a.h || 1);
	return {
		x: b.x + (r.x - a.x) * sx,
		y: b.y + (r.y - a.y) * sy,
		w: r.w * sx,
		h: r.h * sy,
	};
}

function wander(prev: Map<string, number>, ids: string[]): Map<string, number> {
	const next = new Map<string, number>();
	for (const id of ids) {
		const now = prev.get(id) ?? 1;
		const pulled = now + (1 - now) * 0.12;
		next.set(id, clamp(pulled * (1 + (Math.random() - 0.5) * 0.5), 0.4, 2.4));
	}
	return next;
}

function clamp(v: number, lo: number, hi: number): number {
	return v < lo ? lo : v > hi ? hi : v;
}

function parseColor(value: string): RGB | null {
	const hex = value.trim().replace(/^#/, "");
	const full =
		hex.length === 3
			? hex
					.split("")
					.map((c) => c + c)
					.join("")
			: hex;
	if (!/^[0-9a-f]{6}$/i.test(full)) return null;
	const n = parseInt(full, 16);
	return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}

function mix(a: RGB, b: RGB, k: number): RGB {
	return [
		Math.round(a[0] + (b[0] - a[0]) * k),
		Math.round(a[1] + (b[1] - a[1]) * k),
		Math.round(a[2] + (b[2] - a[2]) * k),
	];
}

function css(c: RGB): string {
	return `rgb(${c[0]},${c[1]},${c[2]})`;
}

function luma(c: RGB): number {
	return (0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]) / 255;
}

function subscribeMotion(onChange: () => void): () => void {
	if (typeof window === "undefined" || !window.matchMedia) return () => {};
	const query = window.matchMedia("(prefers-reduced-motion: reduce)");
	query.addEventListener("change", onChange);
	return () => query.removeEventListener("change", onChange);
}

function readMotion(): boolean {
	return (
		typeof window !== "undefined" &&
		!!window.matchMedia &&
		window.matchMedia("(prefers-reduced-motion: reduce)").matches
	);
}

function readMotionOnServer(): boolean {
	return false;
}
```

### 2. `components/registry/treemap/treemap-layout.ts` — supporting file, required

```tsx
export interface TreemapNode {
	id: string;
	label: string;
	value?: number;
	children?: TreemapNode[];
}

export interface Rect {
	x: number;
	y: number;
	w: number;
	h: number;
}

export interface TreemapCell extends Rect {
	id: string;
	node: TreemapNode;
	depth: number;
	group: boolean;
	top: string;
	topIndex: number;
	topCount: number;
	rank: number;
	siblings: number;
	value: number;
}

export interface LayoutOptions {
	depth: number;
	gap: number;
	header: number;
	valueOf: (node: TreemapNode) => number;
	orderOf: (node: TreemapNode) => number;
}

export function squarify(values: number[], box: Rect): Rect[] {
	const n = values.length;
	const out: Rect[] = new Array(n);
	let total = 0;
	for (const v of values) total += v > 0 ? v : 0;
	if (n === 0) return out;
	if (!(total > 0) || box.w <= 0 || box.h <= 0) {
		for (let i = 0; i < n; i++) out[i] = { x: box.x, y: box.y, w: 0, h: 0 };
		return out;
	}
	const floor = total * 1e-6;
	const scale = (box.w * box.h) / total;
	let x = box.x;
	let y = box.y;
	let w = box.w;
	let h = box.h;
	let i = 0;
	while (i < n) {
		const short = Math.min(w, h);
		const s2 = short * short;
		let sum = 0;
		let min = Infinity;
		let max = 0;
		let best = Infinity;
		let j = i;
		while (j < n) {
			const area = Math.max(values[j], floor) * scale;
			const nextSum = sum + area;
			const nextMin = Math.min(min, area);
			const nextMax = Math.max(max, area);
			const worst = Math.max(
				(s2 * nextMax) / (nextSum * nextSum),
				(nextSum * nextSum) / (s2 * nextMin),
			);
			if (j > i && worst > best) break;
			sum = nextSum;
			min = nextMin;
			max = nextMax;
			best = worst;
			j++;
		}
		const thick = short > 0 ? sum / short : 0;
		const wide = w >= h;
		let offset = 0;
		for (let k = i; k < j; k++) {
			const area = Math.max(values[k], floor) * scale;
			const length = thick > 0 ? area / thick : 0;
			out[k] = wide
				? { x, y: y + offset, w: thick, h: length }
				: { x: x + offset, y, w: length, h: thick };
			offset += length;
		}
		if (wide) {
			x += thick;
			w -= thick;
		} else {
			y += thick;
			h -= thick;
		}
		i = j;
	}
	return out;
}

export function layoutTree(
	focus: TreemapNode,
	width: number,
	height: number,
	options: LayoutOptions,
): TreemapCell[] {
	const { depth, gap, header, valueOf, orderOf } = options;
	const half = gap / 2;
	const pad = Math.max(2, gap);
	const out: TreemapCell[] = [];

	const place = (
		parent: TreemapNode,
		box: Rect,
		level: number,
		top: string | null,
		topIndex: number,
		topCount: number,
	) => {
		const kids = (parent.children ?? [])
			.slice()
			.sort((a, b) => orderOf(b) - orderOf(a));
		const rects = squarify(kids.map(valueOf), box);
		kids.forEach((kid, i) => {
			const r = rects[i];
			const cell: Rect = {
				x: r.x + half,
				y: r.y + half,
				w: Math.max(0, r.w - gap),
				h: Math.max(0, r.h - gap),
			};
			const roomy = cell.w > header * 3 && cell.h > header * 2.5;
			const group = level < depth && !!kid.children?.length && roomy;
			const isTop = top === null;
			out.push({
				...cell,
				id: kid.id,
				node: kid,
				depth: level,
				group,
				top: isTop ? kid.id : top,
				topIndex: isTop ? i : topIndex,
				topCount: isTop ? kids.length : topCount,
				rank: i,
				siblings: kids.length,
				value: valueOf(kid),
			});
			if (!group) return;
			place(
				kid,
				{
					x: cell.x + pad - half,
					y: cell.y + header - half,
					w: cell.w - pad * 2 + gap,
					h: cell.h - header - pad + gap,
				},
				level + 1,
				isTop ? kid.id : top,
				isTop ? i : topIndex,
				isTop ? kids.length : topCount,
			);
		});
	};

	place(
		focus,
		{ x: -half, y: -half, w: width + gap, h: height + gap },
		1,
		null,
		0,
		0,
	);
	return out;
}
```

### 3. `hooks/use-animation-loop.ts` — peer hook, required

```tsx
"use client";

import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react";

export interface Metrics {
  width: number;
  height: number;
  dpr: number;
  bufferWidth: number;
  bufferHeight: number;
}

export interface FrameInfo {
  now: number;
  dt: number;
  elapsed: number;
  frame: number;
}

export interface AnimationLoopHandle {
  start(): void;
  stop(): void;
  paint(): void;
  resize(): void;
  readonly running: boolean;
}

export interface AnimationLoopOptions {
  target: React.RefObject<HTMLElement | null>;
  halted?: boolean;
  dpr?: number | "auto";
  onResize?(metrics: Metrics): void;
  onFrame?(info: FrameInfo): void | false;
  paintWhenHalted?: boolean;
  resizeDebounceMs?: number;
  gl?(): WebGLRenderingContext | WebGL2RenderingContext | null | undefined;
  onDispose?(): void;
  deps?: unknown[];
}

const MAX_DT = 1 / 15;

export function useAnimationLoop(
  options: AnimationLoopOptions,
): AnimationLoopHandle {
  const opts = useRef(options);
  useLayoutEffect(() => {
    opts.current = options;
  });

  const raf = useRef<number | null>(null);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const running = useRef(false);
  const disposed = useRef(false);
  const startedAt = useRef(0);
  const last = useRef(0);
  const frame = useRef(0);

  const measure = useCallback((): Metrics | null => {
    const el = opts.current.target.current;
    if (!el) return null;
    const rect = el.getBoundingClientRect();
    const cap = opts.current.dpr ?? "auto";
    const limit = cap === "auto" ? 2 : cap;
    const dpr = Math.min(
      typeof window === "undefined" ? 1 : window.devicePixelRatio || 1,
      limit,
    );
    return {
      width: rect.width,
      height: rect.height,
      dpr,
      bufferWidth: Math.max(1, Math.round(rect.width * dpr)),
      bufferHeight: Math.max(1, Math.round(rect.height * dpr)),
    };
  }, []);

  const tick = useCallback(function tick(now: number) {
    if (disposed.current) return;

    if (startedAt.current === 0) startedAt.current = now;
    const dt = last.current === 0 ? 0 : Math.min((now - last.current) / 1000, MAX_DT);
    last.current = now;

    const info: FrameInfo = {
      now,
      dt,
      elapsed: (now - startedAt.current) / 1000,
      frame: frame.current++,
    };

    const verdict = opts.current.onFrame?.(info);

    if (disposed.current) return;

    if (verdict === false || opts.current.halted) {
      running.current = false;
      raf.current = null;
      return;
    }
    raf.current = requestAnimationFrame(tick);
  }, []);

  const start = useCallback(() => {
    if (disposed.current || running.current) return;
    running.current = true;
    last.current = 0;
    raf.current = requestAnimationFrame(tick);
  }, [tick]);

  const stop = useCallback(() => {
    running.current = false;
    if (raf.current !== null) {
      cancelAnimationFrame(raf.current);
      raf.current = null;
    }
  }, []);

  const paint = useCallback(() => start(), [start]);

  const resize = useCallback(() => {
    const metrics = measure();
    if (!metrics) return;
    opts.current.onResize?.(metrics);
    if (opts.current.paintWhenHalted !== false) paint();
    else if (!opts.current.halted) start();
  }, [measure, paint, start]);

  const deps = options.deps ?? [];

  useEffect(() => {
    disposed.current = false;
    const el = opts.current.target.current;
    if (!el) return;

    const run = () => {
      if (disposed.current) return;
      resize();
    };

    const observer = new ResizeObserver(() => {
      const wait = opts.current.resizeDebounceMs ?? 0;
      if (wait <= 0) {
        run();
        return;
      }
      if (timer.current !== null) clearTimeout(timer.current);
      timer.current = setTimeout(() => {
        timer.current = null;
        run();
      }, wait);
    });
    observer.observe(el);

    resize();
    if (!opts.current.halted) start();

    return () => {
      disposed.current = true;
      running.current = false;
      if (raf.current !== null) {
        cancelAnimationFrame(raf.current);
        raf.current = null;
      }
      if (timer.current !== null) {
        clearTimeout(timer.current);
        timer.current = null;
      }
      observer.disconnect();
      opts.current.onDispose?.();
      const context = opts.current.gl?.();
      context?.getExtension("WEBGL_lose_context")?.loseContext();
      startedAt.current = 0;
      last.current = 0;
      frame.current = 0;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);

  const halted = options.halted ?? false;
  useEffect(() => {
    if (!halted) start();
  }, [halted, start]);

  return useMemo<AnimationLoopHandle>(
    () => ({
      start,
      stop,
      paint,
      resize,
      get running() {
        return running.current;
      },
    }),
    [start, stop, paint, resize],
  );
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `gap` | `number` | `3` | Space between cells. Range 0–10 px. |
| `depth` | `number` | `2` | How many levels are drawn below the one you are in. At 1 each division is a single box. Range 1–3. |
| `live` | `boolean` | `true` | The values wander and the map is laid out again as they change. |
| `speed` | `number` | `1` | How often the live values change. Range 0.25–3 ×. Ignored while `live` is `false`. |
| `labels` | `boolean` | `true` | Print a name and a value in every cell that has room. |
| `colorBy` | `"branch" | "size" | "depth"` | `"branch"` | What a cell's shade means: which branch it is in, how big it is, or how deep it sits. |
| `duration` | `number` | `520` | How long a zoom or a reflow takes. 0 cuts. Range 0–1200 ms. |
| `radius` | `number` | `4` | Corner radius of a cell. Range 0–12 px. |
| `accentColor` | `string (hex)` | `"#a855f7"` | The strong end of the color ramp. |
| `baseColor` | `string (hex)` | `"#16121f"` | The weak end of the ramp, and the ground under the cells. |

## Usage

```tsx
import Treemap from "@/components/registry/treemap/treemap";

<Treemap
  gap={3}
  depth={2}
  live={true}
  speed={1}
  labels={true}
  colorBy="branch"
  duration={520}
  radius={4}
  accentColor="#a855f7"
  baseColor="#16121f"
/>
```

The import path matches the file path above; change it if you move the component. Every value shown is the documented default — pass only what you actually want to change. The snippet lists the tunable props only: if the component's props type in the source requires others (content, handlers, data), pass those too.

## Integration rules

- Keep the `"use client"` directive. This is a client component and will not render as a Server Component.
- It fills its parent. Give the wrapper an explicit height (or a definite grid area) — against a height-auto parent it collapses to nothing.
- It takes a `reducedMotion` prop and quiesces when true. Wire it to a `prefers-reduced-motion` listener rather than hardcoding `false`.
- It runs a free-running animation loop. Halt it when off-screen or backgrounded if you care about battery.
- The peer hook is required, not optional. Copy it to `hooks/use-animation-loop.ts` so the component's `@/hooks/use-animation-loop` import resolves.
- The supporting files are part of the component, not examples. Copy every file listed, preserving the directory layout — they import each other by relative path.
- It owns a GPU/canvas context and releases it on unmount. Preserve the cleanup return — leaking contexts kills the tab after a few navigations.

## Your task

1. Tell me where in my project this should live and why.
2. Create the files above verbatim.
3. Wire the component into the place I point you at, with sensible props for that context.
4. Flag anything in my setup that conflicts with the stack assumptions above.

Do not restyle the component or alter the animation math unless I ask.
