Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.
TypeScript ai-agentsanthropicclaude-codeclicode-graphcodexcontext-engineeringcursordeveloper-toolsgeminiknowledge-graphllmmcpmcp-serveropen-sourceopenaitree-sitter
feat(viz): viewer app + graft viz CLI command
Shrish Dwivedi9e49f68bfce6
diff --git a/package-lock.json b/package-lock.jsonindex 6b7c9e0c..b12c686b 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,11 +1,11 @@{- "name": "context-graph-engine",+ "name": "@nanonets/graft","version": "0.1.0","lockfileVersion": 3,"requires": true,"packages": {"": {- "name": "context-graph-engine",+ "name": "@nanonets/graft","version": "0.1.0","license": "MIT","dependencies": {@@ -18,10 +18,13 @@"tree-sitter-typescript": "^0.23.2"},"bin": {- "context-graph": "dist/cli.js"+ "graft": "dist/cli.js"},"devDependencies": {+ "@types/d3-force": "^3.0.10","@types/node": "^26.1.0",+ "d3-force": "^3.0.0",+ "esbuild": "^0.28.1","tsx": "^4.22.4","typescript": "^6.0.3"},@@ -471,6 +474,13 @@"node": ">=18"}},+ "node_modules/@types/d3-force": {+ "version": "3.0.10",+ "resolved": "https://registry.npmjs.org/@types/d3-force/-/d3-force-3.0.10.tgz",+ "integrity": "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/node": {"version": "26.1.0","resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.0.tgz",@@ -505,6 +515,51 @@"node": ">=22.12.0"}},+ "node_modules/d3-dispatch": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz",+ "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==",+ "dev": true,+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-force": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-force/-/d3-force-3.0.0.tgz",+ "integrity": "sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-quadtree": "1 - 3",+ "d3-timer": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-quadtree": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-quadtree/-/d3-quadtree-3.0.1.tgz",+ "integrity": "sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw==",+ "dev": true,+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-timer": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",+ "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",+ "dev": true,+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },"node_modules/dotenv": {"version": "17.4.2","resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz",@@ -831,40 +886,6 @@"integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==","dev": true,"license": "MIT"- },- "node_modules/ws": {- "version": "8.21.0",- "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",- "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",- "license": "MIT",- "optional": true,- "peer": true,- "engines": {- "node": ">=10.0.0"- },- "peerDependencies": {- "bufferutil": "^4.0.1",- "utf-8-validate": ">=5.0.2"- },- "peerDependenciesMeta": {- "bufferutil": {- "optional": true- },- "utf-8-validate": {- "optional": true- }- }- },- "node_modules/zod": {- "version": "4.4.3",- "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",- "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==",- "license": "MIT",- "optional": true,- "peer": true,- "funding": {- "url": "https://github.com/sponsors/colinhacks"- }}}}diff --git a/package.json b/package.jsonindex 0ab21d2f..bfa1c16f 100644--- a/package.json+++ b/package.json@@ -1,5 +1,5 @@{- "name": "context-graph-engine",+ "name": "@nanonets/graft","version": "0.1.0","description": "Build a repo's context graph as a folder of linked markdown files that live in the repo and stay in sync with the code through git.","keywords": [@@ -8,9 +8,21 @@"knowledge-graph","context","codebase",- "llm"+ "llm",+ "graft"],"license": "MIT",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/NanoNets/context-graph-engine.git"+ },+ "homepage": "https://github.com/NanoNets/context-graph-engine#readme",+ "bugs": {+ "url": "https://github.com/NanoNets/context-graph-engine/issues"+ },+ "publishConfig": {+ "access": "public"+ },"type": "module","main": "./dist/index.js","types": "./dist/index.d.ts",@@ -21,7 +33,7 @@}},"bin": {- "context-graph": "./dist/cli.js"+ "graft": "./dist/cli.js"},"files": ["dist",@@ -29,7 +41,7 @@"LICENSE"],"scripts": {- "build": "tsc -p tsconfig.json",+ "build": "tsc -p tsconfig.json && tsc -p viewer/tsconfig.json && node scripts/build-viewer.mjs","dev": "tsc -p tsconfig.json --watch","cli": "tsx src/cli.ts","bench": "tsx bench/run.ts",@@ -50,7 +62,10 @@"tree-sitter-typescript": "^0.23.2"},"devDependencies": {+ "@types/d3-force": "^3.0.10","@types/node": "^26.1.0",+ "d3-force": "^3.0.0",+ "esbuild": "^0.28.1","tsx": "^4.22.4","typescript": "^6.0.3"}diff --git a/scripts/build-viewer.mjs b/scripts/build-viewer.mjsnew file mode 100644index 00000000..bf4fe0ad--- /dev/null+++ b/scripts/build-viewer.mjs@@ -0,0 +1,28 @@+/**+ * Bundles the viewer into dist/viewer/ (app.js via esbuild + copied static+ * assets). Runs as part of `npm run build`; the bundle ships in the package+ * so `graft viz` needs no install or build step at runtime.+ */+import { build } from "esbuild";+import { mkdirSync, copyFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++const root = dirname(dirname(fileURLToPath(import.meta.url)));+const outDir = join(root, "dist", "viewer");+mkdirSync(outDir, { recursive: true });++await build({+ entryPoints: [join(root, "viewer", "main.ts")],+ bundle: true,+ minify: true,+ format: "esm",+ target: "es2022",+ outfile: join(outDir, "app.js"),+});++for (const asset of ["index.html", "style.css"]) {+ copyFileSync(join(root, "viewer", asset), join(outDir, asset));+}++console.log("viewer bundle → dist/viewer/");diff --git a/src/cli.ts b/src/cli.tsindex ae4f10f0..903b3885 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -1,6 +1,6 @@#!/usr/bin/env node/**- * `context-graph` CLI. Two commands:+ * `graft` CLI. Two commands:** init build .context/ from your code (one markdown node per system,* API, or concept; linked to each other; committed to the repo).@@ -12,20 +12,20 @@import "dotenv/config";import { Command } from "commander";import { relative } from "node:path";-import { ContextGraphEngine } from "./engine.js";+import { Graft } from "./engine.js";import { formatCheckReport } from "./context/check.js";import { formatGraphCheckReport } from "./graph/check.js";const program = new Command();program- .name("context-graph")+ .name("graft").description("Build a repo's context graph as linked markdown, and keep it in sync with the code.").option("--dir <path>", "context graph directory (default: <repo>/.context)");-function engineFrom(): ContextGraphEngine {+function engineFrom(): Graft {const opts = program.opts<{ dir?: string }>();- return new ContextGraphEngine({ contextDir: opts.dir });+ return new Graft({ contextDir: opts.dir });}program@@ -105,6 +105,42 @@ programif (!r.ok || (!g.missing && !g.ok)) process.exit(1);});+program+ .command("viz")+ .description("Serve an interactive visualization of the context graph (and graph.json when present)")+ .argument("[dir]", "repository root", ".")+ .option("-p, --port <port>", "port to serve on", "4400")+ .option("--no-open", "don't open the browser")+ .action(async (dir: string, opts: { port: string; open: boolean }) => {+ const { existsSync } = await import("node:fs");+ const { resolve, basename } = await import("node:path");+ const { spawn } = await import("node:child_process");+ const { fileURLToPath } = await import("node:url");+ const { contextDirFor } = await import("./context/node-file.js");+ const { startVizServer } = await import("./viz/serve.js");++ const root = resolve(dir);+ const globalOpts = program.opts<{ dir?: string }>();+ const contextDir = contextDirFor(root, globalOpts.dir);+ if (!existsSync(contextDir)) {+ console.error(`✗ no context graph at ${contextDir} — run \`graft init\` first`);+ process.exit(1);+ }+ // dist/cli.js → dist/viewer/ (prebuilt at package build time)+ const viewerDir = fileURLToPath(new URL("./viewer/", import.meta.url));+ const srv = await startVizServer({+ contextDir,+ viewerDir,+ port: Number(opts.port),+ repoName: basename(root),+ });+ console.log(`graft viz → ${srv.url} (ctrl-c to stop)`);+ if (opts.open) {+ const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";+ spawn(opener, [srv.url], { stdio: "ignore", detached: true, shell: process.platform === "win32" }).unref();+ }+ });+program.parseAsync().catch((err) => {console.error(err instanceof Error ? err.message : err);process.exit(1);diff --git a/viewer/data.ts b/viewer/data.tsnew file mode 100644index 00000000..56477604--- /dev/null+++ b/viewer/data.ts@@ -0,0 +1,121 @@+/**+ * Data layer: fetches both graphs from the graft viz server and carries the+ * edge semantics (verb → family → form) defined in the design spec.+ */++export interface VizNode {+ id: string;+ name: string;+ type: string;+ summary: string;+ sources: string[];+}++export interface VizEdge {+ source: string;+ target: string;+ relation: string;+ description?: string;+ confidence?: "extracted" | "inferred";+}++export interface VizGraph {+ meta: { repoName?: string; nodeCount: number; edgeCount: number; skippedFiles?: number; droppedEdges?: number };+ nodes: VizNode[];+ edges: VizEdge[];+}++/** Every relation verb belongs to one family; form follows family. */+export type Family = "structure" | "dependency" | "contract" | "association";++const FAMILY: Record<string, Family> = {+ part_of: "structure", contains: "structure",+ uses: "dependency", depends_on: "dependency", calls: "dependency", imports: "dependency",+ produces: "dependency", configures: "dependency", validates: "dependency",+ extends: "contract", implements: "contract",+ references: "association",+};++export function famOf(rel: string): Family {+ return FAMILY[rel] ?? "association";+}++/** Force-spring rest length per family: hierarchy pulls tight. */+export const REST: Record<Family, number> = { structure: 85, dependency: 145, contract: 150, association: 185 };++/** Chip grouping: "part of" and "uses" are clear as groups; other verbs stand alone. */+export function chipKey(rel: string): string {+ if (famOf(rel) === "structure") return "part of";+ if (rel === "calls" || rel === "uses" || rel === "depends_on" || rel === "imports") return "uses";+ return rel.replace(/_/g, " ");+}++/** Hover hint: the question the verb answers for someone building or reviewing code. */+export const CHIP_HINT: Record<string, string> = {+ "part of": "where does this live? (contains, part of)",+ "uses": "what breaks if the target changes? (calls, uses, depends on, imports)",+ "produces": "where does this output come from?",+ "configures": "what changes its behavior without a code change?",+ "validates": "what checks or judges this? (tests, drift checks, scoring)",+ "extends": "what contract must this honor? (inheritance)",+ "implements": "what contract must this honor? (interface)",+ "references": "mentioned but never called — possible dead coupling",+};++/** Node-type → CSS custom property, per tab. */+const CONTEXT_COLORS: Record<string, string> = { system: "--sys", concept: "--con", file: "--fil", api: "--api" };+const CODE_COLORS: Record<string, string> = {+ file: "--k-file", class: "--k-class", function: "--k-fn", method: "--k-method",+ interface: "--k-iface", type: "--k-type", enum: "--k-enum",+};++export function colorToken(tab: "context" | "code", type: string): string {+ const m = tab === "code" ? CODE_COLORS : CONTEXT_COLORS;+ return m[type] ?? "--edge";+}++export function cvar(name: string): string {+ return getComputedStyle(document.documentElement).getPropertyValue(name).trim();+}++export async function loadContextGraph(): Promise<VizGraph> {+ const res = await fetch("/api/context-graph");+ return (await res.json()) as VizGraph;+}++interface CodeGraphV1 {+ meta: { version: number; nodeCount: number; edgeCount: number };+ nodes: Array<{+ id: string; name: string; kind: string; path: string; span: string;+ signature: string | null; summary: string | null; crux: { code: string; span: string } | null;+ }>;+ edges: Array<{ source: string; target: string; relation: string; confidence: "extracted" | "inferred" }>;+}++/** Fetch graph.json and reshape it into the viewer's graph form (null if absent). */+export async function loadCodeGraph(): Promise<VizGraph | null> {+ const res = await fetch("/api/code-graph");+ if (!res.ok) return null;+ const raw = (await res.json()) as CodeGraphV1;+ const nodes: VizNode[] = raw.nodes.map((n) => ({+ id: n.id,+ name: n.name,+ type: n.kind,+ summary: n.summary ?? n.signature ?? "",+ sources: [`${n.path} · ${n.span}`],+ }));+ const known = new Set(nodes.map((n) => n.id));+ // imports edges may point at unresolved module strings — drop those for rendering+ const edges: VizEdge[] = raw.edges+ .filter((e) => known.has(e.source) && known.has(e.target))+ .map((e) => ({ source: e.source, target: e.target, relation: e.relation, confidence: e.confidence }));+ return { meta: { nodeCount: nodes.length, edgeCount: edges.length }, nodes, edges };+}++/** Subscribe to the server's live-reload channel. */+export function onServerChange(handler: () => void): void {+ const source = new EventSource("/events");+ source.onmessage = (ev) => {+ if (ev.data === "change") handler();+ };+}diff --git a/viewer/detail.ts b/viewer/detail.tsnew file mode 100644index 00000000..b051e25c--- /dev/null+++ b/viewer/detail.ts@@ -0,0 +1,58 @@+/**+ * Detail panel: the selected node's type, summary, sources, and its links in+ * both directions — amber "Depends on" (outgoing) and teal "Depended on by"+ * (incoming), mirroring the focus-mode edge colors.+ */+import { type VizGraph, colorToken, cvar } from "./data.js";++function esc(s: string): string {+ return s.replace(/&/g, "&").replace(/</g, "<");+}++export function renderDetail(+ host: HTMLElement,+ graph: VizGraph | null,+ tab: "context" | "code",+ id: string | null,+ onNavigate: (id: string) => void,+): void {+ if (!id || !graph) {+ host.innerHTML = '<div class="empty">Select a node to view details</div>';+ return;+ }+ const node = graph.nodes.find((n) => n.id === id);+ if (!node) {+ host.innerHTML = '<div class="empty">Select a node to view details</div>';+ return;+ }+ const color = cvar(colorToken(tab, node.type));+ const name = (nid: string) => graph.nodes.find((n) => n.id === nid)?.name ?? nid;+ const out = graph.edges.filter((e) => e.source === id);+ const inn = graph.edges.filter((e) => e.target === id);++ let html = `<span class="d-type"><span class="sw" style="background:${color}"></span>${esc(node.type)}</span>`;+ html += `<h3>${esc(node.name)}</h3>`;+ if (node.summary) html += `<p class="summary">${esc(node.summary)}</p>`;+ if (node.sources.length) {+ html += `<div class="d-label">Sources · ${node.sources.length}</div>`;+ for (const s of node.sources) html += `<div class="src mono">${esc(s)}</div>`;+ }+ const linkList = (edges: typeof out, dotColor: string, title: string, other: (e: (typeof out)[number]) => string) => {+ if (!edges.length) return;+ html += `<div class="d-label"><span class="dot" style="background:${dotColor}"></span>${title} · ${edges.length}</div>`;+ for (const e of edges) {+ html += `<button class="lnk" data-go="${esc(other(e))}">` ++ `<span class="rel">${esc(e.relation.replace(/_/g, " "))}</span> ` ++ `<span class="to">${esc(name(other(e)))}</span>` ++ (e.description ? `<div class="desc">${esc(e.description)}</div>` : "") ++ `</button>`;+ }+ };+ linkList(out, cvar("--fil"), "Depends on", (e) => e.target);+ linkList(inn, cvar("--accent"), "Depended on by", (e) => e.source);++ host.innerHTML = html;+ host.querySelectorAll<HTMLButtonElement>("[data-go]").forEach((b) => {+ b.addEventListener("click", () => onNavigate(b.dataset.go!));+ });+}diff --git a/viewer/graph.ts b/viewer/graph.tsnew file mode 100644index 00000000..eb701c11--- /dev/null+++ b/viewer/graph.ts@@ -0,0 +1,334 @@+/**+ * Force-directed graph view. d3-force drives the simulation (Barnes–Hut, so+ * large graphs stay interactive); rendering is persistent SVG — elements are+ * created when data changes and only attributes are updated per tick.+ *+ * Edge grammar (per the design spec):+ * part of thick · muted · no arrowhead · short spring+ * uses-family solid · open-chevron arrowhead+ * extends/implements hollow arrowhead+ * references faint dots · no arrowhead+ * inferred edges dashed (trust is visible)+ * Focus mode: selecting a node paints outgoing edges amber ("depends on"),+ * incoming teal ("depended on by"), labels the verbs on just those edges,+ * and fades the rest of the graph.+ */+import {+ forceSimulation, forceManyBody, forceLink, forceCenter, forceCollide,+ type Simulation, type SimulationNodeDatum,+} from "d3-force";+import { type VizGraph, type VizEdge, famOf, REST, chipKey, colorToken, cvar } from "./data.js";++interface SimNode extends SimulationNodeDatum {+ id: string;+ name: string;+ type: string;+ deg: number;+ r: number;+ fx?: number | null;+ fy?: number | null;+}++interface SimEdge {+ source: SimNode;+ target: SimNode;+ relation: string;+ description?: string;+ confidence?: string;+}++const NS = "http://www.w3.org/2000/svg";++function el<K extends keyof SVGElementTagNameMap>(tag: K, attrs: Record<string, string | number>): SVGElementTagNameMap[K] {+ const node = document.createElementNS(NS, tag);+ for (const [k, v] of Object.entries(attrs)) node.setAttribute(k, String(v));+ return node;+}++export class GraphView {+ private svg: SVGSVGElement;+ private defs!: SVGDefsElement;+ private viewport!: SVGGElement;+ private sim: Simulation<SimNode, undefined> | null = null;+ private nodes: SimNode[] = [];+ private edges: SimEdge[] = [];+ private edgeEls: { path: SVGPathElement; label: SVGTextElement; edge: SimEdge }[] = [];+ private nodeEls: { group: SVGGElement; circle: SVGCircleElement; ring: SVGCircleElement; label: SVGTextElement; node: SimNode }[] = [];+ private view = { x: 0, y: 0, k: 1 };+ private tab: "context" | "code" = "context";+ selected: string | null = null;+ query = "";+ hiddenRels: Record<string, boolean> = {};+ hiddenTypes: Record<string, boolean> = {};+ onSelect: (id: string | null) => void = () => {};++ constructor(svg: SVGSVGElement) {+ this.svg = svg;+ this.buildChrome();+ this.bindPanZoom();+ }++ private buildChrome(): void {+ this.svg.textContent = "";+ this.defs = el("defs", {});+ this.svg.appendChild(this.defs);+ this.viewport = el("g", {});+ this.svg.appendChild(this.viewport);+ this.svg.addEventListener("click", () => this.select(null));+ }++ private ensureMarkers(): void {+ this.defs.textContent = "";+ const chevron = el("marker", { id: "arr", viewBox: "0 0 10 10", refX: 8, refY: 5, markerWidth: 4.5, markerHeight: 4.5, orient: "auto-start-reverse" });+ chevron.appendChild(el("path", { d: "M2,1.5L8.5,5L2,8.5", fill: "none", stroke: cvar("--edge"), "stroke-width": 1.8, "stroke-linecap": "round", "stroke-linejoin": "round", opacity: 0.75 }));+ const hollow = el("marker", { id: "arrH", viewBox: "0 0 12 12", refX: 10, refY: 6, markerWidth: 6.5, markerHeight: 6.5, orient: "auto-start-reverse" });+ hollow.appendChild(el("path", { d: "M1.5,1.5L10.5,6L1.5,10.5z", fill: cvar("--canvas"), stroke: cvar("--edge"), "stroke-width": 1.4 }));+ const out = el("marker", { id: "arrOut", viewBox: "0 0 10 10", refX: 8, refY: 5, markerWidth: 5, markerHeight: 5, orient: "auto-start-reverse" });+ out.appendChild(el("path", { d: "M1,1L9,5L1,9z", fill: cvar("--fil") }));+ const inn = el("marker", { id: "arrIn", viewBox: "0 0 10 10", refX: 8, refY: 5, markerWidth: 5, markerHeight: 5, orient: "auto-start-reverse" });+ inn.appendChild(el("path", { d: "M1,1L9,5L1,9z", fill: cvar("--accent") }));+ for (const m of [chevron, hollow, out, inn]) this.defs.appendChild(m);+ }++ /** Load (or morph into) a new dataset. Nodes keep their positions by id. */+ setData(graph: VizGraph, tab: "context" | "code"): void {+ this.tab = tab;+ const prev = new Map(this.nodes.map((n) => [n.id, n]));+ const deg: Record<string, number> = {};+ for (const e of graph.edges) {+ deg[e.source] = (deg[e.source] ?? 0) + 1;+ deg[e.target] = (deg[e.target] ?? 0) + 1;+ }+ const W = this.svg.clientWidth || 800;+ const H = this.svg.clientHeight || 600;+ this.nodes = graph.nodes.map((n, i) => {+ const p = prev.get(n.id);+ const angle = (i / Math.max(1, graph.nodes.length)) * Math.PI * 2;+ const d = deg[n.id] ?? 0;+ return {+ id: n.id, name: n.name, type: n.type,+ deg: d, r: 11 + Math.min(13, d * 2.6),+ x: p?.x ?? W / 2 + Math.cos(angle) * Math.min(W, H) / 4,+ y: p?.y ?? H / 2 + Math.sin(angle) * Math.min(W, H) / 4,+ vx: p?.vx ?? 0, vy: p?.vy ?? 0,+ };+ });+ const byId = new Map(this.nodes.map((n) => [n.id, n]));+ this.edges = graph.edges+ .map((e: VizEdge) => ({+ source: byId.get(e.source)!, target: byId.get(e.target)!,+ relation: e.relation, description: e.description, confidence: e.confidence,+ }))+ .filter((e) => e.source && e.target);++ this.sim?.stop();+ this.sim = forceSimulation(this.nodes)+ .force("charge", forceManyBody().strength(-220))+ .force("link", forceLink(this.edges as unknown as { source: SimNode; target: SimNode }[])+ .distance((l) => REST[famOf((l as unknown as SimEdge).relation)])+ .strength(0.5))+ .force("center", forceCenter(W / 2, H / 2))+ .force("collide", forceCollide<SimNode>().radius((n) => n.r + 6))+ .on("tick", () => this.tick());++ this.buildElements();+ this.restyle();+ }++ private buildElements(): void {+ this.ensureMarkers();+ this.viewport.textContent = "";+ this.edgeEls = this.edges.map((edge) => {+ const path = el("path", { fill: "none", "stroke-linecap": "round" });+ const title = el("title", {});+ title.textContent = edge.relation.replace(/_/g, " ") + (edge.description ? ` — ${edge.description}` : "");+ path.appendChild(title);+ const label = el("text", { "text-anchor": "middle", "font-size": 9.5, "font-weight": 700, "stroke-width": 3, "paint-order": "stroke", display: "none" });+ label.textContent = edge.relation.replace(/_/g, " ");+ this.viewport.appendChild(path);+ this.viewport.appendChild(label);+ return { path, label, edge };+ });+ this.nodeEls = this.nodes.map((node) => {+ const group = el("g", { cursor: "pointer" });+ const ring = el("circle", { fill: "none", "stroke-width": 1.6, opacity: 0, r: node.r + 5 });+ const circle = el("circle", { r: node.r, opacity: 0.92 });+ const label = el("text", { y: node.r + 15, "text-anchor": "middle", "font-size": 11.5, "font-weight": 600 });+ label.textContent = node.name;+ group.append(ring, circle, label);+ group.addEventListener("click", (ev) => { ev.stopPropagation(); this.select(node.id); });+ this.bindDrag(group, node);+ this.viewport.appendChild(group);+ return { group, circle, ring, label, node };+ });+ }++ private tick(): void {+ for (const { path, label, edge } of this.edgeEls) {+ const a = edge.source, b = edge.target;+ const dx = (b.x ?? 0) - (a.x ?? 0), dy = (b.y ?? 0) - (a.y ?? 0);+ const d = Math.sqrt(dx * dx + dy * dy) || 1;+ const ux = dx / d, uy = dy / d;+ const sx = (a.x ?? 0) + ux * (a.r + 2), sy = (a.y ?? 0) + uy * (a.r + 2);+ const tx = (b.x ?? 0) - ux * (b.r + 6), ty = (b.y ?? 0) - uy * (b.r + 6);+ const mx = (sx + tx) / 2 - uy * 10, my = (sy + ty) / 2 + ux * 10;+ path.setAttribute("d", `M${sx},${sy} Q${mx},${my} ${tx},${ty}`);+ label.setAttribute("x", String((sx + tx) / 2 - uy * 14));+ label.setAttribute("y", String((sy + ty) / 2 + ux * 14));+ }+ for (const { group, node } of this.nodeEls) {+ group.setAttribute("transform", `translate(${node.x ?? 0},${node.y ?? 0})`);+ }+ }++ /** Re-apply all style attributes (theme, filters, focus, search). */+ restyle(): void {+ this.ensureMarkers();+ const neighbors = new Set<string>();+ if (this.selected) {+ for (const e of this.edges) {+ if (e.source.id === this.selected) neighbors.add(e.target.id);+ if (e.target.id === this.selected) neighbors.add(e.source.id);+ }+ }+ const q = this.query.toLowerCase();+ const nodeShown = (n: SimNode) => !this.hiddenTypes[n.type];++ for (const { path, label, edge } of this.edgeEls) {+ const visible = nodeShown(edge.source) && nodeShown(edge.target) && !this.hiddenRels[chipKey(edge.relation)];+ path.style.display = visible ? "" : "none";+ label.setAttribute("display", "none");+ if (!visible) continue;+ const fam = famOf(edge.relation);+ let stroke = cvar("--edge"), width = 1.3, dash = "none", opacity = 0.5, marker = "url(#arr)";+ if (fam === "structure") { width = 2.4; opacity = 0.32; marker = "none"; }+ else if (fam === "dependency") { width = 1.5; opacity = 0.55; }+ else if (fam === "contract") { opacity = 0.55; marker = "url(#arrH)"; }+ else { dash = "2 5"; width = 1.2; opacity = 0.28; marker = "none"; }+ if (edge.confidence === "inferred") dash = "5 4";+ if (q) opacity = 0.12;+ const role = this.selected+ ? (edge.source.id === this.selected ? "out" : edge.target.id === this.selected ? "in" : "far")+ : "none";+ if (role === "out") { stroke = cvar("--fil"); opacity = 0.95; width += 0.7; marker = "url(#arrOut)"; }+ else if (role === "in") { stroke = cvar("--accent"); opacity = 0.95; width += 0.7; marker = "url(#arrIn)"; }+ else if (role === "far") { opacity = 0.06; }+ path.setAttribute("stroke", stroke);+ path.setAttribute("stroke-width", String(width));+ path.setAttribute("stroke-dasharray", dash);+ path.setAttribute("opacity", String(opacity));+ if (marker === "none") path.removeAttribute("marker-end");+ else path.setAttribute("marker-end", marker);+ if (role === "out" || role === "in") {+ label.removeAttribute("display");+ label.setAttribute("fill", stroke);+ label.setAttribute("stroke", cvar("--canvas"));+ }+ }++ for (const { group, circle, ring, label, node } of this.nodeEls) {+ const shown = nodeShown(node);+ group.style.display = shown ? "" : "none";+ if (!shown) continue;+ const match = !q || node.name.toLowerCase().includes(q);+ let opacity = match ? 1 : 0.22;+ if (this.selected && node.id !== this.selected && !neighbors.has(node.id)) opacity = Math.min(opacity, 0.2);+ group.setAttribute("opacity", String(opacity));+ const color = cvar(colorToken(this.tab, node.type));+ circle.setAttribute("fill", color);+ ring.setAttribute("stroke", color);+ ring.setAttribute("opacity", node.id === this.selected ? "0.55" : "0");+ label.setAttribute("fill", cvar("--ink"));+ }+ }++ select(id: string | null): void {+ this.selected = id;+ this.restyle();+ this.onSelect(id);+ }++ /** Center the view on a node and select it (used by search). */+ focus(id: string): void {+ const node = this.nodes.find((n) => n.id === id);+ if (!node) return;+ const W = this.svg.clientWidth, H = this.svg.clientHeight;+ this.view.k = Math.max(this.view.k, 1.4);+ this.view.x = W / 2 - (node.x ?? 0) * this.view.k;+ this.view.y = H / 2 - (node.y ?? 0) * this.view.k;+ this.applyView();+ this.select(id);+ }++ firstMatch(): SimNode | undefined {+ const q = this.query.toLowerCase();+ return this.nodes.find((n) => !this.hiddenTypes[n.type] && n.name.toLowerCase().includes(q));+ }++ private applyView(): void {+ this.viewport.setAttribute("transform", `translate(${this.view.x},${this.view.y}) scale(${this.view.k})`);+ }++ zoomBy(factor: number): void {+ const W = this.svg.clientWidth / 2, H = this.svg.clientHeight / 2;+ const k = Math.max(0.35, Math.min(3, this.view.k * factor));+ this.view.x = W - (W - this.view.x) * (k / this.view.k);+ this.view.y = H - (H - this.view.y) * (k / this.view.k);+ this.view.k = k;+ this.applyView();+ }++ resetView(): void {+ this.view = { x: 0, y: 0, k: 1 };+ this.applyView();+ }++ reheat(): void {+ this.sim?.alpha(0.6).restart();+ }++ private bindDrag(group: SVGGElement, node: SimNode): void {+ group.addEventListener("pointerdown", (ev) => {+ ev.stopPropagation();+ group.setPointerCapture(ev.pointerId);+ const move = (mv: PointerEvent) => {+ const rect = this.svg.getBoundingClientRect();+ node.fx = (mv.clientX - rect.left - this.view.x) / this.view.k;+ node.fy = (mv.clientY - rect.top - this.view.y) / this.view.k;+ this.sim?.alphaTarget(0.25).restart();+ };+ const up = () => {+ node.fx = null; node.fy = null;+ this.sim?.alphaTarget(0);+ group.removeEventListener("pointermove", move);+ group.removeEventListener("pointerup", up);+ };+ group.addEventListener("pointermove", move);+ group.addEventListener("pointerup", up);+ });+ }++ private bindPanZoom(): void {+ let panStart: { x: number; y: number } | null = null;+ this.svg.addEventListener("pointerdown", (ev) => {+ panStart = { x: ev.clientX - this.view.x, y: ev.clientY - this.view.y };+ });+ this.svg.addEventListener("pointermove", (ev) => {+ if (!panStart) return;+ this.view.x = ev.clientX - panStart.x;+ this.view.y = ev.clientY - panStart.y;+ this.applyView();+ });+ window.addEventListener("pointerup", () => { panStart = null; });+ this.svg.addEventListener("wheel", (ev) => {+ ev.preventDefault();+ const rect = this.svg.getBoundingClientRect();+ const px = ev.clientX - rect.left, py = ev.clientY - rect.top;+ const k = Math.max(0.35, Math.min(3, this.view.k * Math.exp(-ev.deltaY * 0.0016)));+ this.view.x = px - (px - this.view.x) * (k / this.view.k);+ this.view.y = py - (py - this.view.y) * (k / this.view.k);+ this.view.k = k;+ this.applyView();+ }, { passive: false });+ }+}diff --git a/viewer/index.html b/viewer/index.htmlnew file mode 100644index 00000000..437b6c65--- /dev/null+++ b/viewer/index.html@@ -0,0 +1,48 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>graft viz</title>+<link rel="stylesheet" href="/style.css">+</head>+<body>+<header class="appbar">+ <div class="brand"><b>graft</b><span id="repoName"></span></div>+ <div class="counts" id="counts"></div>+ <nav class="tabs" role="tablist" id="tabs">+ <button class="tab" role="tab" aria-selected="true" data-tab="context">Context</button>+ <button class="tab" role="tab" aria-selected="false" data-tab="code">Code</button>+ <button class="tab" role="tab" aria-selected="false" data-tab="outline">Outline</button>+ </nav>+ <div class="searchbox">+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg>+ <input id="search" type="search" placeholder="Search nodes…" aria-label="Search nodes">+ </div>+ <button class="iconbtn" id="themeBtn" title="Toggle theme" aria-label="Toggle theme">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M21 12.8A9 9 0 1 1 11.2 3 7 7 0 0 0 21 12.8z"/></svg>+ </button>+</header>++<main class="stage" id="stage">+ <div class="canvas-wrap" id="canvasWrap">+ <svg class="graph" id="graphSvg" role="img" aria-label="Force-directed graph"></svg>+ <div class="edgestyle" id="edgeChips"><span class="cap">Edges</span></div>+ <div class="lcount" id="lcount"></div>+ <div class="legend" id="legend"></div>+ <div class="zoomctl">+ <button class="iconbtn" id="zin" aria-label="Zoom in">+</button>+ <button class="iconbtn" id="zout" aria-label="Zoom out">−</button>+ <button class="iconbtn" id="zreset" aria-label="Reset view">⟲</button>+ </div>+ <div class="emptytab" id="graphEmpty" hidden></div>+ </div>+ <div class="outline" id="outlineView" hidden>+ <div class="tree" id="tree"></div>+ </div>+ <aside class="detail" id="detail"><div class="empty">Select a node to view details</div></aside>+</main>++<script type="module" src="/app.js"></script>+</body>+</html>diff --git a/viewer/main.ts b/viewer/main.tsnew file mode 100644index 00000000..004f35e9--- /dev/null+++ b/viewer/main.ts@@ -0,0 +1,232 @@+/**+ * graft viz — viewer entry point. Wires tabs, chips, legend, search, theme,+ * SSE live reload, and the three views (Context graph / Code graph / Outline).+ */+import { loadContextGraph, loadCodeGraph, onServerChange, chipKey, CHIP_HINT, colorToken, cvar, famOf, type VizGraph } from "./data.js";+import { GraphView } from "./graph.js";+import { renderDetail } from "./detail.js";+import { renderOutline } from "./tree.js";++type Tab = "context" | "code" | "outline";++const $ = <T extends HTMLElement>(id: string): T => document.getElementById(id) as T;++const state = {+ tab: "context" as Tab,+ context: null as VizGraph | null,+ code: null as VizGraph | null,+ outlineOpen: {} as Record<string, boolean>,+};++const view = new GraphView($("graphSvg") as unknown as SVGSVGElement);++function activeGraph(): VizGraph | null {+ return state.tab === "context" ? state.context : state.code;+}++function graphTab(): "context" | "code" {+ return state.tab === "code" || state.tab === "outline" ? "code" : "context";+}++/* ---------- chips: verbs actually present, grouped only where obvious ---------- */+function renderChips(): void {+ const host = $("edgeChips");+ host.innerHTML = '<span class="cap">Edges</span>';+ const graph = activeGraph();+ if (!graph) return;+ const counts = new Map<string, number>();+ for (const e of graph.edges) {+ const key = chipKey(e.relation);+ counts.set(key, (counts.get(key) ?? 0) + 1);+ }+ const keys = [...counts.keys()].sort((a, b) => {+ const rank = (k: string) => (k === "part of" ? 0 : k === "uses" ? 1 : 2);+ return rank(a) - rank(b) || a.localeCompare(b);+ });+ for (const key of keys) {+ const btn = document.createElement("button");+ btn.type = "button";+ btn.className = "echip" + (view.hiddenRels[key] ? "" : " on");+ btn.innerHTML = `${glyphFor(key)} ${key} <span style="opacity:.55">${counts.get(key)}</span>`;+ btn.title = (CHIP_HINT[key] ?? `"${key}" edges`) + " — click to " + (view.hiddenRels[key] ? "show" : "hide");+ btn.addEventListener("click", () => {+ view.hiddenRels[key] = !view.hiddenRels[key];+ renderChips();+ view.restyle();+ updateShownCount();+ });+ host.appendChild(btn);+ }+}++function glyphFor(key: string): string {+ const fam = key === "part of" ? "structure" : key === "uses" ? "dependency" : famOf(key.replace(/ /g, "_"));+ const glyphs: Record<string, string> = {+ structure: '<svg width="20" height="8" aria-hidden="true"><line x1="1" y1="4" x2="19" y2="4" stroke="currentColor" stroke-width="3" opacity=".5"/></svg>',+ dependency: '<svg width="20" height="8" aria-hidden="true"><line x1="1" y1="4" x2="14" y2="4" stroke="currentColor" stroke-width="1.6"/><path d="M14,1 L19,4 L14,7 z" fill="currentColor"/></svg>',+ contract: '<svg width="20" height="8" aria-hidden="true"><line x1="1" y1="4" x2="13" y2="4" stroke="currentColor" stroke-width="1.4"/><path d="M13,1 L19,4 L13,7 z" fill="none" stroke="currentColor" stroke-width="1.2"/></svg>',+ association: '<svg width="20" height="8" aria-hidden="true"><line x1="1" y1="4" x2="19" y2="4" stroke="currentColor" stroke-width="1.4" stroke-dasharray="2 4" opacity=".7"/></svg>',+ };+ return glyphs[fam];+}++/* ---------- node-type legend ---------- */+function renderLegend(): void {+ const host = $("legend");+ host.innerHTML = "";+ const graph = activeGraph();+ if (!graph) return;+ const counts = new Map<string, number>();+ for (const n of graph.nodes) counts.set(n.type, (counts.get(n.type) ?? 0) + 1);+ for (const [type, count] of counts) {+ const chip = document.createElement("button");+ chip.type = "button";+ chip.className = "lchip" + (view.hiddenTypes[type] ? " off" : "");+ chip.innerHTML = `<span class="sw" style="background:${cvar(colorToken(graphTab(), type))}"></span>${type} <span style="color:var(--muted);font-weight:500">${count}</span>`;+ chip.addEventListener("click", () => {+ view.hiddenTypes[type] = !view.hiddenTypes[type];+ renderLegend();+ view.restyle();+ updateShownCount();+ });+ host.appendChild(chip);+ }+}++function updateShownCount(): void {+ const graph = activeGraph();+ if (!graph) { $("lcount").textContent = ""; return; }+ const shown = graph.nodes.filter((n) => !view.hiddenTypes[n.type]).length;+ $("lcount").textContent = `${shown} / ${graph.nodes.length} nodes shown`;+}++function updateCounts(): void {+ const el = $("counts");+ if (state.tab === "outline" && state.code) {+ const files = state.code.nodes.filter((n) => n.type === "file").length;+ el.textContent = `${files} files · ${state.code.nodes.length} symbols`;+ } else {+ const graph = activeGraph();+ el.textContent = graph ? `${graph.meta.nodeCount} nodes · ${graph.meta.edgeCount} links` : "";+ }+}++/* ---------- detail panel ---------- */+function showDetail(id: string | null): void {+ renderDetail($("detail"), state.tab === "context" ? state.context : state.code, graphTab(), id, (next) => {+ if (state.tab === "outline") {+ showDetail(next);+ renderOutline($("tree"), state.code!, next, state.outlineOpen, showDetail);+ } else {+ view.focus(next);+ }+ });+}++view.onSelect = (id) => showDetail(id);++/* ---------- tabs ---------- */+function setTab(tab: Tab): void {+ state.tab = tab;+ document.querySelectorAll<HTMLButtonElement>(".tab").forEach((b) => {+ b.setAttribute("aria-selected", b.dataset.tab === tab ? "true" : "false");+ });+ const isOutline = tab === "outline";+ $("canvasWrap").hidden = isOutline;+ $("outlineView").hidden = !isOutline;+ view.hiddenRels = {};+ view.hiddenTypes = {};+ view.selected = null;+ showDetail(null);++ const empty = $("graphEmpty");+ if (tab === "outline") {+ if (state.code) renderOutline($("tree"), state.code, null, state.outlineOpen, showDetail);+ else {+ $("outlineView").hidden = true;+ $("canvasWrap").hidden = false;+ showEmpty("No code graph yet — run <code>graft graph</code> to generate <span class=\"mono\">graph.json</span>.");+ }+ } else {+ const graph = activeGraph();+ if (!graph) {+ showEmpty(tab === "code"+ ? "No code graph yet — run <code>graft graph</code> to generate <span class=\"mono\">graph.json</span>."+ : "No context graph — run <code>graft init</code> first.");+ } else {+ empty.hidden = true;+ view.resetView();+ view.setData(graph, graphTab());+ view.reheat();+ }+ }+ renderChips();+ renderLegend();+ updateShownCount();+ updateCounts();+}++function showEmpty(html: string): void {+ const empty = $("graphEmpty");+ empty.innerHTML = html;+ empty.hidden = false;+}++document.querySelectorAll<HTMLButtonElement>(".tab").forEach((b) => {+ b.addEventListener("click", () => setTab(b.dataset.tab as Tab));+});++/* ---------- search ---------- */+const search = $("search") as HTMLInputElement;+search.addEventListener("input", () => {+ view.query = search.value.trim();+ view.restyle();+});+search.addEventListener("keydown", (ev) => {+ if (ev.key === "Enter" && view.query) {+ const hit = view.firstMatch();+ if (hit) view.focus(hit.id);+ }+});++/* ---------- zoom controls ---------- */+$("zin").addEventListener("click", () => view.zoomBy(1.25));+$("zout").addEventListener("click", () => view.zoomBy(1 / 1.25));+$("zreset").addEventListener("click", () => view.resetView());++/* ---------- theme ---------- */+const THEME_KEY = "graft-viz-theme";+const savedTheme = localStorage.getItem(THEME_KEY);+if (savedTheme) document.documentElement.setAttribute("data-theme", savedTheme);+$("themeBtn").addEventListener("click", () => {+ const root = document.documentElement;+ const current = root.getAttribute("data-theme");+ const systemDark = window.matchMedia("(prefers-color-scheme: dark)").matches;+ const isDark = current ? current === "dark" : systemDark;+ const next = isDark ? "light" : "dark";+ root.setAttribute("data-theme", next);+ localStorage.setItem(THEME_KEY, next);+ view.restyle();+ renderChips();+ renderLegend();+ showDetail(view.selected);+});++/* ---------- data loading + live reload ---------- */+async function loadAll(): Promise<void> {+ const [context, code] = await Promise.all([loadContextGraph(), loadCodeGraph()]);+ state.context = context;+ state.code = code;+ $("repoName").textContent = context.meta.repoName ?? "";+ document.title = `graft viz — ${context.meta.repoName ?? ""}`;+ setTab(state.tab);+}++onServerChange(() => {+ const selected = view.selected;+ void loadAll().then(() => {+ if (selected) { view.selected = selected; view.restyle(); showDetail(selected); }+ });+});++void loadAll();diff --git a/viewer/style.css b/viewer/style.cssnew file mode 100644index 00000000..3b9682e5--- /dev/null+++ b/viewer/style.css@@ -0,0 +1,119 @@+/* graft viz — design tokens + app styles.+ Visual reference of record: docs/superpowers/specs/2026-07-15-graft-viz-design.md */+:root{+ --bg:#F4F6F6; --panel:#FFFFFF; --panel2:#FBFCFC; --ink:#17191B; --muted:#6B7278;+ --border:#E2E6E7; --border2:#EDF0F1; --accent:#0B7A69; --accent-ink:#0B7A69;+ --chip:#F0F3F3;+ --sys:#4A7DF0; --con:#A06BDB; --fil:#D98E2B; --api:#D65C7E;+ --k-file:#D98E2B; --k-class:#4A7DF0; --k-fn:#0FA38A; --k-method:#3AA7C9; --k-iface:#A06BDB; --k-type:#D65C7E; --k-enum:#6BAA3F;+ --edge:#9AA4A9; --canvas:#F8FAFA;+}+@media (prefers-color-scheme: dark){+ :root{+ --bg:#0E1012; --panel:#15181B; --panel2:#111417; --ink:#E7E9EA; --muted:#8B9298;+ --border:#252B30; --border2:#1D2226; --accent:#2FBFA4; --accent-ink:#2FBFA4;+ --chip:#1C2125;+ --sys:#6B94F5; --con:#B487E0; --fil:#E0A04A; --api:#E07A97;+ --k-file:#E0A04A; --k-class:#6B94F5; --k-fn:#2FBFA4; --k-method:#56B9D8; --k-iface:#B487E0; --k-type:#E07A97; --k-enum:#8CC45E;+ --edge:#4A545B; --canvas:#101315;+ }+}+:root[data-theme="dark"]{+ --bg:#0E1012; --panel:#15181B; --panel2:#111417; --ink:#E7E9EA; --muted:#8B9298;+ --border:#252B30; --border2:#1D2226; --accent:#2FBFA4; --accent-ink:#2FBFA4;+ --chip:#1C2125;+ --sys:#6B94F5; --con:#B487E0; --fil:#E0A04A; --api:#E07A97;+ --k-file:#E0A04A; --k-class:#6B94F5; --k-fn:#2FBFA4; --k-method:#56B9D8; --k-iface:#B487E0; --k-type:#E07A97; --k-enum:#8CC45E;+ --edge:#4A545B; --canvas:#101315;+}+:root[data-theme="light"]{+ --bg:#F4F6F6; --panel:#FFFFFF; --panel2:#FBFCFC; --ink:#17191B; --muted:#6B7278;+ --border:#E2E6E7; --border2:#EDF0F1; --accent:#0B7A69; --accent-ink:#0B7A69;+ --chip:#F0F3F3;+ --sys:#4A7DF0; --con:#A06BDB; --fil:#D98E2B; --api:#D65C7E;+ --k-file:#D98E2B; --k-class:#4A7DF0; --k-fn:#0FA38A; --k-method:#3AA7C9; --k-iface:#A06BDB; --k-type:#D65C7E; --k-enum:#6BAA3F;+ --edge:#9AA4A9; --canvas:#F8FAFA;+}++*{box-sizing:border-box}+[hidden]{display:none !important}+html,body{margin:0;padding:0;height:100%}+body{+ display:flex;flex-direction:column;+ background:var(--bg);color:var(--ink);+ font-family:"Avenir Next","Segoe UI",system-ui,-apple-system,sans-serif;+ font-size:15px;line-height:1.55;-webkit-font-smoothing:antialiased;+}+.mono{font-family:ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace}+button:focus-visible,input:focus-visible,.tree-row:focus-visible{outline:2px solid var(--accent);outline-offset:2px}++.appbar{display:flex;align-items:center;gap:14px;padding:10px 16px;border-bottom:1px solid var(--border);background:var(--panel);flex:none}+.brand{display:flex;align-items:baseline;gap:8px;flex:none}+.brand b{font-weight:700;letter-spacing:-.01em}+.brand span{color:var(--muted);font-size:13px}+.counts{color:var(--muted);font-size:12.5px;font-variant-numeric:tabular-nums;flex:none}+.tabs{display:flex;background:var(--chip);border-radius:9px;padding:3px;gap:2px;margin-left:auto;flex:none}+.tab{border:0;background:transparent;color:var(--muted);font:inherit;font-size:13px;font-weight:600;padding:5px 14px;border-radius:7px;cursor:pointer}+.tab:hover{color:var(--ink)}+.tab[aria-selected="true"]{background:var(--panel);color:var(--ink);box-shadow:0 1px 3px rgba(0,0,0,.12)}+.searchbox{position:relative;flex:none}+.searchbox input{width:190px;padding:6px 10px 6px 30px;border:1px solid var(--border);border-radius:8px;background:var(--panel2);color:var(--ink);font:inherit;font-size:13px;outline:none}+.searchbox input:focus{border-color:var(--accent)}+.searchbox svg{position:absolute;left:9px;top:50%;transform:translateY(-50%);opacity:.45}+.iconbtn{border:1px solid var(--border);background:var(--panel2);color:var(--ink);border-radius:8px;width:32px;height:32px;cursor:pointer;display:grid;place-items:center;flex:none;font:inherit;font-size:14px}+.iconbtn:hover{border-color:var(--muted)}++.stage{display:flex;flex:1;min-height:0;background:var(--canvas)}+.canvas-wrap{position:relative;flex:1;min-width:0}+svg.graph{display:block;width:100%;height:100%;cursor:grab}+svg.graph:active{cursor:grabbing}++.edgestyle{position:absolute;top:12px;left:14px;display:flex;align-items:center;gap:5px;flex-wrap:wrap;max-width:75%}+.edgestyle .cap{font-size:10px;letter-spacing:.12em;text-transform:uppercase;color:var(--muted);font-weight:700;margin-right:3px}+.echip{display:inline-flex;align-items:center;gap:5px;border:1px solid var(--border);background:var(--panel);color:var(--muted);border-radius:16px;padding:3px 10px;font:inherit;font-size:11.5px;font-weight:600;cursor:pointer}+.echip:hover{color:var(--ink)}+.echip.on{color:var(--ink)}+.echip:not(.on){opacity:.45}++.legend{position:absolute;left:14px;bottom:14px;display:flex;gap:6px;flex-wrap:wrap;max-width:70%}+.lchip{display:flex;align-items:center;gap:6px;font-size:12px;font-weight:600;color:var(--ink);background:var(--panel);border:1px solid var(--border);border-radius:20px;padding:4px 11px;cursor:pointer;user-select:none;font-family:inherit}+.lchip .sw{width:9px;height:9px;border-radius:50%}+.lchip.off{opacity:.38}+.lcount{position:absolute;left:14px;bottom:52px;font-size:11.5px;color:var(--muted);font-variant-numeric:tabular-nums}+.zoomctl{position:absolute;right:14px;bottom:14px;display:flex;flex-direction:column;gap:6px}+.zoomctl .iconbtn{background:var(--panel)}++.detail{width:300px;flex:none;border-left:1px solid var(--border);background:var(--panel);overflow-y:auto;padding:18px 18px 24px}+.detail .empty{color:var(--muted);font-size:13.5px;text-align:center;margin-top:200px}+.d-type{display:inline-flex;align-items:center;gap:6px;font-size:11px;letter-spacing:.1em;text-transform:uppercase;font-weight:700;padding:3px 10px;border-radius:20px;background:var(--chip)}+.d-type .sw{width:8px;height:8px;border-radius:50%}+.detail h3{margin:10px 0 6px;font-size:17px;letter-spacing:-.01em}+.detail p.summary{font-size:13.5px;color:var(--ink);margin:0 0 16px;white-space:pre-line}+.d-label{font-size:10.5px;letter-spacing:.13em;text-transform:uppercase;color:var(--muted);font-weight:700;margin:16px 0 7px;display:flex;align-items:center;gap:5px}+.d-label .dot{display:inline-block;width:7px;height:7px;border-radius:50%}+.src{font-size:12px;color:var(--muted);padding:3px 0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}+.lnk{display:block;width:100%;text-align:left;border:1px solid var(--border2);background:var(--panel2);border-radius:8px;padding:7px 10px;margin-bottom:6px;cursor:pointer;font:inherit;color:var(--ink)}+.lnk:hover{border-color:var(--accent)}+.lnk .rel{font-size:10.5px;letter-spacing:.09em;text-transform:uppercase;color:var(--accent-ink);font-weight:700}+.lnk .to{font-size:13px;font-weight:600}+.lnk .desc{font-size:12px;color:var(--muted)}++.outline{flex:1;display:flex;min-width:0}+.tree{flex:1;overflow-y:auto;padding:14px 8px 20px 14px;background:var(--panel)}+.tree-tools{display:flex;gap:14px;font-size:12.5px;color:var(--muted);padding:2px 8px 10px}+.tree-tools button{border:0;background:none;color:var(--accent-ink);font:inherit;font-size:12.5px;cursor:pointer;padding:0}+.tree-row{display:flex;align-items:center;gap:7px;padding:4px 8px;border-radius:7px;cursor:pointer;border:0;background:none;width:100%;text-align:left;font:inherit;color:var(--ink)}+.tree-row:hover{background:var(--chip)}+.tree-row.sel{background:var(--chip)}+.tree-row .chev{width:14px;flex:none;color:var(--muted);font-size:10px;transition:transform .12s}+.tree-row.open .chev{transform:rotate(90deg)}+.tree-row .k{width:9px;height:9px;border-radius:3px;flex:none}+.tree-row .t{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13.5px}+.tree-row .badge{margin-left:auto;font-size:11px;color:var(--muted);font-variant-numeric:tabular-nums;flex:none}+.tree-kids{margin-left:19px;border-left:1px solid var(--border2);padding-left:4px}++.emptytab{position:absolute;inset:0;display:grid;place-items:center;color:var(--muted);font-size:14px;text-align:center;padding:30px;background:var(--canvas)}+.emptytab code{background:var(--chip);padding:2px 8px;border-radius:6px;font-family:ui-monospace,"SF Mono",Menlo,Consolas,monospace;font-size:.9em}++@media (prefers-reduced-motion:reduce){ .tree-row .chev{transition:none} }+@media (max-width:760px){ .detail{display:none} .searchbox input{width:120px} .counts{display:none} }diff --git a/viewer/tree.ts b/viewer/tree.tsnew file mode 100644index 00000000..135c8777--- /dev/null+++ b/viewer/tree.ts@@ -0,0 +1,66 @@+/**+ * Outline view: the code graph's `contains` hierarchy (file → class → method)+ * as a collapsible tree with kind dots and per-file symbol counts.+ */+import { type VizGraph, colorToken, cvar } from "./data.js";++function esc(s: string): string {+ return s.replace(/&/g, "&").replace(/</g, "<");+}++export function renderOutline(+ host: HTMLElement,+ graph: VizGraph,+ selected: string | null,+ openState: Record<string, boolean>,+ onSelect: (id: string) => void,+): void {+ const kids = (pid: string) =>+ graph.edges+ .filter((e) => e.relation === "contains" && e.source === pid)+ .map((e) => graph.nodes.find((n) => n.id === e.target))+ .filter((n): n is NonNullable<typeof n> => Boolean(n));+ const countDesc = (pid: string): number => {+ const k = kids(pid);+ return k.length + k.reduce((sum, c) => sum + countDesc(c.id), 0);+ };+ const files = graph.nodes.filter((n) => n.type === "file");++ const row = (node: (typeof files)[number]): string => {+ const children = kids(node.id);+ const open = openState[node.id] !== false;+ let html = `<button class="tree-row${open ? " open" : ""}${selected === node.id ? " sel" : ""}"` ++ ` data-id="${esc(node.id)}" data-haskids="${children.length ? 1 : 0}">` ++ `<span class="chev">${children.length ? "▶" : ""}</span>` ++ `<span class="k" style="background:${cvar(colorToken("code", node.type))}"></span>` ++ `<span class="t${node.type === "file" ? " mono" : ""}">${esc(node.name)}</span>` ++ `<span class="badge">${children.length ? countDesc(node.id) + " sym" : esc(node.type)}</span></button>`;+ if (children.length && open) {+ html += `<div class="tree-kids">${children.map(row).join("")}</div>`;+ }+ return html;+ };++ host.innerHTML =+ '<div class="tree-tools"><button data-tool="expand">Expand all</button><button data-tool="collapse">Collapse all</button></div>' ++ files.map(row).join("");++ host.querySelectorAll<HTMLButtonElement>(".tree-row").forEach((r) => {+ r.addEventListener("click", () => {+ const id = r.dataset.id!;+ if (r.dataset.haskids === "1") {+ openState[id] = openState[id] === false;+ renderOutline(host, graph, id, openState, onSelect);+ }+ onSelect(id);+ });+ });+ host.querySelector<HTMLButtonElement>('[data-tool="expand"]')?.addEventListener("click", () => {+ for (const key of Object.keys(openState)) delete openState[key];+ renderOutline(host, graph, selected, openState, onSelect);+ });+ host.querySelector<HTMLButtonElement>('[data-tool="collapse"]')?.addEventListener("click", () => {+ for (const n of graph.nodes) openState[n.id] = false;+ renderOutline(host, graph, selected, openState, onSelect);+ });+}diff --git a/viewer/tsconfig.json b/viewer/tsconfig.jsonnew file mode 100644index 00000000..2fb7facc--- /dev/null+++ b/viewer/tsconfig.json@@ -0,0 +1,14 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "lib": ["ES2022", "DOM", "DOM.Iterable"],+ "strict": true,+ "noEmit": true,+ "skipLibCheck": true,+ "esModuleInterop": true,+ "forceConsistentCasingInFileNames": true+ },+ "include": ["./*.ts"]+}