Skip to content

Graphs that teach > graphs that impress. Turn any code into an interactive knowledge graph you can explore, search, and ask questions about. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, and more.

Merge branch 'main' of github.com:fishinakleinbottle/Understand-Anything into feat/improve-dashboard-ux

Sreeram8fade58812c2
diff --cc understand-anything-plugin/packages/dashboard/src/components/GraphView.tsx
index 55cd25b4,b1d6fe33..5efb5175
--- a/understand-anything-plugin/packages/dashboard/src/components/GraphView.tsx
+++ b/understand-anything-plugin/packages/dashboard/src/components/GraphView.tsx
@@@ -1,6 -1,7 +1,7 @@@
- import { useCallback, useEffect, useMemo } from "react";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
++import { useCallback, useEffect, useMemo, useRef } from "react";
import {
ReactFlow,
+ ReactFlowProvider,
useNodesState,
useEdgesState,
useReactFlow,
@@@ -14,373 -15,289 +15,410 @@@ import "@xyflow/react/dist/style.css"
import CustomNode from "./CustomNode";
import type { CustomFlowNode } from "./CustomNode";
+import LayerClusterNode from "./LayerClusterNode";
+import type { LayerClusterFlowNode } from "./LayerClusterNode";
+import PortalNode from "./PortalNode";
+import type { PortalFlowNode } from "./PortalNode";
+import Breadcrumb from "./Breadcrumb";
import { useDashboardStore } from "../store";
-import { applyDagreLayout, applyDagreLayoutAsync, NODE_WIDTH, NODE_HEIGHT } from "../utils/layout";
-
-const LAYER_PADDING = 40;
+import {
+ applyDagreLayout,
+ applySwimLaneLayout,
+ NODE_WIDTH,
+ NODE_HEIGHT,
+ LAYER_CLUSTER_WIDTH,
+ LAYER_CLUSTER_HEIGHT,
+ PORTAL_NODE_WIDTH,
+ PORTAL_NODE_HEIGHT,
+} from "../utils/layout";
+import {
+ aggregateLayerEdges,
+ computePortals,
+ findCrossLayerFileNodes,
+} from "../utils/edgeAggregation";
-/**
- * Node count above which layout runs in a Web Worker
- * to avoid blocking the main thread.
- */
-const ASYNC_LAYOUT_THRESHOLD = 200;
+const nodeTypes = {
+ custom: CustomNode,
+ "layer-cluster": LayerClusterNode,
+ portal: PortalNode,
+};
-const nodeTypes = { custom: CustomNode };
++// ── Helper components that must live inside <ReactFlow> ────────────────
+
-/**
- * Inner component that pans/zooms to tour-highlighted nodes.
- * Must be rendered inside <ReactFlow> so useReactFlow() works.
- */
++/** Pans/zooms to tour-highlighted nodes. */
+ function TourFitView() {
+ const tourHighlightedNodeIds = useDashboardStore((s) => s.tourHighlightedNodeIds);
+ const { fitView } = useReactFlow();
+ const prevRef = useRef<string[]>([]);
+
+ useEffect(() => {
+ const prev = prevRef.current;
+ const changed =
+ tourHighlightedNodeIds.length > 0 &&
+ (tourHighlightedNodeIds.length !== prev.length ||
+ tourHighlightedNodeIds.some((id, i) => id !== prev[i]));
+ prevRef.current = tourHighlightedNodeIds;
+
+ if (changed) {
- // Small delay to ensure nodes are rendered before fitting
+ requestAnimationFrame(() => {
+ fitView({
+ nodes: tourHighlightedNodeIds.map((id) => ({ id })),
+ duration: 500,
+ padding: 0.3,
+ maxZoom: 1.2,
+ minZoom: 0.01,
+ });
+ });
+ }
+ }, [tourHighlightedNodeIds, fitView]);
+
+ return null;
+ }
+
-/**
- * Centers the graph on the selected node (e.g. from search).
- * Must be rendered inside <ReactFlow> so useReactFlow() works.
- */
++/** Centers the graph on the selected node (e.g. from search). */
+ function SelectedNodeFitView() {
+ const selectedNodeId = useDashboardStore((s) => s.selectedNodeId);
+ const { fitView } = useReactFlow();
+ const prevRef = useRef<string | null>(null);
+
+ useEffect(() => {
+ if (selectedNodeId && selectedNodeId !== prevRef.current) {
+ requestAnimationFrame(() => {
+ fitView({
+ nodes: [{ id: selectedNodeId }],
+ duration: 500,
+ padding: 0.3,
+ maxZoom: 1.2,
+ minZoom: 0.01,
+ });
+ });
+ }
+ prevRef.current = selectedNodeId;
+ }, [selectedNodeId, fitView]);
+
+ return null;
+ }
+
-/**
- * Build topology-only flow data: nodes and edges without visual-only state
- * (selection, tour highlights, search results). This output drives dagre
- * layout and should only recompute when the graph structure changes.
- */
-function buildTopologyData(
- graph: NonNullable<ReturnType<typeof useDashboardStore.getState>["graph"]>,
- persona: string,
- diffMode: boolean,
- changedNodeIds: Set<string>,
- affectedNodeIds: Set<string>,
- handleNodeSelect: (nodeId: string) => void,
-) {
- const filteredGraphNodes =
- persona === "non-technical"
- ? graph.nodes.filter(
- (n) =>
- n.type === "concept" || n.type === "module" || n.type === "file",
- )
- : graph.nodes;
-
- const filteredNodeIds = new Set(filteredGraphNodes.map((n) => n.id));
- const filteredGraphEdges =
- persona === "non-technical"
- ? graph.edges.filter(
- (e) => filteredNodeIds.has(e.source) && filteredNodeIds.has(e.target),
- )
- : graph.edges;
-
- const flowNodes: CustomFlowNode[] = filteredGraphNodes.map((node) => ({
- id: node.id,
- type: "custom" as const,
- position: { x: 0, y: 0 },
- data: {
- label: node.name ?? node.filePath?.split("/").pop() ?? node.id,
- nodeType: node.type,
- summary: node.summary,
- complexity: node.complexity,
- isHighlighted: false,
- searchScore: undefined,
- isSelected: false,
- isTourHighlighted: false,
- isDiffChanged: diffMode && changedNodeIds.has(node.id),
- isDiffAffected: diffMode && affectedNodeIds.has(node.id),
- isDiffFaded: diffMode && !changedNodeIds.has(node.id) && !affectedNodeIds.has(node.id),
- onNodeClick: handleNodeSelect,
- },
- }));
-
- const diffNodeIds = diffMode ? new Set([...changedNodeIds, ...affectedNodeIds]) : new Set<string>();
- const flowEdges: Edge[] = filteredGraphEdges.map((edge, i) => {
- const sourceInDiff = diffMode && diffNodeIds.has(edge.source);
- const targetInDiff = diffMode && diffNodeIds.has(edge.target);
- const isImpacted = diffMode && (sourceInDiff || targetInDiff);
-
- return {
- id: `e-${i}`,
- source: edge.source,
- target: edge.target,
- label: edge.type,
- animated: edge.type === "calls" || isImpacted,
- style: isImpacted
- ? {
- stroke: sourceInDiff && targetInDiff
- ? "rgba(224, 82, 82, 0.7)"
- : "rgba(212, 160, 48, 0.5)",
- strokeWidth: 2.5,
- }
- : diffMode
- ? { stroke: "rgba(212,165,116,0.08)", strokeWidth: 1 }
- : { stroke: "rgba(212,165,116,0.3)", strokeWidth: 1.5 },
- labelStyle: diffMode && !isImpacted
- ? { fill: "rgba(163,151,135,0.3)", fontSize: 10 }
- : { fill: "#a39787", fontSize: 10 },
- };
- });
-
- return { flowNodes, flowEdges };
-}
+// ── Overview level: layers as cluster nodes ────────────────────────────
+
+function useOverviewGraph() {
+ const graph = useDashboardStore((s) => s.graph);
+ const searchResults = useDashboardStore((s) => s.searchResults);
+ const drillIntoLayer = useDashboardStore((s) => s.drillIntoLayer);
+ const tourHighlightedNodeIds = useDashboardStore((s) => s.tourHighlightedNodeIds);
+
+ return useMemo(() => {
+ if (!graph) return { nodes: [] as Node[], edges: [] as Edge[] };
-/**
- * Lightweight overlay of visual-only state onto already-positioned nodes.
- * This is O(n) object spreads — cheap even for thousands of nodes — and
- * avoids triggering a dagre relayout when selection/highlight/search changes.
- */
-function applyVisualState(
- nodes: (CustomFlowNode | Node)[],
- selectedNodeId: string | null,
- tourHighlightedNodeIds: string[],
- searchResults: Array<{ nodeId: string; score: number }>,
-): (CustomFlowNode | Node)[] {
- const searchMap = new Map(searchResults.map((r) => [r.nodeId, r.score]));
- const tourSet = new Set(tourHighlightedNodeIds);
-
- return nodes.map((node) => {
- // Skip group nodes (layer containers) — they have no CustomNodeData
- if (node.type === "group") return node;
-
- const searchScore = searchMap.get(node.id);
- const isHighlighted = searchScore !== undefined;
- const isSelected = selectedNodeId === node.id;
- const isTourHighlighted = tourSet.has(node.id);
-
- const data = node.data as CustomFlowNode["data"];
-
- // Skip creating a new object if nothing visual changed
- if (
- data.isHighlighted === isHighlighted &&
- data.searchScore === searchScore &&
- data.isSelected === isSelected &&
- data.isTourHighlighted === isTourHighlighted
- ) {
- return node;
+ const layers = graph.layers ?? [];
+ if (layers.length === 0) return { nodes: [] as Node[], edges: [] as Edge[] };
+
+ // Build search match counts per layer
+ const searchMatchByLayer = new Map<string, number>();
+ if (searchResults.length > 0) {
+ const nodeToLayer = new Map<string, string>();
+ for (const layer of layers) {
+ for (const nid of layer.nodeIds) {
+ nodeToLayer.set(nid, layer.id);
+ }
+ }
+ for (const result of searchResults) {
+ const lid = nodeToLayer.get(result.nodeId);
+ if (lid) {
+ searchMatchByLayer.set(lid, (searchMatchByLayer.get(lid) ?? 0) + 1);
+ }
+ }
}
- // Build tour highlight set for layers
- const tourLayerIds = new Set<string>();
- if (tourHighlightedNodeIds.length > 0) {
- for (const layer of layers) {
- if (layer.nodeIds.some((nid) => tourHighlightedNodeIds.includes(nid))) {
- tourLayerIds.add(layer.id);
- }
- }
- }
-
- return {
- ...node,
- data: {
- ...data,
- isHighlighted,
- searchScore,
- isSelected,
- isTourHighlighted,
+ // Create cluster nodes
+ const clusterNodes: LayerClusterFlowNode[] = layers.map((layer, i) => {
- // Compute aggregate complexity from member nodes
+ const memberNodes = graph.nodes.filter((n) => layer.nodeIds.includes(n.id));
+ const complexCounts = { simple: 0, moderate: 0, complex: 0 };
+ for (const n of memberNodes) {
+ complexCounts[n.complexity]++;
+ }
+ const aggregateComplexity =
+ complexCounts.complex > memberNodes.length * 0.3
+ ? "complex"
+ : complexCounts.moderate > memberNodes.length * 0.3
+ ? "moderate"
+ : "simple";
+
+ return {
+ id: layer.id,
+ type: "layer-cluster" as const,
+ position: { x: 0, y: 0 },
+ data: {
+ layerId: layer.id,
+ layerName: layer.name,
+ layerDescription: layer.description,
+ fileCount: layer.nodeIds.length,
+ aggregateComplexity,
+ layerColorIndex: i,
+ searchMatchCount: searchMatchByLayer.get(layer.id),
+ onDrillIn: drillIntoLayer,
+ },
+ };
+ });
+
+ // Aggregate edges between layers
+ const aggregated = aggregateLayerEdges(graph);
+ const flowEdges: Edge[] = aggregated.map((agg, i) => ({
+ id: `le-${i}`,
+ source: agg.sourceLayerId,
+ target: agg.targetLayerId,
+ label: `${agg.count}`,
+ style: {
+ stroke: "rgba(212,165,116,0.4)",
+ strokeWidth: Math.min(1 + Math.log2(agg.count + 1), 5),
},
- };
- });
+ labelStyle: { fill: "#a39787", fontSize: 11, fontWeight: 600 },
+ }));
+
- // Layout with cluster dimensions
+ const dims = new Map<string, { width: number; height: number }>();
+ for (const n of clusterNodes) {
+ dims.set(n.id, { width: LAYER_CLUSTER_WIDTH, height: LAYER_CLUSTER_HEIGHT });
+ }
+ const laid = applyDagreLayout(clusterNodes as unknown as Node[], flowEdges, "TB", dims);
+ return { nodes: laid.nodes, edges: laid.edges };
+ }, [graph, searchResults, drillIntoLayer, tourHighlightedNodeIds]);
}
-function applyLayerGroups(
- laidNodes: CustomFlowNode[],
- edges: Edge[],
- layers: Array<{ id: string; name: string; nodeIds: string[] }>,
- showLayers: boolean,
-): { initialNodes: (CustomFlowNode | Node)[]; initialEdges: Edge[] } {
- if (!showLayers || layers.length === 0) {
- return { initialNodes: laidNodes, initialEdges: edges };
- }
+// ── Layer detail level: files + portal nodes ───────────────────────────
- const nodeToLayer = new Map<string, string>();
- for (const layer of layers) {
- for (const nodeId of layer.nodeIds) {
- nodeToLayer.set(nodeId, layer.id);
+function useLayerDetailGraph() {
+ const graph = useDashboardStore((s) => s.graph);
+ const activeLayerId = useDashboardStore((s) => s.activeLayerId);
+ const selectedNodeId = useDashboardStore((s) => s.selectedNodeId);
+ const searchResults = useDashboardStore((s) => s.searchResults);
+ const selectNode = useDashboardStore((s) => s.selectNode);
+ const tourHighlightedNodeIds = useDashboardStore((s) => s.tourHighlightedNodeIds);
+ const persona = useDashboardStore((s) => s.persona);
+ const diffMode = useDashboardStore((s) => s.diffMode);
+ const changedNodeIds = useDashboardStore((s) => s.changedNodeIds);
+ const affectedNodeIds = useDashboardStore((s) => s.affectedNodeIds);
+ const focusNodeId = useDashboardStore((s) => s.focusNodeId);
+ const drillIntoLayer = useDashboardStore((s) => s.drillIntoLayer);
+
+ const handleNodeSelect = useCallback(
+ (nodeId: string) => {
+ selectNode(nodeId);
+ },
+ [selectNode],
+ );
+
+ return useMemo(() => {
+ if (!graph || !activeLayerId)
+ return { nodes: [] as Node[], edges: [] as Edge[] };
+
+ const activeLayer = graph.layers.find((l) => l.id === activeLayerId);
+ if (!activeLayer) return { nodes: [] as Node[], edges: [] as Edge[] };
+
+ const layerNodeIds = new Set(activeLayer.nodeIds);
+
- // Filter to file nodes in this layer
+ let filteredGraphNodes = graph.nodes.filter(
+ (n) => layerNodeIds.has(n.id) && n.type === "file",
+ );
+
- // Persona filtering
+ if (persona === "non-technical") {
+ filteredGraphNodes = filteredGraphNodes.filter(
+ (n) => n.type === "concept" || n.type === "module" || n.type === "file",
+ );
}
- }
- const groupNodes: Node[] = [];
- const adjustedNodes: (CustomFlowNode | Node)[] = [];
+ let filteredNodeIds = new Set(filteredGraphNodes.map((n) => n.id));
- // Intra-layer edges only
- for (const layer of layers) {
- const memberNodes = laidNodes.filter((n) => layer.nodeIds.includes(n.id));
- if (memberNodes.length === 0) continue;
+ let filteredGraphEdges = graph.edges.filter(
+ (e) => filteredNodeIds.has(e.source) && filteredNodeIds.has(e.target),
+ );
- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
- for (const node of memberNodes) {
- minX = Math.min(minX, node.position.x);
- minY = Math.min(minY, node.position.y);
- maxX = Math.max(maxX, node.position.x + NODE_WIDTH);
- maxY = Math.max(maxY, node.position.y + NODE_HEIGHT);
+ // Focus mode: 1-hop neighborhood within the layer
+ if (focusNodeId && filteredNodeIds.has(focusNodeId)) {
+ const focusNeighborIds = new Set<string>([focusNodeId]);
+ for (const edge of filteredGraphEdges) {
+ if (edge.source === focusNodeId) focusNeighborIds.add(edge.target);
+ if (edge.target === focusNodeId) focusNeighborIds.add(edge.source);
+ }
+ filteredGraphNodes = filteredGraphNodes.filter((n) =>
+ focusNeighborIds.has(n.id),
+ );
+ filteredNodeIds = new Set(filteredGraphNodes.map((n) => n.id));
+ filteredGraphEdges = filteredGraphEdges.filter(
+ (e) => filteredNodeIds.has(e.source) && filteredNodeIds.has(e.target),
+ );
}
- const groupX = minX - LAYER_PADDING;
- const groupY = minY - LAYER_PADDING - 24;
- const groupWidth = maxX - minX + LAYER_PADDING * 2;
- const groupHeight = maxY - minY + LAYER_PADDING * 2 + 24;
+ // Neighbor set for selection highlighting
+ const neighborNodeIds = new Set<string>();
+ if (selectedNodeId) {
+ for (const edge of filteredGraphEdges) {
+ if (edge.source === selectedNodeId) neighborNodeIds.add(edge.target);
+ if (edge.target === selectedNodeId) neighborNodeIds.add(edge.source);
+ }
+ neighborNodeIds.add(selectedNodeId);
+ }
- // Build file flow nodes
- groupNodes.push({
- id: layer.id,
- type: "group",
- position: { x: groupX, y: groupY },
- data: { label: layer.name },
- style: {
- width: groupWidth,
- height: groupHeight,
- backgroundColor: "rgba(212,165,116,0.05)",
- borderRadius: 12,
- border: "2px dashed rgba(212,165,116,0.25)",
- padding: 8,
- fontSize: 13,
- fontWeight: 600,
- color: "#d4a574",
- },
+ const flowNodes: CustomFlowNode[] = filteredGraphNodes.map((node) => {
+ const matchResult = searchResults.find((r) => r.nodeId === node.id);
+ const hasSelection = !!selectedNodeId;
+ return {
+ id: node.id,
+ type: "custom" as const,
+ position: { x: 0, y: 0 },
+ data: {
+ label: node.name ?? node.filePath?.split("/").pop() ?? node.id,
+ nodeType: node.type,
+ summary: node.summary,
+ complexity: node.complexity,
+ isHighlighted: !!matchResult,
+ searchScore: matchResult?.score,
+ isSelected: selectedNodeId === node.id,
+ isTourHighlighted: tourHighlightedNodeIds.includes(node.id),
+ isDiffChanged: diffMode && changedNodeIds.has(node.id),
+ isDiffAffected: diffMode && affectedNodeIds.has(node.id),
+ isDiffFaded:
+ diffMode &&
+ !changedNodeIds.has(node.id) &&
+ !affectedNodeIds.has(node.id),
+ isNeighbor:
+ hasSelection &&
+ neighborNodeIds.has(node.id) &&
+ selectedNodeId !== node.id,
+ isSelectionFaded: hasSelection && !neighborNodeIds.has(node.id),
+ onNodeClick: handleNodeSelect,
+ },
+ };
});
- // Build diff-aware edges
- for (const node of memberNodes) {
- adjustedNodes.push({
- ...node,
- parentId: layer.id,
- extent: "parent" as const,
- position: {
- x: node.position.x - groupX,
- y: node.position.y - groupY,
- },
- });
+ const diffNodeIds = diffMode
+ ? new Set([...changedNodeIds, ...affectedNodeIds])
+ : new Set<string>();
+ const flowEdges: Edge[] = filteredGraphEdges.map((edge, i) => {
+ const sourceInDiff = diffMode && diffNodeIds.has(edge.source);
+ const targetInDiff = diffMode && diffNodeIds.has(edge.target);
+ const isImpacted = diffMode && (sourceInDiff || targetInDiff);
+
+ const isSelectedEdge =
+ !!selectedNodeId &&
+ (edge.source === selectedNodeId || edge.target === selectedNodeId);
+ const hasSelection = !!selectedNodeId;
+
+ let edgeStyle: React.CSSProperties;
+ let edgeLabelStyle: React.CSSProperties;
+ let edgeAnimated: boolean;
+
+ if (isImpacted) {
+ edgeStyle = {
+ stroke:
+ sourceInDiff && targetInDiff
+ ? "rgba(224, 82, 82, 0.7)"
+ : "rgba(212, 160, 48, 0.5)",
+ strokeWidth: 2.5,
+ };
+ edgeLabelStyle = { fill: "#a39787", fontSize: 10 };
+ edgeAnimated = true;
+ } else if (diffMode) {
+ edgeStyle = { stroke: "rgba(212,165,116,0.08)", strokeWidth: 1 };
+ edgeLabelStyle = { fill: "rgba(163,151,135,0.3)", fontSize: 10 };
+ edgeAnimated = false;
+ } else if (isSelectedEdge) {
+ edgeStyle = { stroke: "rgba(212,165,116,0.8)", strokeWidth: 2.5 };
+ edgeLabelStyle = { fill: "#d4a574", fontSize: 11, fontWeight: 600 };
+ edgeAnimated = true;
+ } else if (hasSelection) {
+ edgeStyle = { stroke: "rgba(212,165,116,0.08)", strokeWidth: 1 };
+ edgeLabelStyle = { fill: "rgba(163,151,135,0.2)", fontSize: 10 };
+ edgeAnimated = false;
+ } else {
+ edgeStyle = { stroke: "rgba(212,165,116,0.3)", strokeWidth: 1.5 };
+ edgeLabelStyle = { fill: "#a39787", fontSize: 10 };
+ edgeAnimated = edge.type === "calls";
+ }
+
+ return {
+ id: `e-${i}`,
+ source: edge.source,
+ target: edge.target,
+ label: edge.type,
+ animated: edgeAnimated,
+ style: edgeStyle,
+ labelStyle: edgeLabelStyle,
+ };
+ });
+
+ // Portal nodes for connected external layers
+ const portals = computePortals(graph, activeLayerId);
+ const layerIndexMap = new Map(graph.layers.map((l, i) => [l.id, i]));
+
+ const portalNodes: PortalFlowNode[] = portals.map((portal) => ({
+ id: `portal:${portal.layerId}`,
+ type: "portal" as const,
+ position: { x: 0, y: 0 },
+ data: {
+ targetLayerId: portal.layerId,
+ targetLayerName: portal.layerName,
+ connectionCount: portal.connectionCount,
+ layerColorIndex: layerIndexMap.get(portal.layerId) ?? 0,
+ onNavigate: drillIntoLayer,
+ },
+ }));
+
- // Connect portal nodes to the file nodes that have cross-layer edges
+ const portalEdges: Edge[] = [];
+ let portalEdgeIdx = flowEdges.length;
+ for (const portal of portals) {
+ const crossFiles = findCrossLayerFileNodes(
+ graph,
+ activeLayerId,
+ portal.layerId,
+ );
+ for (const fileId of crossFiles) {
+ if (filteredNodeIds.has(fileId)) {
+ portalEdges.push({
+ id: `e-${portalEdgeIdx++}`,
+ source: fileId,
+ target: `portal:${portal.layerId}`,
+ style: { stroke: "rgba(212,165,116,0.2)", strokeWidth: 1, strokeDasharray: "4 4" },
+ animated: false,
+ });
+ }
+ }
}
- }
- // Layout with mixed dimensions
- for (const node of laidNodes) {
- if (!nodeToLayer.has(node.id)) {
- adjustedNodes.push(node);
+ const allFlowNodes: Node[] = [
+ ...(flowNodes as unknown as Node[]),
+ ...(portalNodes as unknown as Node[]),
+ ];
+ const allFlowEdges = [...flowEdges, ...portalEdges];
+
+ const dims = new Map<string, { width: number; height: number }>();
+ for (const n of flowNodes) {
+ dims.set(n.id, { width: NODE_WIDTH, height: NODE_HEIGHT });
+ }
+ for (const n of portalNodes) {
+ dims.set(n.id, { width: PORTAL_NODE_WIDTH, height: PORTAL_NODE_HEIGHT });
}
- }
- return {
- initialNodes: [...groupNodes, ...adjustedNodes],
- initialEdges: edges,
- };
+ const laid = applyDagreLayout(allFlowNodes, allFlowEdges, "TB", dims);
+ return { nodes: laid.nodes, edges: laid.edges };
+ }, [
+ graph,
+ activeLayerId,
+ selectedNodeId,
+ searchResults,
+ tourHighlightedNodeIds,
+ persona,
+ handleNodeSelect,
+ diffMode,
+ changedNodeIds,
+ affectedNodeIds,
+ focusNodeId,
+ drillIntoLayer,
+ ]);
}
-function GraphViewInner() {
+// ── Flow (swim-lane) view: all layers as columns ──────────────────────
+
+function useFlowViewGraph() {
const graph = useDashboardStore((s) => s.graph);
const selectedNodeId = useDashboardStore((s) => s.selectedNodeId);
const searchResults = useDashboardStore((s) => s.searchResults);
@@@ -395,229 -313,103 +433,207 @@@
const handleNodeSelect = useCallback(
(nodeId: string) => {
selectNode(nodeId);
- openCodeViewer(nodeId);
},
- [selectNode, openCodeViewer],
+ [selectNode],
);
- // ── Topology memo: only recomputes when graph structure changes ──
- // Does NOT depend on selectedNodeId, tourHighlightedNodeIds, or searchResults.
- const { topoNodes, topoEdges, needsAsyncLayout } = useMemo(() => {
- if (!graph) {
- return { topoNodes: [] as CustomFlowNode[], topoEdges: [] as Edge[], needsAsyncLayout: false };
+ return useMemo(() => {
+ if (!graph || graph.layers.length === 0)
+ return { nodes: [] as Node[], edges: [] as Edge[] };
+
- // Build all file nodes across all layers
+ const allLayerNodeIds = new Set(
+ graph.layers.flatMap((l) => l.nodeIds),
+ );
+
+ const fileGraphNodes = graph.nodes.filter(
+ (n) => n.type === "file" && allLayerNodeIds.has(n.id),
+ );
+
- // Neighbor set for selection highlighting
+ const fileNodeIds = new Set(fileGraphNodes.map((n) => n.id));
+ const neighborNodeIds = new Set<string>();
+ if (selectedNodeId) {
+ for (const edge of graph.edges) {
+ if (edge.source === selectedNodeId && fileNodeIds.has(edge.target))
+ neighborNodeIds.add(edge.target);
+ if (edge.target === selectedNodeId && fileNodeIds.has(edge.source))
+ neighborNodeIds.add(edge.source);
+ }
+ neighborNodeIds.add(selectedNodeId);
+ }
+
+ const diffNodeIds = diffMode
+ ? new Set([...changedNodeIds, ...affectedNodeIds])
+ : new Set<string>();
+
+ const flowNodes: CustomFlowNode[] = fileGraphNodes.map((node) => {
+ const matchResult = searchResults.find((r) => r.nodeId === node.id);
+ const hasSelection = !!selectedNodeId;
+ return {
+ id: node.id,
+ type: "custom" as const,
+ position: { x: 0, y: 0 },
+ data: {
+ label: node.name ?? node.filePath?.split("/").pop() ?? node.id,
+ nodeType: node.type,
+ summary: node.summary,
+ complexity: node.complexity,
+ isHighlighted: !!matchResult,
+ searchScore: matchResult?.score,
+ isSelected: selectedNodeId === node.id,
+ isTourHighlighted: tourHighlightedNodeIds.includes(node.id),
+ isDiffChanged: diffMode && changedNodeIds.has(node.id),
+ isDiffAffected: diffMode && affectedNodeIds.has(node.id),
+ isDiffFaded:
+ diffMode &&
+ !changedNodeIds.has(node.id) &&
+ !affectedNodeIds.has(node.id),
+ isNeighbor:
+ hasSelection &&
+ neighborNodeIds.has(node.id) &&
+ selectedNodeId !== node.id,
+ isSelectionFaded: hasSelection && !neighborNodeIds.has(node.id),
+ onNodeClick: handleNodeSelect,
+ },
+ };
+ });
+
- // Build cross-lane edges (only between file nodes that are in layers)
+ const flowEdges: Edge[] = [];
+ let edgeIdx = 0;
+ for (const edge of graph.edges) {
+ if (!fileNodeIds.has(edge.source) || !fileNodeIds.has(edge.target))
+ continue;
+
+ const isSelectedEdge =
+ !!selectedNodeId &&
+ (edge.source === selectedNodeId || edge.target === selectedNodeId);
+ const hasSelection = !!selectedNodeId;
+ const sourceInDiff = diffMode && diffNodeIds.has(edge.source);
+ const targetInDiff = diffMode && diffNodeIds.has(edge.target);
+ const isImpacted = diffMode && (sourceInDiff || targetInDiff);
+
+ let edgeStyle: React.CSSProperties;
+ let edgeLabelStyle: React.CSSProperties;
+ let edgeAnimated: boolean;
+
+ if (isImpacted) {
+ edgeStyle = {
+ stroke:
+ sourceInDiff && targetInDiff
+ ? "rgba(224, 82, 82, 0.7)"
+ : "rgba(212, 160, 48, 0.5)",
+ strokeWidth: 2.5,
+ };
+ edgeLabelStyle = { fill: "#a39787", fontSize: 10 };
+ edgeAnimated = true;
+ } else if (diffMode) {
+ edgeStyle = { stroke: "rgba(212,165,116,0.08)", strokeWidth: 1 };
+ edgeLabelStyle = { fill: "rgba(163,151,135,0.3)", fontSize: 10 };
+ edgeAnimated = false;
+ } else if (isSelectedEdge) {
+ edgeStyle = { stroke: "rgba(212,165,116,0.8)", strokeWidth: 2.5 };
+ edgeLabelStyle = { fill: "#d4a574", fontSize: 11, fontWeight: 600 };
+ edgeAnimated = true;
+ } else if (hasSelection) {
+ edgeStyle = { stroke: "rgba(212,165,116,0.08)", strokeWidth: 1 };
+ edgeLabelStyle = { fill: "rgba(163,151,135,0.2)", fontSize: 10 };
+ edgeAnimated = false;
+ } else {
+ edgeStyle = { stroke: "rgba(212,165,116,0.25)", strokeWidth: 1 };
+ edgeLabelStyle = { fill: "#a39787", fontSize: 9 };
+ edgeAnimated = false;
+ }
+
+ flowEdges.push({
+ id: `fe-${edgeIdx++}`,
+ source: edge.source,
+ target: edge.target,
+ label: edge.type,
+ animated: edgeAnimated,
+ style: edgeStyle,
+ labelStyle: edgeLabelStyle,
+ });
}
- const { flowNodes, flowEdges } = buildTopologyData(
- graph, persona, diffMode, changedNodeIds, affectedNodeIds,
- handleNodeSelect,
+
+ const result = applySwimLaneLayout(
+ graph,
+ flowNodes as unknown as Node[],
+ flowEdges,
);
- return { topoNodes: flowNodes, topoEdges: flowEdges, needsAsyncLayout: flowNodes.length > ASYNC_LAYOUT_THRESHOLD };
- }, [graph, persona, handleNodeSelect, diffMode, changedNodeIds, affectedNodeIds]);
+ return { nodes: result.nodes, edges: result.edges };
+ }, [
+ graph,
+ selectedNodeId,
+ searchResults,
+ tourHighlightedNodeIds,
+ handleNodeSelect,
+ diffMode,
+ changedNodeIds,
+ affectedNodeIds,
+ ]);
+}
- // ── Main GraphView component ───────────────────────────────────────────
- // ── Laid-out nodes from the last completed layout pass ──
- // Stored in a ref so layout results persist across visual-state changes.
- const laidOutRef = useRef<{ initialNodes: (CustomFlowNode | Node)[]; initialEdges: Edge[] } | null>(null);
++// ── Main inner component (must be inside ReactFlowProvider) ────────────
- export default function GraphView() {
- // ── Sync layout: for small graphs, run dagre on the main thread ──
- const syncResult = useMemo(() => {
- if (!graph || needsAsyncLayout || topoNodes.length === 0) return null;
- const laid = applyDagreLayout(topoNodes, topoEdges);
- const layers = graph.layers ?? [];
- return applyLayerGroups(laid.nodes as CustomFlowNode[], laid.edges, layers, showLayers);
- }, [graph, topoNodes, topoEdges, needsAsyncLayout, showLayers]);
++function GraphViewInner() {
+ const graph = useDashboardStore((s) => s.graph);
+ const navigationLevel = useDashboardStore((s) => s.navigationLevel);
+ const activeLayerId = useDashboardStore((s) => s.activeLayerId);
+ const viewMode = useDashboardStore((s) => s.viewMode);
+ const selectNode = useDashboardStore((s) => s.selectNode);
+ const drillIntoLayer = useDashboardStore((s) => s.drillIntoLayer);
+ const focusNodeId = useDashboardStore((s) => s.focusNodeId);
+ const setFocusNode = useDashboardStore((s) => s.setFocusNode);
- // Keep laidOutRef in sync with sync layout results
- if (syncResult) {
- laidOutRef.current = syncResult;
- }
+ const overviewGraph = useOverviewGraph();
+ const detailGraph = useLayerDetailGraph();
+ const flowGraph = useFlowViewGraph();
- // ── Visual memo: cheap overlay of selection/highlight/search state ──
- const visualNodes = useMemo(() => {
- const base = laidOutRef.current;
- if (!base) return [] as (CustomFlowNode | Node)[];
- return applyVisualState(base.initialNodes, selectedNodeId, tourHighlightedNodeIds, searchResults);
- }, [laidOutRef.current, selectedNodeId, tourHighlightedNodeIds, searchResults]);
+ const { nodes: initialNodes, edges: initialEdges } =
+ viewMode === "flow"
+ ? flowGraph
+ : navigationLevel === "overview"
+ ? overviewGraph
+ : detailGraph;
- const [nodes, setNodes, onNodesChange] = useNodesState(visualNodes);
- const [edges, setEdges, onEdgesChange] = useEdgesState(laidOutRef.current?.initialEdges ?? []);
+ const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
+ const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
- // ── Push sync layout + visual state to ReactFlow ──
- useEffect(() => {
- if (syncResult) {
- const withVisual = applyVisualState(syncResult.initialNodes, selectedNodeId, tourHighlightedNodeIds, searchResults);
- setNodes(withVisual);
- setEdges(syncResult.initialEdges);
- }
- }, [syncResult, selectedNodeId, tourHighlightedNodeIds, searchResults, setNodes, setEdges]);
+ const { fitView } = useReactFlow();
- // ── Push visual-only changes (no relayout) ──
useEffect(() => {
- if (laidOutRef.current && !layouting) {
- const withVisual = applyVisualState(laidOutRef.current.initialNodes, selectedNodeId, tourHighlightedNodeIds, searchResults);
- setNodes(withVisual);
- }
- }, [selectedNodeId, tourHighlightedNodeIds, searchResults, setNodes, layouting]);
+ setNodes(initialNodes);
+ }, [initialNodes, setNodes]);
- // ── Async layout: for large graphs, run dagre in a Web Worker ──
useEffect(() => {
- if (!graph || !needsAsyncLayout || topoNodes.length === 0) return;
-
- let cancelled = false;
- setLayouting(true);
-
- applyDagreLayoutAsync(topoNodes, topoEdges).then((laid) => {
- if (cancelled) return;
- const layers = graph.layers ?? [];
- const result = applyLayerGroups(laid.nodes as CustomFlowNode[], laid.edges, layers, showLayers);
- laidOutRef.current = result;
- const withVisual = applyVisualState(result.initialNodes, selectedNodeId, tourHighlightedNodeIds, searchResults);
- setNodes(withVisual);
- setEdges(result.initialEdges);
- setLayouting(false);
- }).catch(() => {
- if (cancelled) return;
- setLayouting(false);
- });
+ setEdges(initialEdges);
+ }, [initialEdges, setEdges]);
- return () => { cancelled = true; setLayouting(false); };
- }, [graph, topoNodes, topoEdges, needsAsyncLayout, showLayers, setNodes, setEdges]);
+ // Fit view on level/layer/view-mode transitions
+ useEffect(() => {
+ const timer = setTimeout(() => {
+ fitView({ duration: 400, padding: 0.2 });
+ }, 50);
+ return () => clearTimeout(timer);
+ }, [navigationLevel, activeLayerId, viewMode, fitView]);
- // Zoom-to-node when navigateToNode is called
- const zoomToNodeId = useDashboardStore((s) => s.zoomToNodeId);
- useEffect(() => {
- if (zoomToNodeId) {
- const timer = setTimeout(() => {
- fitView({
- nodes: [{ id: zoomToNodeId }],
- duration: 400,
- padding: 0.5,
- });
- useDashboardStore.setState({ zoomToNodeId: null });
- }, 100);
- return () => clearTimeout(timer);
- }
- }, [zoomToNodeId, fitView]);
-
const onNodeClick = useCallback(
(_: React.MouseEvent, node: { id: string }) => {
- // Ignore clicks on group nodes
- const isGroupNode = graph?.layers?.some((l) => l.id === node.id);
- if (isGroupNode) return;
- selectNode(node.id);
- openCodeViewer(node.id);
+ // In flow view, all clicks are selections (no drill-in)
- // Ignore clicks on lane group nodes
+ if (viewMode === "flow") {
+ if (node.id.startsWith("lane:")) return;
+ selectNode(node.id);
+ return;
+ }
+ if (navigationLevel === "overview") {
- // At overview, clicking a layer cluster drills in
+ drillIntoLayer(node.id);
+ } else if (node.id.startsWith("portal:")) {
- // Portal nodes navigate to that layer
+ const targetLayerId = node.id.replace("portal:", "");
+ drillIntoLayer(targetLayerId);
+ } else {
+ selectNode(node.id);
+ }
},
- [selectNode, openCodeViewer, graph],
+ [viewMode, navigationLevel, drillIntoLayer, selectNode],
);
const onPaneClick = useCallback(() => {
@@@ -654,19 -444,18 +670,23 @@@
onNodeClick={onNodeClick}
onPaneClick={onPaneClick}
nodeTypes={nodeTypes}
+ nodesDraggable={false}
+ nodesConnectable={false}
+ edgesFocusable={false}
+ edgesReconnectable={false}
+ elementsSelectable={false}
fitView
- fitViewOptions={{ padding: 0.2 }}
- minZoom={0.05}
- maxZoom={4}
- panOnScroll
+ fitViewOptions={{ minZoom: 0.01, padding: 0.1 }}
+ minZoom={0.01}
+ maxZoom={2}
colorMode="dark"
>
- <Background variant={BackgroundVariant.Dots} color="rgba(212,165,116,0.15)" gap={20} size={1} />
+ <Background
+ variant={BackgroundVariant.Dots}
+ color="rgba(212,165,116,0.15)"
+ gap={20}
+ size={1}
+ />
<Controls />
<MiniMap
nodeColor="#1a1a1a"
diff --cc understand-anything-plugin/packages/dashboard/src/utils/layout.ts
index e7ff519c,6f55b530..548ebfcf
--- a/understand-anything-plugin/packages/dashboard/src/utils/layout.ts
+++ b/understand-anything-plugin/packages/dashboard/src/utils/layout.ts
@@@ -1,20 -1,13 +1,24 @@@
import dagre from "@dagrejs/dagre";
import type { Node, Edge } from "@xyflow/react";
+import type { KnowledgeGraph } from "@understand-anything/core/types";
+ import type { LayoutMessage, LayoutResult } from "./layout.worker";
export const NODE_WIDTH = 280;
export const NODE_HEIGHT = 120;
+export const LAYER_CLUSTER_WIDTH = 320;
+export const LAYER_CLUSTER_HEIGHT = 180;
+export const PORTAL_NODE_WIDTH = 240;
+export const PORTAL_NODE_HEIGHT = 80;
+
+// Swim-lane constants
+export const LANE_WIDTH = 320;
+export const LANE_GAP = 40;
+export const LANE_PADDING = 30;
+export const LANE_HEADER_HEIGHT = 40;
+ /**
+ * Synchronous dagre layout — used for small graphs.
+ */
export function applyDagreLayout(
nodes: Node[],
edges: Edge[],
@@@ -65,174 -48,78 +69,221 @@@
return { nodes: layoutedNodes, edges };
}
++// ── Async layout via Web Worker ────────────────────────────────────────
++
+ let _worker: Worker | null = null;
+ let _nextRequestId = 0;
+ let _latestRequestId = -1;
+ const _pending = new Map<
+ number,
+ {
+ nodes: Node[];
+ edges: Edge[];
+ resolve: (v: { nodes: Node[]; edges: Edge[] }) => void;
+ reject: (reason?: unknown) => void;
+ }
+ >();
+
+ function getWorker(): Worker {
+ if (!_worker) {
+ _worker = new Worker(
+ new URL("./layout.worker.ts", import.meta.url),
+ { type: "module" },
+ );
+
+ _worker.onmessage = (e: MessageEvent<LayoutResult>) => {
+ const { requestId, positions } = e.data;
+ const entry = _pending.get(requestId);
+ _pending.delete(requestId);
+
- // S1: Discard stale results — only honour the latest request.
++ // Discard stale results — only honour the latest request.
+ if (!entry || requestId !== _latestRequestId) return;
+
+ const layoutedNodes = entry.nodes.map((node) => ({
+ ...node,
+ position: positions[node.id] ?? { x: 0, y: 0 },
+ }));
+
+ entry.resolve({ nodes: layoutedNodes, edges: entry.edges });
+ };
+
+ _worker.onerror = (err: ErrorEvent) => {
+ for (const [, entry] of _pending) {
+ entry.reject(err);
+ }
+ _pending.clear();
+ };
+ }
+ return _worker;
+ }
+
+ /**
+ * Async dagre layout via Web Worker — used for large graphs.
+ * Keeps the main thread responsive while dagre computes positions.
- *
- * Uses request-ID correlation so concurrent calls never cross-wire,
- * and only the latest request's result is honoured (stale ones are discarded).
+ */
+ export function applyDagreLayoutAsync(
+ nodes: Node[],
+ edges: Edge[],
+ direction: "TB" | "LR" = "TB",
+ ): Promise<{ nodes: Node[]; edges: Edge[] }> {
+ return new Promise((resolve, reject) => {
+ const worker = getWorker();
+ const requestId = _nextRequestId++;
+ _latestRequestId = requestId;
+
+ _pending.set(requestId, { nodes, edges, resolve, reject });
+
+ const msg: LayoutMessage = {
+ requestId,
+ nodes: nodes.map((n) => ({ id: n.id, width: NODE_WIDTH, height: NODE_HEIGHT })),
+ edges: edges.map((e) => ({ source: e.source, target: e.target })),
+ direction,
+ };
+
+ worker.postMessage(msg);
+ });
+ }
++
++// ── Swim-lane layout ───────────────────────────────────────────────────
++
+/**
+ * Preferred order of layers for the swim-lane flow view.
+ * Reflects a typical request lifecycle: entry → middleware → logic → data → external.
- * Layers not in this list are appended at the end.
+ */
+const LAYER_FLOW_ORDER = [
+ "API Layer",
+ "UI Layer",
+ "Middleware Layer",
+ "Service Layer",
+ "External Services",
+ "Data Layer",
+ "Background Tasks",
+ "Utility Layer",
+ "Configuration Layer",
+ "Test Layer",
+];
+
+function getLayerSortIndex(layerName: string): number {
+ const idx = LAYER_FLOW_ORDER.indexOf(layerName);
+ return idx >= 0 ? idx : LAYER_FLOW_ORDER.length;
+}
+
+export interface SwimLaneResult {
- /** All nodes: lane background groups + file nodes positioned inside them */
+ nodes: Node[];
- /** Cross-lane and intra-lane edges */
+ edges: Edge[];
- /** Ordered layer info for reference */
+ lanes: Array<{ layerId: string; layerName: string; columnIndex: number }>;
+}
+
+/**
+ * Swim-lane layout: each layer becomes a vertical column (lane), ordered
+ * by the request lifecycle. Within each lane, dagre handles vertical
+ * positioning. File nodes are children of their lane group node.
+ */
+export function applySwimLaneLayout(
+ graph: KnowledgeGraph,
+ fileNodes: Node[],
+ allEdges: Edge[],
+): SwimLaneResult {
- // Sort layers by flow order
+ const sortedLayers = [...graph.layers].sort(
+ (a, b) => getLayerSortIndex(a.name) - getLayerSortIndex(b.name),
+ );
+
- // Build nodeId → layer mapping
+ const nodeToLayerId = new Map<string, string>();
+ for (const layer of sortedLayers) {
+ for (const nid of layer.nodeIds) {
+ nodeToLayerId.set(nid, layer.id);
+ }
+ }
+
- // Group file nodes by layer
+ const nodesByLayer = new Map<string, Node[]>();
+ for (const layer of sortedLayers) {
+ nodesByLayer.set(layer.id, []);
+ }
+ for (const node of fileNodes) {
+ const lid = nodeToLayerId.get(node.id);
+ if (lid && nodesByLayer.has(lid)) {
+ nodesByLayer.get(lid)!.push(node);
+ }
+ }
+
- // For each lane, use dagre to compute y-positions of its nodes
- // (treating the lane as a vertical sub-graph)
+ const laneHeights = new Map<string, number>();
+
+ for (const [layerId, nodes] of nodesByLayer) {
+ if (nodes.length === 0) {
+ laneHeights.set(layerId, LANE_HEADER_HEIGHT + LANE_PADDING * 2);
+ continue;
+ }
+
+ const g = new dagre.graphlib.Graph();
+ g.setDefaultEdgeLabel(() => ({}));
- g.setGraph({
- rankdir: "TB",
- nodesep: 20,
- ranksep: 40,
- marginx: 0,
- marginy: 0,
- });
++ g.setGraph({ rankdir: "TB", nodesep: 20, ranksep: 40, marginx: 0, marginy: 0 });
+
+ const laneNodeIds = new Set(nodes.map((n) => n.id));
+ for (const node of nodes) {
+ g.setNode(node.id, { width: NODE_WIDTH, height: NODE_HEIGHT });
+ }
+
- // Only include edges within this lane for vertical ordering
+ for (const edge of allEdges) {
+ if (laneNodeIds.has(edge.source) && laneNodeIds.has(edge.target)) {
+ g.setEdge(edge.source, edge.target);
+ }
+ }
+
+ dagre.layout(g);
+
- // Read dagre's y-positions and assign relative positions within the lane
+ let maxY = 0;
+ for (const node of nodes) {
+ const pos = g.node(node.id);
+ if (pos) {
- // Store the y position in the node's data for later use
+ (node as Node & { _laneY: number })._laneY = pos.y - NODE_HEIGHT / 2;
+ maxY = Math.max(maxY, pos.y + NODE_HEIGHT / 2);
+ }
+ }
+
+ laneHeights.set(layerId, LANE_HEADER_HEIGHT + maxY + LANE_PADDING * 2);
+ }
+
- // Find the tallest lane so all lanes are the same height
- const maxLaneHeight = Math.max(
- 200,
- ...Array.from(laneHeights.values()),
- );
++ const maxLaneHeight = Math.max(200, ...Array.from(laneHeights.values()));
+
- // Build lane group nodes and position file nodes as children
+ const resultNodes: Node[] = [];
+ const lanes: SwimLaneResult["lanes"] = [];
+
+ sortedLayers.forEach((layer, colIdx) => {
+ const laneX = colIdx * (LANE_WIDTH + LANE_GAP);
+ const laneId = `lane:${layer.id}`;
+
- lanes.push({
- layerId: layer.id,
- layerName: layer.name,
- columnIndex: colIdx,
- });
++ lanes.push({ layerId: layer.id, layerName: layer.name, columnIndex: colIdx });
+
- // Lane background group node
+ resultNodes.push({
+ id: laneId,
+ type: "group",
+ position: { x: laneX, y: 0 },
+ data: { label: layer.name },
+ style: {
+ width: LANE_WIDTH,
+ height: maxLaneHeight,
+ backgroundColor: "rgba(212,165,116,0.03)",
+ borderRadius: 12,
+ border: "1px solid rgba(212,165,116,0.1)",
+ padding: 0,
+ },
+ });
+
- // Position file nodes within this lane
+ const nodes = nodesByLayer.get(layer.id) ?? [];
+ for (const node of nodes) {
+ const laneY = (node as Node & { _laneY?: number })._laneY ?? 0;
+ resultNodes.push({
+ ...node,
+ parentId: laneId,
+ extent: "parent" as const,
+ position: {
+ x: (LANE_WIDTH - NODE_WIDTH) / 2,
+ y: LANE_HEADER_HEIGHT + LANE_PADDING + laneY,
+ },
+ });
- // Clean up temp property
+ delete (node as Node & { _laneY?: number })._laneY;
+ }
+ });
+
+ return { nodes: resultNodes, edges: allEdges, lanes };
+}