import React, { useState, useEffect, useCallback } from 'react'; import { apiUrl } from '../../lib/api'; import ReactFlow, { MiniMap, Controls, Background, useNodesState, useEdgesState, MarkerType, ReactFlowProvider, } from 'reactflow'; import { PanControls } from './graph/PanControls'; import dagre from 'dagre'; import { Search, Info, X } from 'lucide-react'; import 'reactflow/dist/style.css'; interface NodeData { id: string; label: string; category: string; degree: number; centrality: number; } interface EdgeData { source: string; target: string; relationship: string; } interface GraphProps { repoName: string; } const nodeWidth = 200; const nodeHeight = 40; const getLayoutedElements = (nodes: any[], edges: any[], direction = 'TB') => { const dagreGraph = new dagre.graphlib.Graph(); dagreGraph.setDefaultEdgeLabel(() => ({})); dagreGraph.setGraph({ rankdir: direction, ranksep: 60, nodesep: 40 }); nodes.forEach((node) => { dagreGraph.setNode(node.id, { width: nodeWidth, height: nodeHeight }); }); edges.forEach((edge) => { dagreGraph.setEdge(edge.source, edge.target); }); dagre.layout(dagreGraph); const layoutedNodes = nodes.map((node) => { const nodeWithPosition = dagreGraph.node(node.id); return { ...node, position: { x: nodeWithPosition.x - nodeWidth / 2, y: nodeWithPosition.y - nodeHeight / 2, }, }; }); return { nodes: layoutedNodes, edges }; }; const ArchitectureGraphInner: React.FC = ({ repoName }) => { const [nodes, setNodes, onNodesChange] = useNodesState([]); const [edges, setEdges, onEdgesChange] = useEdgesState([]); const [searchQuery, setSearchQuery] = useState(''); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [selectedNode, setSelectedNode] = useState(null); const fetchGraphData = useCallback(async (query = '') => { setLoading(true); setError(null); const [owner, name] = repoName.split('/'); try { const url = apiUrl(`/api/v1/architecture/${owner}/${name}/graph` + (query ? `?q=${encodeURIComponent(query)}` : '')); const response = await fetch(url); if (!response.ok) { throw new Error(await response.text() || 'Failed to fetch graph data'); } const data = await response.json(); if (!data.nodes || data.nodes.length === 0) { setNodes([]); setEdges([]); setLoading(false); return; } // Map raw nodes into React Flow nodes with classes const rawNodes = data.nodes.map((n: NodeData) => { let styleClass = '!bg-zinc-900 !border !border-zinc-700 !text-zinc-300 rounded px-3 py-2 text-center text-xs font-mono truncate shadow cursor-pointer hover:!border-zinc-500 transition-all'; if (n.category === 'entry_point') { styleClass = '!bg-emerald-950/60 !border-2 !border-emerald-500 !text-emerald-400 rounded px-3 py-2 text-center text-xs font-mono font-semibold truncate shadow-lg shadow-emerald-500/5 cursor-pointer hover:!bg-emerald-900/40 transition-all'; } else if (n.category === 'core_module') { styleClass = '!bg-blue-950/60 !border-2 !border-blue-500 !text-blue-400 rounded px-3 py-2 text-center text-xs font-mono font-semibold truncate shadow-lg shadow-blue-500/5 cursor-pointer hover:!bg-blue-900/40 transition-all'; } else if (n.category === 'high_coupling') { styleClass = '!bg-orange-950/60 !border !border-orange-500 !text-orange-400 rounded px-3 py-2 text-center text-xs font-mono truncate shadow cursor-pointer hover:!bg-orange-900/40 transition-all'; } else if (n.category === 'directory') { styleClass = '!bg-purple-950/60 !border !border-purple-500 !text-purple-400 rounded px-3 py-2 text-center text-xs font-mono truncate shadow font-semibold cursor-pointer hover:!bg-purple-900/40 transition-all'; } return { id: n.id, data: { label: n.label, raw: n }, className: styleClass, type: 'default', }; }); // Create a map of node id -> category const categoryMap = new Map(); data.nodes.forEach((n: NodeData) => categoryMap.set(n.id, n.category)); // Map raw edges into React Flow edges const rawEdges = data.edges.map((e: EdgeData) => { const srcCategory = categoryMap.get(e.source) ?? 'regular'; let strokeColor = '#4b5563'; // default gray if (srcCategory === 'entry_point') { strokeColor = '#10b981'; // emerald } else if (srcCategory === 'core_module') { strokeColor = '#3b82f6'; // blue } else if (srcCategory === 'high_coupling') { strokeColor = '#f97316'; // orange } else if (srcCategory === 'directory') { strokeColor = '#a855f7'; // purple } return { id: `${e.source}->${e.target}`, source: e.source, target: e.target, animated: e.relationship === 'imports', style: { stroke: strokeColor, strokeWidth: 1.5 }, markerEnd: { type: MarkerType.ArrowClosed, width: 12, height: 12, color: strokeColor, }, }; }); // Apply Dagre auto-layout const { nodes: layoutedNodes, edges: layoutedEdges } = getLayoutedElements( rawNodes, rawEdges, 'TB' // Top-to-bottom layout ); setNodes(layoutedNodes); setEdges(layoutedEdges); } catch (err: any) { console.error(err); setError(err.message || 'An error occurred loading the graph.'); } finally { setLoading(false); } }, [repoName, setNodes, setEdges]); // Initial load useEffect(() => { fetchGraphData(); }, [fetchGraphData]); const handleSearchSubmit = (e: React.FormEvent) => { e.preventDefault(); fetchGraphData(searchQuery); }; const handleClearSearch = () => { setSearchQuery(''); fetchGraphData(''); }; const onNodeClick = (_event: any, node: any) => { setSelectedNode(node.data.raw); }; return (
{/* Search Bar */}
setSearchQuery(e.target.value)} placeholder="Search files (e.g. api, auth)..." className="w-full bg-canvas border border-border rounded pl-8 pr-8 py-1.5 text-xs font-mono focus:outline-none focus:border-primary/80 text-text" /> {searchQuery && ( )}
Click nodes to view detail analysis
{/* React Flow Area */}
{loading && (
Loading Architecture Graph...
)} {error && (
{error}
)} {!loading && !error && nodes.length === 0 && (
No nodes matched search.
)} { const raw = node.data?.raw; if (!raw) return '#27272a'; if (raw.category === 'entry_point') return '#10b981'; if (raw.category === 'core_module') return '#3b82f6'; if (raw.category === 'high_coupling') return '#f97316'; if (raw.category === 'directory') return '#a855f7'; return '#71717a'; }} maskColor="rgba(9, 9, 11, 0.7)" style={{ backgroundColor: '#09090b', border: '1px solid #27272a' }} />
{/* Node Detail Panel */} {selectedNode && (
Node Analysis Detail
FILE PATH {selectedNode.id}
CATEGORY {selectedNode.category.replace('_', ' ')}
Degree {selectedNode.degree}
Centrality {selectedNode.centrality}
Legend:
  • Green: Entry execution point
  • Blue: Central hub class
  • Orange: High-coupling interface
  • Purple: Grouped directory
)}
); }; export const ArchitectureGraph: React.FC = (props) => { return ( ); };