mirror of
https://github.com/giancarloerra/socraticode.git
synced 2026-07-03 14:05:21 +02:00
feat(visualize): symbol view as focus graph; UX polish & stats consistency
Symbol view (full rebuild)
──────────────────────────
Replaces the unusable "show all symbols at once" mode with a focus
graph (SourceTrail / IntelliJ pattern):
- Landing state shows the alphabetical list of all symbols in the
sidebar; canvas shows a "pick a symbol" overlay constrained to the
canvas area (right: 340px) so the list stays visible.
- Three entry paths to seed: list click, search bar, or symbol click
from a file's sidebar in Files view.
- Once seeded, canvas shows the symbol + its 2-hop callers/callees
neighbourhood (auto-falls back to depth 1 if > 60 nodes).
- Clicking any neighbour re-centres on it. Seed has a distinctive
orange ring + always-visible label so the anchor is obvious.
- "← Back to symbol list" link in the sidebar restores the empty
state — explicit way out instead of relying on accidental
empty-canvas clicks.
- Light file-grouping: each symbol's border colour is a stable hash
of its file path; symbols from the same file share a colour.
Layout dropdown clean-up
────────────────────────
Removed Force-directed (cose). Force-directed is the wrong algorithm
for code dependency graphs — hub clusters collapse, orphans fly off,
labels overlap, no tuning fixes the underlying shape mismatch. Tried
fcose as a substitute; same fundamental problem on dense code graphs.
Default is now Dagre TB; remaining options are Concentric, Breadth-
first, Grid, Circle — all deterministic.
UX polish
─────────
- autoungrabify: true — disables single-click drag, fixes "node jumps
on click" (trackpad clicks always have some motion which Cytoscape's
default interprets as a node grab).
- Tap-to-highlight neighbourhood — clicking any node highlights its
direct neighbours and fades the rest. Less aggressive than the
transitive blast-radius / call-flow buttons in the sidebar.
- Zoom-bound label visibility — labels hidden below zoom 0.55 so 100+
node graphs aren't a soup of overlapping text. Selected / highlighted
nodes always show their label.
- Layout-position persistence — switching Files ↔ Symbols and back
preserves Files-view positions instead of re-running the layout.
TDZ regression test
───────────────────
New tests/unit/viewer-app.test.ts runs the bundled viewer-app.js in a
sandboxed node:vm context with mocked DOM + Cytoscape, triggering
every function-typed style closure on a fake element. Catches TDZ
("Cannot access X before initialization") and other reference errors
at unit-test time. Would have caught both the prior `cy` and
`LABEL_ZOOM_THRESHOLD` ordering bugs before they reached the browser.
Stats-line consistency
──────────────────────
graph-visualize-html.ts — top bar now displays embedded counts
(sym.symbols.length / sym.symbolEdges.length) instead of meta counts.
Previously the top bar said "630 symbols" while the sidebar's "All
symbols" said "722" because meta excludes synthetic <module>
placeholders. Capped mode keeps meta counts with a "(capped)"
qualifier since the embedded set is empty there.
Quality gates
─────────────
- Biome lint: clean
- TypeScript (tsc): clean
- Unit tests: 687/687 (incl. the new viewer-app.js evaluation test)
This commit is contained in:
+394
-57
@@ -83,29 +83,46 @@
|
||||
classes: `${e.cyclic ? "cyclic" : ""} ${e.type === "dynamic-import" ? "dynamic" : ""}`.trim(),
|
||||
}));
|
||||
|
||||
const SYMBOL_NODES = (DATA.symbols || []).map((s) => ({
|
||||
group: "nodes",
|
||||
data: {
|
||||
id: `s::${s.id}`,
|
||||
label: s.name,
|
||||
nodeType: "symbol",
|
||||
qualifiedName: s.qualifiedName,
|
||||
kind: s.kind,
|
||||
file: s.file,
|
||||
line: s.line,
|
||||
},
|
||||
}));
|
||||
const SYMBOL_EDGES = (DATA.symbolEdges || []).map((e, i) => ({
|
||||
group: "edges",
|
||||
data: {
|
||||
id: `se${i}`,
|
||||
source: `s::${e.source}`,
|
||||
target: `s::${e.target}`,
|
||||
confidence: e.confidence,
|
||||
scope: "symbol",
|
||||
},
|
||||
classes: `conf-${e.confidence}`,
|
||||
}));
|
||||
// Symbol-side indices — Symbol view is a FOCUS graph that builds on
|
||||
// demand, not a pre-rendered global graph. These lookup maps let
|
||||
// setSymbolSeed() compute a 2-hop neighbourhood around any symbol in
|
||||
// O(neighbours) time without touching Cytoscape.
|
||||
const SYMBOL_BY_ID = new Map();
|
||||
for (const s of DATA.symbols || []) SYMBOL_BY_ID.set(s.id, s);
|
||||
const OUTGOING_BY_CALLER = new Map();
|
||||
const INCOMING_BY_CALLEE = new Map();
|
||||
for (const e of DATA.symbolEdges || []) {
|
||||
if (!OUTGOING_BY_CALLER.has(e.source)) OUTGOING_BY_CALLER.set(e.source, []);
|
||||
OUTGOING_BY_CALLER.get(e.source).push(e);
|
||||
if (!INCOMING_BY_CALLEE.has(e.target)) INCOMING_BY_CALLEE.set(e.target, []);
|
||||
INCOMING_BY_CALLEE.get(e.target).push(e);
|
||||
}
|
||||
|
||||
/** Stable pastel colour derived from a file path — used as border
|
||||
* colour on symbol nodes so users can eyeball "which symbols live in
|
||||
* the same file" even when nodes are small. */
|
||||
function fileBorderColor(filePath) {
|
||||
if (!filePath) return "#0f172a";
|
||||
let h = 5381;
|
||||
for (let i = 0; i < filePath.length; i++) h = ((h << 5) + h + filePath.charCodeAt(i)) | 0;
|
||||
return `hsl(${Math.abs(h) % 360}, 55%, 45%)`;
|
||||
}
|
||||
|
||||
// Hide labels below this zoom (too cluttered with 100+ nodes rendered at
|
||||
// full zoom-out). Selected / neighbour nodes always show their label
|
||||
// via explicit overrides in the stylesheet.
|
||||
// NOTE: both this constant and `currentZoom` MUST be declared before the
|
||||
// STYLE array — Cytoscape evaluates the label closures during the cy()
|
||||
// constructor call, which happens before any `const` below it binds. A
|
||||
// forward reference would hit the temporal dead zone and blank the graph.
|
||||
const LABEL_ZOOM_THRESHOLD = 0.55;
|
||||
|
||||
// Tracked zoom state — a plain variable readable from the style
|
||||
// functions below, which run inside the cytoscape() constructor call
|
||||
// before `cy` itself is bound. Using `cy.zoom()` inside those closures
|
||||
// would hit the TDZ (`Cannot access 'cy' before initialization`) the
|
||||
// very first time Cytoscape styles the initial elements.
|
||||
let currentZoom = 1;
|
||||
|
||||
// ── Cytoscape style ──────────────────────────────────────────────
|
||||
const STYLE = [
|
||||
@@ -113,7 +130,8 @@
|
||||
selector: 'node[nodeType = "file"]',
|
||||
style: {
|
||||
"background-color": (ele) => colourFor(ele.data("language")),
|
||||
"label": "data(label)",
|
||||
// Hide label below threshold unless the node is selected/highlighted.
|
||||
"label": (ele) => (currentZoom >= LABEL_ZOOM_THRESHOLD || ele.hasClass("always-label")) ? ele.data("label") : "",
|
||||
"font-size": 10, "color": "#1f2937", "text-valign": "bottom",
|
||||
"text-margin-y": 4, "text-background-color": "#fff",
|
||||
"text-background-opacity": 0.8, "text-background-padding": 2,
|
||||
@@ -126,11 +144,25 @@
|
||||
selector: 'node[nodeType = "symbol"]',
|
||||
style: {
|
||||
"background-color": (ele) => KIND_COLORS[ele.data("kind")] || "#64748b",
|
||||
"label": "data(label)",
|
||||
"label": (ele) => (currentZoom >= LABEL_ZOOM_THRESHOLD || ele.hasClass("always-label") || ele.hasClass("seed")) ? ele.data("label") : "",
|
||||
"font-size": 10, "color": "#1f2937", "text-valign": "bottom",
|
||||
"text-margin-y": 4, "shape": "round-rectangle",
|
||||
"width": 40, "height": 18,
|
||||
"border-width": 1, "border-color": "#0f172a",
|
||||
"width": 44, "height": 20,
|
||||
// Border colour encodes the symbol's file — "light" compound-node
|
||||
// behaviour without actual nesting. Same file → same border.
|
||||
"border-width": 2, "border-color": (ele) => fileBorderColor(ele.data("file")),
|
||||
},
|
||||
},
|
||||
// The focus-graph seed — the symbol the user searched for / clicked
|
||||
// into. Bigger, pinned-label, distinctive ring so it's obvious which
|
||||
// node is the anchor.
|
||||
{
|
||||
selector: 'node[nodeType = "symbol"].seed',
|
||||
style: {
|
||||
"width": 64, "height": 28,
|
||||
"border-width": 4, "border-color": "#f59e0b",
|
||||
"font-size": 12, "font-weight": 600,
|
||||
"z-index": 1001,
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -162,6 +194,13 @@
|
||||
},
|
||||
{ selector: "edge.highlight-edge", style: { "line-color": "#ef4444", "target-arrow-color": "#ef4444", "width": 3, "z-index": 999 } },
|
||||
{ selector: "edge.highlight-flow-edge", style: { "line-color": "#3b82f6", "target-arrow-color": "#3b82f6", "width": 3, "z-index": 999 } },
|
||||
// Plain node-click neighbourhood highlight (less aggressive than blast
|
||||
// radius; just surfaces a node's direct imports + dependents).
|
||||
{ selector: ".highlight-selected", style: { "background-color": "#2563eb", "border-color": "#1e40af", "border-width": 3, "z-index": 1000 } },
|
||||
{ selector: ".highlight-neighbour", style: { "border-color": "#2563eb", "border-width": 2, "z-index": 998 } },
|
||||
{ selector: "edge.highlight-neighbour-edge", style: { "line-color": "#2563eb", "target-arrow-color": "#2563eb", "width": 2.5, "z-index": 998 } },
|
||||
// Force-show label on the currently-selected node and its neighbours.
|
||||
{ selector: ".always-label", style: { "text-opacity": 1 } },
|
||||
];
|
||||
|
||||
// ── Instantiate Cytoscape ────────────────────────────────────────
|
||||
@@ -172,37 +211,222 @@
|
||||
wheelSensitivity: 0.2,
|
||||
minZoom: 0.1,
|
||||
maxZoom: 3,
|
||||
// Disable single-click drag: trackpad "clicks" always have some motion,
|
||||
// which Cytoscape's default interprets as a node grab. This is an
|
||||
// exploration viewer — users tap to inspect, not to rearrange.
|
||||
autoungrabify: true,
|
||||
// Disable box (rectangle) selection to avoid accidental selections.
|
||||
boxSelectionEnabled: false,
|
||||
});
|
||||
|
||||
// ── Layout runner ────────────────────────────────────────────────
|
||||
let currentView = "files";
|
||||
let currentLayout = DATA.files.length > 200 ? "dagre" : "cose";
|
||||
// Default to Dagre TB for small graphs (clean layered look) and Dagre
|
||||
// for large graphs too. Cose is available but not default — it's non-
|
||||
// deterministic and looks chaotic on dense code dep graphs.
|
||||
let currentLayout = "dagre";
|
||||
|
||||
// Per-view cached positions — restored when switching back to a view so
|
||||
// "files → symbols → files" lands back on the same layout the user had.
|
||||
const savedPositions = { files: null, symbols: null };
|
||||
|
||||
function capturePositions() {
|
||||
const map = {};
|
||||
cy.nodes().forEach((n) => { map[n.id()] = { ...n.position() }; });
|
||||
savedPositions[currentView] = map;
|
||||
}
|
||||
|
||||
function restorePositions(map) {
|
||||
cy.batch(() => {
|
||||
cy.nodes().forEach((n) => {
|
||||
const p = map[n.id()];
|
||||
if (p) n.position(p);
|
||||
});
|
||||
});
|
||||
cy.fit(undefined, 50);
|
||||
if (cy.zoom() > 1.4) cy.zoom({ level: 1.4, renderedPosition: { x: cy.width() / 2, y: cy.height() / 2 } });
|
||||
}
|
||||
|
||||
function runLayout(name) {
|
||||
currentLayout = name;
|
||||
const opts = { name, animate: true, animationDuration: 300, fit: true, padding: 30 };
|
||||
if (name === "dagre") { opts.rankDir = "LR"; opts.nodeSep = 20; opts.rankSep = 60; }
|
||||
if (name === "cose") { opts.nodeRepulsion = 8000; opts.idealEdgeLength = 80; }
|
||||
cy.layout(opts).run();
|
||||
const n = cy.nodes().length;
|
||||
const opts = { name, animate: n < 200, animationDuration: 250, fit: true, padding: 50 };
|
||||
if (name === "dagre") {
|
||||
// TB (top-bottom) reads better than LR for code graphs because the
|
||||
// dependency chain is typically shallow but fan-in is wide.
|
||||
opts.rankDir = "TB";
|
||||
opts.nodeSep = 28;
|
||||
opts.rankSep = 80;
|
||||
opts.edgeSep = 14;
|
||||
}
|
||||
if (name === "concentric") {
|
||||
opts.concentric = (node) => node.degree();
|
||||
opts.levelWidth = () => 2;
|
||||
opts.minNodeSpacing = 30;
|
||||
}
|
||||
if (name === "breadthfirst") {
|
||||
opts.directed = true;
|
||||
opts.spacingFactor = 1.4;
|
||||
}
|
||||
const layout = cy.layout(opts);
|
||||
layout.one("layoutstop", () => {
|
||||
// Cap zoom after auto-fit so we never start in an absurd view.
|
||||
if (cy.zoom() > 1.4) cy.zoom({ level: 1.4, renderedPosition: { x: cy.width() / 2, y: cy.height() / 2 } });
|
||||
capturePositions();
|
||||
});
|
||||
layout.run();
|
||||
}
|
||||
|
||||
// Symbol focus-graph state — the id of the symbol the view is currently
|
||||
// anchored on. `null` = empty state (no seed picked yet).
|
||||
let symbolSeedId = null;
|
||||
|
||||
// ── View toggle ──────────────────────────────────────────────────
|
||||
function switchView(next) {
|
||||
if (next === currentView) return;
|
||||
|
||||
// Snapshot the view we're leaving (only the Files view uses saved
|
||||
// positions — Symbols view is seeded on every entry).
|
||||
if (currentView === "files") capturePositions();
|
||||
|
||||
currentView = next;
|
||||
clearHighlights();
|
||||
closeSidebar();
|
||||
|
||||
cy.elements().remove();
|
||||
if (next === "files") cy.add([...FILE_NODES, ...FILE_EDGES]);
|
||||
else cy.add([...SYMBOL_NODES, ...SYMBOL_EDGES]);
|
||||
|
||||
document.querySelectorAll(".view-toggle button").forEach((b) => b.classList.toggle("active", b.dataset.view === next));
|
||||
runLayout(currentLayout);
|
||||
|
||||
if (next === "files") {
|
||||
cy.elements().remove();
|
||||
cy.add([...FILE_NODES, ...FILE_EDGES]);
|
||||
hideSymbolEmptyState();
|
||||
if (savedPositions.files) restorePositions(savedPositions.files);
|
||||
else runLayout(currentLayout);
|
||||
return;
|
||||
}
|
||||
|
||||
// Symbols view — focus graph.
|
||||
if (symbolSeedId && SYMBOL_BY_ID.has(symbolSeedId)) {
|
||||
// Re-seed with the last-used symbol so toggling back feels continuous.
|
||||
setSymbolSeed(symbolSeedId);
|
||||
} else {
|
||||
cy.elements().remove();
|
||||
showSymbolEmptyState();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Symbol focus graph ───────────────────────────────────────────
|
||||
/** BFS a bounded neighbourhood around `seedId`, capping total size so
|
||||
* the focus graph stays readable. Follows both directions:
|
||||
* callers (incoming) and callees (outgoing) alike. */
|
||||
function buildSymbolNeighbourhood(seedId, maxDepth) {
|
||||
if (!SYMBOL_BY_ID.has(seedId)) return new Set();
|
||||
const visited = new Set([seedId]);
|
||||
const queue = [[seedId, 0]];
|
||||
while (queue.length) {
|
||||
const [id, depth] = queue.shift();
|
||||
if (depth >= maxDepth) continue;
|
||||
for (const e of OUTGOING_BY_CALLER.get(id) || []) {
|
||||
if (!visited.has(e.target)) { visited.add(e.target); queue.push([e.target, depth + 1]); }
|
||||
}
|
||||
for (const e of INCOMING_BY_CALLEE.get(id) || []) {
|
||||
if (!visited.has(e.source)) { visited.add(e.source); queue.push([e.source, depth + 1]); }
|
||||
}
|
||||
}
|
||||
return visited;
|
||||
}
|
||||
|
||||
function setSymbolSeed(seedId) {
|
||||
if (!SYMBOL_BY_ID.has(seedId)) {
|
||||
showSymbolEmptyState(`Symbol not found: ${seedId}`);
|
||||
return;
|
||||
}
|
||||
symbolSeedId = seedId;
|
||||
|
||||
// Make sure we're in Symbols view regardless of where the call came
|
||||
// from. If we're coming from Files, capture its positions BEFORE we
|
||||
// switch so toggling back to Files lands on the same layout.
|
||||
if (currentView !== "symbols") {
|
||||
if (currentView === "files") capturePositions();
|
||||
currentView = "symbols";
|
||||
document.querySelectorAll(".view-toggle button").forEach((b) => b.classList.toggle("active", b.dataset.view === "symbols"));
|
||||
}
|
||||
|
||||
// Depth 2 by default; fall back to depth 1 if the neighbourhood
|
||||
// explodes (popular utility symbols can have hundreds of callers).
|
||||
let visited = buildSymbolNeighbourhood(seedId, 2);
|
||||
if (visited.size > 60) visited = buildSymbolNeighbourhood(seedId, 1);
|
||||
|
||||
// Build Cytoscape elements for exactly this neighbourhood.
|
||||
const nodes = [];
|
||||
for (const id of visited) {
|
||||
const s = SYMBOL_BY_ID.get(id);
|
||||
if (!s) continue;
|
||||
nodes.push({
|
||||
group: "nodes",
|
||||
data: { id: `s::${s.id}`, label: s.name, nodeType: "symbol", qualifiedName: s.qualifiedName, kind: s.kind, file: s.file, line: s.line },
|
||||
classes: id === seedId ? "seed always-label" : "",
|
||||
});
|
||||
}
|
||||
const edges = [];
|
||||
let edgeCounter = 0;
|
||||
for (const e of DATA.symbolEdges || []) {
|
||||
if (visited.has(e.source) && visited.has(e.target)) {
|
||||
edges.push({
|
||||
group: "edges",
|
||||
data: { id: `se-${edgeCounter++}`, source: `s::${e.source}`, target: `s::${e.target}`, confidence: e.confidence, scope: "symbol" },
|
||||
classes: `conf-${e.confidence}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
clearHighlights();
|
||||
cy.elements().remove();
|
||||
if (nodes.length <= 1 && edges.length === 0) {
|
||||
// Seed has no connections — show the seed alone with an explanation.
|
||||
if (nodes.length === 1) cy.add(nodes);
|
||||
showSymbolEmptyState(`${SYMBOL_BY_ID.get(seedId).name} has no resolved callers or callees in this project.`);
|
||||
return;
|
||||
}
|
||||
hideSymbolEmptyState();
|
||||
cy.add([...nodes, ...edges]);
|
||||
runLayout("dagre");
|
||||
openSymbol(seedId);
|
||||
}
|
||||
|
||||
function showSymbolEmptyState(msg) {
|
||||
const el = document.getElementById("symbol-empty");
|
||||
if (!el) return;
|
||||
el.style.display = "flex";
|
||||
if (msg) {
|
||||
const p = el.querySelector("[data-msg]");
|
||||
if (p) p.textContent = msg;
|
||||
}
|
||||
}
|
||||
function hideSymbolEmptyState() {
|
||||
const el = document.getElementById("symbol-empty");
|
||||
if (el) el.style.display = "none";
|
||||
}
|
||||
|
||||
// ── Highlighting ─────────────────────────────────────────────────
|
||||
function clearHighlights() { cy.elements().removeClass("faded highlight highlight-flow highlight-edge highlight-flow-edge"); }
|
||||
function clearHighlights() {
|
||||
cy.elements().removeClass("faded highlight highlight-flow highlight-edge highlight-flow-edge highlight-selected highlight-neighbour highlight-neighbour-edge always-label");
|
||||
}
|
||||
|
||||
/**
|
||||
* Default highlight on node tap: the tapped node + its direct
|
||||
* incomers/outgoers. Less aggressive than "Blast radius" (transitive),
|
||||
* just surfaces what's wired directly to this node.
|
||||
*/
|
||||
function highlightNeighbourhood(rootId) {
|
||||
clearHighlights();
|
||||
const root = cy.getElementById(rootId);
|
||||
if (root.empty()) return;
|
||||
const neighbourhood = root.closedNeighborhood();
|
||||
cy.elements().difference(neighbourhood).addClass("faded");
|
||||
root.addClass("highlight-selected always-label");
|
||||
neighbourhood.nodes().difference(root).addClass("highlight-neighbour always-label");
|
||||
neighbourhood.edges().addClass("highlight-neighbour-edge");
|
||||
}
|
||||
|
||||
function bfsHighlight(rootId, direction) {
|
||||
clearHighlights();
|
||||
@@ -231,12 +455,61 @@
|
||||
|
||||
function clearSidebar() { while (sidebar.firstChild) sidebar.removeChild(sidebar.firstChild); }
|
||||
|
||||
/**
|
||||
* Reset the sidebar to its default state for the current view:
|
||||
* - Files view → "click a node" hint
|
||||
* - Symbols view with no seed → alphabetical list of all symbols
|
||||
* (so the page isn't blank and users
|
||||
* have something to start from)
|
||||
* - Symbols view with a seed → called rarely; same hint as Files
|
||||
*/
|
||||
function closeSidebar() {
|
||||
clearSidebar();
|
||||
if (currentView === "symbols" && !symbolSeedId) {
|
||||
renderSymbolList();
|
||||
return;
|
||||
}
|
||||
sidebar.className = "empty";
|
||||
sidebar.appendChild(document.createTextNode("Click a node to see details"));
|
||||
}
|
||||
|
||||
/** Alphabetical list of all symbols — the landing-state sidebar for
|
||||
* Symbol view. Clicking any row seeds the focus graph on that symbol
|
||||
* (handled by the existing `li[data-symbol-id]` handler below). */
|
||||
function renderSymbolList() {
|
||||
clearSidebar();
|
||||
sidebar.className = "list";
|
||||
const symbols = DATA.symbols || [];
|
||||
sidebar.appendChild(h("h2", null, "All symbols"));
|
||||
sidebar.appendChild(h("div", { class: "list-count" },
|
||||
`${symbols.length} symbols — click to explore, or type in the search bar to jump to one.`));
|
||||
|
||||
const sorted = [...symbols].sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
|
||||
const ul = h("ul", null);
|
||||
for (const s of sorted) {
|
||||
const basename = (s.file || "").split("/").pop() || s.file || "";
|
||||
const li = h("li", { "data-symbol-id": s.id, title: `${s.qualifiedName} @ ${s.file}:${s.line}` },
|
||||
h("span", { style: `color:${KIND_COLORS[s.kind] || "#64748b"};font-weight:600;` }, s.kind),
|
||||
" ",
|
||||
s.name,
|
||||
h("span", { class: "file-suffix" }, basename),
|
||||
);
|
||||
ul.appendChild(li);
|
||||
}
|
||||
sidebar.appendChild(ul);
|
||||
}
|
||||
|
||||
/** Explicit clear for the focus graph — used by the "Back to symbol
|
||||
* list" link in openSymbol's sidebar output. Resets seed, removes the
|
||||
* graph, shows the empty-state overlay + list. */
|
||||
function clearSymbolSeed() {
|
||||
symbolSeedId = null;
|
||||
clearHighlights();
|
||||
cy.elements().remove();
|
||||
showSymbolEmptyState();
|
||||
closeSidebar(); // re-renders the list because seed is null
|
||||
}
|
||||
|
||||
function actionBar(nodeId) {
|
||||
return h("div", { class: "actions" },
|
||||
h("button", { "data-action": "impact", "data-id": nodeId }, "Blast radius"),
|
||||
@@ -302,6 +575,12 @@
|
||||
if (!sym) return closeSidebar();
|
||||
clearSidebar();
|
||||
sidebar.className = "";
|
||||
// Back link at the top — the deliberate way out of the focus graph,
|
||||
// visible in the one place users look when they want to exit (top of
|
||||
// the sidebar). Clicking empty canvas no longer hides this.
|
||||
if (currentView === "symbols") {
|
||||
sidebar.appendChild(h("button", { class: "back-btn", "data-action": "back-to-list" }, "← Back to symbol list"));
|
||||
}
|
||||
sidebar.appendChild(h("h2", null, sym.name));
|
||||
sidebar.appendChild(h("span", { class: "kind-badge" }, sym.kind));
|
||||
sidebar.appendChild(metaRow("Qualified", sym.qualifiedName));
|
||||
@@ -313,10 +592,45 @@
|
||||
// ── Event wiring ─────────────────────────────────────────────────
|
||||
cy.on("tap", "node", (evt) => {
|
||||
const n = evt.target;
|
||||
if (n.data("nodeType") === "file") openFile(n.data("file"));
|
||||
else openSymbol(n.id().slice(3));
|
||||
if (n.data("nodeType") === "file") {
|
||||
// File view: highlight the direct neighbourhood + open sidebar.
|
||||
highlightNeighbourhood(n.id());
|
||||
openFile(n.data("file"));
|
||||
} else {
|
||||
// Symbol view: clicking a non-seed node RE-CENTRES the focus graph
|
||||
// on that symbol (SourceTrail-style exploration). Clicking the
|
||||
// current seed just refreshes the sidebar.
|
||||
const symId = n.id().slice(3);
|
||||
if (symId !== symbolSeedId) {
|
||||
setSymbolSeed(symId);
|
||||
} else {
|
||||
openSymbol(symId);
|
||||
}
|
||||
}
|
||||
});
|
||||
// Empty-canvas tap — clears highlights. In Symbol view with an active
|
||||
// seed we deliberately DO NOT close the sidebar, so the "Back to symbol
|
||||
// list" link stays visible (accidental-click-destroys-context is a
|
||||
// common graph-viewer anti-pattern).
|
||||
cy.on("tap", (evt) => {
|
||||
if (evt.target !== cy) return;
|
||||
clearHighlights();
|
||||
if (currentView === "symbols" && symbolSeedId) return; // keep sidebar
|
||||
closeSidebar();
|
||||
});
|
||||
|
||||
// Keep the `currentZoom` module variable in sync and re-render labels
|
||||
// when it crosses the threshold (the style functions read it).
|
||||
currentZoom = cy.zoom();
|
||||
let lastLabelState = currentZoom >= LABEL_ZOOM_THRESHOLD;
|
||||
cy.on("zoom", () => {
|
||||
currentZoom = cy.zoom();
|
||||
const state = currentZoom >= LABEL_ZOOM_THRESHOLD;
|
||||
if (state !== lastLabelState) {
|
||||
lastLabelState = state;
|
||||
cy.style().update();
|
||||
}
|
||||
});
|
||||
cy.on("tap", (evt) => { if (evt.target === cy) { closeSidebar(); clearHighlights(); } });
|
||||
|
||||
sidebar.addEventListener("click", (evt) => {
|
||||
const btn = evt.target.closest("button[data-action]");
|
||||
@@ -325,13 +639,14 @@
|
||||
if (action === "impact") highlightImpact(btn.dataset.id);
|
||||
else if (action === "flow") highlightFlow(btn.dataset.id);
|
||||
else if (action === "reset") clearHighlights();
|
||||
else if (action === "back-to-list") clearSymbolSeed();
|
||||
return;
|
||||
}
|
||||
// Clicking a symbol in either (a) a file's sidebar list in File view,
|
||||
// or (b) the all-symbols list in Symbol empty state, seeds the focus
|
||||
// graph on that symbol. Same action inside Symbol view re-centres.
|
||||
const li = evt.target.closest("li[data-symbol-id]");
|
||||
if (li && currentView === "symbols") {
|
||||
const cyNode = cy.getElementById(`s::${li.dataset.symbolId}`);
|
||||
if (!cyNode.empty()) cy.animate({ center: { eles: cyNode }, zoom: 1.3 }, { duration: 300 });
|
||||
}
|
||||
if (li) setSymbolSeed(li.dataset.symbolId);
|
||||
});
|
||||
|
||||
// ── Toolbar wiring ───────────────────────────────────────────────
|
||||
@@ -351,20 +666,42 @@
|
||||
});
|
||||
|
||||
// ── Live search ──────────────────────────────────────────────────
|
||||
// File view → live-filter visible file nodes, highlight + fit matches.
|
||||
// Symbol view → debounced search across ALL symbols (not just what's
|
||||
// on screen); best match seeds the focus graph.
|
||||
let searchDebounce = null;
|
||||
document.getElementById("search").addEventListener("input", (e) => {
|
||||
const q = e.target.value.trim().toLowerCase();
|
||||
clearHighlights();
|
||||
if (!q) return;
|
||||
const matches = cy.nodes().filter((n) => {
|
||||
const label = (n.data("label") || "").toLowerCase();
|
||||
const file = (n.data("file") || "").toLowerCase();
|
||||
const qn = (n.data("qualifiedName") || "").toLowerCase();
|
||||
return label.includes(q) || file.includes(q) || qn.includes(q);
|
||||
});
|
||||
if (matches.length === 0) return;
|
||||
cy.elements().addClass("faded");
|
||||
matches.removeClass("faded").addClass("highlight");
|
||||
if (matches.length <= 20) cy.animate({ fit: { eles: matches, padding: 80 } }, { duration: 300 });
|
||||
|
||||
if (currentView === "files") {
|
||||
clearHighlights();
|
||||
if (!q) return;
|
||||
const matches = cy.nodes().filter((n) => {
|
||||
const label = (n.data("label") || "").toLowerCase();
|
||||
const file = (n.data("file") || "").toLowerCase();
|
||||
return label.includes(q) || file.includes(q);
|
||||
});
|
||||
if (matches.length === 0) return;
|
||||
cy.elements().addClass("faded");
|
||||
matches.removeClass("faded").addClass("highlight");
|
||||
if (matches.length <= 20) cy.animate({ fit: { eles: matches, padding: 80 } }, { duration: 300 });
|
||||
return;
|
||||
}
|
||||
|
||||
// Symbols view: debounce so we don't re-layout on every keystroke.
|
||||
if (searchDebounce) clearTimeout(searchDebounce);
|
||||
if (!q) { if (!symbolSeedId) showSymbolEmptyState(); return; }
|
||||
searchDebounce = setTimeout(() => {
|
||||
// Prefer exact name match, then qualified-name match, then substring.
|
||||
const symbols = DATA.symbols || [];
|
||||
const exact = symbols.find((s) => s.name.toLowerCase() === q);
|
||||
const qname = exact || symbols.find((s) => s.qualifiedName.toLowerCase() === q);
|
||||
const sub = qname || symbols.find((s) =>
|
||||
s.name.toLowerCase().includes(q) || s.qualifiedName.toLowerCase().includes(q),
|
||||
);
|
||||
if (sub) setSymbolSeed(sub.id);
|
||||
else showSymbolEmptyState(`No symbol matching "${q}".`);
|
||||
}, 250);
|
||||
});
|
||||
|
||||
// ── Tooltip on hover ─────────────────────────────────────────────
|
||||
|
||||
@@ -72,6 +72,34 @@ main { flex: 1; display: flex; min-height: 0; position: relative; }
|
||||
#sidebar .actions button.reset:hover { background: #e5e7eb; }
|
||||
#sidebar .actions button.truncated-note { background: transparent; border: none; color: #9ca3af; font-size: 11px; cursor: default; padding: 5px 0; }
|
||||
|
||||
/* ── Symbol list (shown in sidebar when Symbol view has no seed) ──── */
|
||||
#sidebar.list h2 { margin-bottom: 2px; }
|
||||
#sidebar .list-count { color: #6b7280; font-size: 12px; margin-bottom: 12px; }
|
||||
#sidebar li .file-suffix { color: #94a3b8; font-size: 11px; margin-left: 6px; }
|
||||
|
||||
/* ── Back button (sidebar, Symbol view with seed) ─────────────────── */
|
||||
.back-btn {
|
||||
background: none; border: none; padding: 2px 0 8px;
|
||||
color: #2563eb; font-size: 12px; font-family: inherit;
|
||||
cursor: pointer; text-align: left; width: 100%;
|
||||
}
|
||||
.back-btn:hover { color: #1d4ed8; text-decoration: underline; }
|
||||
|
||||
/* ── Symbol-view empty state overlay ────────────────────────────── */
|
||||
/* Constrained to the canvas area only (left of the sidebar) so the
|
||||
* alphabetical symbol list stays visible on the right. `right: 340px`
|
||||
* matches the sidebar width — keep in sync. */
|
||||
.empty-view {
|
||||
position: absolute; top: 0; bottom: 0; left: 0; right: 340px;
|
||||
background: #f8fafc;
|
||||
display: none; align-items: center; justify-content: center;
|
||||
z-index: 5; pointer-events: none;
|
||||
}
|
||||
.empty-view > div { max-width: 480px; text-align: center; padding: 32px; pointer-events: auto; }
|
||||
.empty-view h2 { font-size: 22px; font-weight: 600; color: #0f172a; margin-bottom: 14px; }
|
||||
.empty-view p { font-size: 14px; color: #475569; line-height: 1.6; margin-bottom: 10px; }
|
||||
.empty-view p.hint { font-size: 12px; color: #94a3b8; margin-top: 14px; padding-top: 14px; border-top: 1px solid #e2e8f0; }
|
||||
|
||||
/* ── banner (symbol-mode not available) ─────────────────────────── */
|
||||
#banner {
|
||||
position: absolute; top: 12px; left: 50%; transform: translateX(-50%);
|
||||
|
||||
@@ -18,9 +18,8 @@
|
||||
<div class="toolbar">
|
||||
<label for="layout">Layout</label>
|
||||
<select id="layout">
|
||||
<option value="dagre">Hierarchical (Dagre)</option>
|
||||
<option value="cose">Force-directed</option>
|
||||
<option value="concentric">Concentric</option>
|
||||
<option value="dagre">Hierarchical (Dagre) — recommended</option>
|
||||
<option value="concentric">Concentric (by connections)</option>
|
||||
<option value="breadthfirst">Breadth-first</option>
|
||||
<option value="grid">Grid</option>
|
||||
<option value="circle">Circle</option>
|
||||
@@ -36,6 +35,17 @@
|
||||
</header>
|
||||
<main>
|
||||
<div id="cy"></div>
|
||||
<!-- Empty-state overlay for Symbol view. Symbol view is a FOCUS graph
|
||||
(SourceTrail-style): it starts empty and only ever shows one symbol's
|
||||
call-graph neighbourhood. Search or a click in the File view's
|
||||
sidebar seeds it; clicking a neighbour re-centres on it. -->
|
||||
<div id="symbol-empty" class="empty-view">
|
||||
<div>
|
||||
<h2>Symbol view</h2>
|
||||
<p data-msg>Pick a symbol from the list on the right, type a name in the search bar, or click a symbol in a file's sidebar (Files view).</p>
|
||||
<p class="hint">The symbol view is a <strong>focus graph</strong> — it shows one symbol with its direct callers / callees (depth 2). Click any neighbour to re-centre on it.</p>
|
||||
</div>
|
||||
</div>
|
||||
<aside id="sidebar" class="empty">Click a node to see details</aside>
|
||||
<div id="banner"></div>
|
||||
<div id="tooltip"></div>
|
||||
|
||||
@@ -92,9 +92,17 @@ export interface VizData {
|
||||
}
|
||||
|
||||
// ── Cached assets (read once per process) ─────────────────────────────
|
||||
let _assetCache: { cytoscape: string; dagre: string; cytoscapeDagre: string; styles: string; app: string; template: string } | null = null;
|
||||
interface AssetCache {
|
||||
cytoscape: string;
|
||||
dagre: string;
|
||||
cytoscapeDagre: string;
|
||||
styles: string;
|
||||
app: string;
|
||||
template: string;
|
||||
}
|
||||
let _assetCache: AssetCache | null = null;
|
||||
|
||||
async function loadAssets(): Promise<NonNullable<typeof _assetCache>> {
|
||||
async function loadAssets(): Promise<AssetCache> {
|
||||
if (_assetCache) return _assetCache;
|
||||
const [cytoscape, dagre, cytoscapeDagre, styles, app, template] = await Promise.all([
|
||||
fs.readFile(path.join(ASSETS_DIR, "cytoscape.min.js"), "utf-8"),
|
||||
@@ -277,9 +285,21 @@ export async function buildInteractiveGraphHtml(opts: InteractiveHtmlOptions): P
|
||||
symbolOmitReason: sym.reason,
|
||||
};
|
||||
|
||||
const statsLine = sym.mode === "full"
|
||||
? `${files.length} files · ${fileEdges.length} edges · ${sym.symbolCount ?? 0} symbols · ${sym.edgeCount ?? 0} calls`
|
||||
: `${files.length} files · ${fileEdges.length} edges`;
|
||||
// Use embedded counts (what's actually in this viewer) rather than the
|
||||
// authoritative meta counts — otherwise the top bar and the sidebar's
|
||||
// "All symbols" count can disagree. meta counts include synthetic
|
||||
// <module> placeholders and unresolved call edges that aren't rendered.
|
||||
let statsLine: string;
|
||||
if (sym.mode === "full") {
|
||||
statsLine = `${files.length} files · ${fileEdges.length} edges · ${sym.symbols.length} symbols · ${sym.symbolEdges.length} calls`;
|
||||
} else if (sym.mode === "capped") {
|
||||
// Can't embed — fall back to the authoritative meta counts and flag
|
||||
// the limitation so the number isn't mistaken for "this viewer's
|
||||
// explorable scope".
|
||||
statsLine = `${files.length} files · ${fileEdges.length} edges · ${sym.symbolCount ?? 0} symbols (capped) · ${sym.edgeCount ?? 0} calls (capped)`;
|
||||
} else {
|
||||
statsLine = `${files.length} files · ${fileEdges.length} edges`;
|
||||
}
|
||||
|
||||
// Use function replacers for asset/data injection: string replacements
|
||||
// would interpret `$&`, `$'`, `` $` ``, and `$$` in the replacement, which
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Giancarlo Erra - Altaire Limited
|
||||
|
||||
/**
|
||||
* Regression test for the bundled viewer-app.js — runs it in a mocked
|
||||
* DOM/Cytoscape environment and asserts it loads without throwing.
|
||||
*
|
||||
* This catches TDZ ("Cannot access 'X' before initialization") errors
|
||||
* introduced by declaring a `const`/`let` after it's used inside a style
|
||||
* closure that Cytoscape evaluates during the `cy = cytoscape({...})`
|
||||
* constructor call. The standard unit tests on `graph-visualize-html.ts`
|
||||
* check the generated HTML's structure but never execute the script, so
|
||||
* runtime errors like that only surface when a browser loads the page.
|
||||
*
|
||||
* Uses Node's `vm` module for a sandboxed evaluation — the viewer source
|
||||
* is trusted (we ship it ourselves) but isolating the globals keeps the
|
||||
* test safe and deterministic.
|
||||
*/
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { runInNewContext } from "node:vm";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const VIEWER_JS_PATH = path.resolve(__dirname, "../../src/assets/viewer-app.js");
|
||||
|
||||
describe("viewer-app.js", () => {
|
||||
it("executes top-to-bottom without TDZ or reference errors", () => {
|
||||
const src = readFileSync(VIEWER_JS_PATH, "utf-8");
|
||||
|
||||
// ── Mock DOM ────────────────────────────────────────────────────
|
||||
const makeEl = (id: string) => ({
|
||||
id,
|
||||
className: "",
|
||||
classList: { add: () => {}, remove: () => {}, toggle: () => {} },
|
||||
style: {},
|
||||
disabled: false,
|
||||
title: "",
|
||||
textContent: "",
|
||||
firstChild: null as null | object,
|
||||
dataset: {} as Record<string, string>,
|
||||
addEventListener: () => {},
|
||||
appendChild: () => {},
|
||||
removeChild: () => {},
|
||||
setAttribute: () => {},
|
||||
removeAttribute: () => {},
|
||||
});
|
||||
const elements = new Map<string, ReturnType<typeof makeEl>>();
|
||||
const doc = {
|
||||
createElement: () => makeEl("created"),
|
||||
createTextNode: () => ({}),
|
||||
getElementById: (id: string) => {
|
||||
if (!elements.has(id)) elements.set(id, makeEl(id));
|
||||
return elements.get(id);
|
||||
},
|
||||
querySelectorAll: () => [] as unknown[],
|
||||
};
|
||||
|
||||
// ── Mock Cytoscape — exercises every style closure on a fake ele ──
|
||||
const closureErrors: string[] = [];
|
||||
const makeFakeCy = () => ({
|
||||
on: () => {},
|
||||
zoom: () => 1,
|
||||
width: () => 800,
|
||||
height: () => 600,
|
||||
elements: () => ({
|
||||
remove: () => {},
|
||||
addClass: () => {},
|
||||
removeClass: () => {},
|
||||
difference: () => ({
|
||||
addClass: () => {},
|
||||
nodes: () => ({ difference: () => ({ addClass: () => {} }) }),
|
||||
edges: () => ({ addClass: () => {} }),
|
||||
}),
|
||||
}),
|
||||
nodes: () => ({ forEach: () => {}, length: 0, filter: () => [] as unknown[] }),
|
||||
getElementById: () => ({ empty: () => true }),
|
||||
add: () => {},
|
||||
fit: () => {},
|
||||
style: () => ({ update: () => {} }),
|
||||
layout: () => ({ one: () => {}, run: () => {} }),
|
||||
batch: (fn: () => void) => fn(),
|
||||
png: () => "data:,",
|
||||
animate: () => {},
|
||||
});
|
||||
|
||||
const fakeCy = (config: { style?: Array<{ selector: string; style?: Record<string, unknown> }> }) => {
|
||||
const instance = makeFakeCy();
|
||||
const fakeEle = { data: () => "x", hasClass: () => false, cy: () => instance };
|
||||
// Exercise every function-typed style value. Any TDZ or reference
|
||||
// error surfaces here as a collected closureErrors entry.
|
||||
for (const rule of config.style ?? []) {
|
||||
for (const [key, val] of Object.entries(rule.style ?? {})) {
|
||||
if (typeof val === "function") {
|
||||
try { (val as (ele: unknown) => unknown)(fakeEle); }
|
||||
catch (e) { closureErrors.push(`${rule.selector} → ${key}: ${(e as Error).message}`); }
|
||||
}
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
};
|
||||
|
||||
const data = {
|
||||
project: { name: "smoke" },
|
||||
files: [{ id: "a.ts", label: "a.ts", language: "typescript", deps: 0, dependents: 0, symbolCount: 0 }],
|
||||
fileEdges: [],
|
||||
symbols: [],
|
||||
symbolEdges: [],
|
||||
symbolsByFile: {},
|
||||
symbolMode: "full" as const,
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
document: doc,
|
||||
cytoscape: fakeCy,
|
||||
window: { __SOCRATICODE_DATA__: data, cytoscapeDagre: () => {} },
|
||||
console: { log: () => {}, warn: () => {}, error: () => {} },
|
||||
};
|
||||
|
||||
// Throws if the viewer hits TDZ or any other top-level error.
|
||||
expect(() => runInNewContext(src, ctx, { filename: "viewer-app.js" })).not.toThrow();
|
||||
expect(closureErrors).toEqual([]);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user