feat(dashboard): show the code graph, from its card and from a finding (t82)

The target page's code graph card links to the drawn graph, and a
finding whose location the graph has links to its impact: the entry
points that reach it, the call chains, callers and callees.

The explorer and the impact page follow the current dashboard: German
first through i18n, the target page's header, and graph colours taken
from the theme tokens, so the drawing follows the light and dark theme
and recolours on a switch.

A large graph stays usable: above 1,200 nodes it opens as one node per
group (communities of 10 or more, smaller ones pooled by folder), and a
click opens a group with its members and the groups linked to them.
The grouping runs in Rust (pages/graph_view.rs); graph-viz.js only
draws. A large drawing stops its layout after stabilising. The agent's
truncation of very large graphs is now shown.

/graph leads to the targets list; the file and search queries are
encoded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-11-07 11:24:27 +01:00
1 parent c1a70b025c
commit c8d53d5c30
14 files changed
+1657 -989

No files matched your search

+186 -264
View File
@@ -1,231 +1,238 @@
// ═══════════════════════════════════════════════════════════════
// Graph Visualization — vis-network wrapper for Code Knowledge Graph
// Obsidian Control theme
// ═══════════════════════════════════════════════════════════════
// Code graph drawing: a thin vis-network wrapper.
//
// The dashboard's Rust code decides what is drawn (the whole graph, the
// community overview or one community, see pages/graph_view.rs) and passes
// the nodes, edges and the UI texts in the reader's language. This file only
// draws them, in the colours of the current theme.
(function () {
"use strict";
// Color palette matching Obsidian Control
const NODE_COLORS = {
function: { bg: "#00c8ff", border: "#00a0cc", font: "#060a13" },
method: { bg: "#00c8ff", border: "#00a0cc", font: "#060a13" },
struct: { bg: "#e040fb", border: "#b030d0", font: "#060a13" },
class: { bg: "#e040fb", border: "#b030d0", font: "#060a13" },
enum: { bg: "#ffb020", border: "#cc8c18", font: "#060a13" },
interface: { bg: "#7c4dff", border: "#5c38c0", font: "#ffffff" },
trait: { bg: "#7c4dff", border: "#5c38c0", font: "#ffffff" },
module: { bg: "#ff8a3d", border: "#cc6e30", font: "#060a13" },
file: { bg: "#00e676", border: "#00b85e", font: "#060a13" },
// CSS custom properties per node kind, defined in main.css from the theme
// tokens, so the graph follows the light and dark theme.
var KIND_TOKEN = {
function: "--graph-function",
method: "--graph-function",
class: "--graph-type",
struct: "--graph-type",
enum: "--graph-enum",
interface: "--graph-interface",
trait: "--graph-interface",
module: "--graph-module",
file: "--graph-file",
community: "--graph-community",
folder: "--graph-community",
};
var EDGE_TOKEN = {
calls: "--graph-function",
imports: "--graph-enum",
inherits: "--graph-type",
implements: "--graph-interface",
bundle: "--graph-community",
};
const EDGE_COLORS = {
calls: "#00c8ff",
imports: "#ffb020",
inherits: "#e040fb",
implements: "#7c4dff",
contains: "rgba(94, 114, 145, 0.6)",
type_ref: "rgba(94, 114, 145, 0.5)",
};
var SHAPE = { file: "diamond", module: "square", folder: "hexagon" };
const DEFAULT_NODE_COLOR = { bg: "#5e7291", border: "#3d506b", font: "#e4eaf4" };
const DEFAULT_EDGE_COLOR = "rgba(94, 114, 145, 0.3)";
// Above this many nodes the layout runs a short while and then stops,
// so a large drawing does not keep the CPU busy.
var LARGE = 400;
let network = null;
let nodesDataset = null;
let edgesDataset = null;
let rawNodes = [];
let rawEdges = [];
var network = null;
var nodesDataset = null;
var edgesDataset = null;
var rawNodes = [];
var rawEdges = [];
var texts = { kinds: {}, edges: {}, layout: "", entry: "", file: "" };
function getNodeColor(kind) {
return NODE_COLORS[kind] || DEFAULT_NODE_COLOR;
function token(name) {
return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
}
function getEdgeColor(kind) {
return EDGE_COLORS[kind] || DEFAULT_EDGE_COLOR;
function palette() {
var kinds = {};
Object.keys(KIND_TOKEN).forEach(function (k) {
kinds[k] = token(KIND_TOKEN[k]);
});
var edges = {};
Object.keys(EDGE_TOKEN).forEach(function (k) {
edges[k] = token(EDGE_TOKEN[k]);
});
return {
kinds: kinds,
edges: edges,
quiet: token("--border-strong"),
text: token("--text-primary"),
halo: token("--bg-primary"),
ring: token("--text-primary"),
fallback: token("--text-tertiary"),
font: token("--font-body"),
};
}
// Build a vis-network node from raw graph data
function toVisNode(node, edgeCounts) {
const color = getNodeColor(node.kind);
const connections = edgeCounts[node.qualified_name] || 0;
const size = Math.max(8, Math.min(35, 8 + connections * 2));
function edgeCounts(edges) {
var counts = {};
edges.forEach(function (e) {
counts[e.source] = (counts[e.source] || 0) + 1;
counts[e.target] = (counts[e.target] || 0) + 1;
});
return counts;
}
function toVisNode(node, counts, colors) {
var color = colors.kinds[node.kind] || colors.fallback;
var isGroup = node.kind === "community" || node.kind === "folder";
var kindName = texts.kinds[node.kind] || node.kind;
// A group is sized by its members through `value`, which also scales its
// label, so the large groups stay legible when the overview is zoomed out.
var size = Math.max(8, Math.min(30, 8 + (counts[node.qualified_name] || 0) * 1.5));
var title = isGroup
? kindName + " " + node.name + ": " + node.member_count
: kindName + ": " + node.qualified_name +
"\n" + texts.file + ": " + node.file_path + ":" + node.start_line +
(node.is_entry_point ? "\n" + texts.entry : "");
return {
id: node.qualified_name,
label: node.name,
title: `${node.kind}: ${node.qualified_name}\nFile: ${node.file_path}:${node.start_line}`,
size: size,
label: isGroup ? node.name + "\n" + node.member_count : node.name,
title: title,
size: isGroup ? undefined : size,
value: isGroup ? node.member_count : undefined,
color: {
background: color.bg,
border: color.border,
highlight: { background: color.bg, border: "#ffffff" },
hover: { background: color.bg, border: "#ffffff" },
background: color,
border: node.is_entry_point ? colors.ring : color,
highlight: { background: color, border: colors.ring },
hover: { background: color, border: colors.ring },
},
font: {
color: color.font,
size: 10,
face: "'JetBrains Mono', monospace",
strokeWidth: 2,
strokeColor: "#060a13",
color: colors.text,
size: isGroup ? 13 : 11,
face: colors.font,
strokeWidth: 3,
strokeColor: colors.halo,
},
borderWidth: 1,
borderWidth: node.is_entry_point ? 3 : 1,
borderWidthSelected: 3,
shape: node.kind === "file" ? "diamond" : node.kind === "module" ? "square" : "dot",
// Store raw data for click handler
shape: SHAPE[node.kind] || "dot",
_raw: node,
};
}
function toVisEdge(edge) {
const color = getEdgeColor(edge.kind);
const isDim = edge.kind === "contains" || edge.kind === "type_ref";
function toVisEdge(edge, colors) {
var color = colors.edges[edge.kind] || colors.quiet;
var count = edge.count || 1;
var label = edge.kind === "bundle" ? String(count) : texts.edges[edge.kind] || edge.kind;
return {
id: edge.source + "|" + edge.target + "|" + edge.kind,
from: edge.source,
to: edge.target,
color: {
color: color,
highlight: "#ffffff",
highlight: colors.ring,
hover: color,
opacity: edge.kind === "bundle" ? 0.35 : 0.7,
},
width: isDim ? 1 : 2,
arrows: {
to: {
enabled: edge.kind !== "contains",
scaleFactor: 0.5,
},
},
smooth: {
enabled: true,
type: "continuous",
roundness: 0.3,
},
title: `${edge.kind}: ${edge.source} → ${edge.target}`,
_raw: edge,
width: edge.kind === "bundle" ? Math.min(8, 1 + Math.log2(count)) : 1,
arrows: { to: { enabled: edge.kind !== "contains", scaleFactor: 0.4 } },
smooth: { enabled: true, type: "continuous", roundness: 0.3 },
title: label,
};
}
// Recolour everything after a theme change, without a new layout.
function recolor() {
if (!network) return;
var colors = palette();
var counts = edgeCounts(rawEdges);
nodesDataset.update(rawNodes.map(function (n) {
return toVisNode(n, counts, colors);
}));
edgesDataset.update(rawEdges.map(function (e) {
return toVisEdge(e, colors);
}));
}
new MutationObserver(recolor).observe(document.documentElement, {
attributes: true,
attributeFilter: ["data-theme"],
});
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", recolor);
function uniqueBy(items, key) {
var seen = {};
return items.filter(function (item) {
var k = key(item);
if (seen[k]) return false;
seen[k] = true;
return true;
});
}
/**
* Initialize or reload the graph visualization.
* Called from Rust via eval().
* Draw `nodes` and `edges`, then select and show the nodes named in
* `focus` (may be empty). `labels` holds the UI texts. Called from Rust.
*/
window.__loadGraph = function (nodes, edges) {
window.__loadGraph = function (nodes, edges, labels, focus) {
var container = document.getElementById("graph-canvas");
if (!container) {
console.error("[graph-viz] #graph-canvas not found");
return;
}
if (!container) return;
texts = labels;
// Count edges per node for sizing
const edgeCounts = {};
edges.forEach(function (e) {
edgeCounts[e.source] = (edgeCounts[e.source] || 0) + 1;
edgeCounts[e.target] = (edgeCounts[e.target] || 0) + 1;
});
rawNodes = uniqueBy(nodes, function (n) { return n.qualified_name; });
rawEdges = uniqueBy(edges, function (e) { return e.source + "|" + e.target + "|" + e.kind; });
// Deduplicate nodes by qualified_name (keep first occurrence)
var seenNodes = {};
var uniqueNodes = [];
nodes.forEach(function (n) {
if (!seenNodes[n.qualified_name]) {
seenNodes[n.qualified_name] = true;
uniqueNodes.push(n);
}
});
var colors = palette();
var counts = edgeCounts(rawEdges);
nodesDataset = new vis.DataSet(rawNodes.map(function (n) {
return toVisNode(n, counts, colors);
}));
edgesDataset = new vis.DataSet(rawEdges.map(function (e) {
return toVisEdge(e, colors);
}));
// Deduplicate edges by source+target+kind
var seenEdges = {};
var uniqueEdges = [];
edges.forEach(function (e) {
var key = e.source + "|" + e.target + "|" + e.kind;
if (!seenEdges[key]) {
seenEdges[key] = true;
uniqueEdges.push(e);
}
});
rawNodes = uniqueNodes;
rawEdges = uniqueEdges;
var visNodes = uniqueNodes.map(function (n) {
return toVisNode(n, edgeCounts);
});
var visEdges = uniqueEdges.map(toVisEdge);
nodesDataset = new vis.DataSet(visNodes);
edgesDataset = new vis.DataSet(visEdges);
const options = {
var large = rawNodes.length > LARGE;
var options = {
nodes: {
font: { color: "#e4eaf4", size: 10 },
scaling: { min: 8, max: 35 },
},
edges: {
font: { color: "#5e7291", size: 9, strokeWidth: 0 },
selectionWidth: 3,
scaling: {
min: 12,
max: 56,
label: { enabled: true, min: 22, max: 48, drawThreshold: 5, maxVisible: 30 },
},
},
physics: {
enabled: true,
solver: "forceAtlas2Based",
forceAtlas2Based: {
gravitationalConstant: -80,
centralGravity: 0.005,
springLength: 120,
gravitationalConstant: -60,
centralGravity: 0.008,
springLength: 110,
springConstant: 0.04,
damping: 0.5,
avoidOverlap: 0.6,
damping: 0.6,
avoidOverlap: 0.5,
},
stabilization: {
enabled: true,
iterations: 1500,
updateInterval: 25,
},
maxVelocity: 50,
stabilization: { enabled: true, iterations: large ? 300 : 1000, updateInterval: 25 },
maxVelocity: 40,
minVelocity: 0.75,
},
interaction: {
hover: true,
tooltipDelay: 200,
hideEdgesOnDrag: false,
hideEdgesOnZoom: false,
multiselect: false,
navigationButtons: false,
keyboard: { enabled: true },
},
layout: {
improvedLayout: uniqueNodes.length < 300,
hideEdgesOnDrag: large,
hideEdgesOnZoom: large,
keyboard: { enabled: true, bindToWindow: false },
},
layout: { improvedLayout: rawNodes.length < 300 },
};
// Destroy previous instance
if (network) {
network.destroy();
}
if (network) network.destroy();
network = new vis.Network(container, { nodes: nodesDataset, edges: edgesDataset }, options);
network = new vis.Network(
container,
{ nodes: nodesDataset, edges: edgesDataset },
options
);
// Click handler — sends data to Rust
network.on("click", function (params) {
if (params.nodes.length > 0) {
const nodeId = params.nodes[0];
const visNode = nodesDataset.get(nodeId);
if (visNode && visNode._raw && window.__onNodeClick) {
window.__onNodeClick(JSON.stringify(visNode._raw));
}
}
if (params.nodes.length === 0) return;
var raw = rawNodes.find(function (n) { return n.qualified_name === params.nodes[0]; });
if (raw && window.__onNodeClick) window.__onNodeClick(JSON.stringify(raw));
});
// Stabilization overlay
var overlay = document.getElementById("graph-stabilization-overlay");
var progressFill = document.getElementById("graph-stab-progress-fill");
var pctLabel = document.getElementById("graph-stab-pct");
// Show the overlay
if (overlay) {
overlay.classList.remove("graph-stab-fade-out");
overlay.style.display = "flex";
@@ -233,120 +240,35 @@
network.on("stabilizationProgress", function (params) {
var pct = Math.round((params.iterations / params.total) * 100);
if (progressFill) {
progressFill.style.width = pct + "%";
}
if (pctLabel) {
pctLabel.textContent = pct + "% — computing layout";
}
if (progressFill) progressFill.style.width = pct + "%";
if (pctLabel) pctLabel.textContent = texts.layout + " · " + pct + " %";
});
network.on("stabilizationIterationsDone", function () {
network.once("stabilizationIterationsDone", function () {
if (progressFill) progressFill.style.width = "100%";
if (pctLabel) pctLabel.textContent = "Complete";
// Fade out overlay
if (overlay) {
overlay.classList.add("graph-stab-fade-out");
setTimeout(function () {
overlay.style.display = "none";
}, 900);
setTimeout(function () { overlay.style.display = "none"; }, 600);
}
// Keep physics running so nodes float and respond to dragging,
// but reduce forces for a calm, settled feel
network.setOptions({
physics: {
enabled: true,
solver: "forceAtlas2Based",
forceAtlas2Based: {
gravitationalConstant: -40,
centralGravity: 0.003,
springLength: 120,
springConstant: 0.03,
damping: 0.7,
avoidOverlap: 0.6,
},
maxVelocity: 20,
minVelocity: 0.75,
},
});
// A large drawing stops moving; a small one keeps settling gently
// and answers to dragging.
network.setOptions({ physics: large ? { enabled: false } : { maxVelocity: 15 } });
window.__highlightNodes(focus || []);
});
console.log(
"[graph-viz] Loaded " + nodes.length + " nodes, " + edges.length + " edges"
);
};
/**
* Highlight a node by qualified name. Focuses + selects it.
*/
window.__highlightNode = function (qualifiedName) {
if (!network || !nodesDataset) return;
const node = nodesDataset.get(qualifiedName);
if (!node) return;
network.selectNodes([qualifiedName]);
network.focus(qualifiedName, {
scale: 1.5,
animation: { duration: 500, easingFunction: "easeInOutQuad" },
});
// Trigger click callback too
if (node._raw && window.__onNodeClick) {
window.__onNodeClick(JSON.stringify(node._raw));
}
};
/**
* Highlight multiple nodes (e.g., search results or file nodes).
*/
/** Select the named nodes that are drawn and show them. */
window.__highlightNodes = function (qualifiedNames) {
if (!network || !nodesDataset) return;
network.selectNodes(qualifiedNames);
if (qualifiedNames.length > 0) {
network.fit({
nodes: qualifiedNames,
animation: { duration: 500, easingFunction: "easeInOutQuad" },
});
}
var drawn = qualifiedNames.filter(function (id) { return nodesDataset.get(id); });
if (drawn.length === 0) return;
network.selectNodes(drawn);
network.fit({ nodes: drawn, animation: { duration: 500, easingFunction: "easeInOutQuad" } });
};
/**
* Highlight all nodes belonging to a specific file path.
*/
window.__highlightFileNodes = function (filePath) {
if (!network || !nodesDataset) return;
var matching = [];
rawNodes.forEach(function (n) {
if (n.file_path === filePath) {
matching.push(n.qualified_name);
}
});
if (matching.length > 0) {
network.selectNodes(matching);
network.fit({
nodes: matching,
animation: { duration: 500, easingFunction: "easeInOutQuad" },
});
}
};
/**
* Clear selection.
*/
window.__clearGraphSelection = function () {
if (!network) return;
network.unselectAll();
};
/**
* Fit entire graph in view.
*/
/** Fit the whole drawing in view. */
window.__fitGraph = function () {
if (!network) return;
network.fit({
animation: { duration: 400, easingFunction: "easeInOutQuad" },
});
network.fit({ animation: { duration: 400, easingFunction: "easeInOutQuad" } });
};
})();
+105 -155
View File
@@ -101,6 +101,18 @@
color-scheme: light;
}
/* Code graph colours (graph-viz.js reads them), from the theme tokens, so
they follow the light and dark theme. */
:root {
--graph-function: var(--accent);
--graph-type: var(--success);
--graph-enum: var(--warning);
--graph-interface: var(--info);
--graph-module: var(--orange);
--graph-file: var(--text-faint);
--graph-community: var(--text-tertiary);
}
/* ── Dark ("Nacht") ──
When chosen explicitly (`data-theme="dark"`), or when the OS prefers dark
and no choice was made. */
@@ -1762,85 +1774,6 @@ tbody tr:last-child td {
gap: 24px;
}
/* Orbital rings */
.graph-stab-rings {
position: relative;
width: 120px;
height: 120px;
}
.graph-stab-ring {
position: absolute;
inset: 0;
border-radius: 50%;
border: 1px solid transparent;
}
.graph-stab-ring-1 {
border-top-color: var(--accent);
border-right-color: var(--accent-muted);
animation: stab-orbit 2.4s linear infinite;
}
.graph-stab-ring-2 {
inset: 14px;
border-bottom-color: rgba(224, 64, 251, 0.5);
border-left-color: rgba(224, 64, 251, 0.1);
animation: stab-orbit 1.8s linear infinite reverse;
filter: drop-shadow(0 0 6px rgba(224, 64, 251, 0.25));
}
.graph-stab-ring-3 {
inset: 30px;
border-top-color: var(--success);
border-right-color: var(--success-bg);
animation: stab-orbit 3.2s linear infinite;
}
.graph-stab-core {
position: absolute;
top: 50%;
left: 50%;
width: 10px;
height: 10px;
transform: translate(-50%, -50%);
background: var(--accent);
border-radius: 50%;
box-shadow: 0 0 0 3px var(--border-accent);
animation: stab-pulse 1.6s ease-in-out infinite;
}
@keyframes stab-orbit {
to { transform: rotate(360deg); }
}
@keyframes stab-pulse {
0%, 100% { transform: translate(-50%, -50%) scale(1); opacity: 1; }
50% { transform: translate(-50%, -50%) scale(1.6); opacity: 0.6; }
}
/* Text */
.graph-stab-text {
text-align: center;
}
.graph-stab-title {
font-family: var(--font-display);
font-size: 16px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--text-primary);
margin-bottom: 4px;
}
.graph-stab-subtitle {
font-family: var(--font-mono);
font-size: 12px;
color: var(--text-secondary);
letter-spacing: 0.03em;
}
/* Progress bar */
.graph-stab-progress {
width: 200px;
@@ -1854,23 +1787,9 @@ tbody tr:last-child td {
.graph-stab-progress-fill {
height: 100%;
width: 0%;
background: linear-gradient(90deg, var(--accent), #e040fb);
background: var(--accent);
border-radius: 2px;
transition: width 0.3s ease-out;
box-shadow: none;
position: relative;
}
.graph-stab-progress-fill::after {
content: '';
position: absolute;
right: 0;
top: -2px;
width: 7px;
height: 7px;
background: #fff;
border-radius: 50%;
box-shadow: none;
}
.graph-stab-pct {
@@ -1885,16 +1804,11 @@ tbody tr:last-child td {
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
min-height: 240px;
color: var(--text-tertiary);
gap: 8px;
}
.graph-empty-icon {
font-size: 48px;
opacity: 0.3;
}
.graph-empty-state h3 {
font-family: var(--font-display);
font-size: 16px;
@@ -1905,37 +1819,6 @@ tbody tr:last-child td {
font-size: 13px;
}
/* Stats Bar */
.graph-stats-bar {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 16px;
background: var(--bg-secondary);
border-top: 1px solid var(--border);
font-family: var(--font-mono);
font-size: 11px;
flex-shrink: 0;
}
.graph-stat {
display: inline-flex;
align-items: center;
}
.graph-stat-value {
color: var(--accent);
font-weight: 600;
}
.graph-stat-label {
color: var(--text-tertiary);
}
.graph-stat-divider {
color: var(--border-bright);
}
/* Node Kind Badges */
.node-label-badge {
display: inline-flex;
@@ -1949,40 +1832,96 @@ tbody tr:last-child td {
letter-spacing: 0.04em;
}
.node-kind-function, .node-kind-method {
background: var(--accent-muted);
color: var(--accent);
border: 1px solid var(--border-accent);
/* Node kinds: the badge in the inspector and the legend's dots, in the
colours graph-viz.js draws them with. */
.node-label-badge[class*="graph-kind-"] {
background: color-mix(in oklch, var(--kind) 12%, transparent);
color: var(--kind);
border: 1px solid color-mix(in oklch, var(--kind) 30%, transparent);
}
.node-kind-struct, .node-kind-class {
background: rgba(224, 64, 251, 0.12);
color: #e040fb;
border: 1px solid rgba(224, 64, 251, 0.2);
.graph-kind-function, .graph-kind-method { --kind: var(--graph-function); }
.graph-kind-class, .graph-kind-struct { --kind: var(--graph-type); }
.graph-kind-enum { --kind: var(--graph-enum); }
.graph-kind-interface, .graph-kind-trait { --kind: var(--graph-interface); }
.graph-kind-module { --kind: var(--graph-module); }
.graph-kind-file { --kind: var(--graph-file); }
.graph-kind-community, .graph-kind-folder { --kind: var(--graph-community); }
.graph-legend-dot.graph-kind-folder { border-radius: 2px; }
.graph-legend {
position: absolute;
left: 12px;
bottom: 12px;
z-index: 10;
display: flex;
flex-wrap: wrap;
gap: 4px 12px;
max-width: calc(100% - 24px);
margin: 0;
padding: 6px 10px;
list-style: none;
font-size: 11.5px;
color: var(--text-secondary);
background: color-mix(in oklch, var(--bg-card) 90%, transparent);
border: 1px solid var(--border);
border-radius: var(--radius);
}
.node-kind-enum {
background: rgba(255, 176, 32, 0.12);
color: #ffb020;
border: 1px solid rgba(255, 176, 32, 0.2);
.graph-legend li {
display: inline-flex;
align-items: center;
gap: 6px;
}
.node-kind-interface, .node-kind-trait {
background: rgba(124, 77, 255, 0.12);
color: #7c4dff;
border: 1px solid rgba(124, 77, 255, 0.2);
.graph-legend-dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--kind);
}
.node-kind-module {
background: rgba(255, 138, 61, 0.12);
color: #ff8a3d;
border: 1px solid rgba(255, 138, 61, 0.2);
.graph-legend-entry {
background: transparent;
border: 2px solid var(--text-primary);
}
.node-kind-file {
background: var(--success-bg);
color: var(--success);
border: 1px solid color-mix(in oklch, var(--success) 30%, transparent);
.graph-note {
margin: 0 0 12px;
font-size: 12.5px;
color: var(--text-tertiary);
}
/* A finding's impact: its call chains and the names around it. */
.impact-summary {
grid-template-columns: 1fr;
}
.impact-chains,
.impact-names {
display: grid;
gap: 8px;
margin: 0;
padding: 0;
list-style: none;
}
.impact-chains li {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
}
.impact-chains code,
.impact-names code {
font-family: var(--font-mono);
font-size: 12px;
overflow-wrap: anywhere;
}
.impact-chain-arrow {
color: var(--text-faint);
}
/* Code Inspector Panel */
@@ -2243,12 +2182,23 @@ tbody tr:last-child td {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 8px 12px;
cursor: pointer;
font: inherit;
color: inherit;
text-align: left;
background: none;
border: none;
border-bottom: 1px solid var(--border);
transition: background 0.15s;
}
.search-suggestion-item:focus-visible {
outline: 2px solid var(--accent);
outline-offset: -2px;
}
.search-suggestion-item:last-child {
border-bottom: none;
}
+2 -2
View File
@@ -28,8 +28,8 @@ pub enum Route {
SbomPage { target: String },
#[route("/issues")]
IssuesPage {},
#[route("/graph")]
GraphIndexPage {},
// The code graph opens from its card on the target page.
#[redirect("/graph", || Route::TargetsPage {})]
#[route("/graph/:repo_id")]
GraphExplorerPage { repo_id: String },
#[route("/graph/:repo_id/impact/:finding_id")]
@@ -1,7 +1,10 @@
use dioxus::prelude::*;
use crate::i18n::texts::graph as tx;
use crate::i18n::use_lang;
use crate::infrastructure::graph::fetch_file_content;
/// A file of the code graph, with the selected code unit's lines marked.
#[component]
pub fn CodeInspector(
repo_id: String,
@@ -12,6 +15,7 @@ pub fn CodeInspector(
end_line: u32,
on_close: EventHandler<()>,
) -> Element {
let lang = use_lang()();
let file_path_clone = file_path.clone();
let repo_id_clone = repo_id.clone();
let file_content = use_resource(move || {
@@ -30,18 +34,20 @@ pub fn CodeInspector(
// Header
div { class: "code-inspector-header",
div { class: "code-inspector-title",
span { class: "badge badge-info", "SELECTED" }
span { class: "code-inspector-file-name", "{file_path}" }
}
div { class: "code-inspector-meta",
span { class: "node-label-badge node-kind-{node_kind}", "{node_kind}" }
span { class: "node-label-badge graph-kind-{node_kind}", {tx::kind(&node_kind).get(lang)} }
span { class: "code-inspector-node-name", "{node_name}" }
if start_line > 0 && end_line > 0 {
span { class: "code-inspector-lines", "L{start_line}–L{end_line}" }
span { class: "code-inspector-lines", "{tx::LINES.get(lang)} {start_line}–{end_line}" }
}
}
button {
class: "btn-sm code-inspector-close",
class: "btn btn-ghost btn-sm code-inspector-close",
r#type: "button",
title: tx::CLOSE.get(lang),
"aria-label": tx::CLOSE.get(lang),
onclick: move |_| on_close.call(()),
"\u{2715}"
}
@@ -79,12 +85,10 @@ pub fn CodeInspector(
}
},
Some(None) => rsx! {
div { class: "code-inspector-empty",
"Could not load file content."
}
div { class: "code-inspector-empty", {tx::FILE_FAILED.get(lang)} }
},
None => rsx! {
div { class: "loading", "Loading file..." }
div { class: "loading", {tx::FILE_LOADING.get(lang)} }
},
}
}
+28
View File
@@ -93,6 +93,24 @@ pub fn format_bytes(bytes: u64, lang: Lang) -> String {
}
}
/// A count with thousands separators: `12.345` in German, `12,345` in English.
pub fn format_count(count: u64, lang: Lang) -> String {
let separator = match lang {
Lang::De => '.',
Lang::En => ',',
};
let digits = count.to_string();
let mut grouped = String::with_capacity(digits.len() + digits.len() / 3);
for (i, digit) in digits.chars().enumerate() {
// A separator before every digit that starts a group of three from the right.
if i > 0 && (digits.len() - i).is_multiple_of(3) {
grouped.push(separator);
}
grouped.push(digit);
}
grouped
}
/// A moment in the reader's date convention, in UTC: `30.09.2026 08:05 UTC`
/// in German, `2026-09-30 08:05 UTC` in English.
pub fn format_time(time: &chrono::DateTime<chrono::Utc>, lang: Lang) -> String {
@@ -195,6 +213,16 @@ fn set_document_lang(lang: Lang) {
#[cfg(test)]
mod tests {
#[test]
fn a_count_has_the_languages_thousands_separator() {
use super::{format_count, Lang};
assert_eq!(format_count(0, Lang::De), "0");
assert_eq!(format_count(999, Lang::De), "999");
assert_eq!(format_count(1_000, Lang::De), "1.000");
assert_eq!(format_count(12_345_678, Lang::De), "12.345.678");
assert_eq!(format_count(10_000, Lang::En), "10,000");
}
#[test]
fn a_moment_reads_as_how_long_ago_it_was() {
use chrono::{Duration, TimeZone, Utc};
+288
View File
@@ -1140,6 +1140,10 @@ pub mod targets {
de: "Einstiegspunkte",
en: "entry points",
};
pub const GRAPH_SHOW: Text = Text {
de: "Anzeigen",
en: "Show",
};
pub const GRAPH_NOTE: Text = Text {
de: "Die Bewertung der Befunde berücksichtigt, ob ein Einstiegspunkt die Stelle erreicht.",
en: "Triage takes into account whether an entry point reaches a finding.",
@@ -4595,3 +4599,287 @@ pub mod metering {
}
}
}
/// The code graph's explorer and a finding's impact in it (t82).
pub mod graph {
use super::super::{format_count, Lang};
use super::Text;
pub const TITLE: Text = Text {
de: "Codegraph",
en: "Code graph",
};
pub const BACK: Text = Text {
de: "Zurück",
en: "Back",
};
pub const OVERVIEW: Text = Text {
de: "Übersicht",
en: "Overview",
};
pub const SEARCH: Text = Text {
de: "Baustein suchen …",
en: "Search code units …",
};
pub const FIT: Text = Text {
de: "Alles zeigen",
en: "Fit view",
};
pub const REBUILD: Text = Text {
de: "Neu aufbauen",
en: "Rebuild",
};
pub const BUILDING: Text = Text {
de: "Wird aufgebaut …",
en: "Building …",
};
pub const BUILD_STARTED: Text = Text {
de: "Der Codegraph wird neu aufgebaut.",
en: "The code graph is being rebuilt.",
};
pub const FILES: Text = Text {
de: "Dateien",
en: "Files",
};
pub const FILTER_FILES: Text = Text {
de: "Dateien filtern …",
en: "Filter files …",
};
pub const LOADING: Text = Text {
de: "Codegraph wird geladen …",
en: "Loading the code graph …",
};
pub const LOAD_FAILED: Text = Text {
de: "Der Codegraph konnte nicht geladen werden.",
en: "The code graph could not be loaded.",
};
pub const EMPTY_TITLE: Text = Text {
de: "Noch kein Codegraph",
en: "No code graph yet",
};
pub const EMPTY_BODY: Text = Text {
de: "Er entsteht mit der nächsten Prüfung dieses Prüfobjekts.",
en: "It is built with this target's next scan.",
};
pub const LAYOUT: Text = Text {
de: "Anordnung wird berechnet",
en: "Computing the layout",
};
pub const CODE_UNITS: Text = Text {
de: "Bausteine",
en: "code units",
};
pub const EDGES: Text = Text {
de: "Beziehungen",
en: "relations",
};
pub const GROUPS: Text = Text {
de: "Gruppen",
en: "groups",
};
pub const ENTRY_POINT: Text = Text {
de: "Einstiegspunkt",
en: "Entry point",
};
pub const FILE: Text = Text {
de: "Datei",
en: "File",
};
pub const LINES: Text = Text {
de: "Zeilen",
en: "lines",
};
pub const CLOSE: Text = Text {
de: "Schließen",
en: "Close",
};
pub const FILE_FAILED: Text = Text {
de: "Die Datei konnte nicht geladen werden.",
en: "The file could not be loaded.",
};
pub const FILE_LOADING: Text = Text {
de: "Datei wird geladen …",
en: "Loading the file …",
};
pub const OVERVIEW_NOTE: Text = Text {
de: "Der Graph ist groß: jeder Kreis ist eine Gruppe eng verbundener Bausteine, jedes Sechseck die übrigen Bausteine eines Ordners. Ein Klick öffnet sie.",
en: "The graph is large: each circle is a group of closely connected code units, each hexagon a folder's other code units. Click one to open it.",
};
/// "Ausschnitt: die ersten 10.000 von 23.456 Beziehungen".
pub fn truncated(shown: usize, total: u64, lang: Lang) -> String {
match lang {
Lang::De => format!(
"Ausschnitt: die ersten {} von {} Beziehungen",
format_count(shown as u64, lang),
format_count(total, lang)
),
Lang::En => format!(
"Excerpt: the first {} of {} relations",
format_count(shown as u64, lang),
format_count(total, lang)
),
}
}
/// "Die 1.200 meistverbundenen von 3.400 Bausteinen dieser Gruppe".
pub fn capped(shown: usize, total: usize, lang: Lang) -> String {
let (shown, total) = (
format_count(shown as u64, lang),
format_count(total as u64, lang),
);
match lang {
Lang::De => {
format!("Die {shown} meistverbundenen von {total} Bausteinen dieser Gruppe")
}
Lang::En => format!("The {shown} most connected of this group's {total} code units"),
}
}
/// A node kind's name, for the legend, the tooltip and the inspector.
pub fn kind(kind: &str) -> Text {
match kind {
"function" => Text {
de: "Funktion",
en: "Function",
},
"method" => Text {
de: "Methode",
en: "Method",
},
"class" => Text {
de: "Klasse",
en: "Class",
},
"struct" => Text {
de: "Struktur",
en: "Struct",
},
"enum" => Text {
de: "Aufzählung",
en: "Enum",
},
"interface" => Text {
de: "Schnittstelle",
en: "Interface",
},
"trait" => Text {
de: "Trait",
en: "Trait",
},
"module" => Text {
de: "Modul",
en: "Module",
},
"file" => Text {
de: "Datei",
en: "File",
},
"community" => Text {
de: "Gruppe",
en: "Group",
},
"folder" => Text {
de: "Ordner",
en: "Folder",
},
_ => Text {
de: "Baustein",
en: "Code unit",
},
}
}
/// An edge kind's name, for the tooltip.
pub fn edge_kind(kind: &str) -> Text {
match kind {
"calls" => Text {
de: "ruft auf",
en: "calls",
},
"imports" => Text {
de: "importiert",
en: "imports",
},
"inherits" => Text {
de: "erbt von",
en: "inherits from",
},
"implements" => Text {
de: "implementiert",
en: "implements",
},
"contains" => Text {
de: "enthält",
en: "contains",
},
"type_ref" => Text {
de: "verwendet Typ",
en: "uses type",
},
_ => Text {
de: "Beziehungen",
en: "relations",
},
}
}
// ── Impact of one finding ──
pub const IMPACT_TITLE: Text = Text {
de: "Auswirkung im Codegraph",
en: "Impact in the code graph",
};
pub const IMPACT_SUBTITLE: Text = Text {
de: "Welche Einstiegspunkte die Stelle des Befunds erreichen und was von ihr aus erreichbar ist.",
en: "Which entry points reach the finding's location and what it reaches in turn.",
};
pub const IMPACT_NONE: Text = Text {
de: "Für diesen Befund gibt es im Codegraph keine Stelle.",
en: "The code graph has no location for this finding.",
};
pub const IMPACT_LOADING: Text = Text {
de: "Auswirkung wird geladen …",
en: "Loading the impact …",
};
pub const REACHED_BY: Text = Text {
de: "Einstiegspunkte erreichen die Stelle",
en: "entry points reach the location",
};
pub const BLAST_RADIUS: Text = Text {
de: "Bausteine von der Stelle aus erreichbar",
en: "code units reachable from the location",
};
pub const ENTRY_POINTS: Text = Text {
de: "Einstiegspunkte",
en: "Entry points",
};
pub const CALL_CHAINS: Text = Text {
de: "Aufrufketten",
en: "Call chains",
};
pub const CALL_CHAINS_HINT: Text = Text {
de: "Vom Einstiegspunkt bis zur Stelle des Befunds.",
en: "From the entry point to the finding's location.",
};
pub const CALLERS: Text = Text {
de: "Direkte Aufrufer",
en: "Direct callers",
};
pub const CALLEES: Text = Text {
de: "Direkt aufgerufen",
en: "Directly called",
};
pub const NONE: Text = Text {
de: "Keine.",
en: "None.",
};
pub const SHOW_IMPACT: Text = Text {
de: "Auswirkung anzeigen",
en: "Show the impact",
};
pub const OPEN_GRAPH: Text = Text {
de: "Im Codegraph öffnen",
en: "Open in the code graph",
};
}
@@ -11,6 +11,16 @@ pub struct GraphData {
pub build: Option<serde_json::Value>,
pub nodes: Vec<serde_json::Value>,
pub edges: Vec<serde_json::Value>,
/// The agent sent only the first of the graph's edges (and the nodes they
/// connect).
#[serde(default)]
pub truncated: bool,
/// Edges in the whole graph.
#[serde(default)]
pub total_edges: u64,
/// Nodes in the whole graph.
#[serde(default)]
pub total_nodes: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
@@ -18,12 +28,6 @@ pub struct ImpactResponse {
pub data: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CommunitiesResponse {
pub data: Vec<serde_json::Value>,
pub total: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct NodesResponse {
pub data: Vec<serde_json::Value>,
@@ -111,32 +115,19 @@ pub async fn fetch_impact(
Ok(body)
}
#[server]
pub async fn fetch_communities(repo_id: String) -> Result<CommunitiesResponse, ServerFnError> {
let resp = super::agent_client::agent_get(&format!("/api/v1/graph/{repo_id}/communities"))
.await?
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
let body: CommunitiesResponse = resp
.json()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
Ok(body)
}
#[server]
pub async fn fetch_file_content(
repo_id: String,
file_path: String,
) -> Result<FileContentResponse, ServerFnError> {
let resp = super::agent_client::agent_get(&format!(
"/api/v1/graph/{repo_id}/file-content?path={file_path}"
))
.await?
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
// The path as a query parameter, encoded: file names can hold spaces,
// `#` or `&`.
let resp = super::agent_client::agent_get(&format!("/api/v1/graph/{repo_id}/file-content"))
.await?
.query(&[("path", file_path.as_str())])
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
let body: FileContentResponse = resp
.json()
.await
@@ -146,13 +137,12 @@ pub async fn fetch_file_content(
#[server]
pub async fn search_nodes(repo_id: String, query: String) -> Result<SearchResponse, ServerFnError> {
let resp = super::agent_client::agent_get(&format!(
"/api/v1/graph/{repo_id}/search?q={query}&limit=50"
))
.await?
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
let resp = super::agent_client::agent_get(&format!("/api/v1/graph/{repo_id}/search"))
.await?
.query(&[("q", query.as_str()), ("limit", "50")])
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
let body: SearchResponse = resp
.json()
.await
@@ -7,11 +7,13 @@ use crate::components::code_snippet::CodeSnippet;
use crate::components::markdown::render_markdown;
use crate::components::page_header::PageHeader;
use crate::components::severity_badge::SeverityBadge;
use crate::i18n::texts::{common, findings as tx};
use crate::i18n::{format_time, use_lang};
use crate::i18n::texts::{common, findings as tx, graph as graph_tx};
use crate::i18n::{format_count, format_time, use_lang};
use crate::infrastructure::evidence::{fetch_catalog_controls, CatalogControl};
use crate::infrastructure::findings::{location, mask_secrets, wire_name};
use crate::infrastructure::graph::fetch_impact;
use crate::pages::findings::status_icon;
use crate::pages::graph_view::impact_has_content;
use compliance_core::models::{FindingStatus, ScanType};
/// What happened to the last save on this page, shown next to what was saved.
@@ -57,6 +59,24 @@ pub fn FindingDetailPage(id: String) -> Element {
.ok()
});
// The finding's place in the code graph, when the graph has its location.
// Impact analyses are stored under the finding's fingerprint.
let impact = use_resource(move || async move {
let (repo_id, fingerprint) = finding
.read()
.as_ref()
.and_then(|f| f.as_ref())
.map(|f| (f.repo_id.clone(), f.fingerprint.clone()))?;
let data = fetch_impact(repo_id, fingerprint.clone())
.await
.ok()?
.data?;
impact_has_content(&data).then(|| {
let reached_by = data["affected_entry_points"].as_array().map_or(0, Vec::len);
(fingerprint, reached_by as u64)
})
});
let snapshot = finding.read().clone();
match snapshot {
@@ -194,6 +214,21 @@ pub fn FindingDetailPage(id: String) -> Element {
}
}
if let Some((fingerprint, reached_by)) = impact.read().clone().flatten() {
div { class: "card",
div { class: "target-card-head",
div { class: "card-header", {graph_tx::TITLE.get(lang)} }
Link {
to: Route::ImpactAnalysisPage { repo_id: f.repo_id.clone(), finding_id: fingerprint },
class: "target-card-link",
{graph_tx::SHOW_IMPACT.get(lang)}
Icon { icon: BsArrowRight, width: 14, height: 14 }
}
}
p { "{format_count(reached_by, lang)} {graph_tx::REACHED_BY.get(lang)}" }
}
}
if let Some(rationale) = &f.triage_rationale {
div { class: "card",
div { class: "card-header", {tx::TRIAGE.get(lang)} }
+370 -344
View File
@@ -1,253 +1,331 @@
//! One target's code graph, drawn: its files, its code units and how they
//! call and use each other. Opened from the code graph card on the target
//! page. A large graph opens as its groups (see [`super::graph_view`]).
use dioxus::prelude::*;
use dioxus_free_icons::icons::bs_icons::*;
use dioxus_free_icons::Icon;
use serde_json::{json, Value};
use super::graph_view::{draw, node_id, GraphView, Group, Grouping};
use crate::app::Route;
use crate::components::code_inspector::CodeInspector;
use crate::components::file_tree::{build_file_tree, FileTree};
use crate::components::page_header::PageHeader;
use crate::components::toast::{ToastType, Toasts};
use crate::infrastructure::graph::{fetch_graph, search_nodes, trigger_graph_build};
use crate::i18n::texts::{compliance::language_name, graph as tx};
use crate::i18n::{format_count, use_lang, Lang};
use crate::infrastructure::graph::{fetch_graph, search_nodes, trigger_graph_build, GraphData};
use crate::infrastructure::onboarding::fetch_target;
/// The node kinds in the legend, in the order shown.
const LEGEND_KINDS: [&str; 6] = ["function", "class", "interface", "enum", "module", "file"];
/// What stands for a group in the legend, outside the whole view.
const LEGEND_GROUPS: [&str; 2] = ["community", "folder"];
/// The texts `graph-viz.js` shows, in `lang`.
fn viz_labels(lang: Lang) -> Value {
let kinds: serde_json::Map<String, Value> = [
"function",
"method",
"class",
"struct",
"enum",
"interface",
"trait",
"module",
"file",
"community",
"folder",
]
.into_iter()
.map(|k| (k.to_string(), tx::kind(k).get(lang).into()))
.collect();
let edges: serde_json::Map<String, Value> = [
"calls",
"imports",
"inherits",
"implements",
"contains",
"type_ref",
]
.into_iter()
.map(|k| (k.to_string(), tx::edge_kind(k).get(lang).into()))
.collect();
json!({
"kinds": kinds,
"edges": edges,
"layout": tx::LAYOUT.get(lang),
"entry": tx::ENTRY_POINT.get(lang),
"file": tx::FILE.get(lang),
})
}
/// What the page's header and notes say about the loaded graph.
#[derive(Debug, Clone, PartialEq)]
struct GraphFacts {
/// Nodes the agent sent, so the ones that can be drawn.
drawable: usize,
/// Code units, relations and groups in the whole graph.
units: u64,
relations: u64,
groups: u64,
/// The languages parsed, by name.
languages: Vec<String>,
/// `(edges sent, edges in the graph)` when the agent sent only part.
truncated: Option<(usize, u64)>,
}
impl GraphFacts {
fn of(data: &GraphData) -> Self {
let build = data.build.as_ref();
let count = |key: &str| build.and_then(|b| b[key].as_u64()).unwrap_or(0);
Self {
drawable: data.nodes.len(),
units: data.total_nodes.max(count("node_count")),
relations: data.total_edges.max(count("edge_count")),
groups: count("community_count"),
languages: build
.and_then(|b| b["languages_parsed"].as_array())
.map(|codes| {
codes
.iter()
.filter_map(Value::as_str)
.map(|code| language_name(code).to_string())
.collect()
})
.unwrap_or_default(),
truncated: data
.truncated
.then_some((data.edges.len(), data.total_edges)),
}
}
}
#[component]
pub fn GraphExplorerPage(repo_id: String) -> Element {
rsx! {
div { class: "back-nav",
button {
class: "btn btn-ghost btn-back",
onclick: move |_| { navigator().go_back(); },
Icon { icon: BsArrowLeft, width: 16, height: 16 }
"Back"
}
}
PageHeader {
title: "Code Knowledge Graph",
description: "Interactive visualization of code structure and relationships",
}
GraphExplorerBody { repo_id: repo_id }
}
}
/// Inline variant without back button and page header — for embedding in other pages.
#[component]
pub fn GraphExplorerInline(repo_id: String) -> Element {
rsx! {
GraphExplorerBody { repo_id: repo_id }
}
}
/// Shared graph explorer body used by both the full page and inline variants.
#[component]
fn GraphExplorerBody(repo_id: String) -> Element {
let lang = use_lang()();
let can_write = crate::components::no_access::use_can_write();
let repo_id_clone = repo_id.clone();
let mut graph_data = use_resource(move || {
let rid = repo_id_clone.clone();
async move {
if rid.is_empty() {
return None;
}
fetch_graph(rid).await.ok()
}
let mut toasts = use_context::<Toasts>();
let rid = repo_id.clone();
let target = use_resource(move || {
let rid = rid.clone();
async move { fetch_target(rid).await.ok() }
});
let rid = repo_id.clone();
let mut graph = use_resource(move || {
let rid = rid.clone();
async move { fetch_graph(rid).await.ok() }
});
// The view chosen by a click; `None` is the one the graph opens with.
let mut view = use_signal(|| Option::<GraphView>::None);
// Nodes to select once the next drawing has its layout.
let mut pending_focus = use_signal(Vec::<String>::new);
let mut building = use_signal(|| false);
let mut toasts = use_context::<Toasts>();
let mut selected_node = use_signal(|| Option::<serde_json::Value>::None);
let mut inspector_open = use_signal(|| false);
let mut selected = use_signal(|| Option::<Value>::None);
let mut search_query = use_signal(String::new);
let mut search_results = use_signal(Vec::<serde_json::Value>::new);
let mut search_results = use_signal(Vec::<Value>::new);
let mut file_filter = use_signal(String::new);
let mut nodes_json = use_signal(String::new);
let mut edges_json = use_signal(String::new);
let mut graph_ready = use_signal(|| false);
let graph_data_read = graph_data.read();
if let Some(Some(data)) = &*graph_data_read {
if !data.data.nodes.is_empty() && !graph_ready() {
let nj = serde_json::to_string(&data.data.nodes).unwrap_or_else(|_| "[]".into());
let ej = serde_json::to_string(&data.data.edges).unwrap_or_else(|_| "[]".into());
nodes_json.set(nj);
edges_json.set(ej);
graph_ready.set(true);
}
}
let (node_count, edge_count, community_count, languages, file_tree_data) =
if let Some(Some(data)) = &*graph_data_read {
let build = data.data.build.clone().unwrap_or_default();
let nc = build
.get("node_count")
.and_then(|n| n.as_u64())
.unwrap_or(0);
let ec = build
.get("edge_count")
.and_then(|n| n.as_u64())
.unwrap_or(0);
let cc = build
.get("community_count")
.and_then(|n| n.as_u64())
.unwrap_or(0);
let langs: Vec<String> = build
.get("languages_parsed")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
let tree = build_file_tree(&data.data.nodes);
(nc, ec, cc, langs, tree)
} else {
(0, 0, 0, Vec::new(), Vec::new())
};
let has_graph_data = matches!(&*graph_data_read, Some(Some(d)) if !d.data.nodes.is_empty());
drop(graph_data_read);
// Each node's group, the view drawn, and what is drawn: recomputed only
// when the graph or the chosen view changes.
let grouping = use_memo(move || {
let graph = graph.read();
Some(Grouping::new(&graph.as_ref()?.as_ref()?.data.nodes))
});
let shown_view = use_memo(move || {
let graph = graph.read();
let count = graph.as_ref()?.as_ref()?.data.nodes.len();
Some(view().unwrap_or_else(|| GraphView::initial(count)))
});
// The header's figures and the file tree, so a render (a keystroke in the
// search box) doesn't copy or walk the graph.
let facts = use_memo(move || Some(GraphFacts::of(&graph.read().as_ref()?.as_ref()?.data)));
let file_tree = use_memo(move || {
let graph = graph.read();
graph
.as_ref()
.and_then(|g| g.as_ref())
.map(|g| build_file_tree(&g.data.nodes))
.unwrap_or_default()
});
let drawn = use_memo(move || {
let graph = graph.read();
let d = &graph.as_ref()?.as_ref()?.data;
Some(draw(
&d.nodes,
&d.edges,
grouping.read().as_ref()?,
shown_view.read().as_ref()?,
))
});
use_effect(move || {
let ready = graph_ready();
if !ready {
let drawn = drawn.read();
let Some(drawn) = drawn.as_ref().filter(|d| !d.nodes.is_empty()) else {
return;
}
let nj = nodes_json();
let ej = edges_json();
if nj.is_empty() {
return;
}
spawn(async move {
let js = format!(
r#"
window.__onNodeClick = function(nodeJson) {{
var el = document.getElementById('graph-node-click-data');
if (el) {{
el.value = nodeJson;
el.dispatchEvent(new Event('input', {{ bubbles: true }}));
}}
}};
setTimeout(function() {{
if (window.__loadGraph) {{
window.__loadGraph({nj}, {ej});
}}
}}, 300);
"#
);
let _ = document::eval(&js);
});
};
let nodes = serde_json::to_string(&drawn.nodes).unwrap_or_else(|_| "[]".into());
let edges = serde_json::to_string(&drawn.edges).unwrap_or_else(|_| "[]".into());
let focus = serde_json::to_string(&*pending_focus.peek()).unwrap_or_else(|_| "[]".into());
let labels = viz_labels(lang);
// The canvas is in the DOM once this render is committed; the timeout
// lets vis-network measure it.
let js = format!(
r#"
window.__onNodeClick = function (nodeJson) {{
var el = document.getElementById('graph-node-click-data');
if (el) {{
el.value = nodeJson;
el.dispatchEvent(new Event('input', {{ bubbles: true }}));
}}
}};
setTimeout(function () {{
if (window.__loadGraph) window.__loadGraph({nodes}, {edges}, {labels}, {focus});
}}, 50);
"#
);
let _ = document::eval(&js);
});
let sel = selected_node();
let sel_file = sel
// Show the nodes named `names`: open their group first when its members
// aren't drawn. The group is the first name's.
let mut reveal = move |names: Vec<String>| {
let Some(group) = names
.first()
.and_then(|first| grouping.read().as_ref()?.of(first).cloned())
else {
return;
};
if shown_view().is_some_and(|v| v.shows_members_of(&group)) {
let names = serde_json::to_string(&names).unwrap_or_else(|_| "[]".into());
let _ = document::eval(&format!(
"window.__highlightNodes && window.__highlightNodes({names});"
));
} else {
pending_focus.set(names);
view.set(Some(GraphView::Group(group)));
}
};
let target_name = target
.read()
.as_ref()
.and_then(|n| n.get("file_path").and_then(|v| v.as_str()))
.unwrap_or("")
.to_string();
let sel_name = sel
.as_ref()
.and_then(|n| n.get("name").and_then(|v| v.as_str()))
.unwrap_or("")
.to_string();
let sel_kind = sel
.as_ref()
.and_then(|n| n.get("kind").and_then(|v| v.as_str()))
.unwrap_or("")
.to_string();
let sel_start = sel
.as_ref()
.and_then(|n| n.get("start_line").and_then(|v| v.as_u64()))
.unwrap_or(0) as u32;
let sel_end = sel
.as_ref()
.and_then(|n| n.get("end_line").and_then(|v| v.as_u64()))
.unwrap_or(0) as u32;
.and_then(|t| t.as_ref()?.data["name"].as_str().map(String::from));
let Some(facts) = facts() else {
return rsx! {
GraphBack { repo_id: repo_id.clone() }
match graph.read().as_ref() {
Some(None) => rsx! { div { class: "card", p { {tx::LOAD_FAILED.get(lang)} } } },
_ => rsx! { div { class: "loading", {tx::LOADING.get(lang)} } },
}
};
};
let opens_as_overview = GraphView::initial(facts.drawable) == GraphView::Overview;
let current = shown_view().unwrap_or(GraphView::All);
let units = format_count(facts.units, lang);
let relations = format_count(facts.relations, lang);
let groups = format_count(facts.groups, lang);
let capped = drawn.read().as_ref().and_then(|d| d.capped);
let sel = selected();
let layout_class = if sel.is_some() {
"graph-explorer-layout inspector-open"
} else {
"graph-explorer-layout"
};
rsx! {
if repo_id.is_empty() {
div { class: "card",
p { "Select a repository to view its code graph." }
GraphBack { repo_id: repo_id.clone() }
header { class: "target-head",
div { class: "target-head-text",
h2 { {tx::TITLE.get(lang)} }
p { class: "target-head-meta",
if let Some(name) = target_name {
span { "{name}" }
}
span { "{units} {tx::CODE_UNITS.get(lang)}" }
span { "{relations} {tx::EDGES.get(lang)}" }
span { "{groups} {tx::GROUPS.get(lang)}" }
if !facts.languages.is_empty() {
span { {facts.languages.join(", ")} }
}
}
}
} else {
// Toolbar
div { class: "graph-toolbar",
if can_write {
if can_write {
div { class: "target-head-actions",
button {
class: "btn btn-primary",
class: "btn btn-secondary",
disabled: building(),
onclick: {
let rid = repo_id.clone();
move |_| {
let rid = rid.clone();
building.set(true);
graph_ready.set(false);
nodes_json.set(String::new());
edges_json.set(String::new());
spawn(async move {
match trigger_graph_build(rid).await {
Ok(_) => toasts.push(ToastType::Success, "Graph build triggered"),
Ok(()) => toasts.push(ToastType::Success, tx::BUILD_STARTED.get(lang)),
Err(e) => toasts.push(ToastType::Error, e.to_string()),
}
building.set(false);
graph_data.restart();
view.set(None);
graph.restart();
});
}
},
if building() { "Building..." } else { "Build Graph" }
Icon { icon: BsArrowRepeat, width: 14, height: 14 }
if building() { {tx::BUILDING.get(lang)} } else { {tx::REBUILD.get(lang)} }
}
}
}
}
if facts.drawable == 0 {
div { class: "card graph-empty-state",
h3 { {tx::EMPTY_TITLE.get(lang)} }
p { {tx::EMPTY_BODY.get(lang)} }
}
} else {
div { class: "graph-toolbar",
if opens_as_overview && current != GraphView::Overview {
button {
class: "btn btn-secondary btn-sm",
onclick: move |_| {
pending_focus.set(Vec::new());
view.set(Some(GraphView::Overview));
},
Icon { icon: BsArrowLeft, width: 14, height: 14 }
{tx::OVERVIEW.get(lang)}
}
}
div { class: "graph-search-bar",
input {
r#type: "text",
placeholder: "Search nodes...",
r#type: "search",
placeholder: tx::SEARCH.get(lang),
"aria-label": tx::SEARCH.get(lang),
value: "{search_query}",
oninput: {
let rid = repo_id.clone();
move |e: FormEvent| {
let val = e.value();
search_query.set(val.clone());
if val.len() >= 2 {
let rid = rid.clone();
spawn(async move {
if let Ok(resp) = search_nodes(rid, val).await {
let q = e.value();
search_query.set(q.clone());
if q.chars().count() < 2 {
search_results.set(Vec::new());
return;
}
let rid = rid.clone();
spawn(async move {
// A stale answer for an older query is dropped.
if let Ok(resp) = search_nodes(rid, q.clone()).await {
if search_query() == q {
search_results.set(resp.data);
}
});
} else {
search_results.set(Vec::new());
}
}
},
onkeypress: {
let rid = repo_id.clone();
move |e: KeyboardEvent| {
if e.key() == Key::Enter {
search_results.set(Vec::new());
let q = search_query();
let rid = rid.clone();
if !q.is_empty() {
spawn(async move {
match search_nodes(rid, q).await {
Ok(resp) => {
let names: Vec<String> = resp.data.iter()
.filter_map(|n| n.get("qualified_name").and_then(|v| v.as_str()).map(String::from))
.collect();
let names_json = serde_json::to_string(&names).unwrap_or_else(|_| "[]".into());
let js = format!("if (window.__highlightNodes) {{ window.__highlightNodes({names_json}); }}");
let _ = document::eval(&js);
},
Err(e) => {
toasts.push(ToastType::Error, e.to_string());
}
}
});
} else {
spawn(async move {
let _ = document::eval("if (window.__clearGraphSelection) { window.__clearGraphSelection(); }");
});
}
}
});
}
},
}
@@ -255,29 +333,21 @@ fn GraphExplorerBody(repo_id: String) -> Element {
div { class: "search-suggestions",
for node in search_results() {
{
let name = node.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string();
let kind = node.get("kind").and_then(|v| v.as_str()).unwrap_or("").to_string();
let file_path = node.get("file_path").and_then(|v| v.as_str()).unwrap_or("").to_string();
let node_clone = node.clone();
let qname = node.get("qualified_name").and_then(|v| v.as_str()).unwrap_or("").to_string();
let kind = node["kind"].as_str().unwrap_or_default().to_string();
let name = node["name"].as_str().unwrap_or_default().to_string();
let path = node["file_path"].as_str().unwrap_or_default().to_string();
rsx! {
div {
button {
class: "search-suggestion-item",
r#type: "button",
onclick: move |_| {
let nc = node_clone.clone();
let qn = qname.clone();
selected_node.set(Some(nc));
inspector_open.set(true);
reveal(vec![node_id(&node).to_string()]);
selected.set(Some(node.clone()));
search_results.set(Vec::new());
spawn(async move {
let names_json = serde_json::to_string(&vec![&qn]).unwrap_or_else(|_| "[]".into());
let js = format!("if (window.__highlightNodes) {{ window.__highlightNodes({names_json}); }}");
let _ = document::eval(&js);
});
},
span { class: "search-suggestion-name", "{name}" }
span { class: "search-suggestion-kind", "{kind}" }
span { class: "search-suggestion-path", "{file_path}" }
span { class: "search-suggestion-kind", {tx::kind(&kind).get(lang)} }
span { class: "search-suggestion-path", "{path}" }
}
}
}
@@ -285,177 +355,133 @@ fn GraphExplorerBody(repo_id: String) -> Element {
}
}
}
button {
class: "btn-sm",
class: "btn btn-secondary btn-sm",
onclick: move |_| {
spawn(async move {
let _ = document::eval("if (window.__fitGraph) { window.__fitGraph(); }");
});
let _ = document::eval("window.__fitGraph && window.__fitGraph();");
},
"Fit View"
Icon { icon: BsArrowsFullscreen, width: 14, height: 14 }
{tx::FIT.get(lang)}
}
}
// Hidden input for JS → Rust node click communication
if current == GraphView::Overview {
p { class: "graph-note", {tx::OVERVIEW_NOTE.get(lang)} }
}
if let Some((shown, total)) = capped {
p { class: "graph-note", {tx::capped(shown, total, lang)} }
}
if let Some((shown, total)) = facts.truncated {
p { class: "graph-note", {tx::truncated(shown, total, lang)} }
}
// graph-viz.js reports a clicked node here.
input {
id: "graph-node-click-data",
r#type: "hidden",
value: "",
oninput: move |e| {
let val = e.value();
if !val.is_empty() {
if let Ok(node) = serde_json::from_str::<serde_json::Value>(&val) {
selected_node.set(Some(node));
inspector_open.set(true);
let Ok(node) = serde_json::from_str::<Value>(&e.value()) else { return };
// A group's node opens the group; any other node is shown
// in the inspector.
match serde_json::from_value::<Group>(node["group"].clone()) {
Ok(group) => {
pending_focus.set(Vec::new());
view.set(Some(GraphView::Group(group)));
}
Err(_) => selected.set(Some(node)),
}
},
}
// 3-panel layout: file-tree | [code-inspector] | graph-canvas
div { class: if inspector_open() { "graph-explorer-layout inspector-open" } else { "graph-explorer-layout" },
// Left: File Tree
div { class: layout_class,
div { class: "file-tree-panel",
div { class: "file-tree-header",
h4 { "Files" }
}
div { class: "file-tree-header", h4 { {tx::FILES.get(lang)} } }
div { class: "file-tree-search",
input {
r#type: "text",
placeholder: "Filter files...",
r#type: "search",
placeholder: tx::FILTER_FILES.get(lang),
"aria-label": tx::FILTER_FILES.get(lang),
value: "{file_filter}",
oninput: move |e| file_filter.set(e.value()),
}
}
div { class: "file-tree-content",
if file_tree_data.is_empty() {
div { class: "file-tree-empty", "No files. Build the graph first." }
} else {
FileTree {
tree: file_tree_data,
filter: file_filter(),
on_file_click: move |path: String| {
// Open code inspector for this file
let file_node = serde_json::json!({
"file_path": &path,
"name": path.rsplit('/').next().unwrap_or(&path),
"kind": "file",
"start_line": 1,
"end_line": 0,
});
selected_node.set(Some(file_node));
inspector_open.set(true);
// Also highlight in graph
spawn(async move {
let js = format!(
"if (window.__highlightFileNodes) {{ window.__highlightFileNodes('{path}'); }}"
);
let _ = document::eval(&js);
});
},
}
FileTree {
tree: file_tree(),
filter: file_filter(),
on_file_click: move |path: String| {
let in_file = graph
.read()
.as_ref()
.and_then(|g| g.as_ref())
.map(|g| {
g.data
.nodes
.iter()
.filter(|n| n["file_path"] == path.as_str())
.map(|n| node_id(n).to_string())
.collect()
})
.unwrap_or_default();
reveal(in_file);
selected.set(Some(json!({
"file_path": &path,
"name": path.rsplit('/').next().unwrap_or(&path),
"kind": "file",
})));
},
}
}
}
// Left-center: Code Inspector (between file tree and graph)
if inspector_open() && selected_node().is_some() {
if let Some(node) = sel {
CodeInspector {
repo_id: repo_id.clone(),
file_path: sel_file,
node_name: sel_name,
node_kind: sel_kind,
start_line: sel_start,
end_line: sel_end,
on_close: move |_| {
inspector_open.set(false);
selected_node.set(None);
},
file_path: node["file_path"].as_str().unwrap_or_default().to_string(),
node_name: node["name"].as_str().unwrap_or_default().to_string(),
node_kind: node["kind"].as_str().unwrap_or_default().to_string(),
start_line: node["start_line"].as_u64().unwrap_or(0) as u32,
end_line: node["end_line"].as_u64().unwrap_or(0) as u32,
on_close: move |_| selected.set(None),
}
}
// Right: Graph Canvas
div { class: "graph-canvas-panel",
if has_graph_data {
div {
id: "graph-canvas",
class: "graph-canvas",
}
// Stabilization overlay
div {
id: "graph-stabilization-overlay",
class: "graph-stab-overlay",
div { class: "graph-stab-content",
// Orbital rings
div { class: "graph-stab-rings",
div { class: "graph-stab-ring graph-stab-ring-1" }
div { class: "graph-stab-ring graph-stab-ring-2" }
div { class: "graph-stab-ring graph-stab-ring-3" }
div { class: "graph-stab-core" }
}
div { class: "graph-stab-text",
div { class: "graph-stab-title", "Rendering Graph" }
div { class: "graph-stab-subtitle",
id: "graph-stab-node-info",
"{node_count} nodes \u{00B7} {edge_count} edges"
}
}
// Progress bar
div { class: "graph-stab-progress",
div {
class: "graph-stab-progress-fill",
id: "graph-stab-progress-fill",
}
}
div {
class: "graph-stab-pct",
id: "graph-stab-pct",
"Initializing\u{2026}"
}
div { id: "graph-canvas", class: "graph-canvas" }
div { id: "graph-stabilization-overlay", class: "graph-stab-overlay",
div { class: "graph-stab-content",
div { class: "graph-stab-progress",
div { class: "graph-stab-progress-fill", id: "graph-stab-progress-fill" }
}
}
} else if node_count > 0 {
// Data exists but nodes array was empty (shouldn't happen)
div { class: "loading", "Loading graph visualization..." }
} else if (*graph_data.read()).is_none() {
div { class: "loading", "Loading graph data..." }
} else {
div { class: "graph-empty-state",
div { class: "graph-empty-icon", "\u{29BB}" }
h3 { "No Graph Data" }
p { "Click \"Build Graph\" to analyze the repository's code structure." }
div { class: "graph-stab-pct", id: "graph-stab-pct", {tx::LAYOUT.get(lang)} }
}
}
// Stats bar
if node_count > 0 {
div { class: "graph-stats-bar",
span { class: "graph-stat",
span { class: "graph-stat-value", "{node_count}" }
span { class: "graph-stat-label", " nodes" }
}
span { class: "graph-stat-divider", "|" }
span { class: "graph-stat",
span { class: "graph-stat-value", "{edge_count}" }
span { class: "graph-stat-label", " edges" }
}
span { class: "graph-stat-divider", "|" }
span { class: "graph-stat",
span { class: "graph-stat-value", "{community_count}" }
span { class: "graph-stat-label", " communities" }
}
if !languages.is_empty() {
span { class: "graph-stat-divider", "|" }
span { class: "graph-stat",
span { class: "graph-stat-label", "{languages.join(\", \")}" }
}
ul { class: "graph-legend",
for kind in LEGEND_KINDS {
li { span { class: "graph-legend-dot graph-kind-{kind}" } {tx::kind(kind).get(lang)} }
}
li { span { class: "graph-legend-dot graph-legend-entry" } {tx::ENTRY_POINT.get(lang)} }
if current != GraphView::All {
for kind in LEGEND_GROUPS {
li { span { class: "graph-legend-dot graph-kind-{kind}" } {tx::kind(kind).get(lang)} }
}
}
}
}
}
}
}
}
/// Back to the target the graph belongs to.
#[component]
fn GraphBack(repo_id: String) -> Element {
let lang = use_lang()();
rsx! {
div { class: "back-nav",
Link { to: Route::TargetPage { id: repo_id }, class: "btn btn-ghost btn-back",
Icon { icon: BsArrowLeft, width: 16, height: 16 }
{tx::BACK.get(lang)}
}
}
}
@@ -1,94 +0,0 @@
use dioxus::prelude::*;
use crate::app::Route;
use crate::components::page_header::PageHeader;
use crate::infrastructure::onboarding::fetch_targets;
#[component]
pub fn GraphIndexPage() -> Element {
let repos = use_resource(|| async { fetch_targets().await.ok() });
rsx! {
PageHeader {
title: "Code Knowledge Graph",
description: "Select a repository to explore its code graph",
}
match &*repos.read() {
Some(Some(data)) => {
let repo_list = &data.data;
if repo_list.is_empty() {
rsx! {
div { class: "card",
p { "No repositories found. Add a repository first." }
}
}
} else {
rsx! {
div { class: "graph-index-grid",
for repo in repo_list {
{
let repo_id = repo.get("_id").and_then(|o| o.get("$oid")).and_then(|s| s.as_str()).unwrap_or_default().to_string();
let name = repo.get("name").and_then(|n| n.as_str()).unwrap_or_default().to_string();
let url = repo
.get("artifacts")
.and_then(|a| a.as_array())
.and_then(|arr| {
arr.iter().find(|a| {
a.get("kind").and_then(|k| k.as_str()) == Some("git_repo")
})
})
.and_then(|a| a.get("source_ref"))
.and_then(|s| s.as_str())
.unwrap_or_default()
.to_string();
let branch = repo
.get("artifacts")
.and_then(|a| a.as_array())
.and_then(|arr| {
arr.iter().find_map(|a| {
a.get("git")
.and_then(|g| g.get("default_branch"))
.and_then(|b| b.as_str())
})
})
.unwrap_or("main")
.to_string();
let findings = repo.get("findings_count").and_then(|n| n.as_u64()).unwrap_or(0);
let findings_label = if findings != 1 { format!("{findings} findings") } else { "1 finding".to_string() };
rsx! {
Link {
to: Route::GraphExplorerPage { repo_id },
class: "graph-repo-card",
div { class: "graph-repo-card-header",
div { class: "graph-repo-card-icon", "\u{29BB}" }
h3 { class: "graph-repo-card-name", "{name}" }
}
if !url.is_empty() {
p { class: "graph-repo-card-url", "{url}" }
}
div { class: "graph-repo-card-meta",
span { class: "graph-repo-card-tag",
"\u{E0A0} {branch}"
}
span { class: "graph-repo-card-tag graph-repo-card-tag-findings",
"{findings_label}"
}
}
}
}
}
}
}
}
}
},
Some(None) => rsx! {
div { class: "card", p { "Failed to load repositories." } }
},
None => rsx! {
div { class: "loading", "Loading repositories..." }
},
}
}
}
@@ -0,0 +1,479 @@
//! What the code graph explorer draws.
//!
//! A force-directed layout stays readable up to about a thousand nodes, and a
//! repository's graph can have tens of thousands. So a small graph is drawn
//! whole. A larger one is first drawn as one node per group, and a click opens
//! one group with its members, while its links to other groups stay visible as
//! those groups' nodes. A group is a community the graph build computed
//! (closely connected code units); communities too small to be worth a node
//! of their own are pooled by folder.
//!
//! The functions here are pure and run in the browser's WASM, not in
//! JavaScript; `graph-viz.js` only draws what they return.
use std::collections::{HashMap, HashSet};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
/// The most code units drawn at once.
pub const VIEW_NODE_LIMIT: usize = 1_200;
/// Communities with fewer members are pooled by folder: the build makes many
/// of two to ten (a file and its few functions), which would crowd the
/// overview. On this repository's agent (4,356 nodes) that is 839
/// communities, but about 150 groups.
pub const MIN_COMMUNITY: usize = 10;
/// A group of nodes drawn as one node until it is opened.
///
/// Serialized into the group's drawn node, so a click on it names the group.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(tag = "by", content = "key", rename_all = "snake_case")]
pub enum Group {
/// A community of the graph build.
Community(u32),
/// The nodes of one folder that are in no community of their own size.
Folder(String),
}
impl Group {
/// The group's node id in the drawing.
fn id(&self) -> String {
match self {
Self::Community(id) => format!("group:community:{id}"),
Self::Folder(dir) => format!("group:folder:{dir}"),
}
}
/// The kind its node is drawn as.
fn kind(&self) -> &'static str {
match self {
Self::Community(_) => "community",
Self::Folder(_) => "folder",
}
}
}
/// Which part of the graph is drawn.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GraphView {
/// Every node: the graph is small enough.
All,
/// One node per group.
Overview,
/// One group's members and the groups linked to them.
Group(Group),
}
impl GraphView {
/// The view a graph with `node_count` nodes opens with.
pub fn initial(node_count: usize) -> Self {
if node_count <= VIEW_NODE_LIMIT {
Self::All
} else {
Self::Overview
}
}
/// Whether `group`'s members are drawn as themselves in this view.
pub fn shows_members_of(&self, group: &Group) -> bool {
match self {
Self::All => true,
Self::Overview => false,
Self::Group(shown) => shown == group,
}
}
}
/// The group of every node, by `qualified_name`.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Grouping(HashMap<String, Group>);
impl Grouping {
/// Groups `nodes`: by community when it has at least [`MIN_COMMUNITY`]
/// members, else by folder.
pub fn new(nodes: &[Value]) -> Self {
let mut sizes: HashMap<u32, usize> = HashMap::new();
for id in nodes.iter().filter_map(community) {
*sizes.entry(id).or_default() += 1;
}
Self(
nodes
.iter()
.map(|node| {
let group = match community(node) {
Some(id) if sizes[&id] >= MIN_COMMUNITY => Group::Community(id),
_ => Group::Folder(folder(node).to_string()),
};
(node_id(node).to_string(), group)
})
.collect(),
)
}
/// The group of the node named `id`, if the graph has it.
pub fn of(&self, id: &str) -> Option<&Group> {
self.0.get(id)
}
}
/// The nodes and edges to draw, in the JSON shape `graph-viz.js` reads.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Drawn {
pub nodes: Vec<Value>,
pub edges: Vec<Value>,
/// When the opened group has more members than [`VIEW_NODE_LIMIT`]:
/// `(shown, total)`.
pub capped: Option<(usize, usize)>,
}
/// A node's `qualified_name`, its id in the drawing.
pub fn node_id(node: &Value) -> &str {
node["qualified_name"].as_str().unwrap_or_default()
}
/// A node's community, if the build put it in one.
fn community(node: &Value) -> Option<u32> {
node["community_id"]
.as_u64()
.and_then(|id| u32::try_from(id).ok())
}
/// The folder of a node's file; empty at the repository's root.
fn folder(node: &Value) -> &str {
let path = node["file_path"].as_str().unwrap_or_default();
path.rsplit_once('/').map_or("", |(dir, _)| dir)
}
/// What to draw of `nodes` and `edges` in `view`, with `grouping` made from
/// the same nodes.
///
/// Linear in the number of nodes and edges. Edges that end in a group drawn
/// as one node become one edge per pair of ends, carrying how many it stands
/// for in `count`.
pub fn draw(nodes: &[Value], edges: &[Value], grouping: &Grouping, view: &GraphView) -> Drawn {
let opened = match view {
GraphView::All => {
return Drawn {
nodes: nodes.to_vec(),
edges: edges.to_vec(),
capped: None,
}
}
GraphView::Overview => None,
GraphView::Group(group) => Some(group),
};
// The opened group's members, the most connected first when there are
// more than the limit.
let mut members: Vec<&Value> = nodes
.iter()
.filter(|n| opened.is_some() && grouping.of(node_id(n)) == opened)
.collect();
let member_total = members.len();
if member_total > VIEW_NODE_LIMIT {
let mut degree: HashMap<&str, usize> = HashMap::with_capacity(member_total);
for end in edges.iter().flat_map(|e| [&e["source"], &e["target"]]) {
if let Some(id) = end.as_str() {
*degree.entry(id).or_default() += 1;
}
}
// Ties broken by name so the same graph always shows the same members.
members.sort_by(|a, b| {
let (da, db) = (degree.get(node_id(a)), degree.get(node_id(b)));
db.cmp(&da).then_with(|| node_id(a).cmp(node_id(b)))
});
members.truncate(VIEW_NODE_LIMIT);
}
let shown: HashSet<&str> = members.iter().map(|n| node_id(n)).collect();
// Where an edge end is drawn: the member itself, or its group's node.
// `None` drops the edge: a member left out by the cap, or a name the
// graph has no node for.
let endpoint = |id: &str| -> Option<String> {
let group = grouping.of(id)?;
if opened == Some(group) {
shown.contains(id).then(|| id.to_string())
} else {
Some(group.id())
}
};
let mut drawn_edges = Vec::new();
let mut bundled: HashMap<(String, String), usize> = HashMap::new();
for edge in edges {
let (Some(source), Some(target)) = (
edge["source"].as_str().and_then(endpoint),
edge["target"].as_str().and_then(endpoint),
) else {
continue;
};
let (source_shown, target_shown) = (
shown.contains(source.as_str()),
shown.contains(target.as_str()),
);
if source_shown && target_shown {
drawn_edges.push(edge.clone());
} else if source != target && (opened.is_none() || source_shown || target_shown) {
// With a group opened, only edges that touch one of its members.
*bundled.entry((source, target)).or_default() += 1;
}
}
// With a group opened, only the groups linked to it are drawn.
let linked: HashSet<&str> = bundled
.keys()
.flat_map(|(s, t)| [s.as_str(), t.as_str()])
.collect();
// Each other group with its size and the folder most of its members are
// in, as its label.
let mut stats: HashMap<&Group, (usize, HashMap<&str, usize>)> = HashMap::new();
for node in nodes {
let Some(group) = grouping.of(node_id(node)) else {
continue;
};
if opened == Some(group) {
continue;
}
let (size, folders) = stats.entry(group).or_default();
*size += 1;
*folders.entry(folder(node)).or_default() += 1;
}
let mut groups: Vec<(&Group, usize, &str)> = stats
.into_iter()
.map(|(group, (size, folders))| {
let label = match group {
Group::Folder(dir) => dir.as_str(),
// The most common folder, the first by name on a tie.
Group::Community(_) => folders
.into_iter()
.max_by(|(fa, ca), (fb, cb)| ca.cmp(cb).then_with(|| fb.cmp(fa)))
.map_or("", |(dir, _)| dir),
};
(group, size, label)
})
.filter(|(group, _, _)| opened.is_none() || linked.contains(group.id().as_str()))
.collect();
groups.sort_by(|a, b| a.0.cmp(b.0));
drawn_edges.extend(bundled.into_iter().map(|((source, target), count)| {
json!({ "source": source, "target": target, "kind": "bundle", "count": count })
}));
let mut drawn_nodes: Vec<Value> = members.into_iter().cloned().collect();
drawn_nodes.extend(groups.into_iter().map(|(group, size, label)| {
json!({
"qualified_name": group.id(),
"name": if label.is_empty() { "/" } else { label },
"kind": group.kind(),
"group": group,
"member_count": size,
"file_path": "",
})
}));
Drawn {
nodes: drawn_nodes,
edges: drawn_edges,
capped: (member_total > VIEW_NODE_LIMIT).then_some((VIEW_NODE_LIMIT, member_total)),
}
}
/// Whether a stored impact analysis has anything to show: the analysis is
/// stored for every finding with a file, also when the graph has no node at
/// the finding's location.
pub fn impact_has_content(impact: &Value) -> bool {
let non_empty = |key: &str| impact[key].as_array().is_some_and(|a| !a.is_empty());
impact["blast_radius"].as_u64().unwrap_or(0) > 0
|| [
"affected_entry_points",
"call_chains",
"direct_callers",
"direct_callees",
]
.into_iter()
.any(non_empty)
}
#[cfg(test)]
mod tests {
use super::*;
fn node(name: &str, community: Option<u32>, file: &str) -> Value {
json!({ "qualified_name": name, "name": name, "kind": "function",
"community_id": community, "file_path": file })
}
fn edge(source: &str, target: &str) -> Value {
json!({ "source": source, "target": target, "kind": "calls" })
}
fn ids(values: &[Value]) -> Vec<&str> {
values.iter().map(node_id).collect()
}
/// `(source, target, count)` of the bundled edges, sorted.
fn bundles(drawn: &Drawn) -> Vec<(String, String, u64)> {
let mut bundles: Vec<_> = drawn
.edges
.iter()
.filter(|e| e["kind"] == "bundle")
.map(|e| {
(
e["source"].as_str().unwrap().to_string(),
e["target"].as_str().unwrap().to_string(),
e["count"].as_u64().unwrap(),
)
})
.collect();
bundles.sort();
bundles
}
/// Community 0 with `MIN_COMMUNITY` members in src/net, community 1 with
/// two members in src/ui (pooled), and a node in no community at the root.
fn sample() -> (Vec<Value>, Vec<Value>) {
let mut nodes: Vec<Value> = (0..MIN_COMMUNITY)
.map(|i| node(&format!("a{i}"), Some(0), "src/net/a.c"))
.collect();
nodes.push(node("b0", Some(1), "src/ui/b.c"));
nodes.push(node("b1", Some(1), "src/ui/c.c"));
nodes.push(node("x", None, "main.c"));
let edges = vec![
edge("a0", "b0"),
edge("a1", "b0"),
edge("a0", "a1"),
edge("x", "a0"),
];
(nodes, edges)
}
#[test]
fn a_small_graph_opens_whole_and_a_large_one_as_the_overview() {
assert_eq!(GraphView::initial(VIEW_NODE_LIMIT), GraphView::All);
assert_eq!(GraphView::initial(VIEW_NODE_LIMIT + 1), GraphView::Overview);
}
#[test]
fn small_communities_and_nodes_in_none_are_pooled_by_folder() {
let (nodes, _) = sample();
let grouping = Grouping::new(&nodes);
assert_eq!(grouping.of("a0"), Some(&Group::Community(0)));
assert_eq!(grouping.of("b1"), Some(&Group::Folder("src/ui".into())));
assert_eq!(grouping.of("x"), Some(&Group::Folder(String::new())));
assert_eq!(grouping.of("missing"), None);
}
#[test]
fn the_overview_has_one_node_per_group_and_bundled_edges() {
let (nodes, edges) = sample();
let drawn = draw(&nodes, &edges, &Grouping::new(&nodes), &GraphView::Overview);
assert_eq!(
ids(&drawn.nodes),
["group:community:0", "group:folder:", "group:folder:src/ui"]
);
assert_eq!(drawn.nodes[0]["name"], "src/net");
assert_eq!(drawn.nodes[0]["member_count"], MIN_COMMUNITY);
assert_eq!(drawn.nodes[0]["kind"], "community");
// The root folder is named "/".
assert_eq!(drawn.nodes[1]["name"], "/");
assert_eq!(drawn.nodes[2]["kind"], "folder");
// A click on a group's node names the group.
let clicked: Group = serde_json::from_value(drawn.nodes[2]["group"].clone()).unwrap();
assert_eq!(clicked, Group::Folder("src/ui".into()));
// The edge inside community 0 is not drawn in the overview.
assert_eq!(
bundles(&drawn),
[
("group:community:0".into(), "group:folder:src/ui".into(), 2),
("group:folder:".into(), "group:community:0".into(), 1),
]
);
assert_eq!(drawn.capped, None);
}
#[test]
fn an_opened_group_shows_its_members_and_only_the_groups_linked_to_it() {
let (mut nodes, mut edges) = sample();
// Another community with no link to the folder src/ui.
nodes.extend((0..MIN_COMMUNITY).map(|i| node(&format!("c{i}"), Some(2), "lib/c.c")));
edges.push(edge("c0", "a0"));
let ui = Group::Folder("src/ui".into());
let drawn = draw(
&nodes,
&edges,
&Grouping::new(&nodes),
&GraphView::Group(ui),
);
assert_eq!(ids(&drawn.nodes), ["b0", "b1", "group:community:0"]);
assert_eq!(
bundles(&drawn),
[("group:community:0".into(), "b0".into(), 2)]
);
}
#[test]
fn edges_between_members_are_drawn_as_they_are() {
let (nodes, edges) = sample();
let drawn = draw(
&nodes,
&edges,
&Grouping::new(&nodes),
&GraphView::Group(Group::Community(0)),
);
assert!(drawn.edges.contains(&edges[2]));
assert_eq!(drawn.nodes.len(), MIN_COMMUNITY + 2);
}
#[test]
fn a_group_above_the_limit_keeps_its_most_connected_members() {
let mut nodes: Vec<Value> = (0..VIEW_NODE_LIMIT + 10)
.map(|i| node(&format!("n{i:05}"), Some(3), "src/big.c"))
.collect();
nodes.push(node("hub", Some(3), "src/big.c"));
let edges: Vec<Value> = (0..20).map(|i| edge("hub", &format!("n{i:05}"))).collect();
let drawn = draw(
&nodes,
&edges,
&Grouping::new(&nodes),
&GraphView::Group(Group::Community(3)),
);
assert_eq!(drawn.nodes.len(), VIEW_NODE_LIMIT);
assert_eq!(node_id(&drawn.nodes[0]), "hub");
assert_eq!(drawn.capped, Some((VIEW_NODE_LIMIT, VIEW_NODE_LIMIT + 11)));
// Only edges between drawn members remain.
assert!(drawn.edges.iter().all(|e| e["kind"] == "calls"));
}
#[test]
fn the_whole_view_draws_the_graph_as_it_is() {
let (nodes, edges) = sample();
let community = Group::Community(0);
let drawn = draw(&nodes, &edges, &Grouping::new(&nodes), &GraphView::All);
assert_eq!(drawn.nodes, nodes);
assert_eq!(drawn.edges, edges);
assert!(GraphView::All.shows_members_of(&community));
assert!(!GraphView::Overview.shows_members_of(&community));
assert!(GraphView::Group(community.clone()).shows_members_of(&community));
}
#[test]
fn an_impact_without_a_location_in_the_graph_has_nothing_to_show() {
let empty = json!({ "blast_radius": 0, "affected_entry_points": [],
"call_chains": [], "direct_callers": [], "direct_callees": [] });
assert!(!impact_has_content(&empty));
assert!(impact_has_content(&json!({ "blast_radius": 3 })));
assert!(impact_has_content(&json!({ "direct_callers": ["main"] })));
}
}
+121 -84
View File
@@ -1,107 +1,144 @@
//! One finding's place in the code graph: the entry points that reach it,
//! the call chains from them, and what it reaches in turn. Opened from the
//! finding's page when the graph has its location.
use dioxus::prelude::*;
use dioxus_free_icons::icons::bs_icons::*;
use dioxus_free_icons::Icon;
use serde_json::Value;
use crate::components::page_header::PageHeader;
use super::graph_view::impact_has_content;
use crate::app::Route;
use crate::i18n::texts::graph as tx;
use crate::i18n::{format_count, use_lang};
use crate::infrastructure::graph::fetch_impact;
/// `finding_id` is the finding's fingerprint, the key impact analyses are
/// stored under.
#[component]
pub fn ImpactAnalysisPage(repo_id: String, finding_id: String) -> Element {
let impact_data = use_resource(move || {
let rid = repo_id.clone();
let fid = finding_id.clone();
async move { fetch_impact(rid, fid).await.ok() }
let lang = use_lang()();
let rid = repo_id.clone();
let impact = use_resource(move || {
let (rid, fid) = (rid.clone(), finding_id.clone());
async move { fetch_impact(rid, fid).await.ok().map(|r| r.data) }
});
rsx! {
div { class: "back-nav",
button {
class: "btn btn-ghost btn-back",
onclick: move |_| { navigator().go_back(); },
Icon { icon: BsArrowLeft, width: 16, height: 16 }
"Back"
}
}
let names = |impact: &Value, key: &str| -> Vec<String> {
impact[key]
.as_array()
.map(|a| {
a.iter()
.filter_map(Value::as_str)
.map(String::from)
.collect()
})
.unwrap_or_default()
};
PageHeader {
title: "Impact Analysis",
description: "Blast radius and affected entry points for a security finding",
}
div { class: "card",
match &*impact_data.read() {
Some(Some(resp)) => {
let impact = resp.data.clone().unwrap_or_default();
rsx! {
div { class: "grid grid-cols-2 gap-4 mb-4",
div { class: "stat-card",
div { class: "stat-value",
"{impact.get(\"blast_radius\").and_then(|v| v.as_u64()).unwrap_or(0)}"
}
div { class: "stat-label", "Blast Radius (nodes affected)" }
let body = match impact.read().clone() {
None => rsx! { div { class: "loading", {tx::IMPACT_LOADING.get(lang)} } },
Some(Some(Some(data))) if impact_has_content(&data) => {
let entry_points = names(&data, "affected_entry_points");
let chains: Vec<Vec<String>> = data["call_chains"]
.as_array()
.map(|a| {
a.iter()
.filter_map(Value::as_array)
.map(|c| {
c.iter()
.filter_map(Value::as_str)
.map(String::from)
.collect()
})
.collect()
})
.unwrap_or_default();
let blast_radius = format_count(data["blast_radius"].as_u64().unwrap_or(0), lang);
let reached_by = format_count(entry_points.len() as u64, lang);
rsx! {
div { class: "target-summary impact-summary",
section { class: "card",
div { class: "target-figures",
div {
span { class: "target-figure", "{reached_by}" }
span { class: "target-figure-label", {tx::REACHED_BY.get(lang)} }
}
div { class: "stat-card",
div { class: "stat-value",
"{impact.get(\"affected_entry_points\").and_then(|v| v.as_array()).map(|a| a.len()).unwrap_or(0)}"
}
div { class: "stat-label", "Entry Points Affected" }
div {
span { class: "target-figure", "{blast_radius}" }
span { class: "target-figure-label", {tx::BLAST_RADIUS.get(lang)} }
}
}
h3 { "Affected Entry Points" }
if let Some(entries) = impact.get("affected_entry_points").and_then(|v| v.as_array()) {
if entries.is_empty() {
p { class: "text-muted", "No entry points affected." }
} else {
ul { class: "list",
for entry in entries {
li { "{entry.as_str().unwrap_or(\"-\")}" }
}
}
}
}
h3 { class: "mt-4", "Call Chains" }
if let Some(chains) = impact.get("call_chains").and_then(|v| v.as_array()) {
if chains.is_empty() {
p { class: "text-muted", "No call chains found." }
} else {
for (i, chain) in chains.iter().enumerate() {
div { class: "card mb-2",
strong { "Chain {i + 1}: " }
if let Some(steps) = chain.as_array() {
for (j, step) in steps.iter().enumerate() {
span { "{step.as_str().unwrap_or(\"-\")}" }
if j < steps.len() - 1 {
span { class: "text-muted", " → " }
}
}
}
}
section { class: "card",
div { class: "card-header", {tx::CALL_CHAINS.get(lang)} }
p { class: "graph-note", {tx::CALL_CHAINS_HINT.get(lang)} }
if chains.is_empty() {
p { class: "text-muted", {tx::NONE.get(lang)} }
} else {
ol { class: "impact-chains",
for chain in chains {
li {
for (i, step) in chain.iter().enumerate() {
if i > 0 {
span { class: "impact-chain-arrow", "aria-hidden": "true", "\u{2192}" }
}
}
}
}
}
h3 { class: "mt-4", "Direct Callers" }
if let Some(callers) = impact.get("direct_callers").and_then(|v| v.as_array()) {
if callers.is_empty() {
p { class: "text-muted", "No direct callers." }
} else {
ul { class: "list",
for caller in callers {
li { code { "{caller.as_str().unwrap_or(\"-\")}" } }
code { "{step}" }
}
}
}
}
}
},
Some(None) => rsx! {
p { "No impact analysis data available for this finding." }
},
None => rsx! {
p { "Loading impact analysis..." }
},
}
NameList { title: tx::ENTRY_POINTS.get(lang), names: entry_points }
NameList { title: tx::CALLERS.get(lang), names: names(&data, "direct_callers") }
NameList { title: tx::CALLEES.get(lang), names: names(&data, "direct_callees") }
}
}
Some(_) => rsx! { div { class: "card", p { {tx::IMPACT_NONE.get(lang)} } } },
};
rsx! {
div { class: "back-nav",
button {
class: "btn btn-ghost btn-back",
onclick: move |_| navigator().go_back(),
Icon { icon: BsArrowLeft, width: 16, height: 16 }
{tx::BACK.get(lang)}
}
}
header { class: "target-head",
div { class: "target-head-text",
h2 { {tx::IMPACT_TITLE.get(lang)} }
p { class: "target-head-meta", {tx::IMPACT_SUBTITLE.get(lang)} }
}
div { class: "target-head-actions",
Link { to: Route::GraphExplorerPage { repo_id }, class: "btn btn-secondary",
{tx::OPEN_GRAPH.get(lang)}
Icon { icon: BsArrowRight, width: 14, height: 14 }
}
}
}
{body}
}
}
/// A titled list of qualified names.
#[component]
fn NameList(title: &'static str, names: Vec<String>) -> Element {
let lang = use_lang()();
rsx! {
section { class: "card",
div { class: "card-header", "{title}" }
if names.is_empty() {
p { class: "text-muted", {tx::NONE.get(lang)} }
} else {
ul { class: "impact-names",
for name in names {
li { code { "{name}" } }
}
}
}
}
}
+1 -2
View File
@@ -8,7 +8,7 @@ pub mod dast_targets;
pub mod finding_detail;
pub mod findings;
pub mod graph_explorer;
pub mod graph_index;
pub(crate) mod graph_view;
pub mod impact_analysis;
pub mod issues;
pub mod mcp_servers;
@@ -31,7 +31,6 @@ pub use dast_targets::DastTargetsPage;
pub use finding_detail::FindingDetailPage;
pub use findings::FindingsPage;
pub use graph_explorer::GraphExplorerPage;
pub use graph_index::GraphIndexPage;
pub use impact_analysis::ImpactAnalysisPage;
pub use issues::IssuesPage;
pub use mcp_servers::McpServersPage;
+4
View File
@@ -275,6 +275,10 @@ pub fn TargetPage(id: String) -> Element {
section { class: "card target-graph",
div { class: "target-card-head",
h3 { {tx::GRAPH_TITLE.get(lang)} }
Link { to: Route::GraphExplorerPage { repo_id: id.clone() }, class: "target-card-link",
{tx::GRAPH_SHOW.get(lang)}
Icon { icon: BsArrowRight, width: 14, height: 14 }
}
}
div { class: "target-figures",
div {