import React, { useState, useEffect } from 'react'; import { apiUrl } from '../../lib/api'; import { FilePath } from '../ui/FilePath'; import { BookOpen, Clock, CheckCircle2, Circle, ArrowDown, Layers, Info, X, ExternalLink, MessageSquare, GitMerge, ChevronRight } from 'lucide-react'; interface ReadingOrderEntry { rank: number; file_path: string; reason: string; tier: string; score: number; } interface ReadingOrder { repo: string; ordered_files: ReadingOrderEntry[]; reasoning: string[]; estimated_reading_time: number; total_files_ranked: number; } interface FileSymbol { name: string; type: string; file_path: string; line_number: number; language: string; parent_class?: string | null; } interface FileDependencies { imports: string[]; importedBy: string[]; } type PanelDataState = 'idle' | 'loading' | 'ready' | 'unavailable'; interface TimelineProps { repoName: string; /** Sends a file-specific question to the Chat tab. */ onAskAboutFile?: (filePath: string) => void; /** Focuses the File Graph tab on this file's neighbourhood. */ onViewInGraph?: (filePath: string) => void; } export const ReadingOrderTimeline: React.FC = ({ repoName, onAskAboutFile, onViewInGraph, }) => { const [readingPath, setReadingPath] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); // Progress tracking states const [completedFiles, setCompletedFiles] = useState>({}); const [selectedFile, setSelectedFile] = useState(null); // File Intelligence panel enrichment const [symbols, setSymbols] = useState([]); const [symbolState, setSymbolState] = useState('idle'); const [deps, setDeps] = useState({ imports: [], importedBy: [] }); const [depsState, setDepsState] = useState('idle'); // 1. Fetch reading order data (lazy loaded on mount) useEffect(() => { setSelectedFile(null); setReadingPath(null); const fetchReadingOrder = async () => { setLoading(true); setError(null); try { const response = await fetch(apiUrl('/api/v1/reading-order'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ repo: repoName }) }); if (!response.ok) { throw new Error(await response.text() || 'Failed to fetch reading path'); } const data = await response.json(); setReadingPath(data); // 2. Load completed progress from localStorage const storageKey = `reading-path-${repoName}`; const storedProgress = localStorage.getItem(storageKey); if (storedProgress) { try { setCompletedFiles(JSON.parse(storedProgress)); } catch (e) { console.error('Failed to parse progress from localStorage', e); } } else { setCompletedFiles({}); } } catch (err: any) { console.error(err); setError(err.message || 'An error occurred generating the reading order.'); } finally { setLoading(false); } }; if (repoName) { fetchReadingOrder(); } }, [repoName]); /** * Enriches the File Intelligence panel for the selected file using existing * read-only endpoints: the symbol index and the dependency graph * neighbourhood. Both are optional — a 404 simply hides that section. */ useEffect(() => { const filePath = selectedFile?.file_path; const [owner, repo] = repoName.split('/'); if (!filePath || !owner || !repo) { setSymbols([]); setSymbolState('idle'); setDeps({ imports: [], importedBy: [] }); setDepsState('idle'); return; } const controller = new AbortController(); const encodedPath = filePath.split('/').map(encodeURIComponent).join('/'); setSymbolState('loading'); setDepsState('loading'); fetch(apiUrl(`/api/v1/symbols/${owner}/${repo}/file/${encodedPath}`), { signal: controller.signal }) .then((res) => { if (!res.ok) throw new Error('unavailable'); return res.json(); }) .then((data) => { setSymbols(Array.isArray(data?.symbols) ? data.symbols : []); setSymbolState('ready'); }) .catch((err) => { if (err?.name === 'AbortError') return; setSymbols([]); setSymbolState('unavailable'); }); fetch(apiUrl(`/api/v1/graph/${owner}/${repo}/neighbors/${encodedPath}`), { signal: controller.signal }) .then((res) => { if (!res.ok) throw new Error('unavailable'); return res.json(); }) .then((data) => { const edges: { source: string; target: string }[] = Array.isArray(data?.edges) ? data.edges : []; // Outgoing edges are this file's imports; incoming edges are its consumers. const imports = edges.filter((e) => e.source === filePath).map((e) => e.target); const importedBy = edges.filter((e) => e.target === filePath).map((e) => e.source); setDeps({ imports: Array.from(new Set(imports)).sort(), importedBy: Array.from(new Set(importedBy)).sort(), }); setDepsState('ready'); }) .catch((err) => { if (err?.name === 'AbortError') return; setDeps({ imports: [], importedBy: [] }); setDepsState('unavailable'); }); return () => controller.abort(); }, [selectedFile?.file_path, repoName]); // Handle step completion toggle const handleToggleComplete = (filePath: string) => { const updated = { ...completedFiles, [filePath]: !completedFiles[filePath] }; setCompletedFiles(updated); // Persist to localStorage const storageKey = `reading-path-${repoName}`; localStorage.setItem(storageKey, JSON.stringify(updated)); }; if (loading) { return (
Generating Reading Path...
); } if (error) { return (
{error}
); } if (!readingPath || !readingPath.ordered_files || readingPath.ordered_files.length === 0) { return (
No ranked source code files found for this repository.
); } const { ordered_files, estimated_reading_time } = readingPath; const totalFiles = ordered_files.length; // Calculate completed counts const completedCount = Object.keys(completedFiles).filter( (key) => completedFiles[key] && ordered_files.some((f) => f.file_path === key) ).length; const progressPct = totalFiles > 0 ? (completedCount / totalFiles) * 100 : 0; // Generate ASCII retro progress bar (15 character width) const totalBlocks = 15; const filledBlocks = Math.round((completedCount / totalFiles) * totalBlocks); const emptyBlocks = totalBlocks - filledBlocks; const asciiProgress = '█'.repeat(filledBlocks) + '░'.repeat(emptyBlocks); // Count metrics const entryPointsCount = ordered_files.filter((f) => f.tier === 'entry_point').length; const coreModulesCount = ordered_files.filter((f) => f.tier === 'core').length; // Dynamic estimated minutes per file calculation const getFileReadingTime = (score: number) => { return Math.max(1, Math.round(score / 20)); }; // Importance tier categorization const getImportanceLevel = (score: number) => { if (score > 100) return { label: 'Critical', color: 'text-emerald-400 border-emerald-500/20 bg-emerald-500/10' }; if (score > 50) return { label: 'Important', color: 'text-blue-400 border-blue-500/20 bg-blue-500/10' }; return { label: 'Optional', color: 'text-zinc-400 border-zinc-700 bg-zinc-800/50' }; }; return (
{/* Onboarding Guide Summary Panel */}

