import React, { useState, useEffect, useRef, useCallback, useMemo, } from 'react'; import { Info, RefreshCw, GitBranch, Network, Layers, RotateCw, X } from 'lucide-react'; import { ReactFlowProvider, useReactFlow } from 'reactflow'; import { apiUrl, extractErrorMessage } from '../../../lib/api'; import { normalizeGraphPath, resolveGraphNode } from '../../../lib/graphPathUtils'; import { GraphCanvas } from './GraphCanvas'; import { GraphToolbar } from './GraphToolbar'; import { SearchBar } from './SearchBar'; import { NodeDetailsPanel } from './NodeDetailsPanel'; import { GraphFilterBar } from './GraphFilterBar'; import { GraphBreadcrumbNav } from './GraphBreadcrumbNav'; import { ArchitectureDiagramModal } from './ArchitectureDiagramModal'; import { GraphWorkspaceProvider, useGraphWorkspace } from './workspaceStore'; import { computeGraphStats } from './graphStats'; import { CATEGORY_COLORS, CATEGORY_LABELS } from './types'; import type { GraphNode, GraphEdge, GraphMode, GraphResponse } from './types'; import { EmptyState } from '../../ui/EmptyState'; import { Button } from '../../ui/Button'; // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- /** Build the fetch URL for each graph mode. */ function buildUrl( owner: string, repo: string, mode: GraphMode, focusNode: string | null, searchQuery: string, traceDir: 'forward' | 'backward' | 'both', ): string { const base = `/api/v1/graph/${owner}/${repo}`; switch (mode) { case 'neighbors': return apiUrl(`${base}/neighbors/${focusNode}`); case 'trace_fwd': return apiUrl(`${base}/trace/${focusNode}?direction=forward&depth=6`); case 'trace_bwd': return apiUrl(`${base}/trace/${focusNode}?direction=backward&depth=6`); case 'search': return apiUrl(`${base}/search?q=${encodeURIComponent(searchQuery)}`); case 'full': default: return searchQuery.trim() ? apiUrl(`${base}/full?q=${encodeURIComponent(searchQuery)}`) : apiUrl(`${base}/full`); } } // --------------------------------------------------------------------------- // Component // --------------------------------------------------------------------------- interface InteractiveDependencyGraphProps { repoName: string; /** * Externally requested focus target (e.g. "View in graph" from the reading * path). The `token` lets the same path be re-requested; bumping it re-runs * the focus even when the path is unchanged. */ focusRequest?: { path: string; token: number } | null; } /** * PH2-001 Interactive Dependency Graph orchestrator. * * Owns all state: mode, focusNode, searchQuery, selectedNode, graph data. * Delegates rendering to four sub-components: * GraphToolbar — mode buttons, fit/reset, status * SearchBar — debounced search input * GraphCanvas — React Flow canvas + Dagre layout * NodeDetailsPanel — right-side drawer */ const InteractiveDependencyGraphInner: React.FC< InteractiveDependencyGraphProps > = ({ repoName, focusRequest }) => { const { zoomIn, zoomOut, setViewport, getViewport, setCenter, fitView, getNodes } = useReactFlow(); const { selectNode } = useGraphWorkspace(); // ── Repo split ────────────────────────────────────────────────────────── const [owner, repo] = useMemo(() => { const parts = repoName.split('/'); return [parts[0] ?? '', parts[1] ?? '']; }, [repoName]); // ── Graph data state ──────────────────────────────────────────────────── const [apiNodes, setApiNodes] = useState([]); const [apiEdges, setApiEdges] = useState([]); const [matchCount, setMatchCount] = useState(null); // ── Interaction state ─────────────────────────────────────────────────── const [mode, setMode] = useState('full'); const [focusNode, setFocusNode] = useState(null); const [selectedNode, setSelectedNode] = useState(null); const [nonGraphFileTarget, setNonGraphFileTarget] = useState(null); const [searchQuery, setSearchQuery] = useState(''); const [traceDir, setTraceDir] = useState<'forward' | 'backward' | 'both'>('both'); // ── Request state ─────────────────────────────────────────────────────── const [loading, setLoading] = useState(false); const [error, setError] = useState(null); // ── Refs ───────────────────────────────────────────────────────────────── const fitViewRef = useRef<(() => void) | null>(null); const abortRef = useRef(null); const searchDebounceRef = useRef | null>(null); /** Holds a pending target file to resolve as soon as graph nodes become available. */ const pendingTargetRef = useRef(focusRequest?.path ?? null); // ── Centering and Selection Helpers ───────────────────────────────────── const centerOnNode = useCallback( (nodeId: string) => { let attempts = 0; const tryCenter = () => { attempts++; const nodes = getNodes(); const target = nodes.find((n) => n.id === nodeId); if (target && target.position) { const x = target.position.x + (target.width ?? 200) / 2; const y = target.position.y + (target.height ?? 40) / 2; setCenter(x, y, { zoom: 1.15, duration: 400 }); } else if (attempts < 10) { setTimeout(tryCenter, 60); } else { fitView({ padding: 0.15, duration: 300, minZoom: 0.15, maxZoom: 1.5 }); } }; setTimeout(tryCenter, 50); }, [getNodes, setCenter, fitView], ); const applyTargetSelection = useCallback( (targetPath: string, nodes: GraphNode[]) => { if (!targetPath || !nodes || nodes.length === 0) return; const decodedTarget = decodeURIComponent(targetPath); const match = resolveGraphNode(decodedTarget, nodes, repoName); if (match) { setNonGraphFileTarget(null); setSelectedNode(match); setFocusNode(match.id); selectNode(match.id); centerOnNode(match.id); pendingTargetRef.current = null; // Keep URL in sync with durable file parameter without reload if (typeof window !== 'undefined') { const url = new URL(window.location.href); url.searchParams.set('tab', 'graph'); url.searchParams.set('file', match.id); url.searchParams.delete('focus'); window.history.replaceState({}, '', url.toString()); window.dispatchEvent(new CustomEvent('aria-workspace-file-select', { detail: { path: match.id } })); } } else { // Node not in graph (e.g. documentation or non-indexed file) // Keep the graph fully rendered, set non-graph notice, and fit viewport setNonGraphFileTarget(decodedTarget); pendingTargetRef.current = null; setTimeout(() => fitView({ padding: 0.15, duration: 300, minZoom: 0.15, maxZoom: 1.5 }), 100); } }, [repoName, selectNode, centerOnNode, fitView], ); // ── Core fetch ─────────────────────────────────────────────────────────── const fetchGraph = useCallback( async ( fetchMode: GraphMode, focusId: string | null, query: string, dir: 'forward' | 'backward' | 'both', isOptionalEnrichment = false, ) => { if (!owner || !repo) return; if (!isOptionalEnrichment) { abortRef.current?.abort(); abortRef.current = new AbortController(); setLoading(true); setError(null); setMatchCount(null); } const url = buildUrl(owner, repo, fetchMode, focusId, query, dir); try { const res = await fetch(url, { signal: isOptionalEnrichment ? undefined : abortRef.current?.signal }); if (!res.ok) { let detail = `HTTP ${res.status}`; try { const body = await res.json(); detail = extractErrorMessage(body); } catch { /* ignore */ } if (isOptionalEnrichment) { // CRITICAL: Optional enrichment failure must NOT clear existing nodes! return; } setError(detail); setApiNodes([]); setApiEdges([]); return; } const data: GraphResponse = await res.json(); if (data.error) { if (isOptionalEnrichment) return; setError(data.error); setApiNodes([]); setApiEdges([]); return; } const receivedNodes = data.nodes ?? []; const receivedEdges = data.edges ?? []; setApiNodes(receivedNodes); setApiEdges(receivedEdges); if (data.matched_count !== undefined) { setMatchCount(data.matched_count); } // Asynchronously resolve pending focus target against loaded nodes if (pendingTargetRef.current) { applyTargetSelection(pendingTargetRef.current, receivedNodes); } else { setTimeout(() => fitView({ padding: 0.15, duration: 300, minZoom: 0.15, maxZoom: 1.5 }), 80); } } catch (err: any) { if (err.name === 'AbortError') return; if (isOptionalEnrichment) return; setError(extractErrorMessage(err)); setApiNodes([]); setApiEdges([]); } finally { if (!isOptionalEnrichment) { setLoading(false); } } }, [owner, repo, applyTargetSelection, fitView], ); const lastHandledTokenRef = useRef(focusRequest?.token ?? null); // ── Initial load: always fetch full repository graph first ──────────────── useEffect(() => { if (focusRequest?.path) { pendingTargetRef.current = focusRequest.path; lastHandledTokenRef.current = focusRequest.token; } setMode('full'); fetchGraph('full', null, '', 'both'); return () => abortRef.current?.abort(); }, [repoName]); // ── External focus request handling ─────────────────────────────────────── useEffect(() => { if (!focusRequest?.path || focusRequest.token === lastHandledTokenRef.current) return; lastHandledTokenRef.current = focusRequest.token; pendingTargetRef.current = focusRequest.path; if (apiNodes.length > 0) { applyTargetSelection(focusRequest.path, apiNodes); } }, [focusRequest?.token, focusRequest?.path, apiNodes, applyTargetSelection]); // ── Search debounce ────────────────────────────────────────────────────── const handleSearchChange = useCallback( (value: string) => { setSearchQuery(value); if (searchDebounceRef.current) clearTimeout(searchDebounceRef.current); searchDebounceRef.current = setTimeout(() => { if (value.trim()) { setMode('search'); setFocusNode(null); setSelectedNode(null); fetchGraph('search', null, value, 'both'); } else { setMode('full'); fetchGraph('full', null, '', 'both'); } }, 300); }, [fetchGraph], ); const handleSearchClear = useCallback(() => { setSearchQuery(''); setMatchCount(null); setMode('full'); fetchGraph('full', null, '', 'both'); }, [fetchGraph]); // ── Toolbar actions ────────────────────────────────────────────────────── const handleExpand = useCallback(() => { if (!focusNode) return; setMode('neighbors'); setTraceDir('both'); fetchGraph('neighbors', focusNode, '', 'both'); }, [focusNode, fetchGraph]); const handleTraceForward = useCallback( (nodeId?: string) => { const id = nodeId ?? focusNode; if (!id) return; setFocusNode(id); setMode('trace_fwd'); setTraceDir('forward'); fetchGraph('trace_fwd', id, '', 'forward'); }, [focusNode, fetchGraph], ); const handleTraceBackward = useCallback( (nodeId?: string) => { const id = nodeId ?? focusNode; if (!id) return; setFocusNode(id); setMode('trace_bwd'); setTraceDir('backward'); fetchGraph('trace_bwd', id, '', 'backward'); }, [focusNode, fetchGraph], ); const handleTraceBoth = useCallback( (nodeId?: string) => { const id = nodeId ?? focusNode; if (!id) return; setFocusNode(id); // Reuse trace_fwd mode key — backend gets direction=both setMode('trace_fwd'); setTraceDir('both'); fetchGraph('trace_fwd', id, '', 'both'); }, [focusNode, fetchGraph], ); const handlePanUp = useCallback(() => { const { x, y, zoom } = getViewport(); setViewport({ x, y: y + 150, zoom }, { duration: 200 }); }, [getViewport, setViewport]); const handlePanDown = useCallback(() => { const { x, y, zoom } = getViewport(); setViewport({ x, y: y - 150, zoom }, { duration: 200 }); }, [getViewport, setViewport]); const handlePanLeft = useCallback(() => { const { x, y, zoom } = getViewport(); setViewport({ x: x + 150, y, zoom }, { duration: 200 }); }, [getViewport, setViewport]); const handlePanRight = useCallback(() => { const { x, y, zoom } = getViewport(); setViewport({ x: x - 150, y, zoom }, { duration: 200 }); }, [getViewport, setViewport]); const handleZoomIn = useCallback(() => { zoomIn({ duration: 200 }); }, [zoomIn]); const handleZoomOut = useCallback(() => { zoomOut({ duration: 200 }); }, [zoomOut]); const handleCenterGraph = useCallback(() => { const nodes = getNodes(); if (nodes.length > 0) { let minX = Infinity; let maxX = -Infinity; let minY = Infinity; let maxY = -Infinity; nodes.forEach((node) => { const x = node.position.x; const y = node.position.y; const w = node.width ?? 200; const h = node.height ?? 40; if (x < minX) minX = x; if (x + w > maxX) maxX = x + w; if (y < minY) minY = y; if (y + h > maxY) maxY = y + h; }); const centerX = minX + (maxX - minX) / 2; const centerY = minY + (maxY - minY) / 2; const { zoom } = getViewport(); setCenter(centerX, centerY, { zoom, duration: 200 }); } }, [getNodes, getViewport, setCenter]); const handleReset = useCallback(() => { setMode('full'); setFocusNode(null); setSelectedNode(null); setSearchQuery(''); setMatchCount(null); fetchGraph('full', null, '', 'both'); setTimeout(() => { fitView({ padding: 0.15, duration: 200, minZoom: 0.15, maxZoom: 1.5 }); }, 100); }, [fetchGraph, fitView]); const handleFitView = useCallback(() => { fitView({ padding: 0.15, duration: 200, minZoom: 0.15, maxZoom: 1.5 }); }, [fitView]); // ── Node selection ──────────────────────────────────────────────────────── const handleNodeSelect = useCallback( (node: GraphNode | null) => { setNonGraphFileTarget(null); setSelectedNode(node); if (node) { setFocusNode(node.id); selectNode(node.id); if (typeof window !== 'undefined') { const url = new URL(window.location.href); url.searchParams.set('tab', 'graph'); url.searchParams.set('file', node.id); url.searchParams.delete('focus'); window.history.replaceState({}, '', url.toString()); window.dispatchEvent(new CustomEvent('aria-workspace-file-select', { detail: { path: node.id } })); } } else { setFocusNode(null); selectNode(null); if (typeof window !== 'undefined') { const url = new URL(window.location.href); url.searchParams.delete('file'); url.searchParams.delete('focus'); window.history.replaceState({}, '', url.toString()); window.dispatchEvent(new CustomEvent('aria-workspace-file-select', { detail: { path: null } })); } } }, [selectNode], ); // Compute lightweight stats client-side over current view const stats = useMemo(() => computeGraphStats(apiNodes, apiEdges), [apiNodes, apiEdges]); // Diagram Modal state const [diagramModalNodeId, setDiagramModalNodeId] = useState(null); // ── Render ──────────────────────────────────────────────────────────────── return (
{/* Editorial Technical Header */}
FILE GRAPH / REPOSITORY TOPOLOGY
{apiNodes.length.toLocaleString()} NODES · {apiEdges.length.toLocaleString()} EDGES {stats.components > 0 && ( <> · {stats.components} COMPONENTS )} · DIRECTED
{/* Compact Legend */}
Entry Module Coupled Focus
{/* Filter Bar & Breadcrumb Navigation */} {/* ── Toolbar ─────────────────────────────────────────────────── */} handleTraceForward()} onTraceBackward={() => handleTraceBackward()} onTraceBoth={() => handleTraceBoth()} onNeighbors={handleExpand} onPanUp={handlePanUp} onPanDown={handlePanDown} onPanLeft={handlePanLeft} onPanRight={handlePanRight} onZoomIn={handleZoomIn} onZoomOut={handleZoomOut} onCenterGraph={handleCenterGraph} /> {/* ── Main canvas area ─────────────────────────────────────────── */}
{/* Loading overlay */} {loading && (
)} {/* Error overlay */} {!loading && error && (
)} {/* Empty state */} {!loading && !error && apiNodes.length === 0 && (
)} {/* React Flow canvas */}
{/* Compact instruction hint when no node is selected */} {!selectedNode && !nonGraphFileTarget && apiNodes.length > 0 && (
Select any node to open Architecture Inspector
)} {/* Non-graph file drawer notice */} {nonGraphFileTarget && !selectedNode && (
Topology Notice

{nonGraphFileTarget.split('/').pop() || nonGraphFileTarget}

{nonGraphFileTarget}
File Not Represented in Topology

This file exists in the repository but does not import or export code modules in the structural AST dependency graph (e.g. documentation, static assets, or configs).

The full repository dependency graph remains rendered and interactive. Click any graph node to inspect its architectural properties.

)} {/* Node details panel */} {selectedNode && ( handleNodeSelect(null)} onExpand={(id) => { setFocusNode(id); setMode('neighbors'); fetchGraph('neighbors', id, '', 'both', true); }} onTraceForward={handleTraceForward} onTraceBackward={handleTraceBackward} onTraceBoth={handleTraceBoth} onOpenDiagramModal={(id) => setDiagramModalNodeId(id)} onSelectNode={(id) => { const match = resolveGraphNode(id, apiNodes, repoName) || { id, label: id.split('/').pop() || id, category: 'regular', degree: 1, centrality: 0.1, language: 'typescript', highlighted: false, is_focus: true, }; handleNodeSelect(match); centerOnNode(match.id); }} /> )} {/* Diagram exporter modal */} {diagramModalNodeId && ( setDiagramModalNodeId(null)} /> )}
); }; export const InteractiveDependencyGraph: React.FC< InteractiveDependencyGraphProps > = (props) => { return ( ); }; interface StatPillProps { icon: React.ReactNode; label: string; value: number | string; tone?: 'neutral' | 'danger'; } const StatPill: React.FC = ({ icon, label, value, tone = 'neutral' }) => ( {label} {value} ); export default InteractiveDependencyGraph; // Interactive dependency graph entry point