feat(dashboard): show the code graph, from its card and from a finding (t82) (#939)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Agent (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 3m27s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Agent (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 3m27s
This commit was merged in pull request #939.
This commit is contained in:
1 parent
c1a70b025c
commit
c8deabd4d9
14 files changed
+1680
-955
No files matched your search
@@ -1,231 +1,241 @@
|
|||||||
// ═══════════════════════════════════════════════════════════════
|
// Code graph drawing: a thin vis-network wrapper.
|
||||||
// Graph Visualization — vis-network wrapper for Code Knowledge Graph
|
//
|
||||||
// Obsidian Control theme
|
// 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 () {
|
(function () {
|
||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
// Color palette matching Obsidian Control
|
// CSS custom properties per node kind, defined in main.css from the theme
|
||||||
const NODE_COLORS = {
|
// tokens, so the graph follows the light and dark theme.
|
||||||
function: { bg: "#00c8ff", border: "#00a0cc", font: "#060a13" },
|
var KIND_TOKEN = {
|
||||||
method: { bg: "#00c8ff", border: "#00a0cc", font: "#060a13" },
|
function: "--graph-function",
|
||||||
struct: { bg: "#e040fb", border: "#b030d0", font: "#060a13" },
|
method: "--graph-function",
|
||||||
class: { bg: "#e040fb", border: "#b030d0", font: "#060a13" },
|
class: "--graph-type",
|
||||||
enum: { bg: "#ffb020", border: "#cc8c18", font: "#060a13" },
|
struct: "--graph-type",
|
||||||
interface: { bg: "#7c4dff", border: "#5c38c0", font: "#ffffff" },
|
enum: "--graph-enum",
|
||||||
trait: { bg: "#7c4dff", border: "#5c38c0", font: "#ffffff" },
|
interface: "--graph-interface",
|
||||||
module: { bg: "#ff8a3d", border: "#cc6e30", font: "#060a13" },
|
trait: "--graph-interface",
|
||||||
file: { bg: "#00e676", border: "#00b85e", font: "#060a13" },
|
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 = {
|
var SHAPE = { file: "diamond", module: "square", folder: "hexagon" };
|
||||||
calls: "#00c8ff",
|
|
||||||
imports: "#ffb020",
|
// Above this many nodes the layout runs a short while and then stops,
|
||||||
inherits: "#e040fb",
|
// so a large drawing does not keep the CPU busy.
|
||||||
implements: "#7c4dff",
|
var LARGE = 400;
|
||||||
contains: "rgba(94, 114, 145, 0.6)",
|
|
||||||
type_ref: "rgba(94, 114, 145, 0.5)",
|
var network = null;
|
||||||
|
var nodesDataset = null;
|
||||||
|
var edgesDataset = null;
|
||||||
|
var rawNodes = [];
|
||||||
|
var rawEdges = [];
|
||||||
|
var texts = { kinds: {}, edges: {}, program: "", plc: [], layout: "", entry: "", file: "" };
|
||||||
|
|
||||||
|
function token(name) {
|
||||||
|
return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
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"),
|
||||||
};
|
};
|
||||||
|
|
||||||
const DEFAULT_NODE_COLOR = { bg: "#5e7291", border: "#3d506b", font: "#e4eaf4" };
|
|
||||||
const DEFAULT_EDGE_COLOR = "rgba(94, 114, 145, 0.3)";
|
|
||||||
|
|
||||||
let network = null;
|
|
||||||
let nodesDataset = null;
|
|
||||||
let edgesDataset = null;
|
|
||||||
let rawNodes = [];
|
|
||||||
let rawEdges = [];
|
|
||||||
|
|
||||||
function getNodeColor(kind) {
|
|
||||||
return NODE_COLORS[kind] || DEFAULT_NODE_COLOR;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function getEdgeColor(kind) {
|
function edgeCounts(edges) {
|
||||||
return EDGE_COLORS[kind] || DEFAULT_EDGE_COLOR;
|
var counts = {};
|
||||||
|
edges.forEach(function (e) {
|
||||||
|
counts[e.source] = (counts[e.source] || 0) + 1;
|
||||||
|
counts[e.target] = (counts[e.target] || 0) + 1;
|
||||||
|
});
|
||||||
|
return counts;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build a vis-network node from raw graph data
|
function toVisNode(node, counts, colors) {
|
||||||
function toVisNode(node, edgeCounts) {
|
var color = colors.kinds[node.kind] || colors.fallback;
|
||||||
const color = getNodeColor(node.kind);
|
var isGroup = node.kind === "community" || node.kind === "folder";
|
||||||
const connections = edgeCounts[node.qualified_name] || 0;
|
// A PLC PROGRAM is kept as a module; it is named a program.
|
||||||
const size = Math.max(8, Math.min(35, 8 + connections * 2));
|
var kindName = node.kind === "module" && texts.plc.indexOf(node.language) >= 0
|
||||||
|
? texts.program
|
||||||
|
: 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 {
|
return {
|
||||||
id: node.qualified_name,
|
id: node.qualified_name,
|
||||||
label: node.name,
|
label: isGroup ? node.name + "\n" + node.member_count : node.name,
|
||||||
title: `${node.kind}: ${node.qualified_name}\nFile: ${node.file_path}:${node.start_line}`,
|
title: title,
|
||||||
size: size,
|
size: isGroup ? undefined : size,
|
||||||
|
value: isGroup ? node.member_count : undefined,
|
||||||
color: {
|
color: {
|
||||||
background: color.bg,
|
background: color,
|
||||||
border: color.border,
|
border: node.is_entry_point ? colors.ring : color,
|
||||||
highlight: { background: color.bg, border: "#ffffff" },
|
highlight: { background: color, border: colors.ring },
|
||||||
hover: { background: color.bg, border: "#ffffff" },
|
hover: { background: color, border: colors.ring },
|
||||||
},
|
},
|
||||||
font: {
|
font: {
|
||||||
color: color.font,
|
color: colors.text,
|
||||||
size: 10,
|
size: isGroup ? 13 : 11,
|
||||||
face: "'JetBrains Mono', monospace",
|
face: colors.font,
|
||||||
strokeWidth: 2,
|
strokeWidth: 3,
|
||||||
strokeColor: "#060a13",
|
strokeColor: colors.halo,
|
||||||
},
|
},
|
||||||
borderWidth: 1,
|
borderWidth: node.is_entry_point ? 3 : 1,
|
||||||
borderWidthSelected: 3,
|
borderWidthSelected: 3,
|
||||||
shape: node.kind === "file" ? "diamond" : node.kind === "module" ? "square" : "dot",
|
shape: SHAPE[node.kind] || "dot",
|
||||||
// Store raw data for click handler
|
|
||||||
_raw: node,
|
_raw: node,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function toVisEdge(edge) {
|
function toVisEdge(edge, colors) {
|
||||||
const color = getEdgeColor(edge.kind);
|
var color = colors.edges[edge.kind] || colors.quiet;
|
||||||
const isDim = edge.kind === "contains" || edge.kind === "type_ref";
|
var count = edge.count || 1;
|
||||||
|
var label = edge.kind === "bundle" ? String(count) : texts.edges[edge.kind] || edge.kind;
|
||||||
return {
|
return {
|
||||||
|
id: edge.source + "|" + edge.target + "|" + edge.kind,
|
||||||
from: edge.source,
|
from: edge.source,
|
||||||
to: edge.target,
|
to: edge.target,
|
||||||
color: {
|
color: {
|
||||||
color: color,
|
color: color,
|
||||||
highlight: "#ffffff",
|
highlight: colors.ring,
|
||||||
hover: color,
|
hover: color,
|
||||||
|
opacity: edge.kind === "bundle" ? 0.35 : 0.7,
|
||||||
},
|
},
|
||||||
width: isDim ? 1 : 2,
|
width: edge.kind === "bundle" ? Math.min(8, 1 + Math.log2(count)) : 1,
|
||||||
arrows: {
|
arrows: { to: { enabled: edge.kind !== "contains", scaleFactor: 0.4 } },
|
||||||
to: {
|
smooth: { enabled: true, type: "continuous", roundness: 0.3 },
|
||||||
enabled: edge.kind !== "contains",
|
title: label,
|
||||||
scaleFactor: 0.5,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
smooth: {
|
|
||||||
enabled: true,
|
|
||||||
type: "continuous",
|
|
||||||
roundness: 0.3,
|
|
||||||
},
|
|
||||||
title: `${edge.kind}: ${edge.source} → ${edge.target}`,
|
|
||||||
_raw: edge,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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.
|
* Draw `nodes` and `edges`, then select and show the nodes named in
|
||||||
* Called from Rust via eval().
|
* `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");
|
var container = document.getElementById("graph-canvas");
|
||||||
if (!container) {
|
if (!container) return;
|
||||||
console.error("[graph-viz] #graph-canvas not found");
|
texts = labels;
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Count edges per node for sizing
|
rawNodes = uniqueBy(nodes, function (n) { return n.qualified_name; });
|
||||||
const edgeCounts = {};
|
rawEdges = uniqueBy(edges, function (e) { return e.source + "|" + e.target + "|" + e.kind; });
|
||||||
edges.forEach(function (e) {
|
|
||||||
edgeCounts[e.source] = (edgeCounts[e.source] || 0) + 1;
|
|
||||||
edgeCounts[e.target] = (edgeCounts[e.target] || 0) + 1;
|
|
||||||
});
|
|
||||||
|
|
||||||
// Deduplicate nodes by qualified_name (keep first occurrence)
|
var colors = palette();
|
||||||
var seenNodes = {};
|
var counts = edgeCounts(rawEdges);
|
||||||
var uniqueNodes = [];
|
nodesDataset = new vis.DataSet(rawNodes.map(function (n) {
|
||||||
nodes.forEach(function (n) {
|
return toVisNode(n, counts, colors);
|
||||||
if (!seenNodes[n.qualified_name]) {
|
}));
|
||||||
seenNodes[n.qualified_name] = true;
|
edgesDataset = new vis.DataSet(rawEdges.map(function (e) {
|
||||||
uniqueNodes.push(n);
|
return toVisEdge(e, colors);
|
||||||
}
|
}));
|
||||||
});
|
|
||||||
|
|
||||||
// Deduplicate edges by source+target+kind
|
var large = rawNodes.length > LARGE;
|
||||||
var seenEdges = {};
|
var options = {
|
||||||
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 = {
|
|
||||||
nodes: {
|
nodes: {
|
||||||
font: { color: "#e4eaf4", size: 10 },
|
scaling: {
|
||||||
scaling: { min: 8, max: 35 },
|
min: 12,
|
||||||
|
max: 56,
|
||||||
|
label: { enabled: true, min: 22, max: 48, drawThreshold: 5, maxVisible: 30 },
|
||||||
},
|
},
|
||||||
edges: {
|
|
||||||
font: { color: "#5e7291", size: 9, strokeWidth: 0 },
|
|
||||||
selectionWidth: 3,
|
|
||||||
},
|
},
|
||||||
physics: {
|
physics: {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
solver: "forceAtlas2Based",
|
solver: "forceAtlas2Based",
|
||||||
forceAtlas2Based: {
|
forceAtlas2Based: {
|
||||||
gravitationalConstant: -80,
|
gravitationalConstant: -60,
|
||||||
centralGravity: 0.005,
|
centralGravity: 0.008,
|
||||||
springLength: 120,
|
springLength: 110,
|
||||||
springConstant: 0.04,
|
springConstant: 0.04,
|
||||||
damping: 0.5,
|
damping: 0.6,
|
||||||
avoidOverlap: 0.6,
|
avoidOverlap: 0.5,
|
||||||
},
|
},
|
||||||
stabilization: {
|
stabilization: { enabled: true, iterations: large ? 300 : 1000, updateInterval: 25 },
|
||||||
enabled: true,
|
maxVelocity: 40,
|
||||||
iterations: 1500,
|
|
||||||
updateInterval: 25,
|
|
||||||
},
|
|
||||||
maxVelocity: 50,
|
|
||||||
minVelocity: 0.75,
|
minVelocity: 0.75,
|
||||||
},
|
},
|
||||||
interaction: {
|
interaction: {
|
||||||
hover: true,
|
hover: true,
|
||||||
tooltipDelay: 200,
|
tooltipDelay: 200,
|
||||||
hideEdgesOnDrag: false,
|
hideEdgesOnDrag: large,
|
||||||
hideEdgesOnZoom: false,
|
hideEdgesOnZoom: large,
|
||||||
multiselect: false,
|
keyboard: { enabled: true, bindToWindow: false },
|
||||||
navigationButtons: false,
|
|
||||||
keyboard: { enabled: true },
|
|
||||||
},
|
|
||||||
layout: {
|
|
||||||
improvedLayout: uniqueNodes.length < 300,
|
|
||||||
},
|
},
|
||||||
|
layout: { improvedLayout: rawNodes.length < 300 },
|
||||||
};
|
};
|
||||||
|
|
||||||
// Destroy previous instance
|
if (network) network.destroy();
|
||||||
if (network) {
|
network = new vis.Network(container, { nodes: nodesDataset, edges: edgesDataset }, options);
|
||||||
network.destroy();
|
|
||||||
}
|
|
||||||
|
|
||||||
network = new vis.Network(
|
|
||||||
container,
|
|
||||||
{ nodes: nodesDataset, edges: edgesDataset },
|
|
||||||
options
|
|
||||||
);
|
|
||||||
|
|
||||||
// Click handler — sends data to Rust
|
|
||||||
network.on("click", function (params) {
|
network.on("click", function (params) {
|
||||||
if (params.nodes.length > 0) {
|
if (params.nodes.length === 0) return;
|
||||||
const nodeId = params.nodes[0];
|
var raw = rawNodes.find(function (n) { return n.qualified_name === params.nodes[0]; });
|
||||||
const visNode = nodesDataset.get(nodeId);
|
if (raw && window.__onNodeClick) window.__onNodeClick(JSON.stringify(raw));
|
||||||
if (visNode && visNode._raw && window.__onNodeClick) {
|
|
||||||
window.__onNodeClick(JSON.stringify(visNode._raw));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Stabilization overlay
|
|
||||||
var overlay = document.getElementById("graph-stabilization-overlay");
|
var overlay = document.getElementById("graph-stabilization-overlay");
|
||||||
var progressFill = document.getElementById("graph-stab-progress-fill");
|
var progressFill = document.getElementById("graph-stab-progress-fill");
|
||||||
var pctLabel = document.getElementById("graph-stab-pct");
|
var pctLabel = document.getElementById("graph-stab-pct");
|
||||||
|
|
||||||
// Show the overlay
|
|
||||||
if (overlay) {
|
if (overlay) {
|
||||||
overlay.classList.remove("graph-stab-fade-out");
|
overlay.classList.remove("graph-stab-fade-out");
|
||||||
overlay.style.display = "flex";
|
overlay.style.display = "flex";
|
||||||
@@ -233,120 +243,35 @@
|
|||||||
|
|
||||||
network.on("stabilizationProgress", function (params) {
|
network.on("stabilizationProgress", function (params) {
|
||||||
var pct = Math.round((params.iterations / params.total) * 100);
|
var pct = Math.round((params.iterations / params.total) * 100);
|
||||||
if (progressFill) {
|
if (progressFill) progressFill.style.width = pct + "%";
|
||||||
progressFill.style.width = pct + "%";
|
if (pctLabel) pctLabel.textContent = texts.layout + " · " + pct + " %";
|
||||||
}
|
|
||||||
if (pctLabel) {
|
|
||||||
pctLabel.textContent = pct + "% — computing layout";
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
network.on("stabilizationIterationsDone", function () {
|
network.once("stabilizationIterationsDone", function () {
|
||||||
if (progressFill) progressFill.style.width = "100%";
|
if (progressFill) progressFill.style.width = "100%";
|
||||||
if (pctLabel) pctLabel.textContent = "Complete";
|
|
||||||
|
|
||||||
// Fade out overlay
|
|
||||||
if (overlay) {
|
if (overlay) {
|
||||||
overlay.classList.add("graph-stab-fade-out");
|
overlay.classList.add("graph-stab-fade-out");
|
||||||
setTimeout(function () {
|
setTimeout(function () { overlay.style.display = "none"; }, 600);
|
||||||
overlay.style.display = "none";
|
|
||||||
}, 900);
|
|
||||||
}
|
}
|
||||||
// Keep physics running so nodes float and respond to dragging,
|
// A large drawing stops moving; a small one keeps settling gently
|
||||||
// but reduce forces for a calm, settled feel
|
// and answers to dragging.
|
||||||
network.setOptions({
|
network.setOptions({ physics: large ? { enabled: false } : { maxVelocity: 15 } });
|
||||||
physics: {
|
window.__highlightNodes(focus || []);
|
||||||
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,
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
});
|
|
||||||
|
|
||||||
console.log(
|
|
||||||
"[graph-viz] Loaded " + nodes.length + " nodes, " + edges.length + " edges"
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/** Select the named nodes that are drawn and show them. */
|
||||||
* 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).
|
|
||||||
*/
|
|
||||||
window.__highlightNodes = function (qualifiedNames) {
|
window.__highlightNodes = function (qualifiedNames) {
|
||||||
if (!network || !nodesDataset) return;
|
if (!network || !nodesDataset) return;
|
||||||
network.selectNodes(qualifiedNames);
|
var drawn = qualifiedNames.filter(function (id) { return nodesDataset.get(id); });
|
||||||
if (qualifiedNames.length > 0) {
|
if (drawn.length === 0) return;
|
||||||
network.fit({
|
network.selectNodes(drawn);
|
||||||
nodes: qualifiedNames,
|
network.fit({ nodes: drawn, animation: { duration: 500, easingFunction: "easeInOutQuad" } });
|
||||||
animation: { duration: 500, easingFunction: "easeInOutQuad" },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/** Fit the whole drawing in view. */
|
||||||
* 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.
|
|
||||||
*/
|
|
||||||
window.__fitGraph = function () {
|
window.__fitGraph = function () {
|
||||||
if (!network) return;
|
if (!network) return;
|
||||||
network.fit({
|
network.fit({ animation: { duration: 400, easingFunction: "easeInOutQuad" } });
|
||||||
animation: { duration: 400, easingFunction: "easeInOutQuad" },
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
})();
|
})();
|
||||||
@@ -101,6 +101,18 @@
|
|||||||
color-scheme: light;
|
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") ──
|
/* ── Dark ("Nacht") ──
|
||||||
When chosen explicitly (`data-theme="dark"`), or when the OS prefers dark
|
When chosen explicitly (`data-theme="dark"`), or when the OS prefers dark
|
||||||
and no choice was made. */
|
and no choice was made. */
|
||||||
@@ -1762,85 +1774,6 @@ tbody tr:last-child td {
|
|||||||
gap: 24px;
|
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 */
|
/* Progress bar */
|
||||||
.graph-stab-progress {
|
.graph-stab-progress {
|
||||||
width: 200px;
|
width: 200px;
|
||||||
@@ -1854,23 +1787,9 @@ tbody tr:last-child td {
|
|||||||
.graph-stab-progress-fill {
|
.graph-stab-progress-fill {
|
||||||
height: 100%;
|
height: 100%;
|
||||||
width: 0%;
|
width: 0%;
|
||||||
background: linear-gradient(90deg, var(--accent), #e040fb);
|
background: var(--accent);
|
||||||
border-radius: 2px;
|
border-radius: 2px;
|
||||||
transition: width 0.3s ease-out;
|
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 {
|
.graph-stab-pct {
|
||||||
@@ -1885,16 +1804,11 @@ tbody tr:last-child td {
|
|||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
height: 100%;
|
min-height: 240px;
|
||||||
color: var(--text-tertiary);
|
color: var(--text-tertiary);
|
||||||
gap: 8px;
|
gap: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.graph-empty-icon {
|
|
||||||
font-size: 48px;
|
|
||||||
opacity: 0.3;
|
|
||||||
}
|
|
||||||
|
|
||||||
.graph-empty-state h3 {
|
.graph-empty-state h3 {
|
||||||
font-family: var(--font-display);
|
font-family: var(--font-display);
|
||||||
font-size: 16px;
|
font-size: 16px;
|
||||||
@@ -1905,37 +1819,6 @@ tbody tr:last-child td {
|
|||||||
font-size: 13px;
|
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 Kind Badges */
|
||||||
.node-label-badge {
|
.node-label-badge {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
@@ -1949,40 +1832,96 @@ tbody tr:last-child td {
|
|||||||
letter-spacing: 0.04em;
|
letter-spacing: 0.04em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.node-kind-function, .node-kind-method {
|
/* Node kinds: the badge in the inspector and the legend's dots, in the
|
||||||
background: var(--accent-muted);
|
colours graph-viz.js draws them with. */
|
||||||
color: var(--accent);
|
.node-label-badge[class*="graph-kind-"] {
|
||||||
border: 1px solid var(--border-accent);
|
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 {
|
.graph-kind-function, .graph-kind-method { --kind: var(--graph-function); }
|
||||||
background: rgba(224, 64, 251, 0.12);
|
.graph-kind-class, .graph-kind-struct { --kind: var(--graph-type); }
|
||||||
color: #e040fb;
|
.graph-kind-enum { --kind: var(--graph-enum); }
|
||||||
border: 1px solid rgba(224, 64, 251, 0.2);
|
.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 {
|
.graph-legend li {
|
||||||
background: rgba(255, 176, 32, 0.12);
|
display: inline-flex;
|
||||||
color: #ffb020;
|
align-items: center;
|
||||||
border: 1px solid rgba(255, 176, 32, 0.2);
|
gap: 6px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.node-kind-interface, .node-kind-trait {
|
.graph-legend-dot {
|
||||||
background: rgba(124, 77, 255, 0.12);
|
width: 9px;
|
||||||
color: #7c4dff;
|
height: 9px;
|
||||||
border: 1px solid rgba(124, 77, 255, 0.2);
|
border-radius: 50%;
|
||||||
|
background: var(--kind);
|
||||||
}
|
}
|
||||||
|
|
||||||
.node-kind-module {
|
.graph-legend-entry {
|
||||||
background: rgba(255, 138, 61, 0.12);
|
background: transparent;
|
||||||
color: #ff8a3d;
|
border: 2px solid var(--text-primary);
|
||||||
border: 1px solid rgba(255, 138, 61, 0.2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.node-kind-file {
|
.graph-note {
|
||||||
background: var(--success-bg);
|
margin: 0 0 12px;
|
||||||
color: var(--success);
|
font-size: 12.5px;
|
||||||
border: 1px solid color-mix(in oklch, var(--success) 30%, transparent);
|
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 */
|
/* Code Inspector Panel */
|
||||||
@@ -2243,12 +2182,23 @@ tbody tr:last-child td {
|
|||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 8px;
|
gap: 8px;
|
||||||
|
width: 100%;
|
||||||
padding: 8px 12px;
|
padding: 8px 12px;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
|
font: inherit;
|
||||||
|
color: inherit;
|
||||||
|
text-align: left;
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
border-bottom: 1px solid var(--border);
|
border-bottom: 1px solid var(--border);
|
||||||
transition: background 0.15s;
|
transition: background 0.15s;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.search-suggestion-item:focus-visible {
|
||||||
|
outline: 2px solid var(--accent);
|
||||||
|
outline-offset: -2px;
|
||||||
|
}
|
||||||
|
|
||||||
.search-suggestion-item:last-child {
|
.search-suggestion-item:last-child {
|
||||||
border-bottom: none;
|
border-bottom: none;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,8 +28,8 @@ pub enum Route {
|
|||||||
SbomPage { target: String },
|
SbomPage { target: String },
|
||||||
#[route("/issues")]
|
#[route("/issues")]
|
||||||
IssuesPage {},
|
IssuesPage {},
|
||||||
#[route("/graph")]
|
// The code graph opens from its card on the target page.
|
||||||
GraphIndexPage {},
|
#[redirect("/graph", || Route::TargetsPage {})]
|
||||||
#[route("/graph/:repo_id")]
|
#[route("/graph/:repo_id")]
|
||||||
GraphExplorerPage { repo_id: String },
|
GraphExplorerPage { repo_id: String },
|
||||||
#[route("/graph/:repo_id/impact/:finding_id")]
|
#[route("/graph/:repo_id/impact/:finding_id")]
|
||||||
|
|||||||
@@ -1,17 +1,22 @@
|
|||||||
use dioxus::prelude::*;
|
use dioxus::prelude::*;
|
||||||
|
|
||||||
|
use crate::i18n::texts::graph as tx;
|
||||||
|
use crate::i18n::use_lang;
|
||||||
use crate::infrastructure::graph::fetch_file_content;
|
use crate::infrastructure::graph::fetch_file_content;
|
||||||
|
|
||||||
|
/// A file of the code graph, with the selected code unit's lines marked.
|
||||||
#[component]
|
#[component]
|
||||||
pub fn CodeInspector(
|
pub fn CodeInspector(
|
||||||
repo_id: String,
|
repo_id: String,
|
||||||
file_path: String,
|
file_path: String,
|
||||||
node_name: String,
|
node_name: String,
|
||||||
node_kind: String,
|
node_kind: String,
|
||||||
|
node_language: String,
|
||||||
start_line: u32,
|
start_line: u32,
|
||||||
end_line: u32,
|
end_line: u32,
|
||||||
on_close: EventHandler<()>,
|
on_close: EventHandler<()>,
|
||||||
) -> Element {
|
) -> Element {
|
||||||
|
let lang = use_lang()();
|
||||||
let file_path_clone = file_path.clone();
|
let file_path_clone = file_path.clone();
|
||||||
let repo_id_clone = repo_id.clone();
|
let repo_id_clone = repo_id.clone();
|
||||||
let file_content = use_resource(move || {
|
let file_content = use_resource(move || {
|
||||||
@@ -30,18 +35,20 @@ pub fn CodeInspector(
|
|||||||
// Header
|
// Header
|
||||||
div { class: "code-inspector-header",
|
div { class: "code-inspector-header",
|
||||||
div { class: "code-inspector-title",
|
div { class: "code-inspector-title",
|
||||||
span { class: "badge badge-info", "SELECTED" }
|
|
||||||
span { class: "code-inspector-file-name", "{file_path}" }
|
span { class: "code-inspector-file-name", "{file_path}" }
|
||||||
}
|
}
|
||||||
div { class: "code-inspector-meta",
|
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::node_kind(&node_kind, &node_language).get(lang)} }
|
||||||
span { class: "code-inspector-node-name", "{node_name}" }
|
span { class: "code-inspector-node-name", "{node_name}" }
|
||||||
if start_line > 0 && end_line > 0 {
|
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 {
|
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(()),
|
onclick: move |_| on_close.call(()),
|
||||||
"\u{2715}"
|
"\u{2715}"
|
||||||
}
|
}
|
||||||
@@ -79,12 +86,10 @@ pub fn CodeInspector(
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
Some(None) => rsx! {
|
Some(None) => rsx! {
|
||||||
div { class: "code-inspector-empty",
|
div { class: "code-inspector-empty", {tx::FILE_FAILED.get(lang)} }
|
||||||
"Could not load file content."
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
None => rsx! {
|
None => rsx! {
|
||||||
div { class: "loading", "Loading file..." }
|
div { class: "loading", {tx::FILE_LOADING.get(lang)} }
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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`
|
/// 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.
|
/// in German, `2026-09-30 08:05 UTC` in English.
|
||||||
pub fn format_time(time: &chrono::DateTime<chrono::Utc>, lang: Lang) -> String {
|
pub fn format_time(time: &chrono::DateTime<chrono::Utc>, lang: Lang) -> String {
|
||||||
@@ -195,6 +213,16 @@ fn set_document_lang(lang: Lang) {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
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]
|
#[test]
|
||||||
fn a_moment_reads_as_how_long_ago_it_was() {
|
fn a_moment_reads_as_how_long_ago_it_was() {
|
||||||
use chrono::{Duration, TimeZone, Utc};
|
use chrono::{Duration, TimeZone, Utc};
|
||||||
|
|||||||
@@ -1140,6 +1140,10 @@ pub mod targets {
|
|||||||
de: "Einstiegspunkte",
|
de: "Einstiegspunkte",
|
||||||
en: "entry points",
|
en: "entry points",
|
||||||
};
|
};
|
||||||
|
pub const GRAPH_SHOW: Text = Text {
|
||||||
|
de: "Anzeigen",
|
||||||
|
en: "Show",
|
||||||
|
};
|
||||||
pub const GRAPH_NOTE: Text = Text {
|
pub const GRAPH_NOTE: Text = Text {
|
||||||
de: "Die Bewertung der Befunde berücksichtigt, ob ein Einstiegspunkt die Stelle erreicht.",
|
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.",
|
en: "Triage takes into account whether an entry point reaches a finding.",
|
||||||
@@ -4595,3 +4599,319 @@ 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 PLC PROGRAM, which the graph keeps as a module ("Modul" names a
|
||||||
|
/// bookable product, so it is not used for PLC code).
|
||||||
|
pub const PROGRAM: Text = Text {
|
||||||
|
de: "Programm",
|
||||||
|
en: "Program",
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The languages a PLC project is parsed as; their modules are programs.
|
||||||
|
pub const PLC_LANGUAGES: [&str; 2] = ["structured_text", "plcopen"];
|
||||||
|
|
||||||
|
/// A node's kind name, given its language: a PLC PROGRAM is a "Programm".
|
||||||
|
pub fn node_kind(kind: &str, language: &str) -> Text {
|
||||||
|
if kind == "module" && PLC_LANGUAGES.contains(&language) {
|
||||||
|
PROGRAM
|
||||||
|
} else {
|
||||||
|
self::kind(kind)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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",
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_plc_program_is_named_a_program_not_a_module() {
|
||||||
|
assert_eq!(node_kind("module", "structured_text").de, "Programm");
|
||||||
|
assert_eq!(node_kind("module", "plcopen").de, "Programm");
|
||||||
|
assert_eq!(node_kind("module", "python").de, "Modul");
|
||||||
|
assert_eq!(node_kind("class", "structured_text").de, "Klasse");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,16 @@ pub struct GraphData {
|
|||||||
pub build: Option<serde_json::Value>,
|
pub build: Option<serde_json::Value>,
|
||||||
pub nodes: Vec<serde_json::Value>,
|
pub nodes: Vec<serde_json::Value>,
|
||||||
pub edges: 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)]
|
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||||
@@ -18,12 +28,6 @@ pub struct ImpactResponse {
|
|||||||
pub data: Option<serde_json::Value>,
|
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)]
|
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||||
pub struct NodesResponse {
|
pub struct NodesResponse {
|
||||||
pub data: Vec<serde_json::Value>,
|
pub data: Vec<serde_json::Value>,
|
||||||
@@ -111,29 +115,16 @@ pub async fn fetch_impact(
|
|||||||
Ok(body)
|
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]
|
#[server]
|
||||||
pub async fn fetch_file_content(
|
pub async fn fetch_file_content(
|
||||||
repo_id: String,
|
repo_id: String,
|
||||||
file_path: String,
|
file_path: String,
|
||||||
) -> Result<FileContentResponse, ServerFnError> {
|
) -> Result<FileContentResponse, ServerFnError> {
|
||||||
let resp = super::agent_client::agent_get(&format!(
|
// The path as a query parameter, encoded: file names can hold spaces,
|
||||||
"/api/v1/graph/{repo_id}/file-content?path={file_path}"
|
// `#` or `&`.
|
||||||
))
|
let resp = super::agent_client::agent_get(&format!("/api/v1/graph/{repo_id}/file-content"))
|
||||||
.await?
|
.await?
|
||||||
|
.query(&[("path", file_path.as_str())])
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||||
@@ -146,10 +137,9 @@ pub async fn fetch_file_content(
|
|||||||
|
|
||||||
#[server]
|
#[server]
|
||||||
pub async fn search_nodes(repo_id: String, query: String) -> Result<SearchResponse, ServerFnError> {
|
pub async fn search_nodes(repo_id: String, query: String) -> Result<SearchResponse, ServerFnError> {
|
||||||
let resp = super::agent_client::agent_get(&format!(
|
let resp = super::agent_client::agent_get(&format!("/api/v1/graph/{repo_id}/search"))
|
||||||
"/api/v1/graph/{repo_id}/search?q={query}&limit=50"
|
|
||||||
))
|
|
||||||
.await?
|
.await?
|
||||||
|
.query(&[("q", query.as_str()), ("limit", "50")])
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||||
|
|||||||
@@ -7,11 +7,13 @@ use crate::components::code_snippet::CodeSnippet;
|
|||||||
use crate::components::markdown::render_markdown;
|
use crate::components::markdown::render_markdown;
|
||||||
use crate::components::page_header::PageHeader;
|
use crate::components::page_header::PageHeader;
|
||||||
use crate::components::severity_badge::SeverityBadge;
|
use crate::components::severity_badge::SeverityBadge;
|
||||||
use crate::i18n::texts::{common, findings as tx};
|
use crate::i18n::texts::{common, findings as tx, graph as graph_tx};
|
||||||
use crate::i18n::{format_time, use_lang};
|
use crate::i18n::{format_count, format_time, use_lang};
|
||||||
use crate::infrastructure::evidence::{fetch_catalog_controls, CatalogControl};
|
use crate::infrastructure::evidence::{fetch_catalog_controls, CatalogControl};
|
||||||
use crate::infrastructure::findings::{location, mask_secrets, wire_name};
|
use crate::infrastructure::findings::{location, mask_secrets, wire_name};
|
||||||
|
use crate::infrastructure::graph::fetch_impact;
|
||||||
use crate::pages::findings::status_icon;
|
use crate::pages::findings::status_icon;
|
||||||
|
use crate::pages::graph_view::impact_has_content;
|
||||||
use compliance_core::models::{FindingStatus, ScanType};
|
use compliance_core::models::{FindingStatus, ScanType};
|
||||||
|
|
||||||
/// What happened to the last save on this page, shown next to what was saved.
|
/// 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()
|
.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();
|
let snapshot = finding.read().clone();
|
||||||
|
|
||||||
match snapshot {
|
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 {
|
if let Some(rationale) = &f.triage_rationale {
|
||||||
div { class: "card",
|
div { class: "card",
|
||||||
div { class: "card-header", {tx::TRIAGE.get(lang)} }
|
div { class: "card-header", {tx::TRIAGE.get(lang)} }
|
||||||
|
|||||||
@@ -1,253 +1,350 @@
|
|||||||
|
//! 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::prelude::*;
|
||||||
use dioxus_free_icons::icons::bs_icons::*;
|
use dioxus_free_icons::icons::bs_icons::*;
|
||||||
use dioxus_free_icons::Icon;
|
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::code_inspector::CodeInspector;
|
||||||
use crate::components::file_tree::{build_file_tree, FileTree};
|
use crate::components::file_tree::{build_file_tree, FileTree};
|
||||||
use crate::components::page_header::PageHeader;
|
|
||||||
use crate::components::toast::{ToastType, Toasts};
|
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,
|
||||||
|
"program": tx::PROGRAM.get(lang),
|
||||||
|
"plc": tx::PLC_LANGUAGES,
|
||||||
|
"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>,
|
||||||
|
/// Whether the graph has PLC code, and code in other languages: which
|
||||||
|
/// names its modules get in the legend.
|
||||||
|
has_plc: bool,
|
||||||
|
has_other: bool,
|
||||||
|
/// `(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);
|
||||||
|
let codes: Vec<&str> = build
|
||||||
|
.and_then(|b| b["languages_parsed"].as_array())
|
||||||
|
.map(|codes| codes.iter().filter_map(Value::as_str).collect())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let is_plc = |code: &&str| tx::PLC_LANGUAGES.contains(code);
|
||||||
|
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: codes
|
||||||
|
.iter()
|
||||||
|
.map(|code| language_name(code).to_string())
|
||||||
|
.collect(),
|
||||||
|
has_plc: codes.iter().any(is_plc),
|
||||||
|
has_other: !codes.iter().all(is_plc),
|
||||||
|
truncated: data
|
||||||
|
.truncated
|
||||||
|
.then_some((data.edges.len(), data.total_edges)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[component]
|
#[component]
|
||||||
pub fn GraphExplorerPage(repo_id: String) -> Element {
|
pub fn GraphExplorerPage(repo_id: String) -> Element {
|
||||||
rsx! {
|
let lang = use_lang()();
|
||||||
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 can_write = crate::components::no_access::use_can_write();
|
let can_write = crate::components::no_access::use_can_write();
|
||||||
let repo_id_clone = repo_id.clone();
|
let mut toasts = use_context::<Toasts>();
|
||||||
let mut graph_data = use_resource(move || {
|
|
||||||
let rid = repo_id_clone.clone();
|
let rid = repo_id.clone();
|
||||||
async move {
|
let target = use_resource(move || {
|
||||||
if rid.is_empty() {
|
let rid = rid.clone();
|
||||||
return None;
|
async move { fetch_target(rid).await.ok() }
|
||||||
}
|
});
|
||||||
fetch_graph(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 building = use_signal(|| false);
|
||||||
let mut toasts = use_context::<Toasts>();
|
let mut selected = use_signal(|| Option::<Value>::None);
|
||||||
let mut selected_node = use_signal(|| Option::<serde_json::Value>::None);
|
|
||||||
let mut inspector_open = use_signal(|| false);
|
|
||||||
let mut search_query = use_signal(String::new);
|
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 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();
|
// Each node's group, the view drawn, and what is drawn: recomputed only
|
||||||
if let Some(Some(data)) = &*graph_data_read {
|
// when the graph or the chosen view changes.
|
||||||
if !data.data.nodes.is_empty() && !graph_ready() {
|
let grouping = use_memo(move || {
|
||||||
let nj = serde_json::to_string(&data.data.nodes).unwrap_or_else(|_| "[]".into());
|
let graph = graph.read();
|
||||||
let ej = serde_json::to_string(&data.data.edges).unwrap_or_else(|_| "[]".into());
|
Some(Grouping::new(&graph.as_ref()?.as_ref()?.data.nodes))
|
||||||
nodes_json.set(nj);
|
});
|
||||||
edges_json.set(ej);
|
let shown_view = use_memo(move || {
|
||||||
graph_ready.set(true);
|
let graph = graph.read();
|
||||||
}
|
let count = graph.as_ref()?.as_ref()?.data.nodes.len();
|
||||||
}
|
Some(view().unwrap_or_else(|| GraphView::initial(count)))
|
||||||
|
});
|
||||||
let (node_count, edge_count, community_count, languages, file_tree_data) =
|
// The header's figures and the file tree, so a render (a keystroke in the
|
||||||
if let Some(Some(data)) = &*graph_data_read {
|
// search box) doesn't copy or walk the graph.
|
||||||
let build = data.data.build.clone().unwrap_or_default();
|
let facts = use_memo(move || Some(GraphFacts::of(&graph.read().as_ref()?.as_ref()?.data)));
|
||||||
let nc = build
|
let file_tree = use_memo(move || {
|
||||||
.get("node_count")
|
let graph = graph.read();
|
||||||
.and_then(|n| n.as_u64())
|
graph
|
||||||
.unwrap_or(0);
|
.as_ref()
|
||||||
let ec = build
|
.and_then(|g| g.as_ref())
|
||||||
.get("edge_count")
|
.map(|g| build_file_tree(&g.data.nodes))
|
||||||
.and_then(|n| n.as_u64())
|
.unwrap_or_default()
|
||||||
.unwrap_or(0);
|
});
|
||||||
let cc = build
|
let drawn = use_memo(move || {
|
||||||
.get("community_count")
|
let graph = graph.read();
|
||||||
.and_then(|n| n.as_u64())
|
let d = &graph.as_ref()?.as_ref()?.data;
|
||||||
.unwrap_or(0);
|
Some(draw(
|
||||||
let langs: Vec<String> = build
|
&d.nodes,
|
||||||
.get("languages_parsed")
|
&d.edges,
|
||||||
.and_then(|v| v.as_array())
|
grouping.read().as_ref()?,
|
||||||
.map(|arr| {
|
shown_view.read().as_ref()?,
|
||||||
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);
|
|
||||||
|
|
||||||
use_effect(move || {
|
use_effect(move || {
|
||||||
let ready = graph_ready();
|
let drawn = drawn.read();
|
||||||
if !ready {
|
let Some(drawn) = drawn.as_ref().filter(|d| !d.nodes.is_empty()) else {
|
||||||
return;
|
return;
|
||||||
}
|
};
|
||||||
let nj = nodes_json();
|
let nodes = serde_json::to_string(&drawn.nodes).unwrap_or_else(|_| "[]".into());
|
||||||
let ej = edges_json();
|
let edges = serde_json::to_string(&drawn.edges).unwrap_or_else(|_| "[]".into());
|
||||||
if nj.is_empty() {
|
let focus = serde_json::to_string(&*pending_focus.peek()).unwrap_or_else(|_| "[]".into());
|
||||||
return;
|
let labels = viz_labels(lang);
|
||||||
}
|
// The canvas is in the DOM once this render is committed; the timeout
|
||||||
spawn(async move {
|
// lets vis-network measure it.
|
||||||
let js = format!(
|
let js = format!(
|
||||||
r#"
|
r#"
|
||||||
window.__onNodeClick = function(nodeJson) {{
|
window.__onNodeClick = function (nodeJson) {{
|
||||||
var el = document.getElementById('graph-node-click-data');
|
var el = document.getElementById('graph-node-click-data');
|
||||||
if (el) {{
|
if (el) {{
|
||||||
el.value = nodeJson;
|
el.value = nodeJson;
|
||||||
el.dispatchEvent(new Event('input', {{ bubbles: true }}));
|
el.dispatchEvent(new Event('input', {{ bubbles: true }}));
|
||||||
}}
|
}}
|
||||||
}};
|
}};
|
||||||
setTimeout(function() {{
|
setTimeout(function () {{
|
||||||
if (window.__loadGraph) {{
|
if (window.__loadGraph) window.__loadGraph({nodes}, {edges}, {labels}, {focus});
|
||||||
window.__loadGraph({nj}, {ej});
|
}}, 50);
|
||||||
}}
|
|
||||||
}}, 300);
|
|
||||||
"#
|
"#
|
||||||
);
|
);
|
||||||
let _ = document::eval(&js);
|
let _ = document::eval(&js);
|
||||||
});
|
});
|
||||||
});
|
|
||||||
|
|
||||||
let sel = selected_node();
|
// Show the nodes named `names`: open their group first when its members
|
||||||
let sel_file = sel
|
// 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()
|
.as_ref()
|
||||||
.and_then(|n| n.get("file_path").and_then(|v| v.as_str()))
|
.and_then(|t| t.as_ref()?.data["name"].as_str().map(String::from));
|
||||||
.unwrap_or("")
|
|
||||||
.to_string();
|
let Some(facts) = facts() else {
|
||||||
let sel_name = sel
|
return rsx! {
|
||||||
.as_ref()
|
GraphBack { repo_id: repo_id.clone() }
|
||||||
.and_then(|n| n.get("name").and_then(|v| v.as_str()))
|
match graph.read().as_ref() {
|
||||||
.unwrap_or("")
|
Some(None) => rsx! { div { class: "card", p { {tx::LOAD_FAILED.get(lang)} } } },
|
||||||
.to_string();
|
_ => rsx! { div { class: "loading", {tx::LOADING.get(lang)} } },
|
||||||
let sel_kind = sel
|
}
|
||||||
.as_ref()
|
};
|
||||||
.and_then(|n| n.get("kind").and_then(|v| v.as_str()))
|
};
|
||||||
.unwrap_or("")
|
|
||||||
.to_string();
|
let opens_as_overview = GraphView::initial(facts.drawable) == GraphView::Overview;
|
||||||
let sel_start = sel
|
let current = shown_view().unwrap_or(GraphView::All);
|
||||||
.as_ref()
|
let units = format_count(facts.units, lang);
|
||||||
.and_then(|n| n.get("start_line").and_then(|v| v.as_u64()))
|
let relations = format_count(facts.relations, lang);
|
||||||
.unwrap_or(0) as u32;
|
let groups = format_count(facts.groups, lang);
|
||||||
let sel_end = sel
|
let capped = drawn.read().as_ref().and_then(|d| d.capped);
|
||||||
.as_ref()
|
// A module is a "Programm" in PLC code; a graph with both shows both.
|
||||||
.and_then(|n| n.get("end_line").and_then(|v| v.as_u64()))
|
let legend: Vec<(&str, &str)> = LEGEND_KINDS
|
||||||
.unwrap_or(0) as u32;
|
.into_iter()
|
||||||
|
.flat_map(|kind| match kind {
|
||||||
|
"module" => [
|
||||||
|
facts.has_other.then(|| (kind, tx::kind(kind).get(lang))),
|
||||||
|
facts.has_plc.then(|| (kind, tx::PROGRAM.get(lang))),
|
||||||
|
],
|
||||||
|
_ => [Some((kind, tx::kind(kind).get(lang))), None],
|
||||||
|
})
|
||||||
|
.flatten()
|
||||||
|
.collect();
|
||||||
|
let sel = selected();
|
||||||
|
let layout_class = if sel.is_some() {
|
||||||
|
"graph-explorer-layout inspector-open"
|
||||||
|
} else {
|
||||||
|
"graph-explorer-layout"
|
||||||
|
};
|
||||||
|
|
||||||
rsx! {
|
rsx! {
|
||||||
if repo_id.is_empty() {
|
GraphBack { repo_id: repo_id.clone() }
|
||||||
div { class: "card",
|
|
||||||
p { "Select a repository to view its code graph." }
|
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 {
|
button {
|
||||||
class: "btn btn-primary",
|
class: "btn btn-secondary",
|
||||||
disabled: building(),
|
disabled: building(),
|
||||||
onclick: {
|
onclick: {
|
||||||
let rid = repo_id.clone();
|
let rid = repo_id.clone();
|
||||||
move |_| {
|
move |_| {
|
||||||
let rid = rid.clone();
|
let rid = rid.clone();
|
||||||
building.set(true);
|
building.set(true);
|
||||||
graph_ready.set(false);
|
|
||||||
nodes_json.set(String::new());
|
|
||||||
edges_json.set(String::new());
|
|
||||||
spawn(async move {
|
spawn(async move {
|
||||||
match trigger_graph_build(rid).await {
|
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()),
|
Err(e) => toasts.push(ToastType::Error, e.to_string()),
|
||||||
}
|
}
|
||||||
building.set(false);
|
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",
|
div { class: "graph-search-bar",
|
||||||
input {
|
input {
|
||||||
r#type: "text",
|
r#type: "search",
|
||||||
placeholder: "Search nodes...",
|
placeholder: tx::SEARCH.get(lang),
|
||||||
|
"aria-label": tx::SEARCH.get(lang),
|
||||||
value: "{search_query}",
|
value: "{search_query}",
|
||||||
oninput: {
|
oninput: {
|
||||||
let rid = repo_id.clone();
|
let rid = repo_id.clone();
|
||||||
move |e: FormEvent| {
|
move |e: FormEvent| {
|
||||||
let val = e.value();
|
let q = e.value();
|
||||||
search_query.set(val.clone());
|
search_query.set(q.clone());
|
||||||
if val.len() >= 2 {
|
if q.chars().count() < 2 {
|
||||||
|
search_results.set(Vec::new());
|
||||||
|
return;
|
||||||
|
}
|
||||||
let rid = rid.clone();
|
let rid = rid.clone();
|
||||||
spawn(async move {
|
spawn(async move {
|
||||||
if let Ok(resp) = search_nodes(rid, val).await {
|
// 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);
|
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 +352,22 @@ fn GraphExplorerBody(repo_id: String) -> Element {
|
|||||||
div { class: "search-suggestions",
|
div { class: "search-suggestions",
|
||||||
for node in search_results() {
|
for node in search_results() {
|
||||||
{
|
{
|
||||||
let name = node.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string();
|
let kind = node["kind"].as_str().unwrap_or_default().to_string();
|
||||||
let kind = node.get("kind").and_then(|v| v.as_str()).unwrap_or("").to_string();
|
let language = node["language"].as_str().unwrap_or_default().to_string();
|
||||||
let file_path = node.get("file_path").and_then(|v| v.as_str()).unwrap_or("").to_string();
|
let name = node["name"].as_str().unwrap_or_default().to_string();
|
||||||
let node_clone = node.clone();
|
let path = node["file_path"].as_str().unwrap_or_default().to_string();
|
||||||
let qname = node.get("qualified_name").and_then(|v| v.as_str()).unwrap_or("").to_string();
|
|
||||||
rsx! {
|
rsx! {
|
||||||
div {
|
button {
|
||||||
class: "search-suggestion-item",
|
class: "search-suggestion-item",
|
||||||
|
r#type: "button",
|
||||||
onclick: move |_| {
|
onclick: move |_| {
|
||||||
let nc = node_clone.clone();
|
reveal(vec![node_id(&node).to_string()]);
|
||||||
let qn = qname.clone();
|
selected.set(Some(node.clone()));
|
||||||
selected_node.set(Some(nc));
|
|
||||||
inspector_open.set(true);
|
|
||||||
search_results.set(Vec::new());
|
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-name", "{name}" }
|
||||||
span { class: "search-suggestion-kind", "{kind}" }
|
span { class: "search-suggestion-kind", {tx::node_kind(&kind, &language).get(lang)} }
|
||||||
span { class: "search-suggestion-path", "{file_path}" }
|
span { class: "search-suggestion-path", "{path}" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -285,177 +375,134 @@ fn GraphExplorerBody(repo_id: String) -> Element {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
button {
|
button {
|
||||||
class: "btn-sm",
|
class: "btn btn-secondary btn-sm",
|
||||||
onclick: move |_| {
|
onclick: move |_| {
|
||||||
spawn(async move {
|
let _ = document::eval("window.__fitGraph && window.__fitGraph();");
|
||||||
let _ = document::eval("if (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 {
|
input {
|
||||||
id: "graph-node-click-data",
|
id: "graph-node-click-data",
|
||||||
r#type: "hidden",
|
r#type: "hidden",
|
||||||
value: "",
|
|
||||||
oninput: move |e| {
|
oninput: move |e| {
|
||||||
let val = e.value();
|
let Ok(node) = serde_json::from_str::<Value>(&e.value()) else { return };
|
||||||
if !val.is_empty() {
|
// A group's node opens the group; any other node is shown
|
||||||
if let Ok(node) = serde_json::from_str::<serde_json::Value>(&val) {
|
// in the inspector.
|
||||||
selected_node.set(Some(node));
|
match serde_json::from_value::<Group>(node["group"].clone()) {
|
||||||
inspector_open.set(true);
|
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: layout_class,
|
||||||
div { class: if inspector_open() { "graph-explorer-layout inspector-open" } else { "graph-explorer-layout" },
|
|
||||||
|
|
||||||
// Left: File Tree
|
|
||||||
div { class: "file-tree-panel",
|
div { class: "file-tree-panel",
|
||||||
div { class: "file-tree-header",
|
div { class: "file-tree-header", h4 { {tx::FILES.get(lang)} } }
|
||||||
h4 { "Files" }
|
|
||||||
}
|
|
||||||
div { class: "file-tree-search",
|
div { class: "file-tree-search",
|
||||||
input {
|
input {
|
||||||
r#type: "text",
|
r#type: "search",
|
||||||
placeholder: "Filter files...",
|
placeholder: tx::FILTER_FILES.get(lang),
|
||||||
|
"aria-label": tx::FILTER_FILES.get(lang),
|
||||||
value: "{file_filter}",
|
value: "{file_filter}",
|
||||||
oninput: move |e| file_filter.set(e.value()),
|
oninput: move |e| file_filter.set(e.value()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
div { class: "file-tree-content",
|
div { class: "file-tree-content",
|
||||||
if file_tree_data.is_empty() {
|
|
||||||
div { class: "file-tree-empty", "No files. Build the graph first." }
|
|
||||||
} else {
|
|
||||||
FileTree {
|
FileTree {
|
||||||
tree: file_tree_data,
|
tree: file_tree(),
|
||||||
filter: file_filter(),
|
filter: file_filter(),
|
||||||
on_file_click: move |path: String| {
|
on_file_click: move |path: String| {
|
||||||
// Open code inspector for this file
|
let in_file = graph
|
||||||
let file_node = serde_json::json!({
|
.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,
|
"file_path": &path,
|
||||||
"name": path.rsplit('/').next().unwrap_or(&path),
|
"name": path.rsplit('/').next().unwrap_or(&path),
|
||||||
"kind": "file",
|
"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);
|
|
||||||
});
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// Left-center: Code Inspector (between file tree and graph)
|
if let Some(node) = sel {
|
||||||
if inspector_open() && selected_node().is_some() {
|
|
||||||
CodeInspector {
|
CodeInspector {
|
||||||
repo_id: repo_id.clone(),
|
repo_id: repo_id.clone(),
|
||||||
file_path: sel_file,
|
file_path: node["file_path"].as_str().unwrap_or_default().to_string(),
|
||||||
node_name: sel_name,
|
node_name: node["name"].as_str().unwrap_or_default().to_string(),
|
||||||
node_kind: sel_kind,
|
node_kind: node["kind"].as_str().unwrap_or_default().to_string(),
|
||||||
start_line: sel_start,
|
node_language: node["language"].as_str().unwrap_or_default().to_string(),
|
||||||
end_line: sel_end,
|
start_line: node["start_line"].as_u64().unwrap_or(0) as u32,
|
||||||
on_close: move |_| {
|
end_line: node["end_line"].as_u64().unwrap_or(0) as u32,
|
||||||
inspector_open.set(false);
|
on_close: move |_| selected.set(None),
|
||||||
selected_node.set(None);
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Right: Graph Canvas
|
|
||||||
div { class: "graph-canvas-panel",
|
div { class: "graph-canvas-panel",
|
||||||
if has_graph_data {
|
div { id: "graph-canvas", class: "graph-canvas" }
|
||||||
div {
|
div { id: "graph-stabilization-overlay", class: "graph-stab-overlay",
|
||||||
id: "graph-canvas",
|
|
||||||
class: "graph-canvas",
|
|
||||||
}
|
|
||||||
// Stabilization overlay
|
|
||||||
div {
|
|
||||||
id: "graph-stabilization-overlay",
|
|
||||||
class: "graph-stab-overlay",
|
|
||||||
div { class: "graph-stab-content",
|
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",
|
||||||
div {
|
div { class: "graph-stab-progress-fill", id: "graph-stab-progress-fill" }
|
||||||
class: "graph-stab-progress-fill",
|
}
|
||||||
id: "graph-stab-progress-fill",
|
div { class: "graph-stab-pct", id: "graph-stab-pct", {tx::LAYOUT.get(lang)} }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
div {
|
ul { class: "graph-legend",
|
||||||
class: "graph-stab-pct",
|
for (kind, name) in legend {
|
||||||
id: "graph-stab-pct",
|
li { span { class: "graph-legend-dot graph-kind-{kind}" } {name} }
|
||||||
"Initializing\u{2026}"
|
|
||||||
}
|
}
|
||||||
}
|
li { span { class: "graph-legend-dot graph-legend-entry" } {tx::ENTRY_POINT.get(lang)} }
|
||||||
}
|
if current != GraphView::All {
|
||||||
} else if node_count > 0 {
|
for kind in LEGEND_GROUPS {
|
||||||
// Data exists but nodes array was empty (shouldn't happen)
|
li { span { class: "graph-legend-dot graph-kind-{kind}" } {tx::kind(kind).get(lang)} }
|
||||||
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." }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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(\", \")}" }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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"] })));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,108 +1,145 @@
|
|||||||
|
//! 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::prelude::*;
|
||||||
use dioxus_free_icons::icons::bs_icons::*;
|
use dioxus_free_icons::icons::bs_icons::*;
|
||||||
use dioxus_free_icons::Icon;
|
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;
|
use crate::infrastructure::graph::fetch_impact;
|
||||||
|
|
||||||
|
/// `finding_id` is the finding's fingerprint, the key impact analyses are
|
||||||
|
/// stored under.
|
||||||
#[component]
|
#[component]
|
||||||
pub fn ImpactAnalysisPage(repo_id: String, finding_id: String) -> Element {
|
pub fn ImpactAnalysisPage(repo_id: String, finding_id: String) -> Element {
|
||||||
let impact_data = use_resource(move || {
|
let lang = use_lang()();
|
||||||
let rid = repo_id.clone();
|
let rid = repo_id.clone();
|
||||||
let fid = finding_id.clone();
|
let impact = use_resource(move || {
|
||||||
async move { fetch_impact(rid, fid).await.ok() }
|
let (rid, fid) = (rid.clone(), finding_id.clone());
|
||||||
|
async move { fetch_impact(rid, fid).await.ok().map(|r| r.data) }
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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()
|
||||||
|
};
|
||||||
|
|
||||||
|
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 {
|
||||||
|
span { class: "target-figure", "{blast_radius}" }
|
||||||
|
span { class: "target-figure-label", {tx::BLAST_RADIUS.get(lang)} }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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}" }
|
||||||
|
}
|
||||||
|
code { "{step}" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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! {
|
rsx! {
|
||||||
div { class: "back-nav",
|
div { class: "back-nav",
|
||||||
button {
|
button {
|
||||||
class: "btn btn-ghost btn-back",
|
class: "btn btn-ghost btn-back",
|
||||||
onclick: move |_| { navigator().go_back(); },
|
onclick: move |_| navigator().go_back(),
|
||||||
Icon { icon: BsArrowLeft, width: 16, height: 16 }
|
Icon { icon: BsArrowLeft, width: 16, height: 16 }
|
||||||
"Back"
|
{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}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
PageHeader {
|
/// A titled list of qualified names.
|
||||||
title: "Impact Analysis",
|
#[component]
|
||||||
description: "Blast radius and affected entry points for a security finding",
|
fn NameList(title: &'static str, names: Vec<String>) -> Element {
|
||||||
}
|
let lang = use_lang()();
|
||||||
|
|
||||||
div { class: "card",
|
|
||||||
match &*impact_data.read() {
|
|
||||||
Some(Some(resp)) => {
|
|
||||||
let impact = resp.data.clone().unwrap_or_default();
|
|
||||||
rsx! {
|
rsx! {
|
||||||
div { class: "grid grid-cols-2 gap-4 mb-4",
|
section { class: "card",
|
||||||
div { class: "stat-card",
|
div { class: "card-header", "{title}" }
|
||||||
div { class: "stat-value",
|
if names.is_empty() {
|
||||||
"{impact.get(\"blast_radius\").and_then(|v| v.as_u64()).unwrap_or(0)}"
|
p { class: "text-muted", {tx::NONE.get(lang)} }
|
||||||
}
|
|
||||||
div { class: "stat-label", "Blast Radius (nodes affected)" }
|
|
||||||
}
|
|
||||||
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" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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 {
|
} else {
|
||||||
ul { class: "list",
|
ul { class: "impact-names",
|
||||||
for entry in entries {
|
for name in names {
|
||||||
li { "{entry.as_str().unwrap_or(\"-\")}" }
|
li { code { "{name}" } }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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", " → " }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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(\"-\")}" } }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Some(None) => rsx! {
|
|
||||||
p { "No impact analysis data available for this finding." }
|
|
||||||
},
|
|
||||||
None => rsx! {
|
|
||||||
p { "Loading impact analysis..." }
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -8,7 +8,7 @@ pub mod dast_targets;
|
|||||||
pub mod finding_detail;
|
pub mod finding_detail;
|
||||||
pub mod findings;
|
pub mod findings;
|
||||||
pub mod graph_explorer;
|
pub mod graph_explorer;
|
||||||
pub mod graph_index;
|
pub(crate) mod graph_view;
|
||||||
pub mod impact_analysis;
|
pub mod impact_analysis;
|
||||||
pub mod issues;
|
pub mod issues;
|
||||||
pub mod mcp_servers;
|
pub mod mcp_servers;
|
||||||
@@ -31,7 +31,6 @@ pub use dast_targets::DastTargetsPage;
|
|||||||
pub use finding_detail::FindingDetailPage;
|
pub use finding_detail::FindingDetailPage;
|
||||||
pub use findings::FindingsPage;
|
pub use findings::FindingsPage;
|
||||||
pub use graph_explorer::GraphExplorerPage;
|
pub use graph_explorer::GraphExplorerPage;
|
||||||
pub use graph_index::GraphIndexPage;
|
|
||||||
pub use impact_analysis::ImpactAnalysisPage;
|
pub use impact_analysis::ImpactAnalysisPage;
|
||||||
pub use issues::IssuesPage;
|
pub use issues::IssuesPage;
|
||||||
pub use mcp_servers::McpServersPage;
|
pub use mcp_servers::McpServersPage;
|
||||||
|
|||||||
@@ -275,6 +275,10 @@ pub fn TargetPage(id: String) -> Element {
|
|||||||
section { class: "card target-graph",
|
section { class: "card target-graph",
|
||||||
div { class: "target-card-head",
|
div { class: "target-card-head",
|
||||||
h3 { {tx::GRAPH_TITLE.get(lang)} }
|
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 { class: "target-figures",
|
||||||
div {
|
div {
|
||||||
|
|||||||
Reference in new issue
Block a user