Repository Onboarding Guide

Calculated step-by-step reading flow prioritizing entry points and core library modules.

{estimated_reading_time} MIN TOTAL
{/* Metrics Grid */}
Recommended Files {totalFiles}
Est. Reading Time {estimated_reading_time}m
Entry Points {entryPointsCount}
Core Modules {coreModulesCount}
{/* Progress Tracker UX */}
Progress Tracking
{asciiProgress} {completedCount} / {totalFiles} Files Completed
{/* Visual HTML Progress Bar */}
{Math.round(progressPct)}%
{/* Dynamic Timeline steps */}
{ordered_files.map((entry, idx) => { const isCompleted = !!completedFiles[entry.file_path]; const estMinutes = getFileReadingTime(entry.score); const importance = getImportanceLevel(entry.score); return (
{/* Timeline node circle indicator */}
handleToggleComplete(entry.file_path)} > {isCompleted &&
}
{/* Timeline Step Header */}
Step {idx + 1}
{importance.label} Score: {entry.score.toFixed(2)}
{/* Timeline card panel */}
setSelectedFile(entry)} >
{entry.file_path} {entry.tier !== 'other' && ( {entry.tier.replace('_', ' ')} )}

{entry.reason}

{estMinutes} min
{/* Connecting Arrow (omitted on the last element) */} {idx < totalFiles - 1 && (
)}
); })}
{/* File Intelligence Drawer Panel */} {selectedFile && (
{/* Filename is the strongest element; everything else is telemetry */}
FILE INTELLIGENCE

{selectedFile.file_path.split('/').pop()}

PATH
{/* Importance and read time read as paired instrument values */}
IMPORTANCE {selectedFile.score.toFixed(2)}
READ TIME {getFileReadingTime(selectedFile.score)} min
CATEGORY {selectedFile.tier.replace('_', ' ')}
ARCHITECTURAL CONTEXT

{selectedFile.reason}

{/* Symbols defined in this file — from the AST symbol index */}
DEFINED SYMBOLS {symbolState === 'ready' && symbols.length > 0 && ( {symbols.length} )}
{symbolState === 'loading' && ( )}
); };