Files
RepoPulse-Public/frontend/src/App.tsx
T
Public Source Publisher 787a2b1dc3 RepoPulse: update frontend/src and backend/app (+4 areas)
Public changes compared with the previous published export:
19 files changed.

Affected areas:
- backend/app: 3 files
- dependencies: 2 files
- documentation: 1 file
- frontend: 2 files
- frontend/src: 10 files
- tests: 1 file

Changed files:
- Updated: "backend/app/acquisition.py"
- Added: "backend/app/icons.py"
- Updated: "backend/app/main.py"
- Added: "backend/tests/test_icons.py"
- Updated: "docs/ARCHITECTURE.md"
- Updated: "frontend/package-lock.json"
- Updated: "frontend/package.json"
- Updated: "frontend/playwright.config.ts"
- Updated: "frontend/src/App.tsx"
- Updated: "frontend/src/components/DashboardView.tsx"
- Added: "frontend/src/components/HealthRing.tsx"
- Updated: "frontend/src/components/HistoryView.tsx"
- Added: "frontend/src/components/Icon.tsx"
- Updated: "frontend/src/components/PortfolioAtlas.tsx"
- Updated: "frontend/src/components/RemediationCenter.tsx"
- Added: "frontend/src/components/RepoAvatar.tsx"
- Updated: "frontend/src/main.tsx"
- Updated: "frontend/src/styles.css"
- Updated: "frontend/vite.config.ts"

Export provenance/manifests refreshed; excluded from the change summary.

Publish curated RepoPulse source from 7a60c53ee2c1daebecd66a01656e323f1db72e56
2026-11-20 04:45:33 +00:00

