Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat: zoom-map Knowledge Graph with per-node code health (#918)

Raghav Chamadiya1c7e058d63fd
diff --git a/packages/api-client/src/graph.ts b/packages/api-client/src/graph.ts
index 8beac3618..22d0a13b4 100644
--- a/packages/api-client/src/graph.ts
+++ b/packages/api-client/src/graph.ts
@@ -1,3 +1,4 @@
+import type { ZoomMap } from "@repowise-dev/ui/zoom";
import { apiGet } from "./client";
import type {
ArchitectureGraphResponse,
@@ -154,3 +155,15 @@ export async function getExecutionFlows(
): Promise<ExecutionFlowsResponse> {
return apiGet<ExecutionFlowsResponse>(`/api/graph/${repoId}/execution-flows`, params);
}
+
+/**
+ * The continuous-zoom containment tree (system -> layer -> ... -> file). The
+ * response shape is the shared `ZoomMap` consumed by the canvas renderer.
+ * `focus` + `max_depth` fetch deeper subtrees lazily for large repos.
+ */
+export async function getZoomMap(
+ repoId: string,
+ params?: { max_depth?: number; focus?: string },
+): Promise<ZoomMap> {
+ return apiGet<ZoomMap>(`/api/graph/${repoId}/zoom-map`, params);
+}
diff --git a/packages/server/src/repowise/server/routers/c4.py b/packages/server/src/repowise/server/routers/c4.py
index b39ef42fb..0029db542 100644
--- a/packages/server/src/repowise/server/routers/c4.py
+++ b/packages/server/src/repowise/server/routers/c4.py
@@ -260,6 +260,7 @@ def _zoom_response(zoom: ZoomMap) -> ZoomMapResponse:
),
summary=n.summary,
language=n.language,
+ health_score=(round(n.health_score, 2) if n.health_score is not None else None),
is_entry_point=n.is_entry_point,
is_hotspot=n.is_hotspot,
is_dead=n.is_dead,
diff --git a/packages/server/src/repowise/server/schemas/zoom.py b/packages/server/src/repowise/server/schemas/zoom.py
index a4cd2c6a1..4c7130bd3 100644
--- a/packages/server/src/repowise/server/schemas/zoom.py
+++ b/packages/server/src/repowise/server/schemas/zoom.py
@@ -43,6 +43,10 @@ class ZoomNodeResponse(BaseModel):
layout: ZoomRectResponse | None = None
summary: str = ""
language: str | None = None
+ # Code-health score (0..10, higher = healthier), matching the /files treemap.
+ # None when the file/subtree was unscored (health is sparse); the renderer
+ # reads that as neutral.
+ health_score: float | None = None
is_entry_point: bool = False
is_hotspot: bool = False
is_dead: bool = False
diff --git a/packages/server/src/repowise/server/services/zoom_builder/__init__.py b/packages/server/src/repowise/server/services/zoom_builder/__init__.py
index 39b382248..10ea25cf3 100644
--- a/packages/server/src/repowise/server/services/zoom_builder/__init__.py
+++ b/packages/server/src/repowise/server/services/zoom_builder/__init__.py
@@ -22,7 +22,7 @@ from repowise.server.services.c4_builder.architecture import build_architecture_
from repowise.server.services.c4_builder.models import ArchitectureView
from .layout import lay_out
-from .metrics import rollup_metrics
+from .metrics import rollup_health, rollup_metrics
from .models import ZoomMap, ZoomNode, ZoomRelation
from .relations import aggregate_relations
from .scoring import FileStat, compute_file_signals, score_tree
@@ -51,8 +51,16 @@ def assemble_zoom_map(
*,
max_depth: int | None = None,
focus: str | None = None,
+ health: dict[str, tuple[float, int]] | None = None,
) -> ZoomMap:
- """Pure assembly: ``ArchitectureView`` -> ``ZoomMap``. No DB."""
+ """Pure assembly: ``ArchitectureView`` -> ``ZoomMap``. No DB.
+
+ ``health`` maps a file path to ``(score, loc)`` where ``score`` is the 0..10
+ code-health score (higher = healthier) and ``loc`` is the rollup weight. It is
+ optional so the pure assembly still unit-tests without health data; files not
+ present in the map read as unscored (neutral), exactly like the treemap.
+ """
+ health = health or {}
# The view is loaded file-only, but the curated node_type can be
# config/document/service rather than "file"; a file node is reliably the
# one whose id equals its own path and carries no symbol line range.
@@ -91,6 +99,7 @@ def assemble_zoom_map(
leaf_info: dict[str, LeafInfo] = {}
for n in file_nodes:
sig = signals.get(n.id)
+ hscore, hloc = health.get(n.id, (None, 1))
leaf_info[n.id] = LeafInfo(
summary=n.summary,
language=n.language,
@@ -99,6 +108,8 @@ def assemble_zoom_map(
is_dead=n.is_dead,
is_test=n.is_test,
on_flow=bool(sig and sig.on_flow),
+ health_score=hscore,
+ loc=hloc,
)
layers = [
@@ -117,6 +128,7 @@ def assemble_zoom_map(
root_id, nodes = build_tree(view.project_name, layers, leaf_info)
nodes = rollup_metrics(root_id, nodes)
+ nodes = rollup_health(root_id, nodes)
nodes = score_tree(root_id, nodes, signals)
nodes = lay_out(root_id, nodes)
relations = aggregate_relations(nodes, edges)
@@ -214,5 +226,20 @@ async def build_zoom_map(
focus: str | None = None,
) -> ZoomMap:
"""Derive the zoom map for ``repo_id`` from the persisted graph."""
+ from repowise.core.persistence import crud
+
view = await build_architecture_view(session, repo_id, include_symbols=False)
- return assemble_zoom_map(view, max_depth=max_depth, focus=focus)
+ # One extra read: per-file health, keyed by path -> (effective score, loc).
+ # Effective score prefers the split ``defect_score`` and falls back to the
+ # overall ``score``, exactly like GET /api/repos/{id}/files, so the zoom card
+ # and the /files treemap color off the same number. loc (>=1) is the rollup
+ # weight for container means.
+ metrics = await crud.get_health_metrics(session, repo_id)
+ health = {
+ m.file_path: (
+ m.defect_score if m.defect_score is not None else m.score,
+ max(m.nloc or 1, 1),
+ )
+ for m in metrics
+ }
+ return assemble_zoom_map(view, max_depth=max_depth, focus=focus, health=health)
diff --git a/packages/server/src/repowise/server/services/zoom_builder/metrics.py b/packages/server/src/repowise/server/services/zoom_builder/metrics.py
index 8842fa6c9..ee50264fa 100644
--- a/packages/server/src/repowise/server/services/zoom_builder/metrics.py
+++ b/packages/server/src/repowise/server/services/zoom_builder/metrics.py
@@ -57,3 +57,37 @@ def rollup_metrics(root_id: str, nodes: dict[str, ZoomNode]) -> dict[str, ZoomNo
visit(root_id)
return updated
+
+
+def rollup_health(root_id: str, nodes: dict[str, ZoomNode]) -> dict[str, ZoomNode]:
+ """Fill ``health_score`` on every node from the file leaves.
+
+ A file keeps its own score (already set on the leaf). Each container gets the
+ loc-weighted mean of its scored descendants, matching how the /files treemap
+ colors a folder tile, so the two surfaces stay pixel-consistent. Health is
+ sparse (files can be unscored or excluded); those leaves carry weight 0 and a
+ container with no scored descendant stays ``None``. Post-order, no DB.
+ """
+ updated: dict[str, ZoomNode] = dict(nodes)
+
+ def visit(node_id: str) -> tuple[float, float]:
+ """Return ``(weighted_sum, weight)`` over this subtree's scored files."""
+ node = updated[node_id]
+ if node.kind == "file":
+ if node.health_score is None:
+ return 0.0, 0.0
+ w = float(max(node.loc, 1))
+ return node.health_score * w, w
+
+ weighted_sum = 0.0
+ weight = 0.0
+ for cid in node.children:
+ cs, cw = visit(cid)
+ weighted_sum += cs
+ weight += cw
+ score = weighted_sum / weight if weight > 0 else None
+ updated[node_id] = replace(node, health_score=score)
+ return weighted_sum, weight
+
+ visit(root_id)
+ return updated
diff --git a/packages/server/src/repowise/server/services/zoom_builder/models.py b/packages/server/src/repowise/server/services/zoom_builder/models.py
index fdbe5b6eb..da68d30a0 100644
--- a/packages/server/src/repowise/server/services/zoom_builder/models.py
+++ b/packages/server/src/repowise/server/services/zoom_builder/models.py
@@ -65,6 +65,14 @@ class ZoomNode:
layout: ZoomRect | None = None
summary: str = ""
language: str | None = None
+ # Code-health score on the 0..10 scale (higher = healthier), matching the
+ # /files treemap. A file carries its own defect score (falling back to the
+ # overall score); a container carries the loc-weighted mean over its scored
+ # descendants. None when nothing in the subtree was scored (health is sparse).
+ health_score: float | None = None
+ # Lines of code for the file leaf, used only as the health-rollup weight so
+ # a container's mean matches the treemap. Not surfaced in the response.
+ loc: int = 1
# File-leaf flags (False / defaults on non-file nodes).
is_entry_point: bool = False
is_hotspot: bool = False
diff --git a/packages/server/src/repowise/server/services/zoom_builder/tree.py b/packages/server/src/repowise/server/services/zoom_builder/tree.py
index 44c0cc405..325ecaca8 100644
--- a/packages/server/src/repowise/server/services/zoom_builder/tree.py
+++ b/packages/server/src/repowise/server/services/zoom_builder/tree.py
@@ -53,6 +53,10 @@ class LeafInfo:
is_dead: bool = False
is_test: bool = False
on_flow: bool = False
+ # Code-health score (0..10, higher = healthier) and the loc weight used when
+ # rolling the score up into containers. None score = this file was unscored.
+ health_score: float | None = None
+ loc: int = 1
SYSTEM_ID = "zm:sys"
@@ -162,6 +166,8 @@ class _Builder:
is_dead=info.is_dead,
is_test=info.is_test,
on_flow=info.on_flow,
+ health_score=info.health_score,
+ loc=info.loc,
)
)
diff --git a/packages/ui/__tests__/zoom/camera-anim.test.ts b/packages/ui/__tests__/zoom/camera-anim.test.ts
new file mode 100644
index 000000000..e07cee477
--- /dev/null
+++ b/packages/ui/__tests__/zoom/camera-anim.test.ts
@@ -0,0 +1,52 @@
+import { describe, it, expect } from "vitest";
+import type { Camera } from "../../src/zoom/camera";
+import {
+ easeInOutCubic,
+ flyDuration,
+ interpolateCamera,
+} from "../../src/zoom/camera-anim";
+
+describe("easeInOutCubic", () => {
+ it("pins the endpoints and the midpoint", () => {
+ expect(easeInOutCubic(0)).toBe(0);
+ expect(easeInOutCubic(1)).toBe(1);
+ expect(easeInOutCubic(0.5)).toBeCloseTo(0.5, 9);
+ });
+ it("clamps out-of-range progress", () => {
+ expect(easeInOutCubic(-1)).toBe(0);
+ expect(easeInOutCubic(2)).toBe(1);
+ });
+});
+
+describe("interpolateCamera", () => {
+ const from: Camera = { cx: 0, cy: 0, scale: 100 };
+ const to: Camera = { cx: 1, cy: 2, scale: 10_000 };
+
+ it("returns the endpoints at t=0 and t=1", () => {
+ expect(interpolateCamera(from, to, 0)).toEqual(from);
+ const end = interpolateCamera(from, to, 1);
+ expect(end.cx).toBeCloseTo(1, 9);
+ expect(end.cy).toBeCloseTo(2, 9);
+ expect(end.scale).toBeCloseTo(10_000, 3);
+ });
+
+ it("interpolates scale geometrically, not linearly", () => {
+ // eased(0.5) = 0.5 -> scale = 100 * (10000/100)^0.5 = 100 * 100 = 1000
+ const mid = interpolateCamera(from, to, 0.5);
+ expect(mid.scale).toBeCloseTo(1000, 3);
+ });
+});
+
+describe("flyDuration", () => {
+ const base: Camera = { cx: 0.5, cy: 0.5, scale: 1000 };
+ it("stays within the clamp range", () => {
+ const d = flyDuration(base, { cx: 0.5, cy: 0.5, scale: 1000 });
+ expect(d).toBeGreaterThanOrEqual(260);
+ expect(d).toBeLessThanOrEqual(720);
+ });
+ it("a tiny move is quicker than a cross-system jump", () => {
+ const small = flyDuration(base, { cx: 0.5, cy: 0.5, scale: 1100 });
+ const big = flyDuration(base, { cx: 0.5, cy: 0.5, scale: 4_000_000 });
+ expect(small).toBeLessThan(big);
+ });
+});
diff --git a/packages/ui/__tests__/zoom/camera.test.ts b/packages/ui/__tests__/zoom/camera.test.ts
new file mode 100644
index 000000000..e14fd9e0a
--- /dev/null
+++ b/packages/ui/__tests__/zoom/camera.test.ts
@@ -0,0 +1,110 @@
+import { describe, it, expect } from "vitest";
+import {
+ type Camera,
+ type Viewport,
+ clampScale,
+ fitRoot,
+ frameRect,
+ panByScreen,
+ screenToWorld,
+ worldRectToScreen,
+ worldToScreen,
+ zoomAbout,
+} from "../../src/zoom/camera";
+import { MAX_SCALE, MIN_SCALE } from "../../src/zoom/constants";
+
+const VP: Viewport = { w: 1000, h: 800 };
+
+describe("camera transforms", () => {
+ it("places the centre world point at the viewport centre", () => {
+ const cam: Camera = { cx: 0.5, cy: 0.5, scale: 600 };
+ const p = worldToScreen(cam, VP, 0.5, 0.5);
+ expect(p.sx).toBeCloseTo(500);
+ expect(p.sy).toBeCloseTo(400);
+ });
+
+ it("worldToScreen and screenToWorld are inverses", () => {
+ const cam: Camera = { cx: 0.3, cy: 0.7, scale: 1234.5 };
+ const w = screenToWorld(cam, VP, 137, 642);
+ const s = worldToScreen(cam, VP, w.wx, w.wy);
+ expect(s.sx).toBeCloseTo(137);
+ expect(s.sy).toBeCloseTo(642);
+ });
+
+ it("maps a world rect's size by scale", () => {
+ const cam: Camera = { cx: 0.5, cy: 0.5, scale: 1000 };
+ const r = worldRectToScreen(cam, VP, { x: 0.25, y: 0.25, w: 0.5, h: 0.5 });
+ expect(r.w).toBeCloseTo(500);
+ expect(r.h).toBeCloseTo(500);
+ // centred rect stays centred
+ expect(r.x + r.w / 2).toBeCloseTo(500);
+ expect(r.y + r.h / 2).toBeCloseTo(400);
+ });
+});
+
+describe("zoomAbout", () => {
+ it("keeps the world point under the anchor fixed", () => {
+ const cam: Camera = { cx: 0.5, cy: 0.5, scale: 800 };
+ const anchorSx = 720;
+ const anchorSy = 210;
+ const before = screenToWorld(cam, VP, anchorSx, anchorSy);
+ const zoomed = zoomAbout(cam, VP, anchorSx, anchorSy, 2.5);
+ const after = worldToScreen(zoomed, VP, before.wx, before.wy);
+ expect(after.sx).toBeCloseTo(anchorSx, 4);
+ expect(after.sy).toBeCloseTo(anchorSy, 4);
+ expect(zoomed.scale).toBeCloseTo(2000);
+ });
+
+ it("respects scale clamps", () => {
+ const cam: Camera = { cx: 0.5, cy: 0.5, scale: 100 };
+ const out = zoomAbout(cam, VP, 500, 400, 1e-9);
+ expect(out.scale).toBe(MIN_SCALE);
+ });
+});
+
+describe("panByScreen", () => {
+ it("shifts the centre by the inverse scaled delta", () => {
+ const cam: Camera = { cx: 0.5, cy: 0.5, scale: 500 };
+ const out = panByScreen(cam, 250, -100);
+ expect(out.cx).toBeCloseTo(0.5 - 250 / 500);
+ expect(out.cy).toBeCloseTo(0.5 + 100 / 500);
+ expect(out.scale).toBe(500);
+ });
+});
+
+describe("framing helpers", () => {
+ it("fitRoot centres the unit square", () => {
+ const cam = fitRoot(VP, 0.9);
+ expect(cam.cx).toBe(0.5);
+ expect(cam.cy).toBe(0.5);
+ expect(cam.scale).toBeCloseTo(800 * 0.9); // bounded by the shorter axis
+ });
+
+ it("frameRect centres and scales to fill the smaller axis", () => {
+ const rect = { x: 0.2, y: 0.4, w: 0.1, h: 0.05 };
+ const cam = frameRect(VP, rect, 0.8);
+ expect(cam.cx).toBeCloseTo(0.25);
+ expect(cam.cy).toBeCloseTo(0.425);
+ // larger rect dimension (0.1) maps to 80% of the 800px axis
+ expect(cam.scale).toBeCloseTo((800 * 0.8) / 0.1);
+ });
+
+ it("clampScale bounds both ends", () => {
+ expect(clampScale(1e12)).toBe(MAX_SCALE);
+ expect(clampScale(1e-12)).toBe(MIN_SCALE);
+ });
+});
+
+describe("deep-zoom precision (centre-anchored rebase)", () => {
+ it("keeps the centre O(1) and round-trips a world point at extreme scale", () => {
+ const cam: Camera = { cx: 0.123456789, cy: 0.987654321, scale: 2_000_000 };
+ expect(Math.abs(cam.cx)).toBeLessThan(2);
+ expect(Math.abs(cam.cy)).toBeLessThan(2);
+ const target = { wx: 0.1234567, wy: 0.9876543 };
+ const s = worldToScreen(cam, VP, target.wx, target.wy);
+ const back = screenToWorld(cam, VP, s.sx, s.sy);
+ // sub-pixel world precision survives a 2e6 scale round-trip
+ expect(back.wx).toBeCloseTo(target.wx, 9);
+ expect(back.wy).toBeCloseTo(target.wy, 9);
+ });
+});
diff --git a/packages/ui/__tests__/zoom/cull.test.ts b/packages/ui/__tests__/zoom/cull.test.ts
new file mode 100644
index 000000000..1c0deea3d
--- /dev/null
+++ b/packages/ui/__tests__/zoom/cull.test.ts
@@ -0,0 +1,72 @@
+import { describe, it, expect } from "vitest";
+import type { Viewport } from "../../src/zoom/camera";
+import { isOnScreen, selectChildren } from "../../src/zoom/cull";
+import type { ZoomNode } from "../../src/zoom/types";
+
+const VP: Viewport = { w: 1000, h: 800 };
+
+describe("isOnScreen", () => {
+ it("keeps rects overlapping the viewport", () => {
+ expect(isOnScreen({ x: 400, y: 300, w: 100, h: 100 }, VP, 0)).toBe(true);
+ expect(isOnScreen({ x: -50, y: -50, w: 100, h: 100 }, VP, 0)).toBe(true);
+ });
+ it("drops fully off-screen rects", () => {
+ expect(isOnScreen({ x: 2000, y: 300, w: 100, h: 100 }, VP, 0)).toBe(false);
+ expect(isOnScreen({ x: 400, y: -500, w: 100, h: 100 }, VP, 0)).toBe(false);
+ });
+ it("honours the margin", () => {
+ expect(isOnScreen({ x: -90, y: 300, w: 50, h: 50 }, VP, 64)).toBe(true);
+ expect(isOnScreen({ x: -200, y: 300, w: 50, h: 50 }, VP, 64)).toBe(false);
+ });
+});
+
+function leaf(id: string, rank: number): ZoomNode {
+ return {
+ id,
+ parent_id: "p",
+ level: 4,
+ kind: "file",
+ name: id,
+ path: id,
+ children: [],
+ importance: 1 / rank,
+ sibling_rank: rank,
+ metrics: {
+ file_count: 1,
+ descendant_count: 0,
+ hotspot_count: 0,
+ dead_count: 0,
+ entry_point_count: 0,
+ on_flow_count: 0,
+ },
+ layout: { x: 0, y: 0, w: 1, h: 1 },
+ summary: "",
+ language: null,
+ is_entry_point: false,
+ is_hotspot: false,
+ is_dead: false,
+ is_test: false,
+ on_flow: false,
+ health_score: null,
+ };
+}
+
+describe("selectChildren", () => {
+ const children = [leaf("e", 5), leaf("a", 1), leaf("c", 3), leaf("b", 2), leaf("d", 4)];
+
+ it("returns everything when under the cap", () => {
+ expect(selectChildren(children, 10)).toHaveLength(5);
+ });
+
+ it("keeps the top-N by sibling_rank but preserves original order", () => {
+ const kept = selectChildren(children, 3);
+ expect(kept.map((c) => c.id)).toEqual(["a", "c", "b"]); // ranks 1,3,2 in input order
+ });
+
+ it("is deterministic on rank ties (breaks by id)", () => {
+ const tied = [leaf("y", 1), leaf("x", 1), leaf("z", 1)];
+ const kept = selectChildren(tied, 2);
+ // ranked: x, y, z -> keep x,y -> input order y,x
+ expect(kept.map((c) => c.id)).toEqual(["y", "x"]);
+ });
+});
diff --git a/packages/ui/__tests__/zoom/edges.test.ts b/packages/ui/__tests__/zoom/edges.test.ts
new file mode 100644
index 000000000..1530a0af6
--- /dev/null
+++ b/packages/ui/__tests__/zoom/edges.test.ts
@@ -0,0 +1,115 @@
+import { describe, it, expect } from "vitest";
+import type { Rect } from "../../src/zoom/camera";
+import {
+ controlPoints,
+ type EdgeInput,
+ facingSide,
+ routeEdges,
+ slotAnchor,
+} from "../../src/zoom/edges";
+
+const box = (x: number, y: number, w: number, h: number): Rect => ({ x, y, w, h });
+
+describe("facingSide", () => {
+ const r = box(0, 0, 100, 50); // centre (50, 25)
+ it("faces the side toward the target", () => {
+ expect(facingSide(r, { x: 500, y: 25 })).toBe("right");
+ expect(facingSide(r, { x: -500, y: 25 })).toBe("left");
+ expect(facingSide(r, { x: 50, y: -500 })).toBe("top");
+ expect(facingSide(r, { x: 50, y: 500 })).toBe("bottom");
+ });
+ it("normalises by half-extents so a wide box still picks a horizontal side", () => {
+ const wide = box(0, 0, 200, 20); // centre (100, 10)
+ // dx=80 dy=8 -> 80/100=0.8 vs 8/10=0.8 tie -> horizontal wins on >=
+ expect(facingSide(wide, { x: 180, y: 18 })).toBe("right");
+ });
+});
+
+describe("slotAnchor", () => {
+ const r = box(0, 0, 100, 100);
+ it("centres a single slot on the side", () => {
+ expect(slotAnchor(r, "top", 0, 1, 0.2)).toEqual({ x: 50, y: 0 });
+ expect(slotAnchor(r, "right", 0, 1, 0.2)).toEqual({ x: 100, y: 50 });
+ expect(slotAnchor(r, "bottom", 0, 1, 0.2)).toEqual({ x: 50, y: 100 });
+ expect(slotAnchor(r, "left", 0, 1, 0.2)).toEqual({ x: 0, y: 50 });
+ });
+ it("fans multiple slots symmetrically around the side centre", () => {
+ const gap = 0.2; // min(0.2*100, 100/4) = 20
+ expect(slotAnchor(r, "top", 0, 3, gap).x).toBeCloseTo(30, 9);
+ expect(slotAnchor(r, "top", 1, 3, gap).x).toBeCloseTo(50, 9);
+ expect(slotAnchor(r, "top", 2, 3, gap).x).toBeCloseTo(70, 9);
+ });
+ it("clamps the gap so the fan never spills past the side", () => {
+ // count 9 would want 0.2*100=20 each, but is clamped to 100/10 = 10
+ const first = slotAnchor(r, "top", 0, 9, 0.2);
+ const last = slotAnchor(r, "top", 8, 9, 0.2);
+ expect(first.x).toBeGreaterThanOrEqual(0);
+ expect(last.x).toBeLessThanOrEqual(100);
+ });
+});
+
+describe("controlPoints", () => {
+ it("projects each control point outward along its side normal", () => {
+ const [c1, c2] = controlPoints({ x: 50, y: 0 }, "top", { x: 50, y: 100 }, "bottom", 0.5);
+ expect(c1).toEqual({ x: 50, y: -50 }); // top normal (0,-1) * (100*0.5)
+ expect(c2).toEqual({ x: 50, y: 150 }); // bottom normal (0,1) * 50
+ });
+});
+
+describe("routeEdges", () => {
+ it("routes a single edge from the facing sides of each box", () => {
+ const rects = new Map([
+ ["A", box(0, 0, 100, 100)],
+ ["B", box(200, 0, 100, 100)],
+ ]);
+ const edges: EdgeInput[] = [
+ { id: "A B", sourceId: "A", targetId: "B", coupling: "tight", edgeCount: 3 },
+ ];
+ const routed = routeEdges(edges, rects);
+ expect(routed).toHaveLength(1);
+ const { route } = routed[0]!;
+ expect(route.start).toEqual({ x: 100, y: 50 }); // A right side
+ expect(route.end).toEqual({ x: 200, y: 50 }); // B left side
+ expect(route.endAngle).toBeCloseTo(0, 6); // arrow points right, into B
+ });
+
+ it("drops edges whose endpoints are not laid out", () => {
+ const rects = new Map([["A", box(0, 0, 100, 100)]]);
+ const edges: EdgeInput[] = [
+ { id: "A Z", sourceId: "A", targetId: "Z", coupling: "loose", edgeCount: 1 },
+ ];
+ expect(routeEdges(edges, rects)).toHaveLength(0);
+ });
+
+ it("fans edges that share a box side into distinct slots", () => {
+ const rects = new Map([
+ ["A", box(0, 0, 100, 100)], // centre (50,50)
+ ["B", box(200, -200, 100, 100)], // up-right of A
+ ["C", box(200, 200, 100, 100)], // down-right of A
+ ]);
+ const edges: EdgeInput[] = [
+ { id: "A B", sourceId: "A", targetId: "B", coupling: "loose", edgeCount: 1 },
+ { id: "A C", sourceId: "A", targetId: "C", coupling: "loose", edgeCount: 1 },
+ ];
+ const routed = routeEdges(edges, rects);
+ const ab = routed.find((r) => r.id === "A B")!;
+ const ac = routed.find((r) => r.id === "A C")!;
+ // Both leave A's right side, but on separate slots -> different start.y.
+ expect(ab.route.start.x).toBe(100);
+ expect(ac.route.start.x).toBe(100);
+ expect(ab.route.start.y).not.toBeCloseTo(ac.route.start.y, 3);
+ });
+
+ it("is deterministic", () => {
+ const rects = new Map([
+ ["A", box(0, 0, 100, 100)],
+ ["B", box(200, 0, 100, 100)],
+ ["C", box(0, 200, 100, 100)],
+ ]);
+ const edges: EdgeInput[] = [
+ { id: "A B", sourceId: "A", targetId: "B", coupling: "tight", edgeCount: 2 },
+ { id: "A C", sourceId: "A", targetId: "C", coupling: "loose", edgeCount: 1 },
+ ];
+ expect(routeEdges(edges, rects)).toEqual(routeEdges(edges, rects));
+ });
+});
diff --git a/packages/ui/__tests__/zoom/focus-path.test.ts b/packages/ui/__tests__/zoom/focus-path.test.ts
new file mode 100644
index 000000000..9429b687f
--- /dev/null
+++ b/packages/ui/__tests__/zoom/focus-path.test.ts
@@ -0,0 +1,80 @@
+import { describe, it, expect } from "vitest";
+import type { Rect } from "../../src/zoom/camera";
+import { focusChain, focusId } from "../../src/zoom/focus-path";
+import type { ZoomScene } from "../../src/zoom/scene";
+import type { ZoomNode } from "../../src/zoom/types";
+
+function node(id: string, children: string[]): ZoomNode {
+ return {
+ id,
+ parent_id: null,
+ level: 0,
+ kind: "folder",
+ name: id,
+ path: id,
+ children,
+ importance: 0.5,
+ sibling_rank: 1,
+ metrics: {
+ file_count: 0,
+ descendant_count: 0,
+ hotspot_count: 0,
+ dead_count: 0,
+ entry_point_count: 0,
+ on_flow_count: 0,
+ },
+ layout: null,
+ summary: "",
+ language: null,
+ is_entry_point: false,
+ is_hotspot: false,
+ is_dead: false,
+ is_test: false,
+ on_flow: false,
+ health_score: null,
+ };
+}
+
+function scene(): ZoomScene {
+ const nodes = new Map<string, ZoomNode>([
+ ["root", node("root", ["a", "b"])],
+ ["a", node("a", ["a1"])],
+ ["b", node("b", [])],
+ ["a1", node("a1", [])],
+ ]);
+ const worldRects = new Map<string, Rect>([
+ ["root", { x: 0, y: 0, w: 1, h: 1 }],
+ ["a", { x: 0, y: 0, w: 0.5, h: 1 }],
+ ["b", { x: 0.5, y: 0, w: 0.5, h: 1 }],
+ ["a1", { x: 0, y: 0, w: 0.5, h: 0.5 }],
+ ]);
+ return { rootId: "root", nodes, worldRects, relationsByParent: new Map(), laidOutCount: 4 };
+}
+
+const VP = { w: 1000, h: 1000 };
+
+describe("focusChain", () => {
+ it("stays at the root until a child fills enough of the viewport", () => {
+ // centre inside a, but a only spans 0.5*1000 = 500px < 0.62*1000 -> not entered
+ const chain = focusChain(scene(), { cx: 0.25, cy: 0.5, scale: 1000 }, VP);
+ expect(chain.map((n) => n.id)).toEqual(["root"]);
+ });
+
+ it("descends into the entered subtree", () => {
+ // scale 2000 -> a spans 1000px (entered), a1 spans 1000px (entered)
+ const chain = focusChain(scene(), { cx: 0.25, cy: 0.25, scale: 2000 }, VP);
+ expect(chain.map((n) => n.id)).toEqual(["root", "a", "a1"]);
+ });
+
+ it("does not descend into a sibling the centre is not over", () => {
+ const chain = focusChain(scene(), { cx: 0.75, cy: 0.5, scale: 2000 }, VP);
+ expect(chain.map((n) => n.id)).toEqual(["root", "b"]);
+ });
+});
+
+describe("focusId", () => {
+ it("returns the deepest entered node id", () => {
+ expect(focusId(scene(), { cx: 0.25, cy: 0.25, scale: 2000 }, VP)).toBe("a1");
+ expect(focusId(scene(), { cx: 0.25, cy: 0.5, scale: 1000 }, VP)).toBe("root");
+ });
+});
diff --git a/packages/ui/__tests__/zoom/geometry.test.ts b/packages/ui/__tests__/zoom/geometry.test.ts
new file mode 100644
index 000000000..957dff796
--- /dev/null
+++ b/packages/ui/__tests__/zoom/geometry.test.ts
@@ -0,0 +1,124 @@
+import { describe, it, expect } from "vitest";
+import {
+ composeRect,
+ computeWorldRects,
+ perimeterPoint,
+ rectContains,
+} from "../../src/zoom/geometry";
+import type { ZoomNode } from "../../src/zoom/types";
+
+function node(id: string, parent: string | null, children: string[], layout: ZoomNode["layout"]): ZoomNode {
+ return {
+ id,
+ parent_id: parent,
+ level: 0,
+ kind: "folder",
+ name: id,
+ path: id,
+ children,
+ importance: 0.5,
+ sibling_rank: 1,
+ metrics: {
+ file_count: 0,
+ descendant_count: 0,
+ hotspot_count: 0,
+ dead_count: 0,
+ entry_point_count: 0,
+ on_flow_count: 0,
+ },
+ layout,
+ summary: "",
+ language: null,
+ is_entry_point: false,
+ is_hotspot: false,
+ is_dead: false,
+ is_test: false,
+ on_flow: false,
+ health_score: null,
+ };
+}
+
+describe("composeRect", () => {
+ it("nests a child's [0,1] rect inside its parent's absolute rect", () => {
+ const parent = { x: 0.2, y: 0.4, w: 0.4, h: 0.2 };
+ const child = composeRect(parent, { x: 0.5, y: 0, w: 0.5, h: 1 });
+ expect(child).toEqual({ x: 0.4, y: 0.4, w: 0.2, h: 0.2 });
+ });
+});
+
+describe("computeWorldRects", () => {
+ it("lays children out within their parent's rect, recursively", () => {
+ const nodes = new Map<string, ZoomNode>([
+ ["root", node("root", null, ["a", "b"], null)],
+ ["a", node("a", "root", ["a1"], null)],
+ ["b", node("b", "root", [], null)],
+ ["a1", node("a1", "a", [], null)],
+ ]);
+ const rects = computeWorldRects(nodes, "root");
+ expect(rects.get("root")).toEqual({ x: 0, y: 0, w: 1, h: 1 });
+ for (const id of ["a", "b", "a1"]) expect(rects.has(id)).toBe(true);
+
+ const within = (child: string, parent: string) => {
+ const c = rects.get(child)!;
+ const p = rects.get(parent)!;
+ const eps = 1e-9;
+ expect(c.x).toBeGreaterThanOrEqual(p.x - eps);
+ expect(c.y).toBeGreaterThanOrEqual(p.y - eps);
+ expect(c.x + c.w).toBeLessThanOrEqual(p.x + p.w + eps);
+ expect(c.y + c.h).toBeLessThanOrEqual(p.y + p.h + eps);
+ };
+ within("a", "root");
+ within("b", "root");
+ within("a1", "a"); // grid layout composes through every depth
+ });
+
+ it("lays out a node even when the backend gave it no layout rect", () => {
+ const nodes = new Map<string, ZoomNode>([
+ ["root", node("root", null, ["a", "ghost"], null)],
+ ["a", node("a", "root", [], null)], // null backend layout -> still placed
+ ["orphan", node("orphan", "nope", [], null)],
+ ]);
+ const rects = computeWorldRects(nodes, "root");
+ expect(rects.has("a")).toBe(true); // layout is computed client-side now
+ expect(rects.has("ghost")).toBe(false); // referenced but absent
+ expect(rects.has("orphan")).toBe(false); // not reachable from root
+ });
+
+ it("returns empty when the root is missing", () => {
+ expect(computeWorldRects(new Map(), "root").size).toBe(0);
+ });
+});
+
+describe("perimeterPoint", () => {
+ const r = { x: 0, y: 0, w: 100, h: 50 }; // centre (50,25)
+ it("exits the right edge toward a point to the right", () => {
+ const p = perimeterPoint(r, 1000, 25);
+ expect(p).toEqual({ x: 100, y: 25 });
+ });
+ it("exits the top edge toward a point straight above", () => {
+ const p = perimeterPoint(r, 50, -1000);
+ expect(p).toEqual({ x: 50, y: 0 });
+ });
+ it("returns the centre when the target coincides with it", () => {
+ expect(perimeterPoint(r, 50, 25)).toEqual({ x: 50, y: 25 });
+ });
+ it("clamps a diagonal to the nearer pair of edges", () => {
+ // direction (1,1): tx = 50/1=50, ty = 25/1=25 -> t=25 -> hits top edge first
+ const p = perimeterPoint(r, 150, 125);
+ expect(p.y).toBe(50); // bottom edge (y grows down)
+ expect(p.x).toBe(75);
+ });
+});
+
+describe("rectContains", () => {
+ const r = { x: 10, y: 20, w: 100, h: 50 };
+ it("includes interior and edges", () => {
+ expect(rectContains(r, 10, 20)).toBe(true);
+ expect(rectContains(r, 110, 70)).toBe(true);
+ expect(rectContains(r, 60, 45)).toBe(true);
+ });
+ it("excludes outside points", () => {
+ expect(rectContains(r, 9, 45)).toBe(false);
+ expect(rectContains(r, 60, 71)).toBe(false);
+ });
+});
diff --git a/packages/ui/__tests__/zoom/layout.test.ts b/packages/ui/__tests__/zoom/layout.test.ts
new file mode 100644
index 000000000..997b66d46
--- /dev/null
+++ b/packages/ui/__tests__/zoom/layout.test.ts
@@ -0,0 +1,117 @@
+import { describe, it, expect } from "vitest";
+import type { Rect } from "../../src/zoom/camera";
+import { CARD_ASPECT } from "../../src/zoom/constants";
+import { gridDimensions, packLayout, type LayoutChild } from "../../src/zoom/layout";
+
+function child(id: string, rank: number, importance = 0.5): LayoutChild {
+ return { id, sibling_rank: rank, importance };
+}
+
+const area = (r: Rect): number => r.w * r.h;
+
+/** Do two rects overlap (strictly, ignoring shared edges)? */
+function overlaps(a: Rect, b: Rect): boolean {
+ return a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
+}
+
+describe("gridDimensions", () => {
+ it("is a single cell for one child", () => {
+ expect(gridDimensions(1, 1)).toEqual({ cols: 1, rows: 1 });
+ });
+ it("is square-ish for a square parent", () => {
+ expect(gridDimensions(4, 1)).toEqual({ cols: 2, rows: 2 });
+ expect(gridDimensions(9, 1)).toEqual({ cols: 3, rows: 3 });
+ });
+ it("stacks vertically in a tall parent", () => {
+ expect(gridDimensions(2, 0.25)).toEqual({ cols: 1, rows: 2 });
+ });
+ it("spreads horizontally in a wide parent", () => {
+ expect(gridDimensions(2, 4)).toEqual({ cols: 2, rows: 1 });
+ });
+ it("is empty for zero children", () => {
+ expect(gridDimensions(0, 1)).toEqual({ cols: 0, rows: 0 });
+ });
+});
+
+describe("packLayout", () => {
+ it("is empty for no children", () => {
+ expect(packLayout([], 1).size).toBe(0);
+ });
+
+ it("sizes cards by importance (more important = larger)", () => {
+ const kids = [child("hi", 1, 0.9), child("mid", 2, 0.5), child("lo", 3, 0.1)];
+ const r = packLayout(kids, 1);
+ expect(area(r.get("hi")!)).toBeGreaterThan(area(r.get("mid")!));
+ expect(area(r.get("mid")!)).toBeGreaterThan(area(r.get("lo")!));
+ });
+
+ it("gives every card the same size when importance is uniform", () => {
+ const kids = [child("a", 1, 0.5), child("b", 2, 0.5), child("c", 3, 0.5)];
+ const r = packLayout(kids, 1);
+ const w = r.get("a")!.w;
+ expect(r.get("b")!.w).toBeCloseTo(w, 9);
+ expect(r.get("c")!.w).toBeCloseTo(w, 9);
+ });
+
+ it("places the most important child in the top row and largest", () => {
+ const kids = [child("low", 4, 0.1), child("top", 1, 0.9), child("mid", 2, 0.5)];
+ const r = packLayout(kids, 1);
+ const top = r.get("top")!;
+ // Rows are centred (so left edges stagger), but the most important card is
+ // always in the top row and the biggest.
+ for (const id of ["low", "mid"]) {
+ expect(top.y).toBeLessThanOrEqual(r.get(id)!.y + 1e-9);
+ expect(area(top)).toBeGreaterThan(area(r.get(id)!));
+ }
+ });
+
+ it("keeps every card a consistent landscape aspect", () => {
+ const kids = Array.from({ length: 7 }, (_, i) => child(`n${i}`, i + 1, (i + 1) / 7));
+ const ratios = [...packLayout(kids, 1.2).values()].map((r) => r.w / r.h);
+ for (const ratio of ratios) expect(ratio).toBeCloseTo(ratios[0]!, 6);
+ });
+
+ it("cancels the parent stretch so on-screen aspect is depth-stable", () => {
+ // Cards are sized in local space; composeRect later re-stretches width by the
+ // parent's world width and height by its world height. Emulate a parent rect
+ // of `{ w: parentAspect, h: 1 }` and confirm every card lands back at
+ // CARD_ASPECT for a range of parent shapes, so nesting cannot compound the
+ // stretch into an unreadable strip (the depth-7 sliver bug).
+ const kids = Array.from({ length: 5 }, (_, i) => child(`n${i}`, i + 1, (i + 1) / 5));
+ for (const parentAspect of [1, 1.5, 3, 6]) {
+ for (const r of packLayout(kids, parentAspect).values()) {
+ const onScreen = (r.w * parentAspect) / r.h; // composeRect re-applies parentAspect
+ expect(onScreen).toBeCloseTo(CARD_ASPECT, 5);
+ }
+ }
+ });
+
+ it("never overlaps siblings and is deterministic", () => {
+ const kids = Array.from({ length: 17 }, (_, i) => child(`n${i}`, i + 1, ((i * 7) % 17) / 17));
+ const a = packLayout(kids, 1.3);
+ const b = packLayout(kids, 1.3);
+ expect([...a.entries()]).toEqual([...b.entries()]);
+ const rects = [...a.values()];
+ for (let i = 0; i < rects.length; i++) {
+ for (let j = i + 1; j < rects.length; j++) {
+ expect(overlaps(rects[i]!, rects[j]!)).toBe(false);
+ }
+ }
+ });
+
+ it("keeps every card inside the unit parent box", () => {
+ const kids = Array.from({ length: 11 }, (_, i) => child(`n${i}`, i + 1, (i % 4) / 4));
+ for (const r of packLayout(kids, 2).values()) {
+ expect(r.x).toBeGreaterThanOrEqual(-1e-9);
+ expect(r.y).toBeGreaterThanOrEqual(-1e-9);
+ expect(r.x + r.w).toBeLessThanOrEqual(1 + 1e-9);
+ expect(r.y + r.h).toBeLessThanOrEqual(1 + 1e-9);
+ }
+ });
+
+ it("gives a lone child the full parent width", () => {
+ const r = packLayout([child("only", 1, 0.5)], 1).get("only")!;
+ expect(r.w).toBeCloseTo(1, 6);
+ expect(r.x).toBeCloseTo(0, 6);
+ });
+});
diff --git a/packages/ui/__tests__/zoom/zoom-transition.test.ts b/packages/ui/__tests__/zoom/zoom-transition.test.ts
new file mode 100644
index 000000000..4ed1a3d1e
--- /dev/null
+++ b/packages/ui/__tests__/zoom/zoom-transition.test.ts
@@ -0,0 +1,68 @@
+import { describe, it, expect } from "vitest";
+import {
+ expandThresholds,
+ fadeAlphas,
+ leafCapScale,
+ transitionT,
+} from "../../src/zoom/zoom-transition";
+
+describe("expandThresholds", () => {
+ it("scales with canvas width within bounds", () => {
+ const t = expandThresholds(1440);
+ expect(t.start).toBeCloseTo(360); // 1440 * 0.25
+ expect(t.end).toBeCloseTo(576); // 1440 * 0.40
+ expect(t.end).toBeGreaterThan(t.start);
+ });
+
+ it("clamps tiny and huge canvases and stays non-degenerate", () => {
+ const small = expandThresholds(100);
+ expect(small.start).toBe(80); // START_MIN_PX
+ expect(small.end).toBe(200); // END_MIN_PX
+ const huge = expandThresholds(10000);
+ expect(huge.start).toBe(450); // START_MAX_PX
+ expect(huge.end).toBe(640); // END_MAX_PX
+ expect(huge.end).toBeGreaterThan(huge.start);
+ });
+});
+
+describe("transitionT", () => {
+ const th = { start: 200, end: 400 };
+ it("is 0 below start and 1 above end", () => {
+ expect(transitionT(150, th, true)).toBe(0);
+ expect(transitionT(500, th, true)).toBe(1);
+ });
+ it("interpolates linearly between", () => {
+ expect(transitionT(300, th, true)).toBeCloseTo(0.5);
+ expect(transitionT(250, th, true)).toBeCloseTo(0.25);
+ });
+ it("is always 0 for leaves regardless of width", () => {
+ expect(transitionT(10000, th, false)).toBe(0);
+ });
+});
+
+describe("fadeAlphas", () => {
+ it("cross-fades body out and children in, conserving inherited alpha", () => {
+ const a = fadeAlphas(1, 0.25);
+ expect(a.body).toBeCloseTo(0.75);
+ expect(a.child).toBeCloseTo(0.25);
+ expect(a.body + a.child).toBeCloseTo(1);
+ });
+ it("scales by the inherited alpha", () => {
+ const a = fadeAlphas(0.5, 0.5);
+ expect(a.body).toBeCloseTo(0.25);
+ expect(a.child).toBeCloseTo(0.25);
+ });
+});
+
+describe("leafCapScale", () => {
+ const th = { start: 200, end: 400 };
+ it("is 1 for nodes with children (they reveal children instead)", () => {
+ expect(leafCapScale(5000, th, true)).toBe(1);
+ });
+ it("is 1 for a leaf still under the end threshold", () => {
+ expect(leafCapScale(300, th, false)).toBe(1);
+ });
+ it("shrinks an over-grown leaf back to the end size", () => {
+ expect(leafCapScale(800, th, false)).toBeCloseTo(0.5); // 400 / 800
+ });
+});
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 0ccecaa08..522d7c9d5 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -86,6 +86,8 @@
"./onboarding/*": "./src/onboarding/*.tsx",
"./present": "./src/present/index.ts",
"./present/*": "./src/present/*.tsx",
+ "./zoom": "./src/zoom/index.ts",
+ "./zoom/*": "./src/zoom/*.tsx",
"./settings": "./src/settings/index.ts",
"./settings/*": "./src/settings/*.tsx",
"./shared": "./src/shared/index.ts",
diff --git a/packages/ui/src/zoom/ZoomCanvas.tsx b/packages/ui/src/zoom/ZoomCanvas.tsx
new file mode 100644
index 000000000..9a6a68c7f
--- /dev/null
+++ b/packages/ui/src/zoom/ZoomCanvas.tsx
@@ -0,0 +1,390 @@
+"use client";
+
+/**
+ * React host for the continuous-zoom canvas. Owns the `<canvas>`, the
+ * `ZoomRenderer` instance, and the interaction layer: wheel-zoom, drag-pan,
+ * keyboard pan/zoom, hover popover and click-to-select. It is a reusable
+ * primitive: navigation chrome (breadcrumb, search box, detail panel, URL sync)
+ * lives in the host page and drives the canvas through the imperative handle
+ * (`flyTo`, `reset`) and the `onFocusChange` callback, so web and hosted share
+ * the exact same canvas.
+ */
+
+import {
+ forwardRef,
+ useEffect,
+ useImperativeHandle,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { type Camera, clampCamera, fitRoot, panByScreen, zoomAbout } from "./camera";
+import { type FlyOptions, ZoomRenderer, type FrameStats } from "./renderer";
+import { buildScene } from "./scene";
+import { resolveZoomPalette } from "./theme";
+import type { ZoomMap, ZoomNode } from "./types";
+import { useThemeVersion } from "../shared/use-theme-tokens";
+
+export interface ZoomCanvasHandle {
+ /** Fly the camera to frame a node by id. Returns false if it is not laid out. */
+ flyTo: (id: string, opts?: FlyOptions) => boolean;
+ /** Fly back to the whole-system overview. */
+ reset: (opts?: FlyOptions) => void;
+}
+
+export interface ZoomCanvasProps {
+ data: ZoomMap;
+ className?: string;
+ onSelect?: (node: ZoomNode | null) => void;
+ /** Fires with the root -> focus chain whenever the focused node changes. */
+ onFocusChange?: (chain: ZoomNode[]) => void;
+ /** Node id to jump to on first render (e.g. from a shared URL). */
+ initialFocusId?: string;
+ /** Show a small live frame-stat overlay (drawn/culled/fps). Dev aid. */
+ showStats?: boolean;
+}
+
+const WHEEL_ZOOM_RATE = 0.0015;
+const CLICK_SLOP_PX = 4;
+const KEY_PAN_PX = 80;
+const KEY_ZOOM_FACTOR = 1.35;
+
+interface HoverState {
+ node: ZoomNode;
+ sx: number;
+ sy: number;
+}
+
+function usePrefersReducedMotion(): boolean {
+ const [reduced, setReduced] = useState(false);
+ useEffect(() => {
+ if (typeof window === "undefined" || !window.matchMedia) return;
+ const mq = window.matchMedia("(prefers-reduced-motion: reduce)");
+ setReduced(mq.matches);
+ const onChange = () => setReduced(mq.matches);
+ mq.addEventListener("change", onChange);
+ return () => mq.removeEventListener("change", onChange);
+ }, []);
+ return reduced;
+}
+
+export const ZoomCanvas = forwardRef<ZoomCanvasHandle, ZoomCanvasProps>(function ZoomCanvas(
+ { data, className, onSelect, onFocusChange, initialFocusId, showStats },
+ ref,
+) {
+ const canvasRef = useRef<HTMLCanvasElement | null>(null);
+ const rendererRef = useRef<ZoomRenderer | null>(null);
+ const themeVersion = useThemeVersion();
+ const reducedMotion = usePrefersReducedMotion();
+ const reducedRef = useRef(reducedMotion);
+ reducedRef.current = reducedMotion;
+
+ const scene = useMemo(() => buildScene(data), [data]);
+ // Node index is derived from the data (stable identity) so the interaction
+ // listeners are not torn down when the scene is rebuilt.
+ const nodeById = useMemo(
+ () => new Map(data.nodes.map((n) => [n.id, n] as const)),
+ [data],
+ );
+
+ const [hover, setHover] = useState<HoverState | null>(null);
+ const [stats, setStats] = useState<FrameStats | null>(null);
+
+ // Keep the latest callbacks in refs so the renderer and the native event
+ // listeners (each created once) always call the current closure without being
+ // torn down and recreated on every render.
+ const onFocusRef = useRef(onFocusChange);
+ onFocusRef.current = onFocusChange;
+ const onSelectRef = useRef(onSelect);
+ onSelectRef.current = onSelect;
+ const onStatsRef = useRef<((s: FrameStats) => void) | undefined>(undefined);
+ onStatsRef.current = showStats ? setStats : undefined;
+
+ useImperativeHandle(
+ ref,
+ (): ZoomCanvasHandle => ({
+ flyTo: (id, opts) =>
+ rendererRef.current?.frameNode(id, { reducedMotion: reducedRef.current, ...opts }) ?? false,
+ reset: (opts) => {
+ const r = rendererRef.current;
+ if (!r) return;
+ r.animateTo(fitRoot(r.getViewport()), { reducedMotion: reducedRef.current, ...opts });
+ },
+ }),
+ [],
+ );
+
+ // Create the renderer once the canvas mounts.
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (!canvas) return;
+ const renderer = new ZoomRenderer({
+ canvas,
+ palette: resolveZoomPalette(),
+ onStats: (s) => onStatsRef.current?.(s),
+ onFocus: (chain) => onFocusRef.current?.(chain),
+ });
+ rendererRef.current = renderer;
+
+ const resizeObs = new ResizeObserver(() => renderer.resize());
+ resizeObs.observe(canvas);
+
+ return () => {
+ resizeObs.disconnect();
+ renderer.destroy();
+ rendererRef.current = null;
+ };
+ }, []);
+
+ // Feed the scene + repaint on data change.
+ useEffect(() => {
+ rendererRef.current?.setScene(scene);
+ }, [scene]);
+
+ // One-shot: jump to the URL-provided focus node once the canvas has done its
+ // initial fit (it needs a real viewport size before a node rect can be framed).
+ const initialAppliedRef = useRef(false);
+ useEffect(() => {
+ if (!initialFocusId || initialAppliedRef.current) return;
+ let raf = 0;
+ const tryApply = () => {
+ const r = rendererRef.current;
+ if (r?.isFramed()) {
+ if (r.frameNode(initialFocusId, { reducedMotion: true })) initialAppliedRef.current = true;
+ } else {
+ raf = requestAnimationFrame(tryApply);
+ }
+ };
+ raf = requestAnimationFrame(tryApply);
+ return () => cancelAnimationFrame(raf);
+ }, [initialFocusId, scene]);
+
+ // Re-resolve theme colors on light/dark switch.
+ useEffect(() => {
+ rendererRef.current?.setPalette(resolveZoomPalette());
+ }, [themeVersion]);
+
+ // Interaction: wheel-zoom + drag-pan + hover + click + keyboard. Native
+ // listeners so we can call preventDefault on wheel (React onWheel is passive).
+ // Handlers read `rendererRef.current` live (never a captured instance) so they
+ // stay correct if the renderer is recreated, and reset cleanly on pointercancel.
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (!canvas) return;
+
+ const localPoint = (e: { clientX: number; clientY: number }) => {
+ const rect = canvas.getBoundingClientRect();
+ return { sx: e.clientX - rect.left, sy: e.clientY - rect.top };
+ };
+
+ let dragging = false;
+ let moved = 0;
+ let last = { x: 0, y: 0 };
+
+ const endDrag = (e: PointerEvent) => {
+ dragging = false;
+ canvas.style.cursor = "grab";
+ if (canvas.hasPointerCapture(e.pointerId)) canvas.releasePointerCapture(e.pointerId);
+ };
+
+ const onWheel = (e: WheelEvent) => {
+ e.preventDefault();
+ const renderer = rendererRef.current;
+ if (!renderer) return;
+ const { sx, sy } = localPoint(e);
+ const factor = Math.exp(-e.deltaY * WHEEL_ZOOM_RATE);
+ const next = clampCamera(zoomAbout(renderer.getCamera(), renderer.getViewport(), sx, sy, factor));
+ renderer.setCamera(next);
+ };
+
+ const onPointerDown = (e: PointerEvent) => {
+ dragging = true;
+ moved = 0;
+ last = { x: e.clientX, y: e.clientY };
+ canvas.setPointerCapture(e.pointerId);
+ canvas.style.cursor = "grabbing";
+ setHover(null);
+ rendererRef.current?.setHovered(null);
+ };
+
+ const onPointerMove = (e: PointerEvent) => {
+ const renderer = rendererRef.current;
+ if (!renderer) return;
+ if (dragging) {
+ const dx = e.clientX - last.x;
+ const dy = e.clientY - last.y;
+ moved += Math.abs(dx) + Math.abs(dy);
+ last = { x: e.clientX, y: e.clientY };
+ const cam: Camera = clampCamera(panByScreen(renderer.getCamera(), dx, dy));
+ renderer.setCamera(cam);
+ renderer.markPanFrame();
+ return;
+ }
+ const { sx, sy } = localPoint(e);
+ const id = renderer.pick(sx, sy);
+ renderer.setHovered(id);
+ const node = id ? nodeById.get(id) : undefined;
+ setHover(node ? { node, sx, sy } : null);
+ canvas.style.cursor = node ? "pointer" : "grab";
+ };
+
+ const selectAt = (sx: number, sy: number) => {
+ const renderer = rendererRef.current;
+ if (!renderer) return;
+ const id = renderer.pick(sx, sy);
+ const node = id ? (nodeById.get(id) ?? null) : null;
+ renderer.setSelected(node?.id ?? null);
+ onSelectRef.current?.(node);
+ };
+
+ const onPointerUp = (e: PointerEvent) => {
+ if (dragging && moved <= CLICK_SLOP_PX) {
+ const { sx, sy } = localPoint(e);
+ selectAt(sx, sy);
+ }
+ endDrag(e);
+ };
+
+ const onPointerCancel = (e: PointerEvent) => endDrag(e);
+ const onPointerLeave = () => {
+ setHover(null);
+ rendererRef.current?.setHovered(null);
+ };
+
+ const onDoubleClick = (e: MouseEvent) => {
+ const renderer = rendererRef.current;
+ if (!renderer) return;
+ const { sx, sy } = localPoint(e);
+ const id = renderer.pick(sx, sy);
+ // Double-click dives into whatever card is under the cursor. This is the
+ // intuitive "zoom into this" gesture (single click just selects); empty
+ // space is ignored so a stray double-click never yanks the camera.
+ if (id) renderer.frameNode(id, { reducedMotion: reducedRef.current });
+ };
+
+ const onKeyDown = (e: KeyboardEvent) => {
+ const renderer = rendererRef.current;
+ if (!renderer) return;
+ const vp = renderer.getViewport();
+ const cam = renderer.getCamera();
+ switch (e.key) {
+ case "ArrowLeft":
+ renderer.setCamera(clampCamera(panByScreen(cam, KEY_PAN_PX, 0)));
+ break;
+ case "ArrowRight":
+ renderer.setCamera(clampCamera(panByScreen(cam, -KEY_PAN_PX, 0)));
+ break;
+ case "ArrowUp":
+ renderer.setCamera(clampCamera(panByScreen(cam, 0, KEY_PAN_PX)));
+ break;
+ case "ArrowDown":
+ renderer.setCamera(clampCamera(panByScreen(cam, 0, -KEY_PAN_PX)));
+ break;
+ case "+":
+ case "=":
+ renderer.setCamera(clampCamera(zoomAbout(cam, vp, vp.w / 2, vp.h / 2, KEY_ZOOM_FACTOR)));
+ break;
+ case "-":
+ case "_":
+ renderer.setCamera(clampCamera(zoomAbout(cam, vp, vp.w / 2, vp.h / 2, 1 / KEY_ZOOM_FACTOR)));
+ break;
+ case "Enter":
+ selectAt(vp.w / 2, vp.h / 2);
+ break;
+ case "Escape":
+ renderer.setSelected(null);
+ onSelectRef.current?.(null);
+ setHover(null);
+ return; // do not preventDefault on Escape
+ default:
+ return;
+ }
+ e.preventDefault();
+ };
+
+ canvas.addEventListener("wheel", onWheel, { passive: false });
+ canvas.addEventListener("pointerdown", onPointerDown);
+ canvas.addEventListener("pointermove", onPointerMove);
+ canvas.addEventListener("pointerup", onPointerUp);
+ canvas.addEventListener("pointercancel", onPointerCancel);
+ canvas.addEventListener("pointerleave", onPointerLeave);
+ canvas.addEventListener("dblclick", onDoubleClick);
+ canvas.addEventListener("keydown", onKeyDown);
+ return () => {
+ canvas.removeEventListener("wheel", onWheel);
+ canvas.removeEventListener("pointerdown", onPointerDown);
+ canvas.removeEventListener("pointermove", onPointerMove);
+ canvas.removeEventListener("pointerup", onPointerUp);
+ canvas.removeEventListener("pointercancel", onPointerCancel);
+ canvas.removeEventListener("pointerleave", onPointerLeave);
+ canvas.removeEventListener("dblclick", onDoubleClick);
+ canvas.removeEventListener("keydown", onKeyDown);
+ };
+ }, [nodeById]);
+
+ return (
+ <div className={`relative h-full w-full overflow-hidden ${className ?? ""}`}>
+ <canvas
+ ref={canvasRef}
+ tabIndex={0}
+ role="application"
+ aria-label="Zoomable system map. Drag to pan, scroll to zoom, double-click a card to dive into it, arrow keys to pan, plus and minus to zoom, Enter to open the centre node."
+ className="h-full w-full touch-none outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ style={{ cursor: "grab" }}
+ />
+ {hover && <HoverCard hover={hover} canvas={canvasRef.current} />}
+ {showStats && stats && <StatsOverlay stats={stats} laidOut={scene.laidOutCount} />}
+ </div>
+ );
+});
+
+const HOVER_KIND_LABEL: Record<ZoomNode["kind"], string> = {
+ system: "System",
+ layer: "Layer",
+ group: "Group",
+ folder: "Folder",
+ file: "File",
+};
+
+/**
+ * A deliberately light tooltip: kind, name, path and a one-line summary. The
+ * full metric breakdown lives in the side panel (open on click), so the hover
+ * stays calm and premium instead of dumping numbers.
+ */
+function HoverCard({ hover, canvas }: { hover: HoverState; canvas: HTMLCanvasElement | null }) {
+ const { node } = hover;
+ // Flip the card toward the interior when the cursor is near the right/bottom
+ // edge, so it never spills off-canvas (N2).
+ const w = canvas?.clientWidth ?? 0;
+ const h = canvas?.clientHeight ?? 0;
+ const flipX = w > 0 && hover.sx > w * 0.66;
+ const flipY = h > 0 && hover.sy > h * 0.66;
+ const tx = flipX ? "calc(-100% - 14px)" : "14px";
+ const ty = flipY ? "calc(-100% - 14px)" : "14px";
+ return (
+ <div
+ className="pointer-events-none absolute z-10 max-w-[16rem] rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3 py-2 text-xs shadow-xl"
+ style={{ left: hover.sx, top: hover.sy, transform: `translate(${tx}, ${ty})` }}
+ >
+ <div className="text-[10px] font-medium uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ {HOVER_KIND_LABEL[node.kind]}
+ </div>
+ <div className="mt-0.5 font-semibold text-[var(--color-text-primary)]">{node.name}</div>
+ {node.path && node.path !== node.name && (
+ <div className="truncate text-[var(--color-text-tertiary)]">{node.path}</div>
+ )}
+ {node.summary && (
+ <div className="mt-1 line-clamp-2 text-[var(--color-text-secondary)]">{node.summary}</div>
+ )}
+ </div>
+ );
+}
+
+function StatsOverlay({ stats, laidOut }: { stats: FrameStats; laidOut: number }) {
+ return (
+ <div className="pointer-events-none absolute bottom-2 left-2 z-10 rounded bg-[var(--color-bg-overlay)] px-2 py-1 font-mono text-[10px] text-[var(--color-text-secondary)]">
+ {stats.drawn} drawn · {stats.culled} culled · depth {stats.maxDepthDrawn} ·{" "}
+ {stats.frameMs.toFixed(2)}ms · {laidOut} nodes
+ </div>
+ );
+}
diff --git a/packages/ui/src/zoom/camera-anim.ts b/packages/ui/src/zoom/camera-anim.ts
new file mode 100644
index 000000000..2e5739a89
--- /dev/null
+++ b/packages/ui/src/zoom/camera-anim.ts
@@ -0,0 +1,57 @@
+/**
+ * Pure camera interpolation for fly-to-node, breadcrumb jumps and the tour.
+ * Browser-free and unit-testable.
+ *
+ * A fly tweens the centre linearly in world space and the scale *geometrically*
+ * (constant zoom-rate per unit time), which reads as a smooth, natural zoom
+ * rather than a linear scale ramp that lurches at the end. Easing shapes the
+ * progress so the motion accelerates out and settles in.
+ */
+
+import type { Camera } from "./camera";
+
+export function clamp01(t: number): number {
+ return t < 0 ? 0 : t > 1 ? 1 : t;
+}
+
+export function easeInOutCubic(t: number): number {
+ const c = clamp01(t);
+ return c < 0.5 ? 4 * c * c * c : 1 - (-2 * c + 2) ** 3 / 2;
+}
+
+function lerp(a: number, b: number, t: number): number {
+ return a + (b - a) * t;
+}
+
+/**
+ * Camera at progress `t` in `[0,1]` along the fly from `from` to `to`. Centre
+ * lerps linearly; scale interpolates geometrically so equal time steps cover
+ * equal zoom ratios. `t` is eased internally, so callers pass raw linear
+ * progress (elapsed / duration).
+ */
+export function interpolateCamera(from: Camera, to: Camera, t: number): Camera {
+ const e = easeInOutCubic(t);
+ const fromScale = from.scale > 0 ? from.scale : 1e-6;
+ const ratio = to.scale > 0 ? to.scale / fromScale : 1;
+ return {
+ cx: lerp(from.cx, to.cx, e),
+ cy: lerp(from.cy, to.cy, e),
+ scale: fromScale * ratio ** e,
+ };
+}
+
+/**
+ * A fly duration that scales with how far the camera must travel: a small nudge
+ * is quick, a cross-system jump takes longer, both clamped to a comfortable
+ * range. Distance blends the centre move (in screen-ish units at the start
+ * scale) with the zoom magnitude (log scale ratio) so a pure deep-zoom still
+ * gets time to breathe.
+ */
+export function flyDuration(from: Camera, to: Camera, minMs = 260, maxMs = 720): number {
+ const dCentre = Math.hypot(to.cx - from.cx, to.cy - from.cy) * from.scale;
+ const fromScale = from.scale > 0 ? from.scale : 1e-6;
+ const toScale = to.scale > 0 ? to.scale : 1e-6;
+ const dZoom = Math.abs(Math.log(toScale / fromScale));
+ const travel = Math.min(1, dCentre / 1200) + Math.min(1, dZoom / 6);
+ return Math.round(minMs + (maxMs - minMs) * Math.min(1, travel / 2));
+}
diff --git a/packages/ui/src/zoom/camera.ts b/packages/ui/src/zoom/camera.ts
new file mode 100644
index 000000000..ef5b6f904
--- /dev/null
+++ b/packages/ui/src/zoom/camera.ts
@@ -0,0 +1,141 @@
+/**
+ * Pure 2D camera for the zoom canvas. Browser-free and fully unit-testable.
+ *
+ * The camera is **center-anchored**: it stores the world point shown at the
+ * viewport centre (`cx`, `cy`) plus a `scale` (screen pixels per world unit).
+ * This is itself the float-precision "rebase": because the visible centre is
+ * always inside the root's `[0,1]` box, `cx`/`cy` stay `O(1)` no matter how far
+ * you zoom in, so the world->screen subtraction `(wx - cx)` is between two
+ * nearby `O(1)` doubles and keeps its relative precision. Only `scale` grows,
+ * and a single float carries it exactly enough for any realistic depth.
+ *
+ * World space: the system root occupies the unit square `[0,1] x [0,1]`. A
+ * node's absolute world rect is its layout rect composed down the tree (see
+ * `geometry.ts`).
+ */
+
+import { MAX_SCALE, MIN_SCALE } from "./constants";
+
+export interface Camera {
+ /** World x shown at the viewport centre. */
+ cx: number;
+ /** World y shown at the viewport centre. */
+ cy: number;
+ /** Screen pixels per world unit. */
+ scale: number;
+}
+
+export interface Viewport {
+ w: number;
+ h: number;
+}
+
+export interface ScreenPoint {
+ sx: number;
+ sy: number;
+}
+
+export interface WorldPoint {
+ wx: number;
+ wy: number;
+}
+
+export interface Rect {
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+}
+
+export function clampScale(scale: number): number {
+ return Math.min(MAX_SCALE, Math.max(MIN_SCALE, scale));
+}
+
+/** World coordinate -> screen pixel. */
+export function worldToScreen(cam: Camera, vp: Viewport, wx: number, wy: number): ScreenPoint {
+ return {
+ sx: vp.w / 2 + (wx - cam.cx) * cam.scale,
+ sy: vp.h / 2 + (wy - cam.cy) * cam.scale,
+ };
+}
+
+/** Screen pixel -> world coordinate. */
+export function screenToWorld(cam: Camera, vp: Viewport, sx: number, sy: number): WorldPoint {
+ return {
+ wx: cam.cx + (sx - vp.w / 2) / cam.scale,
+ wy: cam.cy + (sy - vp.h / 2) / cam.scale,
+ };
+}
+
+/** Map an absolute world rect to a screen rect. */
+export function worldRectToScreen(cam: Camera, vp: Viewport, rect: Rect): Rect {
+ const tl = worldToScreen(cam, vp, rect.x, rect.y);
+ return {
+ x: tl.sx,
+ y: tl.sy,
+ w: rect.w * cam.scale,
+ h: rect.h * cam.scale,
+ };
+}
+
+/**
+ * Zoom by `factor` about a fixed screen anchor (the world point under the
+ * anchor stays put). `factor > 1` zooms in.
+ */
+export function zoomAbout(
+ cam: Camera,
+ vp: Viewport,
+ anchorSx: number,
+ anchorSy: number,
+ factor: number,
+): Camera {
+ const anchor = screenToWorld(cam, vp, anchorSx, anchorSy);
+ const scale = clampScale(cam.scale * factor);
+ // Solve for the centre that keeps `anchor` under (anchorSx, anchorSy):
+ // anchorSx = vp.w/2 + (anchor.wx - cx') * scale
+ return {
+ cx: anchor.wx - (anchorSx - vp.w / 2) / scale,
+ cy: anchor.wy - (anchorSy - vp.h / 2) / scale,
+ scale,
+ };
+}
+
+/** Pan by a screen-pixel delta (dragging the world with the cursor). */
+export function panByScreen(cam: Camera, dxScreen: number, dyScreen: number): Camera {
+ return {
+ cx: cam.cx - dxScreen / cam.scale,
+ cy: cam.cy - dyScreen / cam.scale,
+ scale: cam.scale,
+ };
+}
+
+/**
+ * Keep the viewport centre within the root box (with a small margin) so the
+ * user cannot lose the graph off-screen. Pure: returns a corrected camera.
+ */
+export function clampCamera(cam: Camera, margin = 0.25): Camera {
+ return {
+ cx: Math.min(1 + margin, Math.max(-margin, cam.cx)),
+ cy: Math.min(1 + margin, Math.max(-margin, cam.cy)),
+ scale: clampScale(cam.scale),
+ };
+}
+
+/**
+ * A camera that fits the unit root box into the viewport with padding. The
+ * shorter viewport axis bounds the scale so the whole square is visible.
+ */
+export function fitRoot(vp: Viewport, padding = 0.9): Camera {
+ const scale = clampScale(Math.min(vp.w, vp.h) * padding);
+ return { cx: 0.5, cy: 0.5, scale };
+}
+
+/**
+ * A camera that frames an absolute world rect, centred, filling `fill` of the
+ * smaller viewport axis. Used by "zoom to node" interactions.
+ */
+export function frameRect(vp: Viewport, rect: Rect, fill = 0.8): Camera {
+ const span = Math.max(rect.w, rect.h, 1e-12);
+ const scale = clampScale((Math.min(vp.w, vp.h) * fill) / span);
+ return { cx: rect.x + rect.w / 2, cy: rect.y + rect.h / 2, scale };
+}
diff --git a/packages/ui/src/zoom/constants.ts b/packages/ui/src/zoom/constants.ts
new file mode 100644
index 000000000..c598281bd
--- /dev/null
+++ b/packages/ui/src/zoom/constants.ts
@@ -0,0 +1,88 @@
+/**
+ * Tunable constants for the continuous-zoom canvas.
+ *
+ * Kept in one browser-free module so the renderer and the pure math share a
+ * single source of truth and the unit tests can assert against them.
+ */
+
+/** Fade thresholds scale with canvas width so the feel is resolution-independent. */
+export const START_FRACTION = 0.25; // fade begins when a node spans this fraction of width
+export const END_FRACTION = 0.4; // fade completes (children fully in) at this fraction
+export const START_MIN_PX = 80;
+export const START_MAX_PX = 450;
+export const END_MIN_PX = 200;
+export const END_MAX_PX = 640;
+
+/** A node narrower than this many screen pixels is not worth drawing. */
+export const MIN_DRAW_PX = 2;
+
+/** Below this inherited alpha a subtree is fully transparent: skip it. */
+export const ALPHA_EPSILON = 0.01;
+
+/** Camera zoom (world units -> screen pixels) is clamped to this range. */
+export const MIN_SCALE = 0.05;
+export const MAX_SCALE = 4_000_000;
+
+/**
+ * Safety ceiling on children drawn per parent. With the uniform grid layout the
+ * cells appear together as the parent grows (no per-frame top-N selection, which
+ * left holes when only the highest-ranked cells of a fixed grid were drawn);
+ * instead every child is laid out and the natural level-of-detail bounds the
+ * live count: a subtree is skipped once it is off-screen (`isOnScreen`) or
+ * sub-pixel (`MIN_DRAW_PX`). This ceiling only bites a pathologically flat
+ * folder (hundreds of immediate children), where the least-important tail is
+ * dropped by `sibling_rank` so the frame stays cheap.
+ */
+export const MAX_CHILDREN_DRAWN = 320;
+
+/** Off-screen culling keeps a margin (in screen px) so panning has no pop-in. */
+export const CULL_MARGIN_PX = 64;
+
+/**
+ * Per-parent masonry pack. Children are sized by importance (bigger = more
+ * central) and row-packed into centred, variable-width rows, so the canvas reads
+ * as an organic architecture map rather than a rigid lattice. Cards keep a fixed
+ * landscape aspect (readable text); only their scale varies. Tuning:
+ * - CARD_ASPECT: width:height of every card.
+ * - PACK_SIZE_MIN/MAX: card height (relative units) for the least / most
+ * important sibling; the ratio sets how dramatic the size variation is.
+ * - PACK_IMPORTANCE_GAMMA: <1 lifts small cards so minor nodes stay readable.
+ * - PACK_GUTTER: whitespace between cards (same relative units); generous, to
+ * give the on-hover relation arrows room to breathe.
+ */
+export const CARD_ASPECT = 1.5;
+export const PACK_SIZE_MIN = 0.58;
+export const PACK_SIZE_MAX = 1.0;
+export const PACK_IMPORTANCE_GAMMA = 0.7;
+export const PACK_GUTTER = 0.3;
+
+/**
+ * Graph-paper line grid painted under the cards (anchored to the camera so it
+ * parallaxes like a real surface, at a fixed screen spacing). Every
+ * `GRID_MAJOR_EVERY`-th line is a firmer "major" line for depth; both stay subtle
+ * via the low alpha of `--color-zoom-grid` / `--color-zoom-grid-strong`.
+ */
+export const GRID_SPACING_PX = 32;
+export const GRID_MAJOR_EVERY = 4;
+
+/**
+ * Relations are revealed on demand, not drawn all at once: only the edges
+ * touching the hovered or selected box appear, so the canvas stays calm and the
+ * arrows you do see are the ones you asked for.
+ */
+export const EDGE_MAX_PER_PARENT = 10; // cap arrows per zoom level (only the strongest incident relations show, keeping it calm)
+export const EDGE_MIN_BOX_PX = 40; // skip edges to boxes smaller than this on screen
+export const ARROW_MIN_BOX_PX = 96; // suppress the arrowhead below this box size
+export const ARROW_SIZE_PX = 7; // arrowhead length in screen px
+export const EDGE_LINE_PX = 1.25; // edge stroke width in screen px
+export const EDGE_FOCUS_ALPHA = 0.95; // relations touching the focused node
+
+/**
+ * Edge-routing tunables. Each connector leaves the source box from the side that
+ * faces the target, curves outward (control points projected along the side
+ * normal so the line bows around intervening boxes), and several edges sharing a
+ * side fan out into distinct slots so they never collapse onto one another.
+ */
+export const EDGE_CONTROL_PROJECTION = 0.55; // bezier control offset as a fraction of the endpoint gap (higher = more bow, edges clear the boxes)
+export const EDGE_SLOT_GAP_FRACTION = 0.26; // slot spacing as a fraction of the box side length (higher = fan spreads wider)
+export const EDGE_MAX_SLOTS = 6; // distinct anchor slots per box side
diff --git a/packages/ui/src/zoom/cull.ts b/packages/ui/src/zoom/cull.ts
new file mode 100644
index 000000000..5a43e1765
--- /dev/null
+++ b/packages/ui/src/zoom/cull.ts
@@ -0,0 +1,41 @@
+/**
+ * Pure viewport culling and level-of-detail. Browser-free.
+ *
+ * These keep the live drawn-node count bounded no matter how large the tree is:
+ * - `isOnScreen` drops subtrees whose screen rect lies outside the viewport.
+ * - `MIN_DRAW_PX` (in the renderer) drops nodes too small to see.
+ * - `selectChildren` is only a safety ceiling for a pathologically flat folder;
+ * normal parents draw all their children and rely on the two gates above.
+ */
+
+import type { Rect, Viewport } from "./camera";
+import { CULL_MARGIN_PX } from "./constants";
+import type { ZoomNode } from "./types";
+
+/** Is any part of a screen rect within the viewport (plus a pan margin)? */
+export function isOnScreen(screenRect: Rect, vp: Viewport, margin = CULL_MARGIN_PX): boolean {
+ return (
+ screenRect.x + screenRect.w > -margin &&
+ screenRect.y + screenRect.h > -margin &&
+ screenRect.x < vp.w + margin &&
+ screenRect.y < vp.h + margin
+ );
+}
+
+/**
+ * Choose which children to draw: the top `cap` by `sibling_rank` (1 = most
+ * important). Pure and deterministic; ties break by id so the selection is
+ * stable frame-to-frame. Returns the ids in their original child order so the
+ * treemap layout (which the renderer reads from each node) still lines up.
+ */
+export function selectChildren(
+ children: readonly ZoomNode[],
+ cap: number,
+): ZoomNode[] {
+ if (children.length <= cap) return [...children];
+ const ranked = [...children].sort(
+ (a, b) => a.sibling_rank - b.sibling_rank || (a.id < b.id ? -1 : 1),
+ );
+ const keep = new Set(ranked.slice(0, cap).map((c) => c.id));
+ return children.filter((c) => keep.has(c.id));
+}
diff --git a/packages/ui/src/zoom/draw-tree.ts b/packages/ui/src/zoom/draw-tree.ts
new file mode 100644
index 000000000..6cf98a8b4
--- /dev/null
+++ b/packages/ui/src/zoom/draw-tree.ts
@@ -0,0 +1,265 @@
+/**
+ * Recursive clip-and-scale draw of the containment tree. Browser code.
+ *
+ * Each node resolves to a screen rect from its absolute world rect and the
+ * camera. We draw the node's card (fading out as `t` grows), then clip to its
+ * rect and recurse into the top-N children (fading in), so a card *visibly
+ * opens into its parts* as you zoom. Off-screen subtrees, sub-pixel nodes and
+ * fully-faded subtrees are skipped, and a density cap bounds how many children
+ * are drawn at any depth, keeping the live node count bounded on huge trees.
+ */
+
+import { type Camera, type Rect, type Viewport, worldRectToScreen } from "./camera";
+import {
+ ALPHA_EPSILON,
+ ARROW_MIN_BOX_PX,
+ EDGE_FOCUS_ALPHA,
+ EDGE_MAX_PER_PARENT,
+ EDGE_MIN_BOX_PX,
+ GRID_MAJOR_EVERY,
+ GRID_SPACING_PX,
+ MAX_CHILDREN_DRAWN,
+ MIN_DRAW_PX,
+} from "./constants";
+import { isOnScreen, selectChildren } from "./cull";
+import { type EdgeInput, routeEdges } from "./edges";
+import { drawCard, drawEdge } from "./nodes";
+import type { PaperTexture } from "./paper";
+import { childNodes, type ZoomScene } from "./scene";
+import type { ZoomPalette } from "./theme";
+import type { ZoomNode } from "./types";
+import {
+ expandThresholds,
+ fadeAlphas,
+ leafCapScale,
+ transitionT,
+} from "./zoom-transition";
+
+export interface DrawOptions {
+ selectedId: string | null;
+ hoveredId: string | null;
+ lowDetail: boolean;
+ /** Shared ruled-paper card texture; null until the asset loads (or on SSR). */
+ paper?: PaperTexture | null;
+}
+
+/**
+ * A faint graph-paper line grid under the cards, anchored to the camera so it
+ * parallaxes on pan (fixed screen spacing) and reads as a designed surface. Every
+ * `GRID_MAJOR_EVERY`-th line, counted from the world origin so majors stay put on
+ * pan, is drawn a touch firmer. Cheap: two batched stroke passes.
+ */
+function drawGrid(
+ ctx: CanvasRenderingContext2D,
+ cam: Camera,
+ vp: Viewport,
+ palette: ZoomPalette,
+): void {
+ const sp = GRID_SPACING_PX;
+ const maj = GRID_MAJOR_EVERY;
+ const baseX = vp.w / 2 - cam.cx * cam.scale; // screen x of world x = 0
+ const baseY = vp.h / 2 - cam.cy * cam.scale;
+ const ox = ((baseX % sp) + sp) % sp;
+ const oy = ((baseY % sp) + sp) % sp;
+ const startKx = Math.round((ox - baseX) / sp); // world-line index of the first line
+ const startKy = Math.round((oy - baseY) / sp);
+ const isMajor = (k: number): boolean => (((k % maj) + maj) % maj) === 0;
+
+ const pass = (major: boolean): void => {
+ ctx.beginPath();
+ let kx = startKx;
+ for (let x = ox; x < vp.w; x += sp, kx++) {
+ if (isMajor(kx) !== major) continue;
+ const xx = Math.round(x) + 0.5; // crisp 1px line
+ ctx.moveTo(xx, 0);
+ ctx.lineTo(xx, vp.h);
+ }
+ let ky = startKy;
+ for (let y = oy; y < vp.h; y += sp, ky++) {
+ if (isMajor(ky) !== major) continue;
+ const yy = Math.round(y) + 0.5;
+ ctx.moveTo(0, yy);
+ ctx.lineTo(vp.w, yy);
+ }
+ ctx.strokeStyle = major ? palette.gridStrong : palette.grid;
+ ctx.lineWidth = 1;
+ ctx.stroke();
+ };
+
+ pass(false); // minor lines
+ pass(true); // major lines on top
+}
+
+export interface PickEntry {
+ id: string;
+ rect: Rect;
+ depth: number;
+}
+
+export interface DrawStats {
+ drawn: number;
+ culled: number;
+ maxDepthDrawn: number;
+ /** Drawn cards, deepest last, for hit-testing the most recent frame. */
+ pick: PickEntry[];
+}
+
+/** Shrink a rect about its centre by `scale` (used for the leaf cap). */
+function shrinkAboutCentre(rect: Rect, scale: number): Rect {
+ if (scale >= 1) return rect;
+ const w = rect.w * scale;
+ const h = rect.h * scale;
+ return { x: rect.x + (rect.w - w) / 2, y: rect.y + (rect.h - h) / 2, w, h };
+}
+
+export function drawScene(
+ ctx: CanvasRenderingContext2D,
+ scene: ZoomScene,
+ cam: Camera,
+ vp: Viewport,
+ palette: ZoomPalette,
+ opts: DrawOptions,
+): DrawStats {
+ const thresholds = expandThresholds(vp.w);
+ const stats: DrawStats = { drawn: 0, culled: 0, maxDepthDrawn: 0, pick: [] };
+ // Resolve the paper pattern once per frame (lazily built against this ctx).
+ const paper = opts.paper?.get(ctx) ?? null;
+
+ ctx.fillStyle = palette.bg;
+ ctx.fillRect(0, 0, vp.w, vp.h);
+ drawGrid(ctx, cam, vp, palette);
+
+ const root = scene.nodes.get(scene.rootId);
+ if (!root) return stats;
+
+ // The node under the cursor (or selected) lifts its incident relations out of
+ // the quiet baseline. Hover wins for immediate feedback.
+ const focusId = opts.hoveredId ?? opts.selectedId;
+
+ const drawNode = (node: ZoomNode, inheritedAlpha: number, depth: number): void => {
+ const worldRect = scene.worldRects.get(node.id);
+ if (!worldRect) return;
+ const screen = worldRectToScreen(cam, vp, worldRect);
+
+ if (!isOnScreen(screen, vp)) {
+ stats.culled++;
+ return;
+ }
+ if (screen.w < MIN_DRAW_PX || screen.h < MIN_DRAW_PX) {
+ stats.culled++;
+ return;
+ }
+
+ const kids = childNodes(scene, node);
+ const hasChildren = kids.length > 0;
+ const t = transitionT(screen.w, thresholds, hasChildren);
+ const { body, child } = fadeAlphas(inheritedAlpha, t);
+
+ // Leaf cap: a file stops growing once it fills enough of the screen.
+ const cap = leafCapScale(screen.w, thresholds, hasChildren);
+ const drawnRect = cap < 1 ? shrinkAboutCentre(screen, cap) : screen;
+
+ if (body > ALPHA_EPSILON) {
+ drawCard(ctx, drawnRect, node, palette, body, {
+ selected: node.id === opts.selectedId,
+ hovered: node.id === opts.hoveredId,
+ lowDetail: opts.lowDetail,
+ }, t, paper);
+ }
+ stats.drawn++;
+ stats.maxDepthDrawn = Math.max(stats.maxDepthDrawn, depth);
+ stats.pick.push({ id: node.id, rect: drawnRect, depth });
+
+ if (!hasChildren || child <= ALPHA_EPSILON) return;
+
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(screen.x, screen.y, screen.w, screen.h);
+ ctx.clip();
+
+ // Draw every child (uniform cells fade and grow in together); the cap is a
+ // safety net for a pathologically flat folder, dropping the least-important
+ // tail so the frame stays cheap. Each child still self-culls below.
+ const visible =
+ kids.length > MAX_CHILDREN_DRAWN ? selectChildren(kids, MAX_CHILDREN_DRAWN) : kids;
+
+ // Screen rects of the children big enough to anchor an arrow to. Edges are
+ // drawn (behind the cards) only between boxes that are actually on screen,
+ // so an arrow can never point at a culled or density-capped sibling.
+ const childRects = new Map<string, Rect>();
+ for (const kid of visible) {
+ const wr = scene.worldRects.get(kid.id);
+ if (!wr) continue;
+ const r = worldRectToScreen(cam, vp, wr);
+ if (isOnScreen(r, vp) && r.w >= EDGE_MIN_BOX_PX) childRects.set(kid.id, r);
+ }
+ drawEdges(ctx, scene, node, childRects, palette, child, opts.lowDetail, focusId);
+
+ for (const kid of visible) drawNode(kid, child, depth + 1);
+
+ ctx.restore();
+ };
+
+ drawNode(root, 1, 0);
+ return stats;
+}
+
+/**
+ * Draw the relations among the children of a parent we are zoomed into, as
+ * routed directed connectors (see `edges.ts`). Only edges whose BOTH endpoints
+ * are in `childRects` (currently drawn) are considered; the rest are dropped.
+ * The set is capped to the strongest `EDGE_MAX_PER_PARENT` by edge count so a
+ * dense level never sprays the canvas, then routed so edges that share a box
+ * side fan out and curve around the boxes between their endpoints.
+ */
+function drawEdges(
+ ctx: CanvasRenderingContext2D,
+ scene: ZoomScene,
+ parent: ZoomNode,
+ childRects: Map<string, Rect>,
+ palette: ZoomPalette,
+ alpha: number,
+ lowDetail: boolean,
+ focusId: string | null,
+): void {
+ // Relations are revealed only for the box the user is pointing at / has
+ // selected, so the canvas is not a thicket of arrows. No focus -> no edges.
+ if (lowDetail || childRects.size < 2 || focusId === null) return;
+ const rels = scene.relationsByParent.get(parent.id);
+ if (!rels) return;
+
+ const drawable = rels.filter(
+ (r) =>
+ r.source_id !== r.target_id &&
+ (r.source_id === focusId || r.target_id === focusId) &&
+ childRects.has(r.source_id) &&
+ childRects.has(r.target_id),
+ );
+ if (drawable.length === 0) return;
+ drawable.sort((a, b) => b.edge_count - a.edge_count);
+ const top = drawable.length > EDGE_MAX_PER_PARENT ? drawable.slice(0, EDGE_MAX_PER_PARENT) : drawable;
+
+ const inputs: EdgeInput[] = top.map((r) => ({
+ id: `${r.source_id} ${r.target_id}`,
+ sourceId: r.source_id,
+ targetId: r.target_id,
+ coupling: r.coupling,
+ edgeCount: r.edge_count,
+ }));
+ for (const routed of routeEdges(inputs, childRects)) {
+ const to = childRects.get(routed.targetId)!;
+ const withArrow = to.w >= ARROW_MIN_BOX_PX && to.h >= ARROW_MIN_BOX_PX;
+ drawEdge(ctx, routed.route, routed.coupling, palette, alpha * EDGE_FOCUS_ALPHA, withArrow);
+ }
+}
+
+/** Deepest drawn card containing the screen point, or null. Pure. */
+export function pickNode(stats: DrawStats, sx: number, sy: number): string | null {
+ let best: PickEntry | null = null;
+ for (const entry of stats.pick) {
+ const r = entry.rect;
+ if (sx < r.x || sx > r.x + r.w || sy < r.y || sy > r.y + r.h) continue;
+ if (!best || entry.depth >= best.depth) best = entry;
+ }
+ return best ? best.id : null;
+}
diff --git a/packages/ui/src/zoom/edges.ts b/packages/ui/src/zoom/edges.ts
new file mode 100644
index 000000000..dec53ea01
Binary files /dev/null and b/packages/ui/src/zoom/edges.ts differ
diff --git a/packages/ui/src/zoom/focus-path.ts b/packages/ui/src/zoom/focus-path.ts
new file mode 100644
index 000000000..386a04a28
--- /dev/null
+++ b/packages/ui/src/zoom/focus-path.ts
@@ -0,0 +1,54 @@
+/**
+ * "You are here" focus tracking. Pure, browser-free and unit-testable.
+ *
+ * The breadcrumb and the URL need to know which node the camera is currently
+ * looking *into*. We walk from the root following whichever child contains the
+ * viewport centre, descending only while that child has grown to fill a good
+ * fraction of the viewport (i.e. you have actually zoomed into it). The chain
+ * returned is root -> ... -> focus; its last element is the current focus node.
+ */
+
+import type { Camera, Viewport } from "./camera";
+import type { ZoomScene } from "./scene";
+import type { ZoomNode } from "./types";
+
+/** A child must fill at least this fraction of the viewport width to be "entered". */
+const ENTER_FRACTION = 0.62;
+
+export function focusChain(
+ scene: ZoomScene,
+ cam: Camera,
+ vp: Viewport,
+ enterFraction = ENTER_FRACTION,
+): ZoomNode[] {
+ const chain: ZoomNode[] = [];
+ let current = scene.nodes.get(scene.rootId);
+ // The viewport centre in world space is exactly the camera centre.
+ const cxWorld = cam.cx;
+ const cyWorld = cam.cy;
+
+ while (current) {
+ chain.push(current);
+ let next: ZoomNode | null = null;
+ for (const childId of current.children) {
+ const r = scene.worldRects.get(childId);
+ if (!r) continue;
+ if (cxWorld >= r.x && cxWorld <= r.x + r.w && cyWorld >= r.y && cyWorld <= r.y + r.h) {
+ // Only descend once the child fills enough of the screen to count as
+ // entered. `r.w * cam.scale` is the child's width in screen pixels
+ // (cam.scale is screen px per world unit, matching worldRectToScreen).
+ if (r.w * cam.scale >= vp.w * enterFraction) next = scene.nodes.get(childId) ?? null;
+ break;
+ }
+ }
+ if (!next) break;
+ current = next;
+ }
+ return chain;
+}
+
+/** The current focus node id (deepest entered), or the root id. */
+export function focusId(scene: ZoomScene, cam: Camera, vp: Viewport): string {
+ const chain = focusChain(scene, cam, vp);
+ return chain.length > 0 ? chain[chain.length - 1]!.id : scene.rootId;
+}
diff --git a/packages/ui/src/zoom/geometry.ts b/packages/ui/src/zoom/geometry.ts
new file mode 100644
index 000000000..f53bbeda4
--- /dev/null
+++ b/packages/ui/src/zoom/geometry.ts
@@ -0,0 +1,99 @@
+/**
+ * Pure containment-tree geometry. Browser-free and unit-testable.
+ *
+ * The backend gives every node a `layout` rect in its parent's `[0,1]` space.
+ * Composed down the tree this yields each node's **absolute world rect** inside
+ * the root unit square. We precompute those once per scene; culling, the fade
+ * `t`, hit-testing and "zoom to node" all read them, while the draw pass uses
+ * the same rects to set each node's clip-and-scale transform.
+ */
+
+import type { Rect } from "./camera";
+import { type LayoutChild, packLayout, type PackLayoutOptions } from "./layout";
+import type { ZoomNode } from "./types";
+
+/** Compose a child's parent-space layout rect into absolute world space. */
+export function composeRect(parentAbs: Rect, childLocal: Rect): Rect {
+ return {
+ x: parentAbs.x + childLocal.x * parentAbs.w,
+ y: parentAbs.y + childLocal.y * parentAbs.h,
+ w: childLocal.w * parentAbs.w,
+ h: childLocal.h * parentAbs.h,
+ };
+}
+
+const ROOT_RECT: Rect = { x: 0, y: 0, w: 1, h: 1 };
+
+/**
+ * Walk the tree from `rootId`, composing every node's absolute world rect.
+ * Iterative (explicit stack) so a deep tree cannot overflow the call stack.
+ * Each node's children are laid out client-side as an importance-weighted
+ * masonry pack (see `layout.ts`) keyed off the parent's world aspect, then
+ * composed into world space, so card size encodes importance and the rows
+ * stagger. The backend treemap rects are intentionally ignored; unreachable
+ * nodes are skipped.
+ */
+export function computeWorldRects(
+ nodes: Map<string, ZoomNode>,
+ rootId: string,
+ opts: PackLayoutOptions = {},
+): Map<string, Rect> {
+ const rects = new Map<string, Rect>();
+ const root = nodes.get(rootId);
+ if (!root) return rects;
+ rects.set(rootId, ROOT_RECT);
+
+ const stack: string[] = [rootId];
+ while (stack.length > 0) {
+ const id = stack.pop()!;
+ const node = nodes.get(id);
+ const parentAbs = rects.get(id);
+ if (!node || !parentAbs) continue;
+
+ const kids: LayoutChild[] = [];
+ for (const childId of node.children) {
+ const child = nodes.get(childId);
+ if (child) kids.push(child);
+ }
+ if (kids.length === 0) continue;
+
+ const aspect = parentAbs.h > 0 ? parentAbs.w / parentAbs.h : 1;
+ const local = packLayout(kids, aspect, opts);
+ for (const child of kids) {
+ const lr = local.get(child.id);
+ if (!lr) continue;
+ rects.set(child.id, composeRect(parentAbs, lr));
+ stack.push(child.id);
+ }
+ }
+ return rects;
+}
+
+/**
+ * The point on a rect's perimeter along the ray from its centre toward
+ * `(towardX, towardY)`. Used to anchor relation arrows to box edges instead of
+ * their centres (so a line visibly exits one box and enters another).
+ */
+export function perimeterPoint(
+ rect: Rect,
+ towardX: number,
+ towardY: number,
+): { x: number; y: number } {
+ const cx = rect.x + rect.w / 2;
+ const cy = rect.y + rect.h / 2;
+ const dx = towardX - cx;
+ const dy = towardY - cy;
+ if (dx === 0 && dy === 0) return { x: cx, y: cy };
+ const halfW = rect.w / 2;
+ const halfH = rect.h / 2;
+ // Largest t such that (t*dx, t*dy) stays within the half-extents.
+ const tx = dx !== 0 ? halfW / Math.abs(dx) : Infinity;
+ const ty = dy !== 0 ? halfH / Math.abs(dy) : Infinity;
+ const t = Math.min(tx, ty);
+ return { x: cx + dx * t, y: cy + dy * t };
+}
+
+/** Does a screen point fall inside a screen rect? (inclusive of edges) */
+export function rectContains(rect: Rect, sx: number, sy: number): boolean {
+ return sx >= rect.x && sx <= rect.x + rect.w && sy >= rect.y && sy <= rect.y + rect.h;
+}
diff --git a/packages/ui/src/zoom/index.ts b/packages/ui/src/zoom/index.ts
new file mode 100644
index 000000000..9678b101b
--- /dev/null
+++ b/packages/ui/src/zoom/index.ts
@@ -0,0 +1,84 @@
+/**
+ * @repowise-dev/ui/zoom: continuous-zoom knowledge-graph canvas.
+ *
+ * Public entry point. Host pages mount `<ZoomCanvas data={zoomMap} />` with the
+ * map fetched from `/api/graph/{repo_id}/zoom-map`. The renderer, camera and
+ * pure tree/fade/cull math are exported too so downstream surfaces (and tests)
+ * can reuse them. Everything except `ZoomCanvas` and `renderer`/`theme` is
+ * browser-free and unit-testable in isolation.
+ */
+
+export { ZoomCanvas } from "./ZoomCanvas";
+export type { ZoomCanvasProps, ZoomCanvasHandle } from "./ZoomCanvas";
+
+export { ZoomRenderer } from "./renderer";
+export type { ZoomRendererOptions, FrameStats, FlyOptions } from "./renderer";
+
+export { easeInOutCubic, flyDuration, interpolateCamera } from "./camera-anim";
+export { focusChain, focusId } from "./focus-path";
+
+export { buildScene, childNodes } from "./scene";
+export type { ZoomScene } from "./scene";
+
+export { drawScene, pickNode } from "./draw-tree";
+export type { DrawOptions, DrawStats, PickEntry } from "./draw-tree";
+
+export { resolveZoomPalette } from "./theme";
+export type { ZoomPalette } from "./theme";
+
+export {
+ type Camera,
+ type Viewport,
+ type Rect,
+ type ScreenPoint,
+ type WorldPoint,
+ clampCamera,
+ clampScale,
+ fitRoot,
+ frameRect,
+ panByScreen,
+ screenToWorld,
+ worldRectToScreen,
+ worldToScreen,
+ zoomAbout,
+} from "./camera";
+
+export { composeRect, computeWorldRects, perimeterPoint, rectContains } from "./geometry";
+
+export { gridDimensions, packLayout } from "./layout";
+export type { LayoutChild, PackLayoutOptions } from "./layout";
+
+export {
+ controlPoints,
+ facingSide,
+ routeEdges,
+ slotAnchor,
+} from "./edges";
+export type {
+ EdgeInput,
+ EdgeRoute,
+ Point,
+ RoutedEdge,
+ RouteOptions,
+ Side,
+} from "./edges";
+
+export {
+ type FadeThresholds,
+ type FadeAlphas,
+ expandThresholds,
+ fadeAlphas,
+ leafCapScale,
+ transitionT,
+} from "./zoom-transition";
+
+export { isOnScreen, selectChildren } from "./cull";
+
+export type {
+ ZoomKind,
+ ZoomRect,
+ ZoomMetrics,
+ ZoomNode,
+ ZoomRelation,
+ ZoomMap,
+} from "./types";
diff --git a/packages/ui/src/zoom/layout.ts b/packages/ui/src/zoom/layout.ts
new file mode 100644
index 000000000..eea97158e
--- /dev/null
+++ b/packages/ui/src/zoom/layout.ts
@@ -0,0 +1,182 @@
+/**
+ * Per-parent masonry pack layout. Pure, browser-free and unit-testable.
+ *
+ * The backend ships a containment tree but its layout rects are a squarified
+ * treemap (space-filling, extreme aspect ratios). We ignore those and lay each
+ * parent's children out client-side instead: every card is sized by importance
+ * (more central = bigger, within bounds so nothing is unreadably small) and the
+ * cards are row-packed into centred, variable-width rows. The staggered row
+ * edges and the size variation give an organic architecture-map feel rather than
+ * a rigid grid, while the whole cluster is uniform-fit (aspect-preserving) into
+ * the parent so cards keep a single landscape shape. The rect emitted is still in
+ * parent `[0,1]` space, so the clip-and-scale composition in `geometry.ts` is
+ * unchanged.
+ */
+
+import type { Rect } from "./camera";
+import {
+ CARD_ASPECT,
+ PACK_GUTTER,
+ PACK_IMPORTANCE_GAMMA,
+ PACK_SIZE_MAX,
+ PACK_SIZE_MIN,
+} from "./constants";
+
+/** The minimal slice of a node the layout needs (placement order + sizing). */
+export interface LayoutChild {
+ id: string;
+ sibling_rank: number;
+ importance: number;
+}
+
+export interface PackLayoutOptions {
+ /** Whitespace between cards, in the same relative units as the card sides. */
+ gutter?: number;
+ /** Card height for the least-important sibling. */
+ sizeMin?: number;
+ /** Card height for the most-important sibling. */
+ sizeMax?: number;
+ /** Importance curve; <1 lifts small cards so minor nodes stay readable. */
+ gamma?: number;
+ /** Card width : height. */
+ aspect?: number;
+}
+
+/**
+ * Choose a target column count whose column/row ratio tracks the parent's world
+ * aspect, so the packed cluster's bounding box roughly matches the parent shape
+ * and fits with little margin. Returns the tightened dimensions (no empty
+ * trailing column). Shared with the pack (which packs to ~`cols` cards per row).
+ */
+export function gridDimensions(
+ count: number,
+ parentAspect: number,
+): { cols: number; rows: number } {
+ if (count <= 0) return { cols: 0, rows: 0 };
+ if (count === 1) return { cols: 1, rows: 1 };
+ const aspect = Math.min(6, Math.max(1 / 6, parentAspect || 1));
+ let cols = Math.round(Math.sqrt(count * aspect));
+ cols = Math.min(count, Math.max(1, cols));
+ const rows = Math.ceil(count / cols);
+ // Re-derive columns from the row count so the grid is as tight as possible for
+ // that many rows (this can narrow the column count, which is intended).
+ return { cols: Math.ceil(count / rows), rows };
+}
+
+interface Packed {
+ id: string;
+ w: number;
+ h: number;
+}
+
+/**
+ * Lay `children` out as an importance-weighted masonry pack inside the unit
+ * parent box. Children are ordered by `sibling_rank` (most important first, so
+ * the biggest cards read top-left), sized by importance normalised across the
+ * sibling set, then greedily row-packed to ~`cols` cards per row. Rows are
+ * centred (so left edges stagger) and each card is centred in its row band (so
+ * top edges stagger); the whole cluster is uniform-fit into `[0,1]²`. Returns
+ * each child's rect in parent `[0,1]` space. Deterministic: stable order, ties
+ * broken by id; no randomness.
+ */
+export function packLayout(
+ children: readonly LayoutChild[],
+ parentAspect: number,
+ opts: PackLayoutOptions = {},
+): Map<string, Rect> {
+ const gutter = opts.gutter ?? PACK_GUTTER;
+ const sizeMin = opts.sizeMin ?? PACK_SIZE_MIN;
+ const sizeMax = opts.sizeMax ?? PACK_SIZE_MAX;
+ const gamma = opts.gamma ?? PACK_IMPORTANCE_GAMMA;
+ const baseAspect = opts.aspect ?? CARD_ASPECT;
+ // Cards are sized in the parent's LOCAL [0,1] box, but `composeRect` later
+ // stretches that box by the parent's own world width and height separately.
+ // Since a parent card is itself landscape, sizing to `baseAspect` directly
+ // would let every nesting level re-multiply the horizontal stretch, so a few
+ // levels deep a card collapses into an unreadable sliver. Pre-divide by the
+ // parent aspect: once `composeRect` re-applies it, each card lands at
+ // `baseAspect` on screen at any depth. Clamp so an extreme parent shape can't
+ // invert or explode the local card.
+ const aspect = Math.min(8, Math.max(0.2, baseAspect / (parentAspect || 1)));
+
+ const out = new Map<string, Rect>();
+ const n = children.length;
+ if (n === 0) return out;
+
+ const ordered = [...children].sort(
+ (a, b) => a.sibling_rank - b.sibling_rank || (a.id < b.id ? -1 : 1),
+ );
+
+ // Normalise importance across this sibling set so each parent shows a full
+ // range of sizes (min-max within the group). If they are all equal, everyone
+ // gets the max size (a uniform, generously-sized cluster).
+ let lo = Infinity;
+ let hi = -Infinity;
+ for (const c of ordered) {
+ const v = Number.isFinite(c.importance) ? c.importance : 0;
+ if (v < lo) lo = v;
+ if (v > hi) hi = v;
+ }
+ const span = hi - lo;
+ const heightOf = (c: LayoutChild): number => {
+ const v = Number.isFinite(c.importance) ? c.importance : 0;
+ const norm = span > 1e-9 ? (v - lo) / span : 1;
+ return sizeMin + (sizeMax - sizeMin) * Math.pow(norm, gamma);
+ };
+
+ const cards: Packed[] = ordered.map((c) => {
+ const h = heightOf(c);
+ return { id: c.id, w: h * aspect, h };
+ });
+
+ // Greedy row packing to a target width of ~`cols` average-width cards.
+ const { cols } = gridDimensions(n, parentAspect);
+ const avgW = cards.reduce((s, c) => s + c.w, 0) / n;
+ const targetRowW = cols * avgW + Math.max(0, cols - 1) * gutter;
+
+ const rows: Packed[][] = [];
+ let cur: Packed[] = [];
+ let curW = 0;
+ for (const card of cards) {
+ const add = (cur.length > 0 ? gutter : 0) + card.w;
+ if (cur.length > 0 && curW + add > targetRowW) {
+ rows.push(cur);
+ cur = [];
+ curW = 0;
+ }
+ curW += (cur.length > 0 ? gutter : 0) + card.w;
+ cur.push(card);
+ }
+ if (cur.length > 0) rows.push(cur);
+
+ const rowW = (row: Packed[]): number =>
+ row.reduce((s, c) => s + c.w, 0) + Math.max(0, row.length - 1) * gutter;
+ const rowH = (row: Packed[]): number => row.reduce((m, c) => Math.max(m, c.h), 0);
+
+ const maxRowW = Math.max(...rows.map(rowW));
+ const totalH = rows.reduce((s, r) => s + rowH(r), 0) + Math.max(0, rows.length - 1) * gutter;
+
+ // Uniform (aspect-preserving) fit of the packed cluster into the unit box,
+ // centred, so cards keep one shape and nothing spills outside the parent.
+ const scale = Math.min(1 / maxRowW, 1 / totalH);
+ const offX = (1 - maxRowW * scale) / 2;
+ const offY = (1 - totalH * scale) / 2;
+
+ let y = 0;
+ for (const row of rows) {
+ const h = rowH(row);
+ let x = (maxRowW - rowW(row)) / 2; // centre the row -> staggered left edges
+ for (const card of row) {
+ const cy = y + (h - card.h) / 2; // centre in the band -> staggered top edges
+ out.set(card.id, {
+ x: offX + x * scale,
+ y: offY + cy * scale,
+ w: card.w * scale,
+ h: card.h * scale,
+ });
+ x += card.w + gutter;
+ }
+ y += h + gutter;
+ }
+ return out;
+}
diff --git a/packages/ui/src/zoom/nodes.ts b/packages/ui/src/zoom/nodes.ts
new file mode 100644
index 000000000..634619d53
--- /dev/null
+++ b/packages/ui/src/zoom/nodes.ts
@@ -0,0 +1,414 @@
+/**
+ * Node-card and relation drawing on a 2D canvas. Browser code.
+ *
+ * Everything is drawn in screen-pixel space (the recursion in `draw-tree.ts`
+ * resolves each node's screen rect from the camera), so text stays crisp at any
+ * zoom instead of being scaled and blurred. Level-of-detail thresholds gate
+ * label and summary drawing by the card's on-screen size.
+ *
+ * Visual language (Linear/Stripe idiom): cards are clean surfaces that float on
+ * a faint dot-grid via a soft drop shadow and a hairline border. Role (entry /
+ * hotspot / dead / on-flow) is shown as one small status dot, never a colored
+ * frame, and detailed metrics live in the side panel rather than on the card, so
+ * the canvas stays calm at a glance. Relations are deliberately low-emphasis: a
+ * single neutral hue, thin, faded behind the cards.
+ */
+
+import { ALERT_MAX, HEALTHY_MIN } from "@repowise-dev/types/health";
+
+import type { Rect } from "./camera";
+import { ARROW_SIZE_PX, EDGE_LINE_PX } from "./constants";
+import type { EdgeRoute } from "./edges";
+import type { ZoomPalette } from "./theme";
+import type { ZoomKind, ZoomNode } from "./types";
+
+const LABEL_MIN_PX = 44; // draw the name once a card is at least this wide
+const SUMMARY_MIN_PX = 260; // draw a one-line summary on large cards
+const DOT_MIN_PX = 60; // draw the role status dot once there is room
+const CORNER_PX = 12;
+const TEXTURE_MIN_PX = 96; // paint the paper texture once the card is big enough
+const GLYPH_MIN_PX = 52; // draw the kind glyph beside the title once there is room
+const FOOTER_MIN_W_PX = 132; // draw the bottom signal row on cards at least this wide
+const FOOTER_MIN_H_PX = 104; // ...and at least this tall
+
+/** Human label per node kind, shown small in the card footer. */
+const KIND_LABEL: Record<ZoomKind, string> = {
+ system: "System",
+ layer: "Layer",
+ group: "Group",
+ folder: "Folder",
+ file: "File",
+};
+
+/**
+ * A minimal monoline glyph per node kind, drawn into the `[x, y, s, s]` box in the
+ * caller's current stroke style. Canvas-native rather than the KG cards' Lucide
+ * components (which cannot be drawn to a 2D context), but echoes the same visual
+ * language: stacked planes = layer, folder = folder/group, a page = file, a grid
+ * of boxes = the whole system.
+ */
+function drawKindGlyph(
+ ctx: CanvasRenderingContext2D,
+ x: number,
+ y: number,
+ s: number,
+ kind: ZoomKind,
+): void {
+ const at = (fx: number, fy: number): [number, number] => [x + fx * s, y + fy * s];
+ ctx.beginPath();
+ switch (kind) {
+ case "system": {
+ // 2x2 grid of small boxes.
+ const d = 0.34 * s;
+ const cells: Array<[number, number]> = [
+ [0.1, 0.1],
+ [0.56, 0.1],
+ [0.1, 0.56],
+ [0.56, 0.56],
+ ];
+ for (const [gx, gy] of cells) {
+ ctx.rect(x + gx * s, y + gy * s, d, d);
+ }
+ break;
+ }
+ case "layer": {
+ // Two stacked planes (Lucide "Layers" idiom).
+ ctx.moveTo(...at(0.5, 0.1));
+ ctx.lineTo(...at(0.88, 0.32));
+ ctx.lineTo(...at(0.5, 0.54));
+ ctx.lineTo(...at(0.12, 0.32));
+ ctx.closePath();
+ ctx.moveTo(...at(0.12, 0.52));
+ ctx.lineTo(...at(0.5, 0.74));
+ ctx.lineTo(...at(0.88, 0.52));
+ break;
+ }
+ case "group": {
+ // Two overlapping cards (a collection).
+ ctx.rect(x + 0.34 * s, y + 0.14 * s, 0.44 * s, 0.44 * s);
+ ctx.rect(x + 0.14 * s, y + 0.36 * s, 0.44 * s, 0.44 * s);
+ break;
+ }
+ case "folder": {
+ // Classic tabbed folder.
+ ctx.moveTo(...at(0.14, 0.3));
+ ctx.lineTo(...at(0.42, 0.3));
+ ctx.lineTo(...at(0.5, 0.42));
+ ctx.lineTo(...at(0.86, 0.42));
+ ctx.lineTo(...at(0.86, 0.82));
+ ctx.lineTo(...at(0.14, 0.82));
+ ctx.closePath();
+ break;
+ }
+ case "file": {
+ // Page with a folded corner.
+ ctx.moveTo(...at(0.24, 0.08));
+ ctx.lineTo(...at(0.6, 0.08));
+ ctx.lineTo(...at(0.78, 0.26));
+ ctx.lineTo(...at(0.78, 0.92));
+ ctx.lineTo(...at(0.24, 0.92));
+ ctx.closePath();
+ ctx.moveTo(...at(0.6, 0.08));
+ ctx.lineTo(...at(0.6, 0.26));
+ ctx.lineTo(...at(0.78, 0.26));
+ break;
+ }
+ }
+ ctx.stroke();
+}
+
+/**
+ * The single most useful bottom-right signal for a node. Files show their
+ * language; containers show how many files they hold. Code health is shown
+ * separately as the footer's leading dot (see `healthColor`).
+ */
+function primaryMetric(node: ZoomNode): string {
+ if (node.kind === "file") return node.language ? node.language.toUpperCase() : "";
+ const n = node.metrics.file_count;
+ return n > 0 ? `${n} ${n === 1 ? "file" : "files"}` : "";
+}
+
+/**
+ * Traffic-light ink for a node's code-health score, on the same 0-10 bands the
+ * /files treemap uses (`bandForScore`: <4 alert, <8 warning, else healthy) so a
+ * card and a treemap tile never disagree. Null (unscored, sparse) reads neutral.
+ */
+function healthColor(score: number | null, palette: ZoomPalette): string {
+ if (score === null) return palette.healthNeutral;
+ if (score < ALERT_MAX) return palette.healthAlert;
+ if (score < HEALTHY_MIN) return palette.healthWarning;
+ return palette.healthHealthy;
+}
+
+/**
+ * Paint the shared ruled-paper photo inside a card, washed by the card's own
+ * per-theme wash so the tint and text contrast survive. This is the canvas
+ * equivalent of the KG cards' `--kg-card-texture` (paper photo under a
+ * translucent wash), reusing the very same asset via `PaperTexture`. The ruled
+ * lines and grain come from the photo, so no lines are drawn procedurally.
+ *
+ * Order matters: the opaque paper tile is laid down first, then the wash pulls
+ * the composite back toward the card color. Wrapped in save/restore, so the
+ * clip and the temporary alpha are both undone for the caller.
+ */
+function drawPaperTexture(
+ ctx: CanvasRenderingContext2D,
+ rect: Rect,
+ radius: number,
+ paper: CanvasPattern,
+ palette: ZoomPalette,
+ alpha: number,
+): void {
+ ctx.save();
+ roundRectPath(ctx, rect, radius);
+ ctx.clip();
+ ctx.globalAlpha = alpha;
+ ctx.fillStyle = paper;
+ ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
+ // The wash carries its own per-theme alpha (the `--color-zoom-card-paper-wash`
+ // token); globalAlpha here only folds in the card's body-fade.
+ ctx.globalAlpha = alpha;
+ ctx.fillStyle = palette.paperWash;
+ ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
+ ctx.restore();
+}
+
+/** The single most salient role color for a node's status dot, or null. */
+function roleColor(node: ZoomNode, palette: ZoomPalette): string | null {
+ if (node.is_entry_point || node.metrics.entry_point_count > 0) return palette.entry;
+ if (node.is_hotspot || node.metrics.hotspot_count > 0) return palette.hotspot;
+ if (node.is_dead || node.metrics.dead_count > 0) return palette.dead;
+ if (node.on_flow || node.metrics.on_flow_count > 0) return palette.flow;
+ return null;
+}
+
+function roundRectPath(ctx: CanvasRenderingContext2D, r: Rect, radius: number): void {
+ const rad = Math.max(0, Math.min(radius, r.w / 2, r.h / 2));
+ ctx.beginPath();
+ ctx.roundRect(r.x, r.y, r.w, r.h, rad);
+}
+
+function fitText(ctx: CanvasRenderingContext2D, text: string, maxW: number): string {
+ if (ctx.measureText(text).width <= maxW) return text;
+ const ell = "…";
+ let lo = 0;
+ let hi = text.length;
+ while (lo < hi) {
+ const mid = (lo + hi + 1) >> 1;
+ if (ctx.measureText(text.slice(0, mid) + ell).width <= maxW) lo = mid;
+ else hi = mid - 1;
+ }
+ return lo > 0 ? text.slice(0, lo) + ell : "";
+}
+
+export interface CardState {
+ selected: boolean;
+ hovered: boolean;
+ /** During a pan we skip the (costlier) shadow so dragging stays smooth. */
+ lowDetail: boolean;
+}
+
+/** Draw one node's card body in screen space, at the given alpha. */
+export function drawCard(
+ ctx: CanvasRenderingContext2D,
+ rect: Rect,
+ node: ZoomNode,
+ palette: ZoomPalette,
+ alpha: number,
+ state: CardState,
+ t: number,
+ paper: CanvasPattern | null,
+): void {
+ if (alpha <= 0) return;
+ const { selected, hovered, lowDetail } = state;
+ ctx.globalAlpha = alpha;
+
+ const radius = Math.max(0, Math.min(CORNER_PX, rect.w / 2, rect.h / 2));
+ roundRectPath(ctx, rect, radius);
+
+ // Base fill with a soft elevation shadow (skipped on tiny cards / during pans
+ // so the frame stays cheap). This lays down the card silhouette + shadow; the
+ // paper texture below is painted over it and the border re-strokes the rect.
+ const elevate = !lowDetail && rect.w >= 56 && rect.h >= 36;
+ ctx.save();
+ if (elevate) {
+ ctx.shadowColor = palette.shadow;
+ ctx.shadowBlur = hovered ? 26 : 14;
+ ctx.shadowOffsetY = hovered ? 7 : 3;
+ }
+ ctx.fillStyle = node.kind === "file" ? palette.nodeFill : palette.nodeFillAlt;
+ ctx.fill();
+ ctx.restore();
+
+ // Ruled-paper texture (shared KG asset) inside the card, skipped on tiny cards
+ // / pans and whenever the texture has not loaded yet (then the base fill above
+ // stands in). The photo supplies the ruled lines, so none are drawn by hand.
+ if (paper && !lowDetail && rect.w >= TEXTURE_MIN_PX && rect.h >= TEXTURE_MIN_PX) {
+ drawPaperTexture(ctx, rect, radius, paper, palette, alpha);
+ }
+
+ // Hairline border; the hovered card firms up, the selected card gets an accent
+ // ring. No role color on the frame (that lives in the status dot). Re-establish
+ // the rounded path first: the fill/texture passes above left their own paths.
+ roundRectPath(ctx, rect, radius);
+ ctx.lineWidth = selected ? 2 : 1;
+ ctx.strokeStyle = selected
+ ? palette.accent
+ : hovered
+ ? palette.nodeBorderHover
+ : palette.nodeBorder;
+ ctx.stroke();
+
+ // Role status dot, top-right. One dot, most-salient role only.
+ if (rect.w >= DOT_MIN_PX && rect.h >= 28) {
+ const role = roleColor(node, palette);
+ if (role) {
+ ctx.beginPath();
+ ctx.arc(rect.x + rect.w - 13, rect.y + 13, 3.5, 0, Math.PI * 2);
+ ctx.fillStyle = role;
+ ctx.fill();
+ }
+ }
+
+ // The node's own text recedes faster than its frame so that, mid-zoom, the
+ // children fading in inside it read cleanly instead of overlapping its label.
+ const textAlpha = alpha * Math.max(0, 1 - 2 * t);
+ if (rect.w < LABEL_MIN_PX || rect.h < 16 || textAlpha <= 0.02) {
+ ctx.globalAlpha = 1;
+ return;
+ }
+
+ const pad = Math.min(12, rect.w * 0.06);
+ const fontSize = Math.max(11, Math.min(17, rect.h * 0.16, rect.w * 0.09));
+ ctx.globalAlpha = textAlpha;
+ ctx.fillStyle = palette.nodeText;
+ ctx.font = `600 ${fontSize}px ui-sans-serif, system-ui, sans-serif`;
+ ctx.textBaseline = "top";
+
+ // Kind glyph before the title so layers / folders / files are distinguishable
+ // at a glance (mirrors the KG cards' kind icon). The title shifts right to clear it.
+ let titleX = rect.x + pad;
+ if (rect.w >= GLYPH_MIN_PX && rect.h >= 28) {
+ const gs = fontSize;
+ ctx.save();
+ ctx.globalAlpha = textAlpha * 0.85;
+ ctx.strokeStyle = palette.nodeText;
+ ctx.lineWidth = Math.max(1, fontSize * 0.1);
+ ctx.lineJoin = "round";
+ ctx.lineCap = "round";
+ drawKindGlyph(ctx, rect.x + pad, rect.y + pad, gs, node.kind);
+ ctx.restore();
+ titleX += gs + Math.max(5, fontSize * 0.4);
+ }
+ // Leave room for the dot so a long name never collides with it.
+ const labelMax = rect.x + rect.w - pad - titleX - (rect.w >= DOT_MIN_PX ? 14 : 0);
+ const label = fitText(ctx, node.name, labelMax);
+ ctx.fillText(label, titleX, rect.y + pad);
+
+ if (rect.w >= SUMMARY_MIN_PX && rect.h >= 96 && node.summary) {
+ ctx.fillStyle = palette.textMuted;
+ ctx.font = `400 ${Math.max(11, fontSize - 3)}px ui-sans-serif, system-ui, sans-serif`;
+ const summary = fitText(ctx, node.summary, rect.w - pad * 2);
+ ctx.fillText(summary, rect.x + pad, rect.y + pad + fontSize + 6);
+ }
+
+ // Footer signal row (large cards): health dot + kind label left, primary metric right.
+ if (rect.w >= FOOTER_MIN_W_PX && rect.h >= FOOTER_MIN_H_PX) {
+ const fFont = Math.max(9, Math.min(11, fontSize - 4));
+ const baseY = rect.y + rect.h - pad;
+ let kindX = rect.x + pad;
+ // A small health dot leads the footer, colored on the same bands as the
+ // /files treemap. Only drawn when the node has a score, so unscored files
+ // (health is sparse) stay quiet rather than showing a neutral dot everywhere.
+ if (node.health_score !== null) {
+ const r = 3;
+ ctx.globalAlpha = textAlpha * 0.9;
+ ctx.fillStyle = healthColor(node.health_score, palette);
+ ctx.beginPath();
+ ctx.arc(kindX + r, baseY - fFont * 0.34, r, 0, Math.PI * 2);
+ ctx.fill();
+ kindX += 2 * r + Math.max(5, fFont * 0.5);
+ }
+ ctx.font = `600 ${fFont}px ui-sans-serif, system-ui, sans-serif`;
+ ctx.textBaseline = "bottom";
+ ctx.textAlign = "left";
+ ctx.globalAlpha = textAlpha * 0.62;
+ ctx.fillStyle = palette.textMuted;
+ ctx.fillText(KIND_LABEL[node.kind].toUpperCase(), kindX, baseY);
+ const metric = primaryMetric(node);
+ if (metric) {
+ ctx.textAlign = "right";
+ ctx.globalAlpha = textAlpha * 0.82;
+ ctx.fillStyle = palette.nodeText;
+ ctx.fillText(fitText(ctx, metric, rect.w * 0.5), rect.x + rect.w - pad, baseY);
+ }
+ // Reset the text state the rest of the renderer expects.
+ ctx.textAlign = "left";
+ ctx.textBaseline = "top";
+ }
+
+ ctx.globalAlpha = 1;
+}
+
+/** Coupling tier -> line width multiplier (kept subtle). */
+function couplingWidth(coupling: string): number {
+ if (coupling === "tight") return 1.5;
+ if (coupling === "moderate") return 1.2;
+ return 1;
+}
+
+function fillArrowHead(
+ ctx: CanvasRenderingContext2D,
+ x: number,
+ y: number,
+ angle: number,
+ size: number,
+): void {
+ ctx.save();
+ ctx.translate(x, y);
+ ctx.rotate(angle);
+ ctx.beginPath();
+ ctx.moveTo(0, 0);
+ ctx.lineTo(-size, -size * 0.5);
+ ctx.lineTo(-size, size * 0.5);
+ ctx.closePath();
+ ctx.fill();
+ ctx.restore();
+}
+
+/**
+ * Draw an aggregated relation as a directed bezier connector (see `edges.ts` for
+ * the routing). Relations are intentionally quiet: a single neutral hue, thin,
+ * and faded so they read as a hint behind the cards rather than the main event.
+ * `withArrow` is false for small boxes and unfocused edges, where a head would
+ * just add clutter.
+ */
+export function drawEdge(
+ ctx: CanvasRenderingContext2D,
+ route: EdgeRoute,
+ coupling: string,
+ palette: ZoomPalette,
+ alpha: number,
+ withArrow: boolean,
+): void {
+ if (alpha <= 0.02) return;
+ const { start, c1, c2, end, endAngle } = route;
+ const color = coupling === "tight" ? palette.edgeStrong : palette.edge;
+ ctx.globalAlpha = alpha;
+ ctx.strokeStyle = color;
+ ctx.lineWidth = EDGE_LINE_PX * couplingWidth(coupling);
+ // Stop the curve just shy of the head so the stroke and the fill do not overlap.
+ const headBack = withArrow ? ARROW_SIZE_PX : 0;
+ const ex = end.x - Math.cos(endAngle) * headBack;
+ const ey = end.y - Math.sin(endAngle) * headBack;
+ ctx.beginPath();
+ ctx.moveTo(start.x, start.y);
+ ctx.bezierCurveTo(c1.x, c1.y, c2.x, c2.y, ex, ey);
+ ctx.stroke();
+
+ if (withArrow) {
+ ctx.fillStyle = color;
+ fillArrowHead(ctx, end.x, end.y, endAngle, ARROW_SIZE_PX);
+ }
+ ctx.globalAlpha = 1;
+}
diff --git a/packages/ui/src/zoom/paper.ts b/packages/ui/src/zoom/paper.ts
new file mode 100644
index 000000000..cdd20ae71
--- /dev/null
+++ b/packages/ui/src/zoom/paper.ts
@@ -0,0 +1,49 @@
+/**
+ * Shared ruled-paper card texture for the zoom canvas. Browser code.
+ *
+ * The KG node cards (`c4/nodes/ink-node-shell.tsx`) get their tactile "ruled
+ * paper" look from a real photo, `packages/web/public/kg-card-paper.jpg`, applied
+ * as a CSS `background-image` under a translucent wash (see `--kg-card-texture` in
+ * globals.css). The zoom map is a `<canvas>`, which cannot consume a CSS
+ * background-image, so we load the same asset and expose it as a `CanvasPattern`
+ * for `drawCard` to paint under a matching per-theme wash. Reusing the one asset
+ * keeps the two surfaces visually identical, so the zoom map can stand in for the
+ * KG without a second texture to maintain.
+ *
+ * The load is async; `onReady` fires once the image is decoded so the renderer can
+ * repaint the (already-drawn) first frame with the texture in place.
+ */
+
+/** Served from `packages/web/public`; consumers must ship this asset too. */
+const PAPER_SRC = "/kg-card-paper.jpg";
+
+export class PaperTexture {
+ private img: HTMLImageElement | null = null;
+ private pattern: CanvasPattern | null = null;
+ private loaded = false;
+
+ constructor(onReady: () => void) {
+ // SSR / no-DOM: stay inert. `get()` returns null and cards fall back to a
+ // flat fill, so the canvas still renders without the texture.
+ if (typeof Image === "undefined") return;
+ const img = new Image();
+ img.onload = () => {
+ this.img = img;
+ this.loaded = true;
+ onReady();
+ };
+ img.src = PAPER_SRC;
+ }
+
+ /**
+ * The tiling pattern, built lazily against the drawing context and cached. The
+ * tile is anchored to the canvas (screen space), so cards slide over a
+ * continuous paper sheet; camera-anchored parallax (like the dot-grid) is a
+ * possible future refinement.
+ */
+ get(ctx: CanvasRenderingContext2D): CanvasPattern | null {
+ if (!this.loaded || !this.img) return null;
+ if (!this.pattern) this.pattern = ctx.createPattern(this.img, "repeat");
+ return this.pattern;
+ }
+}
diff --git a/packages/ui/src/zoom/renderer.ts b/packages/ui/src/zoom/renderer.ts
new file mode 100644
index 000000000..474dede24
--- /dev/null
+++ b/packages/ui/src/zoom/renderer.ts
@@ -0,0 +1,272 @@
+/**
+ * The canvas render loop: a thin, framework-agnostic shell around the pure math
+ * and the recursive draw. Browser code.
+ *
+ * Dirty-flag `requestAnimationFrame`: the loop only paints when something
+ * actually changed (`invalidate()`), then stops, so an idle canvas costs zero
+ * CPU. A running camera fly (`animateTo` / `frameNode`) keeps the loop alive for
+ * its duration and then settles. The backing store is sized to `devicePixelRatio`
+ * for crisp text, and a short low-detail window after a pan suppresses
+ * labels/relations so dragging stays smooth. A WebGL upgrade path is open: the
+ * draw layer is isolated behind `drawScene`, so a future GPU backend can replace
+ * it without touching camera, culling or scene code.
+ */
+
+import { type Camera, type Viewport, fitRoot, frameRect } from "./camera";
+import { flyDuration, interpolateCamera } from "./camera-anim";
+import { type DrawStats, drawScene, pickNode } from "./draw-tree";
+import { focusChain } from "./focus-path";
+import { PaperTexture } from "./paper";
+import type { ZoomScene } from "./scene";
+import type { ZoomPalette } from "./theme";
+import type { ZoomNode } from "./types";
+
+export interface FrameStats {
+ drawn: number;
+ culled: number;
+ maxDepthDrawn: number;
+ frameMs: number;
+}
+
+export interface FlyOptions {
+ /** Explicit duration in ms; omitted -> derived from travel distance. */
+ durationMs?: number;
+ /** Skip the tween and jump (used for reduced-motion and URL restore). */
+ reducedMotion?: boolean;
+ /** Fraction of the viewport the framed node should fill. */
+ fill?: number;
+}
+
+export interface ZoomRendererOptions {
+ canvas: HTMLCanvasElement;
+ palette: ZoomPalette;
+ onStats?: ((stats: FrameStats) => void) | undefined;
+ /** Fires (with the root -> focus chain) whenever the focus node changes. */
+ onFocus?: ((chain: ZoomNode[]) => void) | undefined;
+}
+
+const PAN_LOW_DETAIL_FRAMES = 2;
+
+interface Tween {
+ from: Camera;
+ to: Camera;
+ start: number;
+ dur: number;
+}
+
+function now(): number {
+ return typeof performance !== "undefined" ? performance.now() : 0;
+}
+
+export class ZoomRenderer {
+ private readonly canvas: HTMLCanvasElement;
+ private readonly ctx: CanvasRenderingContext2D;
+ private palette: ZoomPalette;
+ private readonly onStats: ((stats: FrameStats) => void) | undefined;
+ private readonly onFocus: ((chain: ZoomNode[]) => void) | undefined;
+ /** Shared ruled-paper card texture; repaints once when the asset loads. */
+ private readonly paper: PaperTexture;
+
+ private scene: ZoomScene | null = null;
+ private cam: Camera = { cx: 0.5, cy: 0.5, scale: 600 };
+ private vp: Viewport = { w: 1, h: 1 };
+ private dpr = 1;
+ private hasFramedScene = false;
+
+ private selectedId: string | null = null;
+ private hoveredId: string | null = null;
+ private lowDetailFrames = 0;
+ private tween: Tween | null = null;
+ private lastFocusId: string | null = null;
+ private dirty = true;
+ private rafId: number | null = null;
+ private lastStats: DrawStats | null = null;
+
+ constructor(opts: ZoomRendererOptions) {
+ this.canvas = opts.canvas;
+ const ctx = opts.canvas.getContext("2d");
+ if (!ctx) throw new Error("ZoomRenderer: 2D canvas context unavailable");
+ this.ctx = ctx;
+ this.palette = opts.palette;
+ this.onStats = opts.onStats;
+ this.onFocus = opts.onFocus;
+ // Repaint once the paper photo decodes so the first frame picks up the texture.
+ this.paper = new PaperTexture(() => this.invalidate());
+ this.resize();
+ }
+
+ getCamera(): Camera {
+ return this.cam;
+ }
+
+ getViewport(): Viewport {
+ return this.vp;
+ }
+
+ /** Manual camera set (pan/zoom): cancels any running fly. */
+ setCamera(cam: Camera): void {
+ this.tween = null;
+ this.cam = cam;
+ this.invalidate();
+ }
+
+ setPalette(palette: ZoomPalette): void {
+ this.palette = palette;
+ this.invalidate();
+ }
+
+ setSelected(id: string | null): void {
+ if (id === this.selectedId) return;
+ this.selectedId = id;
+ this.invalidate();
+ }
+
+ /** The hovered node lifts its incident relations and firms its border. */
+ setHovered(id: string | null): void {
+ if (id === this.hoveredId) return;
+ this.hoveredId = id;
+ this.invalidate();
+ }
+
+ setScene(scene: ZoomScene): void {
+ this.scene = scene;
+ // Only frame once we have a real layout size; otherwise the first resize
+ // callback (which delivers the true dimensions) does the initial fit.
+ if (!this.hasFramedScene && this.vp.w > 1) {
+ this.cam = fitRoot(this.vp);
+ this.hasFramedScene = true;
+ }
+ this.invalidate();
+ }
+
+ /** Has the scene been framed at least once (initial fit done)? */
+ isFramed(): boolean {
+ return this.hasFramedScene;
+ }
+
+ /**
+ * Animate the camera to `target`. Reduced-motion or duration<=0 jumps. Calling
+ * this mid-fly is intentional: `this.cam` is the live tweened position the last
+ * frame drew, so a new fly starts smoothly from there (and `flyDuration` sizes
+ * itself to the now-shorter remaining travel) rather than snapping.
+ */
+ animateTo(target: Camera, opts: FlyOptions = {}): void {
+ if (opts.reducedMotion) {
+ this.setCamera(target);
+ return;
+ }
+ const dur = opts.durationMs ?? flyDuration(this.cam, target);
+ if (dur <= 0) {
+ this.setCamera(target);
+ return;
+ }
+ this.tween = { from: this.cam, to: target, start: now(), dur };
+ this.invalidate();
+ }
+
+ /** Fly the camera to frame a node by id. Returns false if it is not laid out. */
+ frameNode(id: string, opts: FlyOptions = {}): boolean {
+ if (!this.scene) return false;
+ const rect = this.scene.worldRects.get(id);
+ if (!rect) return false;
+ this.animateTo(frameRect(this.vp, rect, opts.fill ?? 0.72), opts);
+ return true;
+ }
+
+ /** Re-read the element size and resize the backing store for crisp pixels. */
+ resize(): void {
+ const cssW = Math.max(1, this.canvas.clientWidth);
+ const cssH = Math.max(1, this.canvas.clientHeight);
+ const dpr = typeof window === "undefined" ? 1 : window.devicePixelRatio || 1;
+ this.dpr = dpr;
+ this.vp = { w: cssW, h: cssH };
+ this.canvas.width = Math.round(cssW * dpr);
+ this.canvas.height = Math.round(cssH * dpr);
+ // Deferred initial fit, once the element has a real size.
+ if (this.scene && !this.hasFramedScene && cssW > 1) {
+ this.cam = fitRoot(this.vp);
+ this.hasFramedScene = true;
+ }
+ this.invalidate();
+ }
+
+ /** Flag the next pan window so labels/relations are suppressed briefly. */
+ markPanFrame(): void {
+ this.lowDetailFrames = PAN_LOW_DETAIL_FRAMES;
+ }
+
+ /** Hit-test the most recently drawn frame. */
+ pick(sx: number, sy: number): string | null {
+ return this.lastStats ? pickNode(this.lastStats, sx, sy) : null;
+ }
+
+ invalidate(): void {
+ this.dirty = true;
+ if (this.rafId === null && typeof requestAnimationFrame !== "undefined") {
+ this.rafId = requestAnimationFrame(this.frame);
+ }
+ }
+
+ destroy(): void {
+ if (this.rafId !== null && typeof cancelAnimationFrame !== "undefined") {
+ cancelAnimationFrame(this.rafId);
+ }
+ this.rafId = null;
+ }
+
+ private emitFocus(): void {
+ if (!this.scene || !this.onFocus) return;
+ const chain = focusChain(this.scene, this.cam, this.vp);
+ const id = chain.length > 0 ? chain[chain.length - 1]!.id : this.scene.rootId;
+ if (id !== this.lastFocusId) {
+ this.lastFocusId = id;
+ this.onFocus(chain);
+ }
+ }
+
+ private readonly frame = (): void => {
+ this.rafId = null;
+
+ let animating = false;
+ if (this.tween) {
+ const t = (now() - this.tween.start) / this.tween.dur;
+ if (t >= 1) {
+ this.cam = this.tween.to;
+ this.tween = null;
+ } else {
+ this.cam = interpolateCamera(this.tween.from, this.tween.to, t);
+ animating = true;
+ }
+ this.dirty = true;
+ }
+
+ if (!this.dirty) return;
+
+ const start = now();
+ this.ctx.setTransform(this.dpr, 0, 0, this.dpr, 0, 0);
+
+ if (this.scene) {
+ const lowDetail = this.lowDetailFrames > 0;
+ this.lastStats = drawScene(this.ctx, this.scene, this.cam, this.vp, this.palette, {
+ selectedId: this.selectedId,
+ hoveredId: this.hoveredId,
+ lowDetail,
+ paper: this.paper,
+ });
+ if (this.onStats) {
+ this.onStats({
+ drawn: this.lastStats.drawn,
+ culled: this.lastStats.culled,
+ maxDepthDrawn: this.lastStats.maxDepthDrawn,
+ frameMs: now() - start,
+ });
+ }
+ this.emitFocus();
+ }
+
+ this.dirty = false;
+ if (this.lowDetailFrames > 0) this.lowDetailFrames--;
+ // Keep the loop alive while a fly is in flight or a pan window is settling.
+ if (animating || this.lowDetailFrames > 0) this.invalidate();
+ };
+}
diff --git a/packages/ui/src/zoom/scene.ts b/packages/ui/src/zoom/scene.ts
new file mode 100644
index 000000000..bf6ac7113
--- /dev/null
+++ b/packages/ui/src/zoom/scene.ts
@@ -0,0 +1,58 @@
+/**
+ * Pure scene model derived from the fetched zoom map. Browser-free.
+ *
+ * Indexes the flat node list by id, precomputes every node's absolute world
+ * rect (see `geometry.ts`) and buckets relations by their `parent_id` so the
+ * renderer can pull just the relations relevant to whichever node it has zoomed
+ * into. Rebuilt only when a new map arrives (or a deeper subtree is fetched),
+ * never per frame.
+ */
+
+import type { Rect } from "./camera";
+import { computeWorldRects } from "./geometry";
+import type { PackLayoutOptions } from "./layout";
+import type { ZoomMap, ZoomNode, ZoomRelation } from "./types";
+
+export interface ZoomScene {
+ rootId: string;
+ nodes: Map<string, ZoomNode>;
+ worldRects: Map<string, Rect>;
+ relationsByParent: Map<string, ZoomRelation[]>;
+ /** Total nodes that received a world rect (reachable, laid-out). */
+ laidOutCount: number;
+}
+
+export function buildScene(map: ZoomMap, layout: PackLayoutOptions = {}): ZoomScene {
+ const nodes = new Map<string, ZoomNode>();
+ for (const n of map.nodes) nodes.set(n.id, n);
+
+ const worldRects = computeWorldRects(nodes, map.root_id, layout);
+
+ const relationsByParent = new Map<string, ZoomRelation[]>();
+ for (const r of map.relations) {
+ // Only keep relations whose endpoints both exist and are laid out, so the
+ // renderer never dereferences a pruned node.
+ if (!worldRects.has(r.source_id) || !worldRects.has(r.target_id)) continue;
+ const bucket = relationsByParent.get(r.parent_id);
+ if (bucket) bucket.push(r);
+ else relationsByParent.set(r.parent_id, [r]);
+ }
+
+ return {
+ rootId: map.root_id,
+ nodes,
+ worldRects,
+ relationsByParent,
+ laidOutCount: worldRects.size,
+ };
+}
+
+/** Resolve a node's children to node objects, skipping any missing/unlaid-out. */
+export function childNodes(scene: ZoomScene, node: ZoomNode): ZoomNode[] {
+ const out: ZoomNode[] = [];
+ for (const id of node.children) {
+ const child = scene.nodes.get(id);
+ if (child && scene.worldRects.has(id)) out.push(child);
+ }
+ return out;
+}
diff --git a/packages/ui/src/zoom/theme.ts b/packages/ui/src/zoom/theme.ts
new file mode 100644
index 000000000..2f8c1ff0e
--- /dev/null
+++ b/packages/ui/src/zoom/theme.ts
@@ -0,0 +1,125 @@
+/**
+ * Theme palette for the zoom canvas.
+ *
+ * Canvas 2D needs concrete color strings (it cannot consume `var(--token)`), so
+ * we resolve the design-system CSS custom properties to their computed values
+ * at runtime via the shared token resolver, and re-resolve on theme switch. No
+ * color literals live here (the file is scanned by the no-raw-hex gate): every
+ * value comes from a `--color-*` token, and the SSR/no-window fallback is a CSS
+ * named color, never a hex string.
+ */
+
+import { resolveTokens } from "../shared/use-theme-tokens";
+
+export interface ZoomPalette {
+ bg: string;
+ /** Faint minor grid-line color painted under the cards (graph-paper backdrop). */
+ grid: string;
+ /** Slightly firmer major grid line, drawn every few cells for depth. */
+ gridStrong: string;
+ /** Leaf (file) card fill. */
+ nodeFill: string;
+ /** Container (folder/group/layer/system) card fill. */
+ nodeFillAlt: string;
+ /** Hairline card border. */
+ nodeBorder: string;
+ /** Slightly stronger border for the hovered card. */
+ nodeBorderHover: string;
+ /** Soft drop-shadow color for card elevation. */
+ shadow: string;
+ /** Faint ruled-line color giving cards a notebook-paper texture. */
+ rule: string;
+ /**
+ * Translucent wash painted over the shared paper photo so the card keeps its
+ * tint and text contrast (mirrors the KG `--kg-card-texture` wash). Its alpha
+ * carries the per-theme paper strength, so the same compositing works in light
+ * and dark without branching.
+ */
+ paperWash: string;
+ nodeText: string;
+ textMuted: string;
+ accent: string;
+ /** Neutral connector hue (edges are intentionally low-emphasis). */
+ edge: string;
+ /** Slightly stronger neutral for tightly-coupled relations. */
+ edgeStrong: string;
+ hotspot: string;
+ dead: string;
+ entry: string;
+ flow: string;
+ /** Code-health traffic-light inks, matching the /files treemap bands. */
+ healthAlert: string;
+ healthWarning: string;
+ healthHealthy: string;
+ /** Neutral ink for an unscored file/subtree (health is sparse). */
+ healthNeutral: string;
+}
+
+/** Map each palette slot to its design-system token. */
+const TOKEN_SPEC: Record<keyof ZoomPalette, string> = {
+ // Paint the canvas in the page background so the map sits on the same surface
+ // as the rest of the page (no distinct dark "container" box around it).
+ bg: "--color-bg-root",
+ grid: "--color-zoom-grid",
+ gridStrong: "--color-zoom-grid-strong",
+ nodeFill: "--color-zoom-card-fill",
+ nodeFillAlt: "--color-zoom-card-fill-2",
+ nodeBorder: "--color-zoom-card-border",
+ nodeBorderHover: "--color-zoom-card-border-hover",
+ shadow: "--color-zoom-card-shadow",
+ rule: "--color-zoom-card-rule",
+ paperWash: "--color-zoom-card-paper-wash",
+ nodeText: "--color-zoom-card-text",
+ textMuted: "--color-text-muted",
+ accent: "--color-accent-primary",
+ edge: "--color-zoom-edge",
+ edgeStrong: "--color-zoom-edge-strong",
+ hotspot: "--color-risk-high",
+ dead: "--color-stale",
+ entry: "--color-success",
+ flow: "--color-accent-secondary",
+ // Same tokens the health tokens.ts `healthInk` maps to, so a zoom card and the
+ // /files treemap tile agree on what counts as red/amber/green.
+ healthAlert: "--color-error",
+ healthWarning: "--color-warning",
+ healthHealthy: "--color-success",
+ healthNeutral: "--color-text-tertiary",
+};
+
+/** CSS named-color fallbacks (lint-safe, only hit before tokens resolve). */
+const FALLBACK: ZoomPalette = {
+ bg: "white",
+ grid: "rgba(0,0,0,0.045)",
+ gridStrong: "rgba(0,0,0,0.08)",
+ nodeFill: "white",
+ nodeFillAlt: "white",
+ nodeBorder: "gainsboro",
+ nodeBorderHover: "silver",
+ shadow: "rgba(0,0,0,0.1)",
+ rule: "transparent",
+ paperWash: "rgba(255,255,255,0.82)",
+ nodeText: "black",
+ textMuted: "gray",
+ accent: "blue",
+ edge: "silver",
+ edgeStrong: "gray",
+ hotspot: "crimson",
+ dead: "gray",
+ entry: "green",
+ flow: "teal",
+ healthAlert: "crimson",
+ healthWarning: "orange",
+ healthHealthy: "green",
+ healthNeutral: "gray",
+};
+
+/** Resolve the live palette from the document theme. Call on the client only. */
+export function resolveZoomPalette(): ZoomPalette {
+ const resolved = resolveTokens(TOKEN_SPEC);
+ const out = {} as ZoomPalette;
+ for (const key in TOKEN_SPEC) {
+ const k = key as keyof ZoomPalette;
+ out[k] = resolved[k] || FALLBACK[k];
+ }
+ return out;
+}
diff --git a/packages/ui/src/zoom/types.ts b/packages/ui/src/zoom/types.ts
new file mode 100644
index 000000000..5ea27ecef
--- /dev/null
+++ b/packages/ui/src/zoom/types.ts
@@ -0,0 +1,78 @@
+/**
+ * Zoom-map data model (mirror of the backend response).
+ *
+ * The backend serves one nested containment tree (system -> layer -> group ->
+ * folder -> file) as a flat list of nodes, each carrying its own `id`, plus
+ * parent-relative `relations`. The renderer indexes the list by id and rebuilds
+ * the tree from `parent_id` / `children`. Every node's `layout` rect is in its
+ * parent's `[0,1]` space, which composes multiplicatively down the tree into an
+ * absolute world rect for clip-and-scale drawing.
+ *
+ * Source of truth: `packages/server/src/repowise/server/schemas/zoom.py`.
+ */
+
+/** Node kinds, coarsest to finest. A leaf is always `file`. */
+export type ZoomKind = "system" | "layer" | "group" | "folder" | "file";
+
+/** A child's allocation inside its parent, in parent `[0,1]` space. */
+export interface ZoomRect {
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+}
+
+/** Counts rolled up over a node's subtree (a file is its own subtree). */
+export interface ZoomMetrics {
+ file_count: number;
+ descendant_count: number;
+ hotspot_count: number;
+ dead_count: number;
+ entry_point_count: number;
+ on_flow_count: number;
+}
+
+export interface ZoomNode {
+ id: string;
+ parent_id: string | null;
+ level: number;
+ kind: ZoomKind;
+ name: string;
+ path: string;
+ children: string[];
+ importance: number;
+ sibling_rank: number;
+ metrics: ZoomMetrics;
+ layout: ZoomRect | null;
+ summary: string;
+ language: string | null;
+ /** Code-health score (0-10, higher = healthier), matching the /files treemap.
+ * Null when the file/subtree was unscored (health is sparse) — read as neutral. */
+ health_score: number | null;
+ is_entry_point: boolean;
+ is_hotspot: boolean;
+ is_dead: boolean;
+ is_test: boolean;
+ on_flow: boolean;
+}
+
+/** An aggregated edge between two sibling subtrees under a shared parent. */
+export interface ZoomRelation {
+ parent_id: string;
+ source_id: string;
+ target_id: string;
+ label: string;
+ edge_count: number;
+ coupling: string; // loose | moderate | tight
+}
+
+/** The complete zoom map for one repository at a given depth/focus. */
+export interface ZoomMap {
+ root_id: string;
+ project_name: string;
+ total_files: number;
+ max_depth: number;
+ truncated: boolean;
+ nodes: ZoomNode[];
+ relations: ZoomRelation[];
+}
diff --git a/packages/ui/src/zoom/zoom-transition.ts b/packages/ui/src/zoom/zoom-transition.ts
new file mode 100644
index 000000000..eeef6ea8c
--- /dev/null
+++ b/packages/ui/src/zoom/zoom-transition.ts
@@ -0,0 +1,83 @@
+/**
+ * Pure continuous-zoom fade math. Browser-free and unit-testable.
+ *
+ * A single per-node scalar `t` drives the cross-fade. `t` is derived from the
+ * node's on-screen pixel width: while a node is small it is drawn as one solid
+ * card (`t = 0`); as you zoom in and it grows past `start` px, its body fades
+ * out while its children fade in, completing at `end` px (`t = 1`). The same
+ * `t` makes a card *visibly open into its children* rather than being remounted.
+ */
+
+import {
+ END_FRACTION,
+ END_MAX_PX,
+ END_MIN_PX,
+ START_FRACTION,
+ START_MAX_PX,
+ START_MIN_PX,
+} from "./constants";
+
+export interface FadeThresholds {
+ /** Screen-px node width where the body begins to fade and children appear. */
+ start: number;
+ /** Screen-px node width where the body is gone and children are fully in. */
+ end: number;
+}
+
+export interface FadeAlphas {
+ /** Alpha for the node's own card body (label, fill, chips). */
+ body: number;
+ /** Base alpha handed to the node's children subtree. */
+ child: number;
+}
+
+function clamp01(v: number): number {
+ return v < 0 ? 0 : v > 1 ? 1 : v;
+}
+
+/**
+ * Fade thresholds scale with canvas width so the experience is consistent
+ * across a phone and a 4K monitor. Clamped to sane absolute bounds.
+ */
+export function expandThresholds(canvasW: number): FadeThresholds {
+ const start = Math.min(START_MAX_PX, Math.max(START_MIN_PX, canvasW * START_FRACTION));
+ const end = Math.min(END_MAX_PX, Math.max(END_MIN_PX, canvasW * END_FRACTION));
+ // Guarantee a non-degenerate interval even after clamping.
+ return { start, end: Math.max(end, start + 1) };
+}
+
+/**
+ * The transition scalar for a node `screenW` pixels wide. `hasChildren` is
+ * false for file leaves, which never cross-fade (they are the deepest content).
+ */
+export function transitionT(
+ screenW: number,
+ thresholds: FadeThresholds,
+ hasChildren: boolean,
+): number {
+ if (!hasChildren) return 0;
+ return clamp01((screenW - thresholds.start) / (thresholds.end - thresholds.start));
+}
+
+/**
+ * Split an inherited alpha into the body alpha (fades out with `t`) and the
+ * child alpha (fades in with `t`).
+ */
+export function fadeAlphas(inherited: number, t: number): FadeAlphas {
+ return { body: inherited * (1 - t), child: inherited * t };
+}
+
+/**
+ * Leaf-cap: once a leaf would grow past `end` px it stops growing on screen, so
+ * a file card "freezes" at a readable size while the camera keeps zooming into
+ * empty space. Returns a scale `<= 1` to apply about the node's centre, or `1`
+ * when no cap is needed.
+ */
+export function leafCapScale(
+ screenW: number,
+ thresholds: FadeThresholds,
+ hasChildren: boolean,
+): number {
+ if (hasChildren || screenW <= thresholds.end) return 1;
+ return thresholds.end / screenW;
+}
diff --git a/packages/ui/styles/globals.css b/packages/ui/styles/globals.css
index bdb7b3da6..df79e7ff4 100644
--- a/packages/ui/styles/globals.css
+++ b/packages/ui/styles/globals.css
@@ -157,6 +157,29 @@
--color-diagram-cluster-border: #826aa0; /* plum-400 */
--color-diagram-grid: rgba(245, 149, 32, 0.10); /* faint orange grid */
+ /* Zoom canvas — premium "floating card" surfaces (Linear/Stripe idiom):
+ clean cards on a faint dot-grid, hairline borders + soft shadow for depth,
+ role shown as a small status dot (not a colored frame). Kept separate from
+ the kg-node "blueprint" tokens so the C4 view that consumes those is
+ untouched. LIGHT: white cards on warm paper; DARK overrides below. */
+ --color-zoom-card-fill: #ffffff; /* leaf (file) card */
+ --color-zoom-card-fill-2: #fbf4ee; /* container (folder/group/layer) card */
+ --color-zoom-card-text: #241b2c;
+ --color-zoom-card-border: rgba(88, 67, 108, 0.14); /* hairline */
+ --color-zoom-card-border-hover: rgba(88, 67, 108, 0.28);
+ --color-zoom-card-shadow: rgba(36, 27, 44, 0.10); /* soft elevation */
+ --color-zoom-edge: rgba(36, 27, 44, 0.20); /* neutral connector */
+ --color-zoom-edge-strong: rgba(36, 27, 44, 0.38); /* tight coupling */
+ --color-zoom-card-rule: rgba(36, 27, 44, 0.05); /* faint notebook ruled lines */
+ /* Wash painted over the shared /kg-card-paper.jpg photo on each card (canvas
+ equivalent of --kg-card-texture). Alpha = 1 - paper strength: at 0.82 the
+ ruled-paper grain shows through ~18%, matching the KG cards' feel. */
+ --color-zoom-card-paper-wash: rgba(255, 255, 255, 0.82);
+ /* Graph-paper backdrop for the canvas: faint minor lines with a slightly
+ firmer major line every few cells, for a premium "designed surface" feel. */
+ --color-zoom-grid: rgba(36, 27, 44, 0.045);
+ --color-zoom-grid-strong: rgba(36, 27, 44, 0.08);
+
/* Language colors (canonical brand hues — theme-independent) */
--color-lang-python: #3776ab;
--color-lang-typescript: #3178c6;
@@ -382,6 +405,22 @@
--color-diagram-cluster-border: #a98fc4;
--color-diagram-grid: rgba(222, 210, 235, 0.05);
+ /* Zoom canvas — dark: elevated graphite cards on the near-black canvas. */
+ --color-zoom-card-fill: #2b2c2e; /* leaf card (bg-elevated) */
+ --color-zoom-card-fill-2: #232325; /* container card (bg-surface) */
+ --color-zoom-card-text: #ececed;
+ --color-zoom-card-border: rgba(255, 255, 255, 0.10);
+ --color-zoom-card-border-hover: rgba(255, 255, 255, 0.20);
+ --color-zoom-card-shadow: rgba(0, 0, 0, 0.45);
+ --color-zoom-edge: rgba(255, 255, 255, 0.16);
+ --color-zoom-edge-strong: rgba(255, 255, 255, 0.30);
+ --color-zoom-card-rule: rgba(255, 255, 255, 0.06);
+ /* Heavier wash in dark (matches the KG dark texture): the light paper photo
+ only reads as ~10% relief so cards stay graphite instead of washing out. */
+ --color-zoom-card-paper-wash: rgba(43, 44, 46, 0.90);
+ --color-zoom-grid: rgba(255, 255, 255, 0.03);
+ --color-zoom-grid-strong: rgba(255, 255, 255, 0.055);
+
/* C4 / graph canvas surfaces — dark variants (the var()-derived aliases
flip on their own; only the explicit rgbas need a dark override). */
--color-canvas-dot: rgba(255, 255, 255, 0.05);
diff --git a/packages/web/src/app/repos/[id]/knowledge-graph/page.tsx b/packages/web/src/app/repos/[id]/knowledge-graph/page.tsx
index ce9d1d4ca..ff00601c5 100644
--- a/packages/web/src/app/repos/[id]/knowledge-graph/page.tsx
+++ b/packages/web/src/app/repos/[id]/knowledge-graph/page.tsx
@@ -1,41 +1,123 @@
"use client";
/**
- * Knowledge Graph — `/repos/[id]/knowledge-graph`.
+ * Knowledge Graph: `/repos/[id]/knowledge-graph`.
*
- * The single curated mental-model surface: the layered architecture view
- * (tour, personas, layered C4). This route claims the "Knowledge Graph" name
- * so it stops leaking across the constellation, the layers error copy and the
- * legacy C4 header. No lens toggle — Communities and the dependency graphs live
- * under Architecture.
+ * A continuous-zoom canvas of the system: start at the whole repo and zoom
+ * *into* a card to reveal its layers, groups, folders and files, ranked by how
+ * the system actually runs. The page wraps the shared `<ZoomCanvas>` with the
+ * navigation chrome (breadcrumb, search-to-zoom, detail panel, first-visit hint)
+ * and keeps the focused node in the URL so a zoom state is shareable.
*
- * Mounts the layered view client-side (it drives a Zustand store and ReactFlow).
+ * This replaced the earlier node-link / layered-C4 Knowledge Graph. The reusable
+ * C4 machinery it used to render still lives on (backend `c4_builder`, the zoom
+ * map's own `/zoom-map` endpoint, and `@repowise-dev/ui/c4` for the VS Code
+ * webview); only the old web surface for it was retired.
*/
-import { use } from "react";
-import { Waypoints } from "lucide-react";
+import { use, useCallback, useMemo, useRef, useState } from "react";
+import { parseAsString, useQueryState } from "nuqs";
+import { ScanSearch } from "lucide-react";
import { PageShell } from "@repowise-dev/ui/shared/page-shell";
-import { KnowledgeGraphView } from "@/components/architecture/c4-view";
-import { useRepo } from "@/lib/hooks/use-repo";
-
-export default function KnowledgeGraphPage({
- params,
-}: {
- params: Promise<{ id: string }>;
-}) {
+import { ZoomCanvas } from "@repowise-dev/ui/zoom";
+import type { ZoomCanvasHandle, ZoomNode } from "@repowise-dev/ui/zoom";
+import { useZoomMap } from "@/lib/hooks/use-graph";
+import { ZoomBreadcrumb } from "@/components/zoom/zoom-breadcrumb";
+import { ZoomSearch } from "@/components/zoom/zoom-search";
+import { ZoomDetailPanel } from "@/components/zoom/zoom-detail-panel";
+import { ZoomHint } from "@/components/zoom/zoom-hint";
+
+export default function KnowledgeGraphPage({ params }: { params: Promise<{ id: string }> }) {
const { id: repoId } = use(params);
- const { repo } = useRepo(repoId);
- const repoName = repo?.name ?? "System";
+
+ const { zoomMap, error, isLoading } = useZoomMap(repoId);
+ const canvasRef = useRef<ZoomCanvasHandle | null>(null);
+
+ const [focusParam, setFocusParam] = useQueryState(
+ "focus",
+ parseAsString.withOptions({ history: "replace", shallow: true }),
+ );
+ const [chain, setChain] = useState<ZoomNode[]>([]);
+ const [selected, setSelected] = useState<ZoomNode | null>(null);
+
+ // Snapshot the initial URL focus once so later URL writes don't re-trigger a jump.
+ const initialFocus = useRef(focusParam ?? undefined).current;
+
+ const flyTo = useCallback((id: string) => {
+ canvasRef.current?.flyTo(id);
+ }, []);
+
+ const onFocusChange = useCallback(
+ (next: ZoomNode[]) => {
+ setChain(next);
+ const deepest = next[next.length - 1];
+ // Keep the URL in step with where the camera has settled (root = no param).
+ void setFocusParam(deepest && deepest.parent_id ? deepest.id : null);
+ },
+ [setFocusParam],
+ );
+
+ const allNodes = useMemo(() => zoomMap?.nodes ?? [], [zoomMap]);
+ const nodeById = useMemo(() => new Map(allNodes.map((n) => [n.id, n])), [allNodes]);
+ const showStats = process.env.NODE_ENV === "development";
return (
<PageShell
title="Knowledge Graph"
- icon={<Waypoints className="h-5 w-5 text-[var(--color-accent-primary)]" />}
- description="The curated layered view of the system — tour it, switch personas, drill into a layer."
+ icon={<ScanSearch className="h-5 w-5 text-[var(--color-accent-primary)]" />}
+ description="Explore your codebase like a map: scroll to zoom, drag to pan, and double-click any card to dive into its layers, folders and files, ranked by how the code actually runs."
maxWidth="wide"
>
- <div className="flex h-[calc(100vh-13rem)] min-h-[480px] flex-col overflow-hidden rounded-lg">
- <KnowledgeGraphView repoId={repoId} repoName={repoName} />
+ {/* Full-bleed canvas (no framing border): the map blends into the page.
+ Breadcrumb + search float over the canvas as an overlay rather than a
+ chrome bar, and a first-visit hint teaches the zoom gestures, so the map
+ gets the whole area. */}
+ <div className="relative h-[calc(100vh-12rem)] min-h-[520px] overflow-hidden rounded-lg">
+ {isLoading && (
+ <div className="flex h-full items-center justify-center text-sm text-[var(--color-text-secondary)]">
+ Building the knowledge graph…
+ </div>
+ )}
+ {error && !isLoading && (
+ <div className="flex h-full items-center justify-center text-sm text-[var(--color-error)]">
+ Could not load the knowledge graph for this repository.
+ </div>
+ )}
+ {zoomMap && !isLoading && (
+ <>
+ <ZoomCanvas
+ ref={canvasRef}
+ data={zoomMap}
+ initialFocusId={initialFocus}
+ onSelect={setSelected}
+ onFocusChange={onFocusChange}
+ showStats={showStats}
+ />
+ <div className="pointer-events-none absolute inset-x-0 top-0 z-10 flex items-start justify-between gap-3 p-3">
+ <div className="pointer-events-auto rounded-lg border border-[var(--color-border-subtle)] bg-[var(--color-bg-glass)] px-2 py-1 shadow-sm backdrop-blur">
+ <ZoomBreadcrumb chain={chain} onCrumb={flyTo} />
+ </div>
+ <div className="pointer-events-auto">
+ <ZoomSearch
+ nodes={allNodes}
+ onPick={(id) => {
+ flyTo(id);
+ setSelected(nodeById.get(id) ?? null);
+ }}
+ />
+ </div>
+ </div>
+ {selected && (
+ <ZoomDetailPanel
+ node={selected}
+ repoId={repoId}
+ onClose={() => setSelected(null)}
+ onZoom={(id) => flyTo(id)}
+ />
+ )}
+ <ZoomHint />
+ </>
+ )}
</div>
</PageShell>
);
diff --git a/packages/web/src/app/repos/[id]/zoom/page.tsx b/packages/web/src/app/repos/[id]/zoom/page.tsx
new file mode 100644
index 000000000..d2fbd3281
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/zoom/page.tsx
@@ -0,0 +1,19 @@
+import { redirect } from "next/navigation";
+
+/**
+ * Legacy route: the zoom map now lives at `/knowledge-graph` (it replaced the
+ * old node-link view under that name). Keep old `/zoom` links working, forwarding
+ * a `?focus=` deep-link if present.
+ */
+export default async function ZoomRedirect({
+ params,
+ searchParams,
+}: {
+ params: Promise<{ id: string }>;
+ searchParams: Promise<{ focus?: string }>;
+}) {
+ const { id } = await params;
+ const { focus } = await searchParams;
+ const qs = focus ? `?focus=${encodeURIComponent(focus)}` : "";
+ redirect(`/repos/${id}/knowledge-graph${qs}`);
+}
diff --git a/packages/web/src/components/architecture/c4-view.tsx b/packages/web/src/components/architecture/c4-view.tsx
deleted file mode 100644
index 35dd885cd..000000000
--- a/packages/web/src/components/architecture/c4-view.tsx
+++ /dev/null
@@ -1,295 +0,0 @@
-"use client";
-
-/**
- * Knowledge Graph view — the curated layered architecture surface.
- *
- * URL params are synced bidirectionally with the Zustand store so that
- * refresh + share preserve the view state.
- */
-
-import { useCallback, useEffect, useRef } from "react";
-import { useQueryState, parseAsString, parseAsStringLiteral } from "nuqs";
-import {
- ArchCanvas,
- useArchitectureStore,
- useArchitectureLayout,
- useArchitectureNavigation,
- SearchBar,
- ArchBreadcrumb,
- PersonaSelector,
- ArchTourButton,
- NodeTypeCategoryFilters,
- FilterPanel,
- CodeViewer,
- PathFinderModal,
- type Persona,
-} from "@repowise-dev/ui/c4";
-import { ReactFlowProvider, useReactFlow, type Node } from "@xyflow/react";
-import { useArchitectureView } from "@/lib/hooks/use-architecture";
-import { ArchDetailPanelHost } from "@/components/c4/arch-detail-panel-host";
-
-const VIEW_VALUES = ["overview", "groups", "detail"] as const;
-const PERSONA_VALUES = ["overview", "learn", "deep-dive"] as const;
-// Unified click grammar (kg-ux plan B5): single click = select + inspect on
-// every node kind. Only true non-entities stay unselectable — portals are
-// navigation stubs, the scope frame is a pointer-events-none underlay.
-const SYNTHETIC_NODE_TYPES = new Set(["portal", "scopeFrame"]);
-
-/**
- * The curated layered architecture view, ready to mount client-side. The
- * Knowledge Graph route renders this inside a `PageShell` (passing
- * `embedded` so the inner title band is suppressed and the page owns the
- * heading). Must be a client component because it drives a Zustand store and
- * `useReactFlow`.
- */
-export function KnowledgeGraphView({
- repoId,
- repoName,
-}: {
- repoId: string;
- repoName: string;
-}) {
- return (
- <ReactFlowProvider>
- <ArchitectureViewInner repoId={repoId} repoName={repoName} embedded />
- </ReactFlowProvider>
- );
-}
-
-function ArchitectureViewInner({
- repoId,
- repoName,
- embedded,
-}: {
- repoId: string;
- repoName: string;
- embedded?: boolean;
-}) {
- const { view, error, isLoading } = useArchitectureView(repoId);
- const { fitView } = useReactFlow();
-
- // Renamed from "view" — the parent Architecture page owns `?view=` for its
- // sub-view switcher (graph | c4 | symbols).
- const [, setViewParam] = useQueryState(
- "c4view",
- parseAsStringLiteral(VIEW_VALUES).withDefault("overview"),
- );
- const [layerParam, setLayerParam] = useQueryState("layer", parseAsString);
- const [groupParam, setGroupParam] = useQueryState("group", parseAsString);
- const [nodeParam, setNodeParam] = useQueryState("node", parseAsString);
- const [personaParam, setPersonaParam] = useQueryState(
- "persona",
- parseAsStringLiteral(PERSONA_VALUES).withDefault("overview"),
- );
-
- const setView = useArchitectureStore((s) => s.setView);
- const navigationLevel = useArchitectureStore((s) => s.navigationLevel);
- const activeLayerId = useArchitectureStore((s) => s.activeLayerId);
- const activeSubGroupId = useArchitectureStore((s) => s.activeSubGroupId);
- const selectedNodeId = useArchitectureStore((s) => s.selectedNodeId);
- const persona = useArchitectureStore((s) => s.persona);
- const drillIntoLayer = useArchitectureStore((s) => s.drillIntoLayer);
- const drillIntoSubGroup = useArchitectureStore((s) => s.drillIntoSubGroup);
- const selectNode = useArchitectureStore((s) => s.selectNode);
- const setPersona = useArchitectureStore((s) => s.setPersona);
- const setReactFlowInstance = useArchitectureStore((s) => s.setReactFlowInstance);
- const pathFinderOpen = useArchitectureStore((s) => s.pathFinderOpen);
-
- useEffect(() => {
- if (view) setView(view);
- }, [view, setView]);
-
- const initializedRef = useRef(false);
- useEffect(() => {
- if (!view || initializedRef.current) return;
- initializedRef.current = true;
-
- if (personaParam && personaParam !== "overview") {
- setPersona(personaParam as Persona);
- }
- if (layerParam) {
- drillIntoLayer(layerParam);
- }
- if (groupParam) {
- drillIntoSubGroup(groupParam);
- }
- if (nodeParam) {
- selectNode(nodeParam);
- }
- }, [view, layerParam, groupParam, nodeParam, personaParam,
- drillIntoLayer, drillIntoSubGroup, selectNode, setPersona]);
-
- const syncingRef = useRef(false);
- useEffect(() => {
- // Until the deep-link restore above has run, the store still holds its
- // default overview state — syncing that to the URL would null out the
- // very params the restore is about to read, so every shared link
- // snapped back to the overview.
- if (!initializedRef.current) return;
- if (syncingRef.current) return;
- syncingRef.current = true;
- void setViewParam(
- navigationLevel === "layer-detail"
- ? "detail"
- : navigationLevel === "layer-groups"
- ? "groups"
- : "overview",
- );
- void setLayerParam(activeLayerId);
- void setGroupParam(activeSubGroupId);
- void setNodeParam(selectedNodeId);
- void setPersonaParam(persona);
- syncingRef.current = false;
- }, [navigationLevel, activeLayerId, activeSubGroupId, selectedNodeId, persona,
- setViewParam, setLayerParam, setGroupParam, setNodeParam, setPersonaParam]);
-
- useArchitectureNavigation();
-
- const { nodes, edges, loading: layoutLoading, hiddenEdgeCount } = useArchitectureLayout();
-
- const pendingFitRef = useRef(false);
- const prevNavRef = useRef({ navigationLevel, activeLayerId });
- useEffect(() => {
- if (
- prevNavRef.current.navigationLevel !== navigationLevel ||
- prevNavRef.current.activeLayerId !== activeLayerId
- ) {
- pendingFitRef.current = true;
- prevNavRef.current = { navigationLevel, activeLayerId };
- }
- }, [navigationLevel, activeLayerId]);
-
- useEffect(() => {
- if (!pendingFitRef.current || nodes.length === 0) return;
- pendingFitRef.current = false;
- const raf = requestAnimationFrame(() => {
- fitView({ duration: 400, padding: 0.2 });
- });
- return () => cancelAnimationFrame(raf);
- }, [nodes, fitView]);
-
- // Camera ease on select (kg-ux plan B5): frame the selected node without
- // drilling. Eases once per selection — layout refreshes (dimming etc.)
- // never re-center a camera the user has panned away.
- const lastEasedRef = useRef<string | null>(null);
- useEffect(() => {
- if (!selectedNodeId) {
- lastEasedRef.current = null;
- return;
- }
- if (lastEasedRef.current === selectedNodeId) return;
- if (!nodes.some((n) => n.id === selectedNodeId)) return;
- lastEasedRef.current = selectedNodeId;
- const raf = requestAnimationFrame(() => {
- fitView({ nodes: [{ id: selectedNodeId }], duration: 250, padding: 0.4, maxZoom: 1.15 });
- });
- return () => cancelAnimationFrame(raf);
- }, [selectedNodeId, nodes, fitView]);
-
- const handleNodeClick = useCallback(
- (_: React.MouseEvent, node: Node) => {
- if (SYNTHETIC_NODE_TYPES.has(node.type ?? "")) return;
- selectNode(node.id);
- },
- [selectNode],
- );
-
- // Double click = drill (grammar): layer → groups/detail, group → detail,
- // folder → expand/collapse. (Drilling clears selection in the store.)
- const handleNodeDoubleClick = useCallback(
- (_: React.MouseEvent, node: Node) => {
- if (node.type === "layerCluster") {
- drillIntoLayer(node.id);
- } else if (node.type === "subGroupCluster") {
- useArchitectureStore.getState().drillIntoSubGroup(node.id);
- } else if (node.type === "archContainer") {
- useArchitectureStore.getState().toggleContainer(node.id);
- }
- },
- [drillIntoLayer],
- );
-
- const handlePaneClick = useCallback(() => {
- selectNode(null);
- }, [selectNode]);
-
- const fetchContent = useCallback(
- async (filePath: string) => {
- const apiBase =
- typeof window !== "undefined"
- ? (process.env.NEXT_PUBLIC_REPOWISE_API_URL ?? "")
- : "";
- const apiKey =
- typeof window !== "undefined"
- ? localStorage.getItem("repowise_api_key")
- : null;
- const res = await fetch(
- `${apiBase}/api/repos/${repoId}/file-content?` +
- new URLSearchParams({ file_path: filePath }).toString(),
- { headers: apiKey ? { Authorization: `Bearer ${apiKey}` } : {} },
- );
- if (!res.ok) {
- throw new Error(`Failed to fetch file content (${res.status})`);
- }
- return res.text();
- },
- [repoId],
- );
-
- const anyLoading = isLoading || layoutLoading;
-
- return (
- <>
- <div className="shrink-0 px-4 sm:px-6 py-3 border-b border-[var(--color-border-default)]">
- <div className="flex items-center justify-between">
- {!embedded ? (
- <div>
- <h1 className="text-lg font-semibold text-[var(--color-text-primary)]">
- Layers
- </h1>
- <p className="text-xs text-[var(--color-text-secondary)] mt-0.5">
- {repoName} — curated layered view of the system.
- </p>
- </div>
- ) : (
- <span aria-hidden />
- )}
- <div className="flex items-center gap-3">
- <ArchTourButton />
- <PersonaSelector />
- <NodeTypeCategoryFilters />
- </div>
- </div>
- <div className="mt-2 flex items-center gap-4">
- <SearchBar />
- <ArchBreadcrumb />
- </div>
- </div>
-
- <div className="flex-1 min-h-0 relative">
- {/* The layered canvas chrome (ReactFlow host, controls, minimap, owl
- chips, weaker-link chip, legend) now lives in `ui/c4` so it upgrades
- via a package bump. Web keeps store/data wiring and the panel hosts. */}
- <ArchCanvas
- nodes={nodes}
- edges={edges}
- loading={anyLoading}
- error={error}
- hiddenEdgeCount={hiddenEdgeCount}
- onInit={setReactFlowInstance}
- onNodeClick={handleNodeClick}
- onNodeDoubleClick={handleNodeDoubleClick}
- onPaneClick={handlePaneClick}
- errorTitle="Couldn't load the architecture layers"
- loadingLabel="Loading layers…"
- >
- {/* Orientation and the tour player render in the right Sidebar only. */}
- <ArchDetailPanelHost repoId={repoId} />
- <FilterPanel />
- <CodeViewer fetchContent={fetchContent} />
- {pathFinderOpen && <PathFinderModal />}
- </ArchCanvas>
- </div>
- </>
- );
-}
diff --git a/packages/web/src/components/c4/arch-detail-panel-host.tsx b/packages/web/src/components/c4/arch-detail-panel-host.tsx
deleted file mode 100644
index 953eab55f..000000000
--- a/packages/web/src/components/c4/arch-detail-panel-host.tsx
+++ /dev/null
@@ -1,78 +0,0 @@
-"use client";
-
-import { useRouter } from "next/navigation";
-import {
- Sidebar,
- useArchitectureStore,
- type ArchNodeHealth,
-} from "@repowise-dev/ui/c4";
-import { ChatMarkdown } from "@repowise-dev/ui/chat/chat-markdown";
-import { useC4SelectionContext, useC4DocsPathSet } from "@/lib/hooks/use-c4-context";
-
-interface ArchDetailPanelHostProps {
- repoId: string;
-}
-
-export function ArchDetailPanelHost({ repoId }: ArchDetailPanelHostProps) {
- const router = useRouter();
- const selectedNodeId = useArchitectureStore((s) => s.selectedNodeId);
- const nodesById = useArchitectureStore((s) => s.nodesById);
-
- const node = selectedNodeId ? nodesById.get(selectedNodeId) ?? null : null;
- const filePath = node?.file_path ?? null;
-
- const { pageIdByPath } = useC4DocsPathSet(repoId);
- const pageId = (() => {
- if (!filePath) return null;
- const direct = pageIdByPath.get(filePath);
- if (direct) return direct;
- let parent = filePath;
- while (parent.includes("/")) {
- parent = parent.substring(0, parent.lastIndexOf("/"));
- const hit = pageIdByPath.get(parent);
- if (hit) return hit;
- }
- return null;
- })();
-
- const { health, page, isLoading } = useC4SelectionContext(
- repoId,
- filePath,
- pageId,
- );
-
- const contributors =
- health?.owners
- ?.slice(0, 5)
- .map((o) => ({ name: o.name, files: o.file_count, pct: o.pct })) ?? [];
-
- const archHealth: ArchNodeHealth | undefined = health
- ? {
- health_score: health.health_score,
- hotspot_count: health.hotspot_count,
- dead_code_count: health.dead_code_count,
- doc_coverage_pct: health.doc_coverage_pct,
- contributor_count: health.contributor_count,
- is_silo: health.is_silo,
- }
- : undefined;
-
- return (
- <Sidebar
- health={archHealth}
- contributors={contributors}
- docContent={page ? (page.content.length > 300 ? page.content.slice(0, 300).trimEnd() + "..." : page.content) : null}
- renderDoc={(content) => <ChatMarkdown content={content} />}
- onOpenInGraph={
- filePath
- ? (p) => router.push(`/repos/${repoId}/architecture?view=graph&node=${encodeURIComponent(p)}`)
- : undefined
- }
- onOpenDoc={() => {
- if (page) {
- router.push(`/repos/${repoId}/docs?page=${encodeURIComponent(page.id)}`);
- }
- }}
- />
- );
-}
diff --git a/packages/web/src/components/layout/nav-items.ts b/packages/web/src/components/layout/nav-items.ts
index 2d1d69137..c8e02b08e 100644
--- a/packages/web/src/components/layout/nav-items.ts
+++ b/packages/web/src/components/layout/nav-items.ts
@@ -22,6 +22,7 @@ import {
Lightbulb,
Link2,
MessageSquare,
+ ScanSearch,
Settings,
ShieldCheck,
Users,
@@ -63,7 +64,7 @@ export function repoNavGroups(repoId: string): NavGroup[] {
{ label: "Overview", href: `${base}/overview`, icon: Activity },
{ label: "Docs", href: `${base}/docs`, icon: BookOpen },
{ label: "Architecture", href: `${base}/architecture`, icon: Boxes },
- { label: "Knowledge Graph", href: `${base}/knowledge-graph`, icon: Waypoints },
+ { label: "Knowledge Graph", href: `${base}/knowledge-graph`, icon: ScanSearch },
{ label: "Code Health", href: `${base}/code-health`, icon: HeartPulse },
{ label: "Refactoring", href: `${base}/refactoring`, icon: Wrench },
{ label: "Files", href: `${base}/files`, icon: FolderTree },
diff --git a/packages/web/src/components/layout/repo-breadcrumb-label.ts b/packages/web/src/components/layout/repo-breadcrumb-label.ts
index a3e9325af..caf0c3d0c 100644
--- a/packages/web/src/components/layout/repo-breadcrumb-label.ts
+++ b/packages/web/src/components/layout/repo-breadcrumb-label.ts
@@ -25,6 +25,7 @@ const SEGMENT_LABELS: Record<string, string> = {
security: "Security",
settings: "Settings",
"knowledge-graph": "Knowledge Graph",
+ zoom: "Zoom Map",
files: "Files",
};
diff --git a/packages/web/src/components/layout/repo-breadcrumb.test.ts b/packages/web/src/components/layout/repo-breadcrumb.test.ts
index 5928b6b41..52f56d47f 100644
--- a/packages/web/src/components/layout/repo-breadcrumb.test.ts
+++ b/packages/web/src/components/layout/repo-breadcrumb.test.ts
@@ -5,6 +5,7 @@ describe("getRepoBreadcrumbSegmentLabel", () => {
it("keeps configured route segment labels", () => {
expect(getRepoBreadcrumbSegmentLabel("dead-code")).toBe("Dead Code");
expect(getRepoBreadcrumbSegmentLabel("knowledge-graph")).toBe("Knowledge Graph");
+ expect(getRepoBreadcrumbSegmentLabel("zoom")).toBe("Zoom Map");
});
it("decodes dynamic path segments for display", () => {
diff --git a/packages/web/src/components/zoom/zoom-breadcrumb.tsx b/packages/web/src/components/zoom/zoom-breadcrumb.tsx
new file mode 100644
index 000000000..e46835fc1
--- /dev/null
+++ b/packages/web/src/components/zoom/zoom-breadcrumb.tsx
@@ -0,0 +1,60 @@
+"use client";
+
+/**
+ * "You are here" breadcrumb for the zoom canvas. Renders the root -> focus chain
+ * the canvas reports; clicking a crumb flies the camera to that node. Purely
+ * presentational: the page owns the chain state and the fly callback.
+ */
+
+import { ChevronRight, Home } from "lucide-react";
+import type { ZoomNode } from "@repowise-dev/ui/zoom";
+
+interface ZoomBreadcrumbProps {
+ chain: ZoomNode[];
+ onCrumb: (id: string) => void;
+}
+
+export function ZoomBreadcrumb({ chain, onCrumb }: ZoomBreadcrumbProps) {
+ if (chain.length === 0) return null;
+ const root = chain[0]!;
+ const rest = chain.slice(1);
+
+ return (
+ <nav
+ aria-label="Zoom location"
+ className="flex min-w-0 items-center gap-1 overflow-x-auto text-xs text-[var(--color-text-secondary)]"
+ >
+ <button
+ type="button"
+ onClick={() => onCrumb(root.id)}
+ className="flex shrink-0 items-center gap-1 rounded px-1.5 py-1 hover:bg-[var(--color-bg-hover)] hover:text-[var(--color-text-primary)]"
+ title={root.name}
+ >
+ <Home className="h-3.5 w-3.5" />
+ <span className="hidden sm:inline">{root.name}</span>
+ </button>
+ {rest.map((node, i) => {
+ const isLast = i === rest.length - 1;
+ return (
+ <span key={node.id} className="flex shrink-0 items-center gap-1">
+ <ChevronRight className="h-3.5 w-3.5 text-[var(--color-text-muted)]" />
+ {isLast ? (
+ <span className="max-w-[16rem] truncate px-1 py-1 font-medium text-[var(--color-text-primary)]">
+ {node.name}
+ </span>
+ ) : (
+ <button
+ type="button"
+ onClick={() => onCrumb(node.id)}
+ className="max-w-[12rem] truncate rounded px-1.5 py-1 hover:bg-[var(--color-bg-hover)] hover:text-[var(--color-text-primary)]"
+ title={node.path || node.name}
+ >
+ {node.name}
+ </button>
+ )}
+ </span>
+ );
+ })}
+ </nav>
+ );
+}
diff --git a/packages/web/src/components/zoom/zoom-detail-panel.tsx b/packages/web/src/components/zoom/zoom-detail-panel.tsx
new file mode 100644
index 000000000..02d979710
--- /dev/null
+++ b/packages/web/src/components/zoom/zoom-detail-panel.tsx
@@ -0,0 +1,142 @@
+"use client";
+
+/**
+ * Detail panel for the selected zoom node. A self-contained inspector (metadata,
+ * rolled-up metrics, summary) plus a "zoom here" action that flies the camera
+ * into the node. Kept lightweight and decoupled from the architecture-view
+ * selection store so the zoom canvas owns its own selection lifecycle.
+ */
+
+import Link from "next/link";
+import { FileCode, ScanSearch, X } from "lucide-react";
+import type { ZoomNode } from "@repowise-dev/ui/zoom";
+import { scoreTextColor } from "@repowise-dev/ui/health";
+
+interface ZoomDetailPanelProps {
+ node: ZoomNode;
+ repoId: string;
+ onClose: () => void;
+ onZoom: (id: string) => void;
+}
+
+/** Route to a file's own page. Segments are encoded but the slashes are kept so
+ * the `/files/[...path]` catch-all receives the real path. */
+function fileHref(repoId: string, path: string): string {
+ const encoded = path.split("/").map(encodeURIComponent).join("/");
+ return `/repos/${repoId}/files/${encoded}`;
+}
+
+const KIND_LABEL: Record<ZoomNode["kind"], string> = {
+ system: "System",
+ layer: "Layer",
+ group: "Group",
+ folder: "Folder",
+ file: "File",
+};
+
+function Stat({ label, value, tone }: { label: string; value: number; tone?: string }) {
+ return (
+ <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-canvas)] px-2.5 py-1.5">
+ <div className={`text-sm font-semibold ${tone ?? "text-[var(--color-text-primary)]"}`}>
+ {value}
+ </div>
+ <div className="text-[10px] uppercase tracking-wide text-[var(--color-text-muted)]">{label}</div>
+ </div>
+ );
+}
+
+export function ZoomDetailPanel({ node, repoId, onClose, onZoom }: ZoomDetailPanelProps) {
+ const m = node.metrics;
+ const isFile = node.kind === "file";
+ return (
+ <aside className="absolute right-3 top-3 z-20 flex max-h-[calc(100%-1.5rem)] w-72 flex-col overflow-hidden rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] shadow-xl">
+ <header className="flex items-start justify-between gap-2 border-b border-[var(--color-border-default)] px-3 py-2.5">
+ <div className="min-w-0">
+ <div className="flex items-center gap-1.5">
+ <span className="rounded bg-[var(--color-bg-canvas)] px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ {KIND_LABEL[node.kind]}
+ </span>
+ {node.is_entry_point && (
+ <span className="text-[10px] font-medium text-[var(--color-success)]">entry</span>
+ )}
+ {node.on_flow && !node.is_entry_point && (
+ <span className="text-[10px] font-medium text-[var(--color-accent-secondary)]">on flow</span>
+ )}
+ </div>
+ <h2 className="mt-1 truncate text-sm font-semibold text-[var(--color-text-primary)]" title={node.name}>
+ {node.name}
+ </h2>
+ {node.path && node.path !== node.name && (
+ <p className="truncate text-xs text-[var(--color-text-tertiary)]" title={node.path}>
+ {node.path}
+ </p>
+ )}
+ </div>
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label="Close details"
+ className="shrink-0 rounded p-1 text-[var(--color-text-muted)] hover:bg-[var(--color-bg-hover)] hover:text-[var(--color-text-primary)]"
+ >
+ <X className="h-4 w-4" />
+ </button>
+ </header>
+
+ <div className="flex-1 overflow-auto px-3 py-3">
+ {node.summary && (
+ <p className="mb-3 text-xs leading-relaxed text-[var(--color-text-secondary)]">{node.summary}</p>
+ )}
+ <div className="grid grid-cols-2 gap-2">
+ {node.health_score !== null && (
+ <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-canvas)] px-2.5 py-1.5">
+ <div className={`text-sm font-semibold ${scoreTextColor(node.health_score)}`}>
+ {node.health_score.toFixed(1)}
+ </div>
+ <div className="text-[10px] uppercase tracking-wide text-[var(--color-text-muted)]">
+ {isFile ? "health" : "health (avg)"}
+ </div>
+ </div>
+ )}
+ {!isFile && <Stat label="files" value={m.file_count} />}
+ {m.hotspot_count > 0 && (
+ <Stat label="hotspots" value={m.hotspot_count} tone="text-[var(--color-risk-high)]" />
+ )}
+ {m.entry_point_count > 0 && (
+ <Stat label="entry points" value={m.entry_point_count} tone="text-[var(--color-success)]" />
+ )}
+ {m.on_flow_count > 0 && <Stat label="on flow" value={m.on_flow_count} />}
+ {m.dead_count > 0 && <Stat label="dead" value={m.dead_count} />}
+ </div>
+ {node.language && (
+ <div className="mt-3 text-xs text-[var(--color-text-tertiary)]">
+ Language: <span className="text-[var(--color-text-secondary)]">{node.language}</span>
+ </div>
+ )}
+ </div>
+
+ {(node.children.length > 0 || isFile) && (
+ <footer className="flex flex-col gap-2 border-t border-[var(--color-border-default)] p-2">
+ {node.children.length > 0 && (
+ <button
+ type="button"
+ onClick={() => onZoom(node.id)}
+ className="flex w-full items-center justify-center gap-1.5 rounded-md bg-[var(--color-accent-primary)] px-3 py-1.5 text-xs font-medium text-[var(--color-text-on-accent)] hover:opacity-90"
+ >
+ <ScanSearch className="h-3.5 w-3.5" />
+ Zoom in
+ </button>
+ )}
+ {isFile && node.path && (
+ <Link
+ href={fileHref(repoId, node.path)}
+ className="flex w-full items-center justify-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-3 py-1.5 text-xs font-medium text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)]"
+ >
+ <FileCode className="h-3.5 w-3.5" />
+ Open file page
+ </Link>
+ )}
+ </footer>
+ )}
+ </aside>
+ );
+}
diff --git a/packages/web/src/components/zoom/zoom-hint.tsx b/packages/web/src/components/zoom/zoom-hint.tsx
new file mode 100644
index 000000000..6b0248033
--- /dev/null
+++ b/packages/web/src/components/zoom/zoom-hint.tsx
@@ -0,0 +1,69 @@
+"use client";
+
+/**
+ * A one-time coaching hint that floats over the canvas on a first visit. The
+ * zoom-map interaction model (scroll to zoom, double-click a card to dive in) is
+ * not obvious from a static frame, so we spell it out once and remember the
+ * dismissal in localStorage. Deliberately calm: a single glass pill, no modal
+ * and no backdrop, so it guides without getting in the way.
+ */
+
+import { useEffect, useState } from "react";
+import { Move, MousePointerClick, X, ZoomIn } from "lucide-react";
+
+const DISMISS_KEY = "repowise:zoom-hint-dismissed";
+
+export function ZoomHint() {
+ // Start hidden so SSR and the pre-hydration paint never flash the hint; reveal
+ // it only after we have checked localStorage on the client.
+ const [show, setShow] = useState(false);
+
+ useEffect(() => {
+ try {
+ if (localStorage.getItem(DISMISS_KEY) !== "1") setShow(true);
+ } catch {
+ // Private mode / storage disabled: still guide the user, just don't persist.
+ setShow(true);
+ }
+ }, []);
+
+ if (!show) return null;
+
+ const dismiss = () => {
+ setShow(false);
+ try {
+ localStorage.setItem(DISMISS_KEY, "1");
+ } catch {
+ // Non-fatal: the hint simply reappears next time.
+ }
+ };
+
+ return (
+ <div className="pointer-events-none absolute inset-x-0 bottom-4 z-10 flex justify-center px-3">
+ <div className="pointer-events-auto flex max-w-full items-center gap-3 overflow-x-auto rounded-full border border-[var(--color-border-subtle)] bg-[var(--color-bg-glass)] py-1.5 pl-4 pr-2 text-xs text-[var(--color-text-secondary)] shadow-sm backdrop-blur">
+ <span className="flex shrink-0 items-center gap-1.5">
+ <ZoomIn className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
+ Scroll to zoom
+ </span>
+ <span className="text-[var(--color-border-default)]">·</span>
+ <span className="flex shrink-0 items-center gap-1.5">
+ <Move className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
+ Drag to pan
+ </span>
+ <span className="text-[var(--color-border-default)]">·</span>
+ <span className="flex shrink-0 items-center gap-1.5">
+ <MousePointerClick className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
+ Double-click a card to dive in
+ </span>
+ <button
+ type="button"
+ onClick={dismiss}
+ aria-label="Dismiss hint"
+ className="ml-1 shrink-0 rounded-full p-1 text-[var(--color-text-muted)] hover:bg-[var(--color-bg-hover)] hover:text-[var(--color-text-primary)]"
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/components/zoom/zoom-search.tsx b/packages/web/src/components/zoom/zoom-search.tsx
new file mode 100644
index 000000000..58bf85490
--- /dev/null
+++ b/packages/web/src/components/zoom/zoom-search.tsx
@@ -0,0 +1,134 @@
+"use client";
+
+/**
+ * Search-to-zoom: type a file/folder/layer name and the camera flies to it.
+ * Searches the already-loaded zoom tree client-side (no request), ranks name
+ * matches above path matches, and exposes keyboard navigation. The page passes
+ * the node list and the fly callback.
+ */
+
+import { useMemo, useRef, useState } from "react";
+import { Search, X } from "lucide-react";
+import type { ZoomNode } from "@repowise-dev/ui/zoom";
+
+interface ZoomSearchProps {
+ nodes: ZoomNode[];
+ onPick: (id: string) => void;
+}
+
+const MAX_RESULTS = 8;
+
+function rank(node: ZoomNode, q: string): number {
+ const name = node.name.toLowerCase();
+ const path = node.path.toLowerCase();
+ if (name === q) return 0;
+ if (name.startsWith(q)) return 1;
+ if (name.includes(q)) return 2;
+ if (path.includes(q)) return 3;
+ return Number.POSITIVE_INFINITY;
+}
+
+export function ZoomSearch({ nodes, onPick }: ZoomSearchProps) {
+ const [query, setQuery] = useState("");
+ const [open, setOpen] = useState(false);
+ const [active, setActive] = useState(0);
+ const inputRef = useRef<HTMLInputElement | null>(null);
+
+ const results = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ if (q.length < 2) return [];
+ return nodes
+ .map((n) => ({ n, r: rank(n, q) }))
+ .filter((x) => Number.isFinite(x.r))
+ .sort((a, b) => a.r - b.r || a.n.path.length - b.n.path.length)
+ .slice(0, MAX_RESULTS)
+ .map((x) => x.n);
+ }, [nodes, query]);
+
+ const pick = (node: ZoomNode | undefined) => {
+ if (!node) return;
+ onPick(node.id);
+ setQuery("");
+ setOpen(false);
+ inputRef.current?.blur();
+ };
+
+ const onKeyDown = (e: React.KeyboardEvent) => {
+ if (!open || results.length === 0) return;
+ if (e.key === "ArrowDown") {
+ e.preventDefault();
+ setActive((a) => Math.min(results.length - 1, a + 1));
+ } else if (e.key === "ArrowUp") {
+ e.preventDefault();
+ setActive((a) => Math.max(0, a - 1));
+ } else if (e.key === "Enter") {
+ e.preventDefault();
+ pick(results[active]);
+ } else if (e.key === "Escape") {
+ setOpen(false);
+ }
+ };
+
+ return (
+ <div className="relative w-56">
+ <div className="flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1">
+ <Search className="h-3.5 w-3.5 shrink-0 text-[var(--color-text-muted)]" />
+ <input
+ ref={inputRef}
+ value={query}
+ onChange={(e) => {
+ setQuery(e.target.value);
+ setOpen(true);
+ setActive(0);
+ }}
+ onFocus={() => setOpen(true)}
+ onBlur={() => setTimeout(() => setOpen(false), 120)}
+ onKeyDown={onKeyDown}
+ placeholder="Search files…"
+ aria-label="Search the system map"
+ className="w-full bg-transparent text-xs text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-muted)]"
+ />
+ {query && (
+ <button
+ type="button"
+ onClick={() => {
+ setQuery("");
+ inputRef.current?.focus();
+ }}
+ aria-label="Clear search"
+ className="shrink-0 text-[var(--color-text-muted)] hover:text-[var(--color-text-primary)]"
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ )}
+ </div>
+ {open && results.length > 0 && (
+ <ul className="absolute z-20 mt-1 max-h-72 w-full overflow-auto rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] py-1 text-xs shadow-lg">
+ {results.map((node, i) => (
+ <li key={node.id}>
+ <button
+ type="button"
+ // onMouseDown (not onClick) so it fires before the input blur.
+ onMouseDown={(e) => {
+ e.preventDefault();
+ pick(node);
+ }}
+ onMouseEnter={() => setActive(i)}
+ className={`flex w-full flex-col items-start px-2.5 py-1.5 text-left ${
+ i === active ? "bg-[var(--color-bg-hover)]" : ""
+ }`}
+ >
+ <span className="font-medium text-[var(--color-text-primary)]">{node.name}</span>
+ {node.path && node.path !== node.name && (
+ <span className="max-w-full truncate text-[var(--color-text-tertiary)]">
+ {node.path}
+ </span>
+ )}
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ );
+}
diff --git a/packages/web/src/lib/hooks/use-architecture.ts b/packages/web/src/lib/hooks/use-architecture.ts
deleted file mode 100644
index a48d8f0d2..000000000
--- a/packages/web/src/lib/hooks/use-architecture.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-"use client";
-
-import useSWR from "swr";
-import type { ArchitectureView } from "@repowise-dev/ui/c4";
-import { getArchitectureView } from "@/lib/api/c4";
-
-const SWR_OPTS = { revalidateOnFocus: false, revalidateOnReconnect: false };
-
-export function useArchitectureView(repoId: string | null) {
- const { data, error, isLoading } = useSWR<ArchitectureView>(
- repoId ? `architecture-view:${repoId}` : null,
- () => getArchitectureView(repoId!),
- SWR_OPTS,
- );
- return { view: data ?? null, error: (error as Error | undefined) ?? null, isLoading };
-}
diff --git a/packages/web/src/lib/hooks/use-graph.ts b/packages/web/src/lib/hooks/use-graph.ts
index c9f959991..01bc4daa3 100644
--- a/packages/web/src/lib/hooks/use-graph.ts
+++ b/packages/web/src/lib/hooks/use-graph.ts
@@ -1,5 +1,6 @@
"use client";
+import type { ZoomMap } from "@repowise-dev/ui/zoom";
import useSWR from "swr";
import {
getArchitecture,
@@ -14,6 +15,7 @@ import {
getGraphMetrics,
getHotFilesGraph,
getModuleGraph,
+ getZoomMap,
} from "@/lib/api/graph";
import type {
ArchitectureGraphResponse,
@@ -31,6 +33,21 @@ import type {
const SWR_OPTS = { revalidateOnFocus: false, revalidateOnReconnect: false };
+export function useZoomMap(
+ repoId: string | null,
+ params?: { max_depth?: number; focus?: string },
+) {
+ const key = repoId
+ ? `zoom-map:${repoId}:${params?.max_depth ?? ""}:${params?.focus ?? ""}`
+ : null;
+ const { data, error, isLoading } = useSWR<ZoomMap>(
+ key,
+ () => getZoomMap(repoId!, params),
+ SWR_OPTS,
+ );
+ return { zoomMap: data, error, isLoading };
+}
+
export function useGraph(repoId: string | null, limit?: number) {
const { data, error, isLoading } = useSWR<GraphExportResponse>(
repoId ? `graph:${repoId}:${limit ?? "default"}` : null,
diff --git a/tests/unit/server/services/test_zoom_builder.py b/tests/unit/server/services/test_zoom_builder.py
index c26cda56e..115a855de 100644
--- a/tests/unit/server/services/test_zoom_builder.py
+++ b/tests/unit/server/services/test_zoom_builder.py
@@ -12,7 +12,7 @@ from repowise.server.services.c4_builder.models import (
)
from repowise.server.services.zoom_builder import assemble_zoom_map
from repowise.server.services.zoom_builder.layout import lay_out
-from repowise.server.services.zoom_builder.metrics import rollup_metrics
+from repowise.server.services.zoom_builder.metrics import rollup_health, rollup_metrics
from repowise.server.services.zoom_builder.models import ZoomNode
from repowise.server.services.zoom_builder.relations import aggregate_relations
from repowise.server.services.zoom_builder.scoring import (
@@ -242,6 +242,48 @@ def test_rollup_metrics_counts_subtree():
assert root.metrics.on_flow_count == 1
+def test_rollup_health_loc_weighted_mean():
+ layers = [
+ LayerSpec(
+ id="layer:service",
+ name="Service",
+ display_order=0,
+ node_ids=["pkg/a.py", "pkg/b.py", "pkg/c.py"],
+ ),
+ ]
+ leaf_info = {
+ "pkg/a.py": LeafInfo(health_score=2.0, loc=100),
+ "pkg/b.py": LeafInfo(health_score=8.0, loc=300),
+ # c.py is unscored: it must drop out of the mean entirely (weight 0), the
+ # same way the /files treemap excludes files with no measured score.
+ "pkg/c.py": LeafInfo(health_score=None, loc=50),
+ }
+ root_id, nodes = build_tree("proj", layers, leaf_info)
+ nodes = rollup_health(root_id, nodes)
+
+ # A file keeps its own score; an unscored file stays None.
+ assert nodes[file_id("pkg/a.py")].health_score == 2.0
+ assert nodes[file_id("pkg/c.py")].health_score is None
+ # Container = loc-weighted mean over scored descendants only:
+ # (2*100 + 8*300) / (100 + 300) = 2600 / 400 = 6.5
+ assert nodes[root_id].health_score == 6.5
+
+
+def test_rollup_health_none_when_no_scored_descendant():
+ layers = [
+ LayerSpec(
+ id="layer:service",
+ name="Service",
+ display_order=0,
+ node_ids=["pkg/x.py", "pkg/y.py"],
+ ),
+ ]
+ leaf_info = {"pkg/x.py": LeafInfo(), "pkg/y.py": LeafInfo()} # both unscored
+ root_id, nodes = build_tree("proj", layers, leaf_info)
+ nodes = rollup_health(root_id, nodes)
+ assert nodes[root_id].health_score is None
+
+
# ---------------------------------------------------------------------------
# layout
# ---------------------------------------------------------------------------
@@ -441,6 +483,32 @@ def test_assemble_zoom_map_full():
assert not zoom.truncated
+def test_assemble_zoom_map_health_rolls_up():
+ # Effective score keyed by path -> (score, loc); util.py is omitted, so it
+ # reads as unscored and drops out of every container mean.
+ health = {
+ "pkg/main.py": (9.0, 100),
+ "pkg/core/engine.py": (3.0, 300),
+ }
+ zoom = assemble_zoom_map(_view(), health=health)
+
+ assert zoom.nodes[file_id("pkg/main.py")].health_score == 9.0
+ assert zoom.nodes[file_id("pkg/core/util.py")].health_score is None
+ # The "core" group holds engine (scored) + util (unscored): only engine
+ # contributes, so the group mean is engine's score.
+ group = next(n for n in zoom.nodes.values() if n.kind == "group")
+ assert group.health_score == 3.0
+ # The system rolls both scored files: (9*100 + 3*300) / (100 + 300) = 4.5
+ assert zoom.nodes[zoom.root_id].health_score == 4.5
+
+
+def test_assemble_zoom_map_health_optional_defaults_to_unscored():
+ # No health argument: every node reads as unscored (None), so the pure
+ # assembly still works without a DB read.
+ zoom = assemble_zoom_map(_view())
+ assert all(n.health_score is None for n in zoom.nodes.values())
+
+
def test_assemble_zoom_map_max_depth_prunes_and_flags_truncated():
zoom = assemble_zoom_map(_view(), max_depth=1)
# only system (level 0) + layers (level 1) survive