194 lines
47 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { type FormEvent, lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { api, type AppMeta, type RepositorySummary, type ScanComparison, type ScanJob, type ScanReport, type ScanSummary, type TrendPoint } from './api'
import { filterRepositories, orderSwitcherRepositories, paginateRepositories, readinessLabel, repositoryReadiness, sortRepositories, stateLabel, type CatalogFilters, type CatalogSort, type CatalogSortKey, type Readiness } from './catalog'
import { BrandLockup, BrandMark } from './components/Brand'
import { Icon, type IconName } from './components/Icon'
import { HealthRing } from './components/HealthRing'
import { RepoAvatar } from './components/RepoAvatar'
import { DashboardView } from './components/DashboardView'
import { DependenciesView } from './components/DependenciesView'
import { FindingsView } from './components/FindingsView'
import { HistoryView } from './components/HistoryView'
import { HotspotsView } from './components/HotspotsView'
import { OverviewView } from './components/OverviewView'
import { RepositoryVisual } from './components/RepositoryVisual'
import { ScanRunsView } from './components/ScanRunsView'
import { DETAIL_VIEWS, parseRoute, routePath, type DetailView, type Route } from './navigation'
// React Flow is only needed on the Architecture tab; keep it out of the initial bundle.
const ArchitectureView = lazy(() => import('./components/ArchitectureView').then((module) => ({ default: module.ArchitectureView })))
const ACTIVE_JOB_STATES: ScanJob['status'][] = ['queued', 'acquiring_source', 'scanning', 'analyzing', 'persisting']
const PINNED_STORAGE_KEY = 'repopulse:pinned-repositories'
const RECENT_STORAGE_KEY = 'repopulse:recent-repositories'
const CATALOG_VIEW_STORAGE_KEY = 'repopulse:catalog-view'
const DEFAULT_FILTERS: CatalogFilters = { query: '', state: 'all', readiness: 'all', owner: 'all', branch: 'all', visibility: 'all', archived: 'active' }
function readIdList(key: string) {
try {
const parsed = JSON.parse(window.localStorage.getItem(key) ?? '[]')
return Array.isArray(parsed) ? parsed.filter((value): value is string => typeof value === 'string') : []
} catch { return [] }
}
function readCatalogView(): 'table' | 'grid' {
try { return window.localStorage.getItem(CATALOG_VIEW_STORAGE_KEY) === 'grid' ? 'grid' : 'table' } catch { return 'table' }
}
function writeIdList(key: string, ids: string[]) { try { window.localStorage.setItem(key, JSON.stringify(ids)) } catch { /* preferences are best effort */ } }
function shortRevision(revision: string | null) { return revision ? revision.slice(0, 10) : 'not acquired' }
function statusClass(value: string) { return value.replace(/_/g, '-') }
function formatDate(value: string | null) { if (!value) return 'Never'; const date = new Date(value); return Number.isNaN(date.getTime()) ? 'Unknown' : date.toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) }
function formatRelativeDate(value: string | null) { if (!value) return 'Never scanned'; const difference = Date.now() - new Date(value).getTime(); if (Number.isNaN(difference)) return 'Unknown'; if (difference < 3_600_000) return `${Math.max(1, Math.floor(difference / 60_000))}m ago`; if (difference < 86_400_000) return `${Math.floor(difference / 3_600_000)}h ago`; return `${Math.floor(difference / 86_400_000)}d ago` }
function downloadText(filename: string, content: string, mime: string) { const url = URL.createObjectURL(new Blob([content], { type: mime })); const anchor = document.createElement('a'); anchor.href = url; anchor.download = filename; anchor.style.display = 'none'; document.body.appendChild(anchor); anchor.click(); window.setTimeout(() => { anchor.remove(); URL.revokeObjectURL(url) }, 0) }
function reportFilename(repositoryName: string, format: 'html' | 'json') { const safeName = repositoryName.replace(/[\u0000-\u001f\u007f<>:"/\\|?*]/g, '_').replace(/[ .]+$/g, '').slice(0, 100).replace(/[ .]+$/g, '') || 'repository'; return `repopulse-${safeName}.${format}` }
function detailViewLabel(view: DetailView, report: ScanReport | null) { if (view === 'overview') return 'Overview'; if (view === 'findings') return report ? `Findings (${report.findings.filter((finding) => !finding.suppressed).length})` : 'Findings'; if (view === 'architecture') return report ? `Architecture (${report.architecture.nodes.length})` : 'Architecture'; if (view === 'hotspots') return report ? `Hotspots (${report.hotspots.length})` : 'Hotspots'; if (view === 'dependencies') return 'Dependencies'; if (view === 'history') return 'History'; return 'Scan runs' }
export default function App() {
const [route, setRoute] = useState<Route>(() => parseRoute(window.location.pathname))
const [repositories, setRepositories] = useState<RepositorySummary[]>([])
const [catalogLoading, setCatalogLoading] = useState(true)
const [selectedDetailsLoading, setSelectedDetailsLoading] = useState(false)
const [scanSummaries, setScanSummaries] = useState<ScanSummary[]>([])
const [report, setReport] = useState<ScanReport | null>(null)
const [comparison, setComparison] = useState<ScanComparison | null>(null)
const [trend, setTrend] = useState<TrendPoint[]>([])
const [path, setPath] = useState('')
const [job, setJob] = useState<ScanJob | null>(null)
const [meta, setMeta] = useState<AppMeta | null>(null)
const [standaloneReport, setStandaloneReport] = useState<ScanReport | null>(null)
const [pinnedIds, setPinnedIds] = useState<string[]>(() => readIdList(PINNED_STORAGE_KEY))
const [recentIds, setRecentIds] = useState<string[]>(() => readIdList(RECENT_STORAGE_KEY))
const [catalogFilters, setCatalogFilters] = useState<CatalogFilters>(DEFAULT_FILTERS)
const [catalogSort, setCatalogSort] = useState<CatalogSort>({ key: 'name', direction: 'asc' })
const [catalogPage, setCatalogPage] = useState(1)
const [catalogPageSize, setCatalogPageSize] = useState(24)
const [catalogView, setCatalogView] = useState<'table' | 'grid'>(readCatalogView)
const [busy, setBusy] = useState(false)
const [catalogBusy, setCatalogBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
const [notice, setNotice] = useState<string | null>(null)
const [switcherOpen, setSwitcherOpen] = useState(false)
const [switcherQuery, setSwitcherQuery] = useState('')
const [switcherIndex, setSwitcherIndex] = useState(0)
const [advancedOpen, setAdvancedOpen] = useState(false)
const switcherInputRef = useRef<HTMLInputElement>(null)
const selectedId = route.repositoryId ?? null
const selectedRepository = useMemo(() => repositories.find((repository) => repository.id === selectedId) ?? null, [repositories, selectedId])
const activeJob = job && job.repository_id === selectedId && ACTIVE_JOB_STATES.includes(job.status) ? job : null
const navigate = useCallback((next: Route, replace = false) => { const href = routePath(next); if (window.location.pathname !== href) window.history[replace ? 'replaceState' : 'pushState']({}, '', href); setRoute(next); setAdvancedOpen(false); window.scrollTo?.({ top: 0, behavior: 'auto' }) }, [])
const handleNavigation = useCallback((event: React.MouseEvent<HTMLAnchorElement>, next: Route) => { if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; event.preventDefault(); navigate(next) }, [navigate])
const refreshCatalog = useCallback(async () => { const next = await api.repositories(); setRepositories(next); return next }, [])
const refreshMeta = useCallback(async () => { try { setMeta(await api.meta()) } catch { /* catalog navigation must remain usable */ } }, [])
useEffect(() => {
const onPopState = () => setRoute(parseRoute(window.location.pathname))
window.addEventListener('popstate', onPopState)
void (async () => { setCatalogLoading(true); try { await refreshCatalog() } catch { try { const legacy = await api.recent(); setStandaloneReport(legacy[0] ?? null); setPath(legacy[0]?.repository_path ?? ''); setError(legacy.length ? 'Repository catalog is unavailable; showing the last local report in Settings.' : 'Could not load the repository catalog.') } catch (err) { setError(err instanceof Error ? err.message : 'Could not load the repository catalog.') } } finally { setCatalogLoading(false) } })()
void refreshMeta()
return () => window.removeEventListener('popstate', onPopState)
}, [refreshCatalog, refreshMeta])
useEffect(() => { document.title = route.page === 'dashboard' ? 'RepoPulse — Portfolio intelligence' : 'RepoPulse — Repository intelligence' }, [route.page])
useEffect(() => {
if (!selectedId) { setReport(null); setScanSummaries([]); setTrend([]); setComparison(null); setSelectedDetailsLoading(false); return }
let live = true
setSelectedDetailsLoading(true); setReport(null); setComparison(null); setTrend([])
void Promise.all([api.repository(selectedId), api.repositoryScans(selectedId), api.repositoryTrend(selectedId)]).then(([detail, summaries, nextTrend]) => { if (!live) return; setScanSummaries(summaries); setTrend(nextTrend); setReport(detail.latest_scan); setError(null); if (detail.latest_scan?.repository_path) setPath(detail.latest_scan.repository_path) }).catch((err) => { if (live) setError(err instanceof Error ? err.message : 'Could not load repository details.') }).finally(() => { if (live) setSelectedDetailsLoading(false) })
return () => { live = false }
}, [selectedId])
useEffect(() => { if (!report) { setComparison(null); return }; let live = true; void api.comparison(report.id).then((next) => { if (live) setComparison(next) }).catch(() => { if (live) setComparison(null) }); return () => { live = false } }, [report])
useEffect(() => { if (!selectedRepository?.active_job_id || job?.id === selectedRepository.active_job_id) return; let live = true; void api.scanJob(selectedRepository.active_job_id).then((next) => { if (live) setJob(next) }).catch(() => undefined); return () => { live = false } }, [job?.id, selectedRepository])
useEffect(() => {
const jobId = activeJob?.id
if (!jobId || !selectedId) return
let live = true
let failures = 0
let timer: number | undefined
const poll = async () => {
try {
const next = await api.scanJob(jobId)
if (!live) return
failures = 0
if (next.status === 'completed' && next.scan_id) {
const nextReport = await api.repositoryScan(next.repository_id, next.scan_id)
if (!live) return
const [summaries, nextTrend] = await Promise.all([api.repositoryScans(next.repository_id), api.repositoryTrend(next.repository_id)])
if (!live) return
await refreshCatalog()
if (!live) return
setJob(next)
setReport(nextReport)
setScanSummaries(summaries)
setTrend(nextTrend)
setNotice(next.deduplicated ? 'The selected revision was already analyzed; showing the existing report.' : 'Repository analysis completed.')
return
}
setJob(next)
if (next.status === 'failed') { setError(next.error_detail || 'Repository analysis failed.'); return }
} catch (err) {
failures += 1
if (!live) return
if (failures >= 5) { setError(err instanceof Error ? `${err.message} Progress polling paused after five failed attempts.` : 'Progress polling paused after five failed attempts.'); return }
}
if (live) timer = window.setTimeout(() => void poll(), 1500)
}
void poll()
return () => { live = false; if (timer) window.clearTimeout(timer) }
}, [activeJob?.id, refreshCatalog, selectedId])
useEffect(() => { if (selectedId) setRecentIds((current) => [selectedId, ...current.filter((id) => id !== selectedId)].slice(0, 8)) }, [selectedId])
useEffect(() => writeIdList(PINNED_STORAGE_KEY, pinnedIds), [pinnedIds])
useEffect(() => writeIdList(RECENT_STORAGE_KEY, recentIds), [recentIds])
useEffect(() => { try { window.localStorage.setItem(CATALOG_VIEW_STORAGE_KEY, catalogView) } catch { /* preference only */ } }, [catalogView])
const filteredRepositories = useMemo(() => filterRepositories(repositories, catalogFilters), [catalogFilters, repositories])
const sortedRepositories = useMemo(() => sortRepositories(filteredRepositories, catalogSort), [catalogSort, filteredRepositories])
const catalogWindow = useMemo(() => paginateRepositories(sortedRepositories, catalogPage, catalogPageSize), [catalogPage, catalogPageSize, sortedRepositories])
const ownerOptions = useMemo(() => [...new Set(repositories.map((repository) => repository.owner))].sort(), [repositories])
const branchOptions = useMemo(() => [...new Set(repositories.map((repository) => repository.default_branch))].sort(), [repositories])
const switcherRepositories = useMemo(() => orderSwitcherRepositories(repositories, pinnedIds, recentIds, switcherQuery), [pinnedIds, recentIds, repositories, switcherQuery])
const currentView = route.view ?? 'overview'
useEffect(() => { if (catalogPage !== catalogWindow.page) setCatalogPage(catalogWindow.page) }, [catalogPage, catalogWindow.page])
useEffect(() => { if (switcherOpen) { setSwitcherIndex(0); window.requestAnimationFrame(() => switcherInputRef.current?.focus()) } }, [switcherOpen])
useEffect(() => { const onKeyDown = (event: KeyboardEvent) => { if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') { event.preventDefault(); setSwitcherOpen(true); return }; if (!switcherOpen) return; if (event.key === 'Escape') { event.preventDefault(); setSwitcherOpen(false) } else if (event.key === 'ArrowDown') { event.preventDefault(); setSwitcherIndex((index) => Math.min(index + 1, Math.max(0, switcherRepositories.length - 1))) } else if (event.key === 'ArrowUp') { event.preventDefault(); setSwitcherIndex((index) => Math.max(0, index - 1)) } else if (event.key === 'Enter' && switcherRepositories[switcherIndex]) { event.preventDefault(); selectRepository(switcherRepositories[switcherIndex]); setSwitcherOpen(false) } }; window.addEventListener('keydown', onKeyDown); return () => window.removeEventListener('keydown', onKeyDown) }, [switcherIndex, switcherOpen, switcherRepositories])
const selectRepository = (repository: RepositorySummary) => { setError(null); setNotice(null); navigate({ page: 'repositories', repositoryId: repository.id, view: 'overview' }) }
const togglePinned = (repositoryId: string) => setPinnedIds((current) => current.includes(repositoryId) ? current.filter((id) => id !== repositoryId) : [repositoryId, ...current])
const exploreReadiness = (readiness: Readiness) => { setCatalogFilters({ ...DEFAULT_FILTERS, readiness }); setCatalogPage(1); navigate({ page: 'repositories' }) }
const updateCatalogFilter = <K extends keyof CatalogFilters>(key: K, value: CatalogFilters[K]) => { setCatalogFilters((current) => ({ ...current, [key]: value })); setCatalogPage(1) }
const setCatalogSortKey = (key: CatalogSortKey) => { setCatalogSort((current) => current.key === key ? { key, direction: current.direction === 'asc' ? 'desc' : 'asc' } : { key, direction: key === 'name' || key === 'state' ? 'asc' : 'desc' }); setCatalogPage(1) }
const analyzeRepository = async (repository: RepositorySummary, force = false) => { try { setBusy(true); setError(null); setNotice(null); const next = await api.enqueueRepositoryScan(repository.id, force); setJob(next); setNotice(next.deduplicated ? 'This revision is already in the analysis history.' : 'Analysis queued. Progress will update here.'); if (next.status === 'completed' && next.scan_id) setReport(await api.repositoryScan(repository.id, next.scan_id)) } catch (err) { setError(err instanceof Error ? err.message : 'Could not queue repository analysis.') } finally { setBusy(false) } }
const syncCatalog = async () => { try { setCatalogBusy(true); setError(null); const result = await api.syncRepositories(); await Promise.all([refreshCatalog(), refreshMeta()]); setNotice(result.partial ? `Gitea catalog partially synchronized: ${result.discovered} resolved, ${result.branch_failures ?? 0} branch lookup failure(s). Existing repository evidence was preserved.` : `Gitea catalog synchronized: ${result.discovered} repositories discovered.`) } catch (err) { setError(err instanceof Error ? err.message : 'Gitea catalog synchronization failed.') } finally { setCatalogBusy(false) } }
const scanLocal = async (event: FormEvent) => { event.preventDefault(); try { setBusy(true); setError(null); setNotice(null); const next = await api.scan(path); setStandaloneReport(next); setPath(next.repository_path); await refreshCatalog(); setNotice(`Local analysis completed in ${next.duration_ms} ms. The result is available in Settings.`); navigate({ page: 'settings' }) } catch (err) { setError(err instanceof Error ? err.message : 'Local repository analysis failed.') } finally { setBusy(false) } }
const selectScan = async (summary: ScanSummary) => { try { setBusy(true); setError(null); setReport(await api.repositoryScan(summary.repository_id, summary.id)); navigate({ page: 'repositories', repositoryId: summary.repository_id, view: 'overview' }) } catch (err) { setError(err instanceof Error ? err.message : 'Could not load the selected scan.') } finally { setBusy(false) } }
const exportReport = async (format: 'html' | 'json') => { if (!report) return; try { downloadText(reportFilename(report.repository_name, format), await api.exportReport(report.id, format), format === 'html' ? 'text/html' : 'application/json') } catch (err) { setError(err instanceof Error ? err.message : 'Report export failed.') } }
const navItems: { page: Route['page']; label: string; href: string; icon: IconName; count?: number }[] = [
{ page: 'dashboard', label: 'Dashboard', href: '/', icon: 'dashboard' },
{ page: 'repositories', label: 'Repositories', href: '/repositories', icon: 'repositories', count: repositories.length },
{ page: 'activity', label: 'Activity', href: '/activity', icon: 'activity' },
{ page: 'queue', label: 'Scan queue', href: '/queue', icon: 'queue', count: repositories.filter((repository) => repository.active_job_id || repository.state === 'queued' || repository.state === 'scanning').length || undefined },
{ page: 'settings', label: 'Settings', href: '/settings', icon: 'settings' },
]
const lastSync = meta?.gitea.last_sync && typeof meta.gitea.last_sync === 'object' && 'synced_at' in meta.gitea.last_sync ? String(meta.gitea.last_sync.synced_at) : null
const renderGlobalNav = () => <nav className="global-nav" aria-label="Primary navigation">{navItems.map((item) => <a key={item.page} className={route.page === item.page ? 'active' : ''} aria-current={route.page === item.page ? 'page' : undefined} href={item.href} title={item.label} onClick={(event) => handleNavigation(event, { page: item.page })}><Icon name={item.icon} size={18} /><span className="nav-label">{item.label}</span>{item.count != null && <span className="nav-count">{item.count || '—'}</span>}</a>)}</nav>
const renderSidebar = () => <aside className="sidebar"><a className="brand-home" href="/" onClick={(event) => handleNavigation(event, { page: 'dashboard' })} aria-label="RepoPulse dashboard"><BrandLockup /></a>{renderGlobalNav()}<div className="sidebar-footer"><span className={`live-dot ${meta?.gitea.configured ? 'ok' : 'unknown'}`} aria-hidden="true" /><span><strong>{meta?.gitea.configured ? 'Gitea connected' : meta ? 'Gitea not configured' : 'Connecting…'}</strong><small>{lastSync ? `Synced ${formatRelativeDate(lastSync)}` : 'No sync recorded'}{meta?.version ? ` · v${meta.version}` : ''}</small></span></div></aside>
const renderTopbar = () => <header className="app-header"><a className="brand-home mobile-brand" href="/" onClick={(event) => handleNavigation(event, { page: 'dashboard' })} aria-label="RepoPulse home"><BrandLockup compact /></a><button className="shortcut-button" type="button" onClick={() => setSwitcherOpen(true)} aria-keyshortcuts="Control+K Meta+K"><Icon name="search" /><span>Quick switch</span><kbd>Ctrl K</kbd></button><div className="header-actions"><button className="ghost sync-button" type="button" onClick={() => void syncCatalog()} disabled={catalogBusy} aria-label="Synchronize Gitea catalog" title="Synchronize Gitea catalog"><Icon name="refresh" className={catalogBusy ? 'spin' : ''} /><span>{catalogBusy ? 'Syncing…' : 'Sync'}</span></button></div></header>
const renderCatalogPage = () => <section className="page-content explorer-page" aria-labelledby="repositories-title"><div className="page-heading"><div><h1 id="repositories-title">Repositories <span className="count-badge">{repositories.length}</span></h1><p className="muted">Every repository RepoPulse discovered in Gitea, with its latest retained scan.</p></div><div className="page-heading-actions"><button type="button" onClick={() => void syncCatalog()} disabled={catalogBusy}><Icon name="refresh" className={catalogBusy ? 'spin' : ''} />{catalogBusy ? 'Syncing…' : 'Sync Gitea catalog'}</button></div></div><section className="catalog-toolbar section-card" aria-label="Repository filters"><div className="search-control"><span className="search-glyph" aria-hidden="true"><Icon name="search" /></span><label className="sr-only" htmlFor="catalog-search">Search repositories</label><input id="catalog-search" value={catalogFilters.query} onChange={(event) => updateCatalogFilter('query', event.target.value)} placeholder="Search name, owner or full name" /></div><div className="filter-grid"><label>State<select aria-label="Filter by state" value={catalogFilters.state} onChange={(event) => updateCatalogFilter('state', event.target.value as CatalogFilters['state'])}><option value="all">All states</option><option value="current">Current</option><option value="stale">Stale</option><option value="scanning">Scanning</option><option value="failed">Failed</option><option value="never_scanned">Never scanned</option><option value="archived">Archived</option></select></label><label>Readiness<select aria-label="Filter by readiness" value={catalogFilters.readiness} onChange={(event) => updateCatalogFilter('readiness', event.target.value as CatalogFilters['readiness'])}><option value="all">All readiness</option><option value="ready">Ready</option><option value="warnings">Warnings</option><option value="blocked">Blocked</option></select></label><label>Owner<select aria-label="Filter by owner" value={catalogFilters.owner} onChange={(event) => updateCatalogFilter('owner', event.target.value)}><option value="all">All owners</option>{ownerOptions.map((owner) => <option key={owner} value={owner}>{owner}</option>)}</select></label><label>Branch<select aria-label="Filter by branch" value={catalogFilters.branch} onChange={(event) => updateCatalogFilter('branch', event.target.value)}><option value="all">All branches</option>{branchOptions.map((branch) => <option key={branch} value={branch}>{branch}</option>)}</select></label><label>Visibility<select aria-label="Filter by visibility" value={catalogFilters.visibility} onChange={(event) => updateCatalogFilter('visibility', event.target.value as CatalogFilters['visibility'])}><option value="all">Any visibility</option><option value="private">Private</option><option value="public">Public</option></select></label><label>Lifecycle<select aria-label="Filter by lifecycle" value={catalogFilters.archived} onChange={(event) => updateCatalogFilter('archived', event.target.value as CatalogFilters['archived'])}><option value="active">Active only</option><option value="all">Active and archived</option><option value="archived">Archived only</option></select></label></div><div className="toolbar-footer"><span className="filter-result">{filteredRepositories.length} matching {repositories.length} repositories</span><div className="view-toggle" aria-label="Repository view"><button className={catalogView === 'table' ? 'active' : ''} type="button" onClick={() => setCatalogView('table')} aria-pressed={catalogView === 'table'}>Table</button><button className={catalogView === 'grid' ? 'active' : ''} type="button" onClick={() => setCatalogView('grid')} aria-pressed={catalogView === 'grid'}>Visual grid</button></div><button className="text-button" type="button" onClick={() => { setCatalogFilters(DEFAULT_FILTERS); setCatalogPage(1) }}>Reset filters</button></div></section>{catalogLoading ? <section className="catalog-loading" aria-label="Loading repository catalog"><span /><span /><span /><span /></section> : catalogWindow.items.length ? <>{catalogView === 'table' ? <section className="catalog-table-card section-card" aria-label="Repository catalog results"><div className="table-scroll"><table className="repository-table"><thead><tr><th><button className="sort-button" type="button" onClick={() => setCatalogSortKey('name')}>Repository <span>{catalogSort.key === 'name' ? catalogSort.direction === 'asc' ? '↑' : '↓' : '↕'}</span></button></th><th><button className="sort-button" type="button" onClick={() => setCatalogSortKey('state')}>State <span>{catalogSort.key === 'state' ? catalogSort.direction === 'asc' ? '↑' : '↓' : '↕'}</span></button></th><th>Readiness</th><th>Branch</th><th><button className="sort-button" type="button" onClick={() => setCatalogSortKey('last_scan')}>Last scan <span>{catalogSort.key === 'last_scan' ? catalogSort.direction === 'asc' ? '↑' : '↓' : '↕'}</span></button></th><th><button className="sort-button" type="button" onClick={() => setCatalogSortKey('health')}>Health <span>{catalogSort.key === 'health' ? catalogSort.direction === 'asc' ? '↑' : '↓' : '↕'}</span></button></th></tr></thead><tbody>{catalogWindow.items.map((repository) => { const readiness = repositoryReadiness(repository); const pinned = pinnedIds.includes(repository.id); return <tr key={repository.id} role="link" tabIndex={0} aria-label={`Open ${repository.full_name}`} onClick={() => selectRepository(repository)} onKeyDown={(event) => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); selectRepository(repository) } }}><td><div className="repo-cell"><button className={`star-button ${pinned ? 'pinned' : ''}`} type="button" onClick={(event) => { event.stopPropagation(); togglePinned(repository.id) }} aria-label={pinned ? `Remove ${repository.full_name} from pinned repositories` : `Pin ${repository.full_name}`} aria-pressed={pinned}><span aria-hidden="true">{pinned ? '★' : '☆'}</span></button><RepoAvatar repository={repository} size="sm" /><div><strong className="repo-link">{repository.full_name}</strong><small>{repository.private ? 'Private' : 'Public'} · {repository.provider} · {repository.archived ? 'Archived' : 'Active'}</small></div></div></td><td><span className={`status-label status-${statusClass(repository.state)}`}><i aria-hidden="true" />{stateLabel(repository.state)}</span></td><td><span className={`readiness-label readiness-${readiness}`}><i aria-hidden="true" />{readinessLabel(readiness)}</span></td><td><code>{repository.default_branch}</code></td><td><span className="table-date">{formatRelativeDate(repository.last_scan_at)}<small>{formatDate(repository.last_scan_at)}</small></span></td><td><span className="health-cell"><HealthRing value={repository.last_scan_health} readiness={readiness} size={30} label={false} /><strong className="health-value">{repository.last_scan_health ?? '—'}</strong></span></td></tr> })}</tbody></table></div></section> : <section className="repository-grid" aria-label="Visual repository grid">{catalogWindow.items.map((repository) => { const pinned = pinnedIds.includes(repository.id); const readiness = repositoryReadiness(repository); return <article className={`repository-tile ${readiness}`} key={repository.id}><button className="repository-tile-main" type="button" onClick={() => selectRepository(repository)} aria-label={`Open ${repository.full_name}`}><span className="tile-heading"><RepoAvatar repository={repository} size="lg" /><span className="tile-title"><strong>{repository.name}</strong><small>{repository.owner} · {repository.default_branch}</small></span></span><span className="tile-description">{repository.last_scan_primary_signal?.message ?? repository.description ?? 'No repository description provided.'}</span><span className="tile-meta"><span className={`readiness-label readiness-${readiness}`}><i aria-hidden="true" />{readinessLabel(readiness)}</span><span className="tile-time">{formatRelativeDate(repository.last_scan_at)}</span><HealthRing value={repository.last_scan_health} readiness={readiness} size={38} /></span></button><button className={`tile-pin ${pinned ? 'pinned' : ''}`} type="button" onClick={() => togglePinned(repository.id)} aria-label={pinned ? `Remove ${repository.full_name} from pinned repositories` : `Pin ${repository.full_name}`} aria-pressed={pinned}><span aria-hidden="true">{pinned ? '★' : '☆'}</span></button></article> })}</section>}<div className="pagination-bar"><span>Showing {(catalogWindow.page - 1) * catalogWindow.pageSize + 1}–{Math.min(catalogWindow.page * catalogWindow.pageSize, catalogWindow.total)} of {catalogWindow.total}</span><div className="pagination-controls"><label>Rows<select aria-label="Rows per page" value={catalogPageSize} onChange={(event) => { setCatalogPageSize(Number(event.target.value)); setCatalogPage(1) }}><option value="24">24</option><option value="48">48</option><option value="96">96</option></select></label><button className="ghost" type="button" onClick={() => setCatalogPage((page) => Math.max(1, page - 1))} disabled={catalogWindow.page <= 1}>Previous</button><span className="page-number">Page {catalogWindow.page} / {catalogWindow.pageCount}</span><button className="ghost" type="button" onClick={() => setCatalogPage((page) => Math.min(catalogWindow.pageCount, page + 1))} disabled={catalogWindow.page >= catalogWindow.pageCount}>Next</button></div></div></> : <section className="empty-state section-card"><BrandMark size={38} label="" /><h2>{repositories.length ? 'No repositories match' : 'No repositories yet'}</h2><p className="muted">{repositories.length ? 'Adjust the search or reset your filters to widen the catalog.' : 'Sync the Gitea catalog to discover repositories available to RepoPulse.'}</p><button type="button" onClick={() => { setCatalogFilters(DEFAULT_FILTERS); setCatalogPage(1) }}>{repositories.length ? 'Reset filters' : 'Sync Gitea catalog'}</button></section>}</section>
const renderDetailPage = () => {
if (!selectedRepository) return <section className="page-content"><div className="empty-state section-card"><BrandMark size={38} label="" /><h1>This repository is not in the current catalog.</h1><p className="muted">It may have been archived, removed or the link may be stale.</p><a className="button-link" href="/repositories" onClick={(event) => handleNavigation(event, { page: 'repositories' })}>Back to repositories</a></div></section>
const readiness = repositoryReadiness(selectedRepository); const revision = report?.source.actual_revision || selectedRepository.latest_revision
return <section className="page-content detail-page" aria-labelledby="repository-title"><div className="breadcrumb-row"><a href="/repositories" onClick={(event) => handleNavigation(event, { page: 'repositories' })}>Repositories</a><span aria-hidden="true"><Icon name="chevronRight" size={14} /></span><button type="button" onClick={() => setSwitcherOpen(true)}>{selectedRepository.full_name} <Icon name="chevronDown" size={14} /></button></div><section className="workspace-hero"><div className="workspace-identity"><RepoAvatar repository={selectedRepository} size="xl" /><div><span className="eyebrow">{selectedRepository.provider} repository · {selectedRepository.private ? 'private' : 'public'}</span><h1 id="repository-title">{selectedRepository.full_name}</h1><p>{selectedRepository.description || 'No repository description provided.'}</p><div className="workspace-facts"><span><Icon name="branch" /><code>{selectedRepository.default_branch}</code></span><span><Icon name="commit" /><code>{shortRevision(revision)}</code></span><span className={`status-label status-${statusClass(selectedRepository.state)}`}><i aria-hidden="true" />{stateLabel(selectedRepository.state)}</span></div></div><div className="workspace-score"><HealthRing value={report?.health_score ?? selectedRepository.last_scan_health} readiness={readiness} size={84} /><span>health score</span><small className={`chip ${readiness}`}>{report?.release_readiness ?? readinessLabel(readiness)}</small></div></div><RepositoryVisual repository={selectedRepository} report={report} className="workspace-visual" /><div className="detail-actions"><button type="button" onClick={() => void analyzeRepository(selectedRepository)} disabled={busy || Boolean(activeJob)}>{activeJob ? 'Scanning…' : 'Scan now'}</button><details className="action-menu"><summary><Icon name="download" />Reports</summary><div className="menu-popover"><button type="button" onClick={() => void exportReport('html')} disabled={!report}>Export HTML</button><button type="button" onClick={() => void exportReport('json')} disabled={!report}>Export JSON</button></div></details><details className="action-menu"><summary><Icon name="more" />More</summary><div className="menu-popover"><button type="button" onClick={() => void analyzeRepository(selectedRepository, true)} disabled={busy || Boolean(activeJob)}>Force rescan</button><button type="button" onClick={() => navigate({ page: 'repositories', repositoryId: selectedRepository.id, view: 'scans' })}>View scan runs</button><button type="button" onClick={() => setAdvancedOpen((current) => !current)}>Advanced info</button></div></details><button className={`star-button header-star ${pinnedIds.includes(selectedRepository.id) ? 'pinned' : ''}`} type="button" onClick={() => togglePinned(selectedRepository.id)} aria-label={pinnedIds.includes(selectedRepository.id) ? 'Remove from pinned repositories' : 'Pin repository'} aria-pressed={pinnedIds.includes(selectedRepository.id)}><span aria-hidden="true">{pinnedIds.includes(selectedRepository.id) ? '★' : '☆'}</span></button></div></section>{error && <div className="error-banner" role="alert">{error}</div>}{notice && <div className="notice-banner" role="status">{notice}</div>}{activeJob && <div className="job-progress" role="status"><div><strong>{activeJob.message || 'Analysis in progress'}</strong><span>{activeJob.phase.replaceAll('_', ' ')} · {activeJob.progress}%</span></div><div className="progress-track"><i style={{ width: `${activeJob.progress}%` }} /></div></div>}<nav className="detail-tabs" aria-label="Repository analysis views">{DETAIL_VIEWS.map((view) => <a key={view} className={currentView === view ? 'active' : ''} aria-current={currentView === view ? 'page' : undefined} href={routePath({ page: 'repositories', repositoryId: selectedRepository.id, view })} onClick={(event) => handleNavigation(event, { page: 'repositories', repositoryId: selectedRepository.id, view })}>{detailViewLabel(view, report)}</a>)}</nav>{advancedOpen && <section className="section-card advanced-info"><div><span className="eyebrow">Advanced repository info</span><h2>Identity and policy</h2></div><div className="info-grid"><span><strong>Provider ID</strong><code>{selectedRepository.provider_repository_id}</code></span><span><strong>Visibility</strong>{selectedRepository.private ? 'Private' : 'Public'}</span><span><strong>Auto scan</strong>{selectedRepository.policy.auto_scan ? 'Enabled' : 'Disabled'}</span><span><strong>Minimum health</strong>{selectedRepository.policy.min_health_score}</span><span><strong>Latest revision</strong><code>{shortRevision(selectedRepository.latest_revision)}</code></span><span><strong>Catalog sync</strong>{formatDate(selectedRepository.last_synced_at)}</span></div></section>}{selectedDetailsLoading ? <section className="workspace-loading" role="status"><span /><span /><span /></section> : report ? <section className="detail-content">{currentView === 'overview' && <OverviewView report={report} comparison={comparison} />}{currentView === 'architecture' && <Suspense fallback={<p className="muted" role="status">Loading architecture view…</p>}><ArchitectureView report={report} /></Suspense>}{currentView === 'hotspots' && <HotspotsView report={report} />}{currentView === 'dependencies' && <DependenciesView report={report} />}{currentView === 'findings' && <FindingsView report={report} />}{currentView === 'history' && <HistoryView trend={trend} comparison={comparison} scanSummaries={scanSummaries} currentScanId={report.id} onSelectScan={(summary) => void selectScan(summary)} />}{currentView === 'scans' && <ScanRunsView scanSummaries={scanSummaries} currentScanId={report.id} onSelectScan={(summary) => void selectScan(summary)} />}</section> : <section className="section-card empty-state repository-empty"><BrandMark size={40} label="" /><span className="eyebrow">Ready to analyze</span><h2>{selectedRepository.full_name} has no persisted scan yet.</h2><p className="muted">RepoPulse will fetch the default branch, pin the exact commit, analyze it in an isolated worktree and retain the report by revision.</p><div className="repository-facts"><span>{selectedRepository.private ? 'Private' : 'Public'}</span><span>{selectedRepository.default_branch}</span><span>{shortRevision(selectedRepository.latest_revision)}</span></div><button type="button" onClick={() => void analyzeRepository(selectedRepository)} disabled={busy || Boolean(activeJob)}>{activeJob ? 'Analysis queued…' : 'Scan repository'}</button></section>}</section>
}
const renderActivityPage = () => { const activity = [...repositories].filter((repository) => repository.last_scan_at || repository.state === 'scanning' || repository.state === 'queued').sort((left, right) => (Date.parse(right.last_scan_at ?? '') || 0) - (Date.parse(left.last_scan_at ?? '') || 0)); return <section className="page-content activity-page" aria-labelledby="activity-title"><div className="page-heading"><div><h1 id="activity-title">Activity</h1><p className="muted">Recent scans and running analysis across the catalog.</p></div></div><div className="summary-strip"><div><span>Catalog</span><strong>{repositories.length}</strong></div><div><span>Current</span><strong>{repositories.filter((repository) => repository.state === 'current').length}</strong></div><div><span>Needs attention</span><strong>{repositories.filter((repository) => !repository.archived && repositoryReadiness(repository) !== 'ready').length}</strong></div><div><span>Latest scan</span><strong>{activity[0] ? formatRelativeDate(activity[0].last_scan_at) : '—'}</strong></div></div><section className="activity-timeline section-card"><div className="section-heading"><div><span className="eyebrow">Latest changes</span><h2>Repository activity</h2></div><span className="section-note">Each event opens its repository workspace.</span></div>{activity.length ? activity.slice(0, 30).map((repository) => <button type="button" className="timeline-event" key={repository.id} onClick={() => selectRepository(repository)}><span className={`timeline-rail ${repositoryReadiness(repository)}`} /><RepoAvatar repository={repository} /><span><strong>{repository.full_name}</strong><small>{repository.state === 'scanning' || repository.state === 'queued' ? `${stateLabel(repository.state)} · ${repository.default_branch}` : `Scan completed ${formatRelativeDate(repository.last_scan_at)} · ${repository.default_branch}`}</small></span><HealthRing value={repository.last_scan_health} readiness={repositoryReadiness(repository)} size={36} /></button>) : <div className="empty-state compact-empty"><BrandMark size={34} label="" /><h2>No activity yet</h2><p className="muted">Scan a repository to start building its operational timeline.</p></div>}</section></section> }
const renderQueuePage = () => { const queue = repositories.filter((repository) => repository.active_job_id || repository.state === 'queued' || repository.state === 'scanning'); return <section className="page-content queue-page" aria-labelledby="queue-title"><div className="page-heading"><div><h1 id="queue-title">Scan queue</h1><p className="muted">Background scans, pinned to an exact revision from acquisition to scoring.</p></div></div><div className="summary-strip"><div><span>Waiting</span><strong>{queue.filter((repository) => repository.state === 'queued').length}</strong></div><div><span>Active</span><strong>{queue.filter((repository) => repository.state === 'scanning' || repository.active_job_id).length}</strong></div><div><span>Completed</span><strong>{meta?.completed_jobs ?? '—'}</strong></div><div><span>Failed</span><strong>{meta?.failed_jobs ?? '—'}</strong></div></div><section className="queue-workspace section-card"><div className="section-heading"><div><span className="eyebrow">Live queue</span><h2>{queue.length ? 'Scans in progress' : 'Queue is clear'}</h2></div></div>{queue.length ? <div className="queue-list">{queue.map((repository) => <button type="button" className="queue-row" key={repository.id} onClick={() => selectRepository(repository)}><RepoAvatar repository={repository} /><span><strong>{repository.full_name}</strong><small>{repository.default_branch} · {repository.active_job_id ? 'worker active' : 'waiting for worker'}</small></span><span className={`status-label status-${statusClass(repository.state)}`}><i aria-hidden="true" />{stateLabel(repository.state)}</span></button>)}</div> : <div className="queue-empty"><BrandMark size={48} label="" /><div><h2>No scans are waiting</h2><p className="muted">The worker is healthy and the portfolio is up to date. Start a scan from a repository workspace whenever a fresh revision needs analysis.</p><a className="button-link" href="/repositories" onClick={(event) => handleNavigation(event, { page: 'repositories' })}>Browse repositories</a></div></div>}</section></section> }
const renderSettingsPage = () => <section className="page-content settings-page" aria-labelledby="settings-title"><div className="page-heading"><div><h1 id="settings-title">Settings</h1><p className="muted">Connection, scanning and local preferences.</p></div></div><div className="settings-sections"><section className="settings-section"><div><span className="eyebrow">Connections</span><h2>Gitea catalog</h2><p>Provider-backed repository discovery and exact revision acquisition.</p></div><dl><div><dt>Status</dt><dd><span className={`status-label status-${meta?.gitea.configured ? 'current' : 'failed'}`}><i aria-hidden="true" />{meta?.gitea.configured ? 'Configured' : 'Not configured'}</span></dd></div><div><dt>Repositories</dt><dd>{meta?.repository_count ?? repositories.length}</dd></div><div><dt>Last sync</dt><dd>{meta?.gitea.last_sync && typeof meta.gitea.last_sync === 'object' && 'synced_at' in meta.gitea.last_sync ? formatDate(String(meta.gitea.last_sync.synced_at)) : 'Not available'}</dd></div></dl><button className="ghost" type="button" onClick={() => void syncCatalog()} disabled={catalogBusy}>{catalogBusy ? 'Syncing…' : 'Sync catalog now'}</button></section><section className="settings-section"><div><span className="eyebrow">Scanning & analysis</span><h2>Safe source controls</h2><p>The normal repository flow stays Gitea-native. The advanced path remains available only for mounted local sources.</p></div><dl><div><dt>Scan root</dt><dd>{meta?.scan_root_restricted ? 'Restricted' : 'Configured by server'}</dd></div><div><dt>Concurrency</dt><dd>{meta?.max_concurrent_scans ?? '—'} worker</dd></div><div><dt>Automation</dt><dd>Scheduled discovery enabled</dd></div></dl><form className="local-form" onSubmit={scanLocal}><label><span>Advanced repository path</span><input aria-label="Repository path" value={path} onChange={(event) => setPath(event.target.value)} placeholder="/scan/my-project" required /></label><button disabled={busy}>{busy ? 'Analyzing…' : 'Analyze local source'}</button></form>{standaloneReport && <div className="local-result" role="status"><strong>{standaloneReport.repository_name}</strong><span>{standaloneReport.health_score}/100 · {standaloneReport.release_readiness} · {formatDate(standaloneReport.scanned_at)}</span></div>}</section><section className="settings-section appearance"><div><span className="eyebrow">Appearance</span><h2>Personal workspace preferences</h2><p>View mode, pinned and recent repositories are stored locally in this browser.</p></div><dl><div><dt>Explorer view</dt><dd><div className="view-toggle"><button className={catalogView === 'table' ? 'active' : ''} type="button" onClick={() => setCatalogView('table')}>Table</button><button className={catalogView === 'grid' ? 'active' : ''} type="button" onClick={() => setCatalogView('grid')}>Visual grid</button></div></dd></div><div><dt>Pinned repositories</dt><dd>{pinnedIds.length}</dd></div><div><dt>Recent repositories</dt><dd>{recentIds.length}</dd></div></dl></section></div></section>
return <div className="app-shell">{renderSidebar()}<main className="app-main">{renderTopbar()}{error && !route.repositoryId && <div className="error-banner global-banner" role="alert">{error}</div>}{notice && !route.repositoryId && <div className="notice-banner global-banner" role="status">{notice}</div>}{route.page === 'dashboard' && <DashboardView repositories={repositories} pinnedIds={pinnedIds} onOpenRepository={selectRepository} onExploreReadiness={exploreReadiness} onOpenExplorer={() => navigate({ page: 'repositories' })} loading={catalogLoading} />}{route.page === 'activity' && renderActivityPage()}{route.page === 'queue' && renderQueuePage()}{route.page === 'settings' && renderSettingsPage()}{route.page === 'repositories' && (route.repositoryId ? renderDetailPage() : renderCatalogPage())}</main>{switcherOpen && <div className="modal-backdrop" role="presentation" onMouseDown={() => setSwitcherOpen(false)}><section className="switcher-modal" role="dialog" aria-modal="true" aria-labelledby="switcher-title" onMouseDown={(event) => event.stopPropagation()}><div className="switcher-heading"><div><span className="eyebrow">Repository navigation</span><h2 id="switcher-title">Quick switcher</h2></div><button className="icon-button" type="button" onClick={() => setSwitcherOpen(false)} aria-label="Close quick switcher"><Icon name="close" /></button></div><div className="command-row"><button type="button" onClick={() => { navigate({ page: 'dashboard' }); setSwitcherOpen(false) }}>Open dashboard</button><button type="button" onClick={() => { navigate({ page: 'queue' }); setSwitcherOpen(false) }}>Open scan queue</button><button type="button" onClick={() => void syncCatalog()} disabled={catalogBusy}>Sync Gitea</button></div><label className="switcher-search"><span className="sr-only">Search repositories</span><input ref={switcherInputRef} value={switcherQuery} onChange={(event) => { setSwitcherQuery(event.target.value); setSwitcherIndex(0) }} placeholder="Search repositories…" /><kbd>Esc</kbd></label>{switcherRepositories.length ? <div className="switcher-results" role="listbox" aria-label="Repositories">{switcherRepositories.map((repository, index) => <button className={index === switcherIndex ? 'switcher-item active' : 'switcher-item'} type="button" role="option" aria-selected={index === switcherIndex} key={repository.id} onMouseEnter={() => setSwitcherIndex(index)} onClick={() => { selectRepository(repository); setSwitcherOpen(false) }}><RepoAvatar repository={repository} /><span><strong>{repository.full_name}</strong><small>{repository.owner} · {repository.default_branch} · {repository.last_scan_health ?? 'not scanned'}</small></span><span className={`readiness-label readiness-${repositoryReadiness(repository)}`}><i aria-hidden="true" />{readinessLabel(repositoryReadiness(repository))}</span></button>)}</div> : <div className="empty-state compact-empty"><h2>No repository matches</h2><p className="muted">Try the owner, repository name or branch.</p></div>}<div className="switcher-footer"><span><kbd>↑</kbd><kbd>↓</kbd> Navigate</span><span><kbd>Enter</kbd> Open</span><span><kbd>Esc</kbd> Close</span></div></section></div>}</div>
}