Unverified Commit 2f3f74b1 authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

bundle-analyzer: add compare view with treemap diff (#93521)

Adds a compare mode to the bundle analyzer. When the user picks a
historical snapshot from the new baseline picker in the top bar, the UI
switches into compare mode: routes are diff'd by name and size, and the
per-route view shows a `DiffTreemap` that colors each source tile by its
change status (added/removed/grew/shrank/unchanged).

The compare sidebar shows the import chain for the selected tile on
either the baseline ("A") or current ("B") side. Route totals are
fetched in parallel so the route picker can sort by largest impact and
classify routes as `changed`/`identical` rather than just name-presence.

<!-- NEXT_JS_LLM_PR -->

---------
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarWill Binns-Smith <755844+wbinnssmith@users.noreply.github.com>
parent da6e8b65
'use client' 'use client'
import type React from 'react' import { useEffect, useMemo, useState, type ReactNode } from 'react'
import { useEffect, useMemo, useState } from 'react'
import useSWR from 'swr' import useSWR from 'swr'
import { CompareLayout } from '@/components/compare-layout'
import { ErrorState } from '@/components/error-state' import { ErrorState } from '@/components/error-state'
import { FileSearch } from '@/components/file-search'
import { RouteTypeahead } from '@/components/route-typeahead'
import { Sidebar } from '@/components/sidebar' import { Sidebar } from '@/components/sidebar'
import { TopBar, Environment } from '@/components/top-bar'
import { TreemapVisualizer } from '@/components/treemap-visualizer' import { TreemapVisualizer } from '@/components/treemap-visualizer'
import { Badge } from '@/components/ui/badge' import { Badge } from '@/components/ui/badge'
import { TreemapSkeleton } from '@/components/ui/skeleton' import { TreemapSkeleton } from '@/components/ui/skeleton'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { MultiSelect } from '@/components/ui/multi-select'
import { AnalyzeData, ModulesData } from '@/lib/analyze-data' import { AnalyzeData, ModulesData } from '@/lib/analyze-data'
import { diffRoutesWithSizes, diffSources } from '@/lib/diff'
import { useRouteTotals } from '@/lib/use-route-totals'
import { useSidebarResize } from '@/lib/use-sidebar-resize'
import { computeActiveEntries, computeModuleDepthMap } from '@/lib/module-graph' import { computeActiveEntries, computeModuleDepthMap } from '@/lib/module-graph'
import { fetchStrict } from '@/lib/utils' import { type SnapshotMetadata } from '@/lib/snapshot'
import { fetchStrict, jsonFetcher } from '@/lib/utils'
import { formatBytes } from '@/lib/utils' import { formatBytes } from '@/lib/utils'
import { SizeMode } from '@/lib/treemap-layout' import { SizeMode } from '@/lib/treemap-layout'
import {
Monitor, /**
Server, * Resolve the URL of an `analyze.data` file for a given route. When `baseDir`
FileCode, * is non-empty, the file is fetched from a historical snapshot directory
FileJson, * instead of the live `data/` directory. Returns `null` when no route is
Palette, * selected.
Package, */
} from 'lucide-react' function getAnalyzeDataPath(
route: string | null,
enum Environment { baseDir: 'data' | string
Client = 'client', ): string | null {
Server = 'server', if (!route) return null
if (route === '/') return `${baseDir}/analyze.data`
return `${baseDir}/${route.replace(/^\//, '')}/analyze.data`
} }
export default function Home() { export default function Home() {
...@@ -52,20 +48,70 @@ export default function Home() { ...@@ -52,20 +48,70 @@ export default function Home() {
null null
) )
// Selecting an A snapshot enables compare mode. B defaults to the live
// build, but can be set to any other historical snapshot.
const [baselineSnapshot, setBaselineSnapshot] =
useState<SnapshotMetadata | null>(null)
const [comparisonSnapshot, setComparisonSnapshot] =
useState<SnapshotMetadata | null>(null)
const isCompareMode = baselineSnapshot != null
const comparisonBaseDir = comparisonSnapshot
? `history/${comparisonSnapshot.id}`
: 'data'
const { const {
data: modulesData, data: modulesData,
isLoading: isModulesLoading, isLoading: isModulesLoading,
error: modulesError, error: modulesError,
} = useSWR<ModulesData>('data/modules.data', fetchModulesData) } = useSWR<ModulesData>(`${comparisonBaseDir}/modules.data`, fetchModulesData)
let analyzeDataPath // Baseline modules.data, only fetched in compare mode. Used to power the
if (selectedRoute && selectedRoute === '/') { // import-chain panel for the baseline ("A") side of the compare sidebar.
analyzeDataPath = 'data/analyze.data' // Snapshots are produced by copying the entire data dir (see
} else if (selectedRoute) { // `packages/next/src/build/analyze/snapshot.ts`), so this file is
analyzeDataPath = `data/${selectedRoute.replace(/^\//, '')}/analyze.data` // expected to exist for any historical snapshot.
} else { const baselineModulesPath = baselineSnapshot
analyzeDataPath = null ? `history/${baselineSnapshot.id}/modules.data`
: null
const { data: baselineModulesData } = useSWR<ModulesData>(
baselineModulesPath,
fetchModulesData,
{
revalidateOnFocus: false,
revalidateOnReconnect: false,
shouldRetryOnError: false,
} }
)
// Routes for comparison side B. This is the live build by default, or an
// independently selected historical snapshot.
const { data: currentRoutes } = useSWR<string[]>(
`${comparisonBaseDir}/routes.json`,
jsonFetcher,
{ revalidateOnFocus: false, revalidateOnReconnect: false }
)
// Routes for the historical baseline, used only in compare mode.
const baselineRoutesPath = baselineSnapshot
? `history/${baselineSnapshot.id}/routes.json`
: null
const { data: baselineRoutes } = useSWR<string[]>(
baselineRoutesPath,
jsonFetcher,
{ revalidateOnFocus: false, revalidateOnReconnect: false }
)
// Whether the selected route exists on comparison side B. We only fetch
// its analyze.data when this is true because an output directory can contain
// stale per-route subdirectories from previous builds. routes.json is the
// source of truth for either a live or historical comparison build.
const currentAnalyzeRouteExists =
currentRoutes != null &&
selectedRoute != null &&
currentRoutes.includes(selectedRoute)
const analyzeDataPath = !currentAnalyzeRouteExists
? null
: getAnalyzeDataPath(selectedRoute, comparisonBaseDir)
const { const {
data: analyzeData, data: analyzeData,
...@@ -81,8 +127,29 @@ export default function Home() { ...@@ -81,8 +127,29 @@ export default function Home() {
}, },
}) })
const [sidebarWidth, setSidebarWidth] = useState(20) // percentage // Per-route analyze.data for the baseline build. Only fetched when both a
const [isResizing, setIsResizing] = useState(false) // baseline and a route are selected and the route exists in the baseline.
const baselineAnalyzeRouteExists =
baselineRoutes != null &&
selectedRoute != null &&
baselineRoutes.includes(selectedRoute)
const baselineAnalyzePath =
baselineSnapshot && baselineAnalyzeRouteExists
? getAnalyzeDataPath(selectedRoute, `history/${baselineSnapshot.id}`)
: null
const {
data: baselineAnalyzeData,
isLoading: isBaselineAnalyzeLoading,
error: baselineAnalyzeError,
} = useSWR<AnalyzeData>(baselineAnalyzePath, fetchAnalyzeData, {
revalidateOnFocus: false,
revalidateOnReconnect: false,
// Don't blow up if the baseline file is missing — the UI handles it
// gracefully by labeling the route as "added".
shouldRetryOnError: false,
})
const { sidebarWidth, startResizing } = useSidebarResize()
const [isMouseInTreemap, setIsMouseInTreemap] = useState(false) const [isMouseInTreemap, setIsMouseInTreemap] = useState(false)
const [hoveredNodeInfo, setHoveredNodeInfo] = useState<{ const [hoveredNodeInfo, setHoveredNodeInfo] = useState<{
name: string name: string
...@@ -92,6 +159,18 @@ export default function Home() { ...@@ -92,6 +159,18 @@ export default function Home() {
traced?: boolean traced?: boolean
} | null>(null) } | null>(null)
const [searchQuery, setSearchQuery] = useState('') const [searchQuery, setSearchQuery] = useState('')
// Selected source in compare mode, identified by its full source path
// (the diff row's `key`). Source indices differ between the two builds,
// so we can't reuse `selectedSourceIndex`.
const [compareSelectedKey, setCompareSelectedKey] = useState<string | null>(
null
)
// Reset compare selection when the route or either side changes — the
// previous selection is unlikely to exist in the new diff.
useEffect(() => {
setCompareSelectedKey(null)
}, [selectedRoute, baselineSnapshot, comparisonSnapshot])
useEffect(() => { useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => { const handleKeyDown = (e: KeyboardEvent) => {
...@@ -122,6 +201,18 @@ export default function Home() { ...@@ -122,6 +201,18 @@ export default function Home() {
return computeModuleDepthMap(modulesData, activeEntries) return computeModuleDepthMap(modulesData, activeEntries)
}, [modulesData, analyzeData]) }, [modulesData, analyzeData])
// Same as `moduleDepthMap`, but for the baseline ("A") build. Only
// computed in compare mode when both the baseline modules.data and
// baseline analyze.data have loaded.
const baselineModuleDepthMap = useMemo(() => {
if (!baselineModulesData || !baselineAnalyzeData) return new Map()
const activeEntries = computeActiveEntries(
baselineModulesData,
baselineAnalyzeData
)
return computeModuleDepthMap(baselineModulesData, activeEntries)
}, [baselineModulesData, baselineAnalyzeData])
const filterSource = useMemo(() => { const filterSource = useMemo(() => {
if (!analyzeData) return () => true if (!analyzeData) return () => true
...@@ -144,60 +235,142 @@ export default function Home() { ...@@ -144,60 +235,142 @@ export default function Home() {
} }
}, [analyzeData, environmentFilter, typeFilter]) }, [analyzeData, environmentFilter, typeFilter])
const handleMouseDown = () => { // Build a per-side filter usable by the source diff. Each side gets its own
setIsResizing(true) // closure over its own `analyzeData`, since the source flags are
// route/build-specific.
const compareFilterSource = useMemo(() => {
return (side: 'A' | 'B', sourceIndex: number): boolean => {
const data = side === 'A' ? baselineAnalyzeData : analyzeData
if (!data) return false
const flags = data.getSourceFlags(sourceIndex)
const hasEnvironment =
(environmentFilter === Environment.Client && flags.client) ||
(environmentFilter === Environment.Server && flags.server)
const hasType =
(typeFilter.includes('js') && flags.js) ||
(typeFilter.includes('css') && flags.css) ||
(typeFilter.includes('json') && flags.json) ||
(typeFilter.includes('asset') && flags.asset)
return hasEnvironment && hasType
} }
}, [analyzeData, baselineAnalyzeData, environmentFilter, typeFilter])
const handleMouseMove = (e: React.MouseEvent) => {
if (!isResizing) return // Source-level diff for the currently selected route. Recomputed when
const newWidth = ((window.innerWidth - e.clientX) / window.innerWidth) * 100 // either side's data or the active filters change.
setSidebarWidth(Math.max(10, Math.min(50, newWidth))) // Clamp between 10% and 50% //
// Three cases:
// 1. Route exists in both builds → diff(A, B).
// 2. Route exists only in the baseline (removed) → there is no B-side
// `analyze.data`, but we still want to show the baseline's sources
// flagged as `removed`. We synthesize this by passing the baseline
// as both A and the empty-stand-in for B, then dropping the B side.
// `diffSources` accepts a non-null B, so we feed an empty walk by
// using the baseline data with a filter that always returns false
// for the B side.
// 3. Route exists only in comparison build B (added) → analyzeData
// present, baselineAnalyzeData absent. Already handled below by
// passing `null` for A.
const sourceDiff = useMemo(() => {
if (!baselineSnapshot) return null
if (analyzeData) {
return diffSources(baselineAnalyzeData ?? null, analyzeData, {
filterSource: compareFilterSource,
})
} }
// Removed-route case: only the baseline has data. Diff baseline vs.
const handleMouseUp = () => { // baseline but suppress the B side via the filter so every source
setIsResizing(false) // appears as `removed`.
if (baselineAnalyzeData) {
return diffSources(baselineAnalyzeData, baselineAnalyzeData, {
filterSource: (side, index) =>
side === 'A' && compareFilterSource('A', index),
})
} }
return null
}, [analyzeData, baselineAnalyzeData, baselineSnapshot, compareFilterSource])
// Per-route totals for both sides, used to size the route-level diff so
// that routes whose modules changed can be reported as `changed` rather
// than `identical`. Only fetched in compare mode.
const { totals: currentRouteTotals } = useRouteTotals(
baselineSnapshot ? (currentRoutes ?? null) : null,
baselineSnapshot ? comparisonBaseDir : null
)
const { totals: baselineRouteTotals } = useRouteTotals(
baselineSnapshot ? (baselineRoutes ?? null) : null,
baselineSnapshot ? `history/${baselineSnapshot.id}` : null
)
// Route-level diff. Falls back to a name-only diff (`sizesA == null`)
// while totals are still loading; once both sides' totals arrive, real
// sizes drive `changed`/`identical` classification.
const routeDiff = useMemo(() => {
if (!baselineSnapshot || !currentRoutes) return null
if (!currentRouteTotals) return null
return diffRoutesWithSizes(
baselineRoutes ?? null,
currentRoutes,
baselineRouteTotals,
currentRouteTotals
)
}, [
baselineSnapshot,
baselineRoutes,
currentRoutes,
baselineRouteTotals,
currentRouteTotals,
])
// The compare panel can render even when the *baseline's* per-route data
// failed to load (e.g., the route is new). Don't surface that as a top-level
// error in compare mode.
const error = analyzeError || modulesError const error = analyzeError || modulesError
const isAnyLoading = isAnalyzeLoading || isModulesLoading const isAnyLoading = isAnalyzeLoading || isModulesLoading
const rootSourceIndex = getRootSourceIndex(analyzeData) const rootSourceIndex = getRootSourceIndex(analyzeData)
return ( let analyzerContent: ReactNode = null
<main if (error && !analyzeData) {
className="h-screen flex flex-col bg-background" analyzerContent = <ErrorState error={error} />
onMouseMove={handleMouseMove} } else if (isCompareMode) {
onMouseUp={handleMouseUp} analyzerContent = (
> <CompareLayout
<TopBar baselineSnapshot={baselineSnapshot}
analyzeData={analyzeData} comparisonSnapshot={comparisonSnapshot}
selectedRoute={selectedRoute} selectedRoute={selectedRoute}
setSelectedRoute={setSelectedRoute} comparisonRouteCount={currentRoutes?.length ?? null}
routeDiff={routeDiff}
sourceDiff={sourceDiff}
analyzeData={analyzeData ?? null}
baselineAnalyzeData={baselineAnalyzeData ?? null}
isAnalyzeLoading={isAnalyzeLoading}
isBaselineAnalyzeLoading={isBaselineAnalyzeLoading}
baselineAnalyzeError={
baselineAnalyzeError && baselineAnalyzeRouteExists
? baselineAnalyzeError
: null
}
compressed
compareSelectedKey={compareSelectedKey}
setCompareSelectedKey={setCompareSelectedKey}
modulesData={modulesData ?? null}
baselineModulesData={baselineModulesData ?? null}
moduleDepthMap={moduleDepthMap}
baselineModuleDepthMap={baselineModuleDepthMap}
environmentFilter={environmentFilter} environmentFilter={environmentFilter}
setEnvironmentFilter={setEnvironmentFilter}
setSelectedSourceIndex={setSelectedSourceIndex}
setFocusedSourceIndex={setFocusedSourceIndex}
typeFilter={typeFilter}
setTypeFilter={setTypeFilter}
searchQuery={searchQuery}
setSearchQuery={setSearchQuery}
/> />
)
<div className="flex-1 flex min-h-0"> } else if (isAnyLoading) {
{error && !analyzeData ? ( analyzerContent = (
<ErrorState error={error} />
) : isAnyLoading ? (
<> <>
<div className="flex-1 min-w-0 p-4 bg-background"> <div className="flex-1 min-w-0 p-4 bg-background">
<TreemapSkeleton /> <TreemapSkeleton />
</div> </div>
<button <button
type="button" type="button"
className="flex-none w-1 bg-border cursor-col-resize transition-colors" className="flex-none w-1 bg-border cursor-col-resize transition-colors"
disabled disabled
aria-label="Resize sidebar" aria-label="Resize sidebar"
/> />
<Sidebar <Sidebar
sidebarWidth={sidebarWidth} sidebarWidth={sidebarWidth}
analyzeData={null} analyzeData={null}
...@@ -208,7 +381,9 @@ export default function Home() { ...@@ -208,7 +381,9 @@ export default function Home() {
isLoading={true} isLoading={true}
/> />
</> </>
) : analyzeData ? ( )
} else if (analyzeData) {
analyzerContent = (
<> <>
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<TreemapVisualizer <TreemapVisualizer
...@@ -226,17 +401,15 @@ export default function Home() { ...@@ -226,17 +401,15 @@ export default function Home() {
sizeMode={SizeMode.Compressed} sizeMode={SizeMode.Compressed}
/> />
</div> </div>
<button <button
type="button" type="button"
className="flex-none w-1 bg-border hover:bg-primary cursor-col-resize transition-colors" className="flex-none w-1 bg-border hover:bg-primary cursor-col-resize transition-colors"
onMouseDown={handleMouseDown} onMouseDown={startResizing}
aria-label="Resize sidebar" aria-label="Resize sidebar"
/> />
<Sidebar <Sidebar
sidebarWidth={sidebarWidth} sidebarWidth={sidebarWidth}
analyzeData={analyzeData ?? null} analyzeData={analyzeData}
modulesData={modulesData ?? null} modulesData={modulesData ?? null}
selectedSourceIndex={selectedSourceIndex} selectedSourceIndex={selectedSourceIndex}
moduleDepthMap={moduleDepthMap} moduleDepthMap={moduleDepthMap}
...@@ -244,10 +417,36 @@ export default function Home() { ...@@ -244,10 +417,36 @@ export default function Home() {
filterSource={filterSource} filterSource={filterSource}
/> />
</> </>
) : null} )
</div> }
return (
<main className="h-screen flex flex-col bg-background">
<TopBar
hasSourceData={analyzeData != null}
selectedRoute={selectedRoute}
setSelectedRoute={setSelectedRoute}
environmentFilter={environmentFilter}
setEnvironmentFilter={setEnvironmentFilter}
setSelectedSourceIndex={setSelectedSourceIndex}
setFocusedSourceIndex={setFocusedSourceIndex}
typeFilter={typeFilter}
setTypeFilter={setTypeFilter}
searchQuery={searchQuery}
setSearchQuery={setSearchQuery}
baselineSnapshot={baselineSnapshot}
onBaselineChange={(snapshot) => {
setBaselineSnapshot(snapshot)
if (!snapshot) setComparisonSnapshot(null)
}}
comparisonSnapshot={comparisonSnapshot}
onComparisonChange={setComparisonSnapshot}
routeDiff={routeDiff}
/>
{analyzeData && ( <div className="flex-1 flex min-h-0">{analyzerContent}</div>
{analyzeData && !isCompareMode ? (
<div className="flex-none border-t border-border bg-background px-4 py-2 h-10"> <div className="flex-none border-t border-border bg-background px-4 py-2 h-10">
<div className="text-sm text-muted-foreground"> <div className="text-sm text-muted-foreground">
{hoveredNodeInfo ? ( {hoveredNodeInfo ? (
...@@ -277,120 +476,11 @@ export default function Home() { ...@@ -277,120 +476,11 @@ export default function Home() {
)} )}
</div> </div>
</div> </div>
)} ) : null}
</main> </main>
) )
} }
const typeFilterOptions = [
{
value: 'js',
label: 'JavaScript',
icon: <FileCode className="h-3.5 w-3.5" />,
},
{ value: 'css', label: 'CSS', icon: <Palette className="h-3.5 w-3.5" /> },
{
value: 'json',
label: 'JSON',
icon: <FileJson className="h-3.5 w-3.5" />,
},
{
value: 'asset',
label: 'Asset',
icon: <Package className="h-3.5 w-3.5" />,
},
]
function TopBar({
analyzeData,
selectedRoute,
setSelectedRoute,
environmentFilter,
setEnvironmentFilter,
setSelectedSourceIndex,
setFocusedSourceIndex,
typeFilter,
setTypeFilter,
searchQuery,
setSearchQuery,
}: {
analyzeData: AnalyzeData | undefined
selectedRoute: string | null
setSelectedRoute: (route: string | null) => void
environmentFilter: Environment
setEnvironmentFilter: (env: Environment) => void
setSelectedSourceIndex: (index: number | null) => void
setFocusedSourceIndex: (index: number | null) => void
typeFilter: string[]
setTypeFilter: (types: string[]) => void
searchQuery: string
setSearchQuery: (query: string) => void
}) {
return (
<div className="flex-none px-4 py-2 border-b border-border flex items-center gap-3">
<div className="flex-1 flex">
<RouteTypeahead
selectedRoute={selectedRoute}
onRouteSelected={(route) => {
setSelectedRoute(route)
setSelectedSourceIndex(null)
setFocusedSourceIndex(null)
}}
/>
</div>
<div className="flex items-center gap-2">
{analyzeData && (
<>
<Select
value={environmentFilter}
onValueChange={(value: Environment) =>
setEnvironmentFilter(value)
}
>
<SelectTrigger className="w-28">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={Environment.Client}>
<div className="flex items-center gap-1.5">
<Monitor className="h-3.5 w-3.5" />
<span className="text-xs">Client</span>
</div>
</SelectItem>
<SelectItem value={Environment.Server}>
<div className="flex items-center gap-1.5">
<Server className="h-3.5 w-3.5" />
<span className="text-xs">Server</span>
</div>
</SelectItem>
</SelectContent>
</Select>
<MultiSelect
options={typeFilterOptions}
value={typeFilter}
onValueChange={setTypeFilter}
selectionName={{ singular: 'file type', plural: 'file types' }}
triggerIcon={<FileCode className="h-3.5 w-3.5" />}
triggerClassName="w-36"
aria-label="Filter by file type"
/>
<ControlDivider />
<FileSearch value={searchQuery} onChange={setSearchQuery} />
</>
)}
</div>
</div>
)
}
function ControlDivider() {
return <span className="h-6 w-px bg-muted-foreground/30" />
}
function getRootSourceIndex(analyzeData: AnalyzeData | undefined): number { function getRootSourceIndex(analyzeData: AnalyzeData | undefined): number {
if (!analyzeData) return 0 if (!analyzeData) return 0
const sourceRoots = analyzeData.sourceRoots() const sourceRoots = analyzeData.sourceRoots()
......
'use client'
import useSWR from 'swr'
import {
Check,
ChevronsUpDown,
GitCompareArrows,
Loader,
X,
} from 'lucide-react'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from '@/components/ui/command'
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover'
import { cn, jsonFetcher } from '@/lib/utils'
import { NetworkError } from '@/lib/errors'
import {
formatRelativeTime,
formatSnapshotLabel,
type HistoryIndex,
type SnapshotMetadata,
} from '@/lib/snapshot'
interface BaselinePickerProps {
/** Selected historical snapshot id, or null for the control's default. */
selectedSnapshotId: string | null
onSelectionChange: (snapshot: SnapshotMetadata | null) => void
excludedSnapshotId?: string | null
prefix?: string
placeholder?: string
clearLabel?: string
}
/**
* Top-bar control that lets the user pick one historical analyze snapshot.
* Two instances can select arbitrary A and B snapshots for comparison.
*
* Snapshots are loaded from `history/history.json` — written by
* `writeAnalyzeSnapshot` after each `next build --experimental-analyze`.
*/
export function BaselinePicker({
selectedSnapshotId,
onSelectionChange,
excludedSnapshotId,
prefix = 'vs',
placeholder = 'Compare with…',
clearLabel = 'Stop comparing',
}: BaselinePickerProps) {
const [open, setOpen] = useState(false)
const {
data: history,
isLoading,
error,
} = useSWR<HistoryIndex>('history/history.json', jsonFetcher, {
// History rarely changes during a session — avoid spamming refetches.
revalidateOnFocus: false,
revalidateOnReconnect: false,
// Treat 404 as "no history yet" rather than an error so users on fresh
// installs see a graceful disabled state instead of a red banner.
shouldRetryOnError: false,
})
// Metadata for the *current* build, so we can exclude its corresponding
// entry from the history picker (you can't compare a build with itself).
const { data: currentMetadata } = useSWR<SnapshotMetadata>(
'data/metadata.json',
jsonFetcher,
{
revalidateOnFocus: false,
revalidateOnReconnect: false,
shouldRetryOnError: false,
}
)
const allSnapshots = history?.snapshots ?? []
// Filter out the current build's snapshot — comparing to self is a no-op.
const snapshots = allSnapshots.filter(
(snapshot) =>
snapshot.id !== currentMetadata?.id && snapshot.id !== excludedSnapshotId
)
const selected =
selectedSnapshotId != null
? snapshots.find((s) => s.id === selectedSnapshotId)
: null
// Surface only fatal/network problems; missing history files are not errors.
const hasError = error instanceof NetworkError
const isEmpty = !isLoading && snapshots.length === 0
// When the only snapshot on disk is the current build itself, surface a
// distinct label/tooltip telling the user to run another build.
const isOnlyCurrentBuild =
!isLoading && allSnapshots.length > 0 && snapshots.length === 0
let triggerText: React.ReactNode
if (isLoading) {
triggerText = 'Loading history…'
} else if (selected) {
triggerText = (
<span className="flex items-center gap-1.5 truncate">
<span className="text-muted-foreground text-xs">{prefix}</span>
<span className="font-mono truncate">
{formatSnapshotLabel(selected)}
</span>
</span>
)
} else {
triggerText = placeholder
}
return (
<div className="flex items-center gap-1">
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
disabled={isLoading || hasError}
className="min-w-44 max-w-72 justify-between text-sm"
title={hasError ? 'Unable to load build history' : undefined}
>
<div className="flex items-center min-w-0">
{isLoading ? (
<Loader className="mr-2 h-3.5 w-3.5 inline animate-spin" />
) : (
<GitCompareArrows className="mr-2 h-3.5 w-3.5 inline" />
)}
<span className="truncate">{triggerText}</span>
</div>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-96 p-0">
<Command>
{snapshots.length > 0 ? (
<CommandInput placeholder="Search snapshots…" className="h-9" />
) : null}
<CommandList>
{isOnlyCurrentBuild ? (
<div className="px-3 py-6 text-center text-sm text-muted-foreground">
<div className="font-medium text-foreground">
No prior builds yet
</div>
<div className="mt-1">
Run{' '}
<code className="rounded bg-muted px-1 py-0.5 text-xs">
next experimental-analyze
</code>{' '}
again to capture a baseline you can compare against.
</div>
</div>
) : isEmpty ? (
<div className="px-3 py-6 text-center text-sm text-muted-foreground">
<div className="font-medium text-foreground">
No build history
</div>
<div className="mt-1">
Run{' '}
<code className="rounded bg-muted px-1 py-0.5 text-xs">
next build --experimental-analyze
</code>{' '}
to start collecting snapshots.
</div>
</div>
) : (
<CommandEmpty>No snapshots found.</CommandEmpty>
)}
<CommandGroup>
{snapshots.map((snapshot) => (
<CommandItem
key={snapshot.id}
value={`${snapshot.id} ${snapshot.gitBranch ?? ''} ${snapshot.gitShortSha ?? ''} ${snapshot.gitMessage ?? ''} ${snapshot.baselineName ?? ''}`}
onSelect={() => {
onSelectionChange(snapshot)
setOpen(false)
}}
>
<Check
className={cn(
'mr-2 h-4 w-4',
selectedSnapshotId === snapshot.id
? 'opacity-100'
: 'opacity-0'
)}
/>
<SnapshotRow snapshot={snapshot} />
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
{selected != null && (
<Button
variant="ghost"
size="icon"
aria-label={clearLabel}
onClick={() => onSelectionChange(null)}
className="h-8 w-8"
>
<X className="h-3.5 w-3.5" />
</Button>
)}
</div>
)
}
/** A single row in the snapshot picker list. */
function SnapshotRow({ snapshot }: { snapshot: SnapshotMetadata }) {
return (
<div className="flex flex-col min-w-0 flex-1">
<div className="flex items-center gap-2 min-w-0">
<span className="font-mono text-sm truncate">
{formatSnapshotLabel(snapshot)}
</span>
{snapshot.gitDirty ? (
<span
title="Working tree was dirty when this snapshot was taken"
className="text-xs text-amber-600 dark:text-amber-400"
>
dirty
</span>
) : null}
</div>
{snapshot.gitMessage ? (
<div className="text-xs text-foreground/70 truncate">
{snapshot.gitMessage}
</div>
) : null}
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span>{formatRelativeTime(snapshot.createdAt)}</span>
<span aria-hidden>·</span>
<span>
{snapshot.routeCount} route
{snapshot.routeCount === 1 ? '' : 's'}
</span>
{snapshot.nextVersion ? (
<>
<span aria-hidden>·</span>
<span>v{snapshot.nextVersion}</span>
</>
) : null}
</div>
</div>
)
}
'use client'
import { useSidebarResize } from '@/lib/use-sidebar-resize'
import { CompareSidebar } from '@/components/sidebar'
import { DiffTreemap } from '@/components/diff-treemap'
import { TreemapSkeleton } from '@/components/ui/skeleton'
import { StatCard, CountCard } from '@/components/stat-cards'
import { Environment } from '@/components/top-bar'
import { AnalyzeData, ModulesData } from '@/lib/analyze-data'
import {
diffRoutesWithSizes,
formatDelta,
type DiffSummary,
type SourceDiffRow,
} from '@/lib/diff'
import { formatSnapshotLabel, type SnapshotMetadata } from '@/lib/snapshot'
import { cn, formatBytes } from '@/lib/utils'
export interface CompareLayoutProps {
baselineSnapshot: SnapshotMetadata
comparisonSnapshot: SnapshotMetadata | null
selectedRoute: string | null
comparisonRouteCount: number | null
routeDiff: ReturnType<typeof diffRoutesWithSizes> | null
sourceDiff: DiffSummary<SourceDiffRow> | null
analyzeData: AnalyzeData | null
baselineAnalyzeData: AnalyzeData | null
isAnalyzeLoading: boolean
isBaselineAnalyzeLoading: boolean
baselineAnalyzeError: unknown | null
compressed: boolean
compareSelectedKey: string | null
setCompareSelectedKey: (key: string | null) => void
modulesData: ModulesData | null
baselineModulesData: ModulesData | null
moduleDepthMap: Map<number, number>
baselineModuleDepthMap: Map<number, number>
environmentFilter: Environment
}
/**
* Renders the comparison view (treemap) with a context strip at the top
* showing the two builds being compared. The "before" build (A) is rendered
* on the left and the selected "after" build (B) on the right,
* matching the user's mental model.
*
* Route selection lives in the top-bar route picker (`RouteTypeahead`),
* which also renders per-route deltas in compare mode.
*/
export function CompareLayout({
baselineSnapshot,
comparisonSnapshot,
selectedRoute,
comparisonRouteCount,
routeDiff,
sourceDiff,
analyzeData,
baselineAnalyzeData,
isAnalyzeLoading,
isBaselineAnalyzeLoading,
baselineAnalyzeError,
compressed,
compareSelectedKey,
setCompareSelectedKey,
modulesData,
baselineModulesData,
moduleDepthMap,
baselineModuleDepthMap,
environmentFilter,
}: CompareLayoutProps) {
const { sidebarWidth, startResizing } = useSidebarResize()
return (
<div className="flex h-full w-full min-w-0 flex-col">
{/*
Stats header. On wide viewports the Route stats sit next to the App
stats so the user can compare route-level and app-level deltas
without scrolling. Route is on the left because it's the primary
scope the user's focused on; App is reference context.
On narrow viewports the two strips stack vertically (route above
app) and fall back to the original layout.
*/}
<div className="flex flex-none flex-col border-b border-border xl:flex-row xl:items-stretch">
<RouteStatsCard
selectedRoute={selectedRoute}
sourceDiff={sourceDiff}
isAnalyzeLoading={isAnalyzeLoading}
isBaselineAnalyzeLoading={isBaselineAnalyzeLoading}
baselineAnalyzeError={baselineAnalyzeError}
compressed={compressed}
className="xl:min-w-0 xl:flex-1 xl:basis-0 xl:border-r xl:border-border"
/>
<CompareContextStrip
baselineSnapshot={baselineSnapshot}
comparisonRouteCount={comparisonRouteCount}
routeDiff={routeDiff}
compressed={compressed}
className="xl:min-w-0 xl:flex-1 xl:basis-0"
/>
</div>
{/*
Per-route source diff + sidebar. The sidebar slides in when a
treemap tile is selected and shows the import chain for that source.
*/}
<div className="flex flex-1 min-h-0">
<div className="flex flex-1 min-w-0 flex-col">
<ComparePerRoutePanel
selectedRoute={selectedRoute}
sourceDiff={sourceDiff}
analyzeData={analyzeData}
baselineAnalyzeData={baselineAnalyzeData}
isAnalyzeLoading={isAnalyzeLoading}
isBaselineAnalyzeLoading={isBaselineAnalyzeLoading}
compressed={compressed}
compareSelectedKey={compareSelectedKey}
onCompareSelectedKeyChange={setCompareSelectedKey}
/>
</div>
<button
type="button"
className="flex-none w-1 bg-border hover:bg-primary cursor-col-resize transition-colors"
onMouseDown={startResizing}
aria-label="Resize sidebar"
/>
<CompareSidebar
selectedKey={compareSelectedKey}
sourceDiff={sourceDiff}
analyzeData={analyzeData}
baselineAnalyzeData={baselineAnalyzeData}
modulesData={modulesData}
baselineModulesData={baselineModulesData}
moduleDepthMap={moduleDepthMap}
baselineModuleDepthMap={baselineModuleDepthMap}
environmentFilter={environmentFilter}
sidebarWidth={sidebarWidth}
aLabel={formatSnapshotLabel(baselineSnapshot)}
bLabel={
comparisonSnapshot
? formatSnapshotLabel(comparisonSnapshot)
: 'Latest'
}
/>
</div>
</div>
)
}
/**
* Strip across the top of the compare view that labels the two builds and
* shows headline stats (total routes, added, removed, changed, identical,
* total size). Modeled after the vite bundle-stats compare summary cards:
* each card uses an `A → B` arrow with a delta chip, so size/count changes
* are scannable at a glance.
*
* A/B label pills below identify which snapshot is which.
*/
function CompareContextStrip({
baselineSnapshot,
comparisonRouteCount,
routeDiff,
compressed,
className,
}: {
baselineSnapshot: SnapshotMetadata
comparisonRouteCount: number | null
routeDiff: ReturnType<typeof diffRoutesWithSizes> | null
compressed: boolean
className?: string
}) {
const baselineRoutes = baselineSnapshot.routeCount
const comparisonRoutes =
comparisonRouteCount ??
routeDiff?.rows.filter((r) => r.status !== 'removed').length ??
null
const totalA = routeDiff
? compressed
? routeDiff.totalCompressedA
: routeDiff.totalA
: null
const totalB = routeDiff
? compressed
? routeDiff.totalCompressedB
: routeDiff.totalB
: null
const sizeDelta = totalA != null && totalB != null ? totalB - totalA : null
const counts = routeDiff?.counts
return (
<div
className={cn(
'flex flex-none flex-col gap-2 bg-muted/30 px-4 py-3',
className
)}
>
<div className="flex items-center gap-2">
<span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
App
</span>
<span aria-hidden className="h-px flex-1 bg-border" />
</div>
<div className="flex flex-wrap items-stretch gap-2">
<StatCard
label="Total routes"
a={baselineRoutes}
b={comparisonRoutes}
deltaTone="neutral"
/>
<StatCard
label="Total size"
a={totalA}
b={totalB}
formatValue={formatBytes}
deltaValue={sizeDelta}
formatDeltaValue={(d) => formatDelta(d)}
deltaTone="size"
/>
{counts ? (
<>
<CountCard label="Routes added" value={counts.added} tone="added" />
<CountCard
label="Routes removed"
value={counts.removed}
tone="removed"
/>
<CountCard
label="Routes changed"
value={counts.changed}
tone="changed"
/>
<CountCard
label="Routes identical"
value={counts.identical}
tone="identical"
/>
</>
) : null}
</div>
</div>
)
}
/**
* Route-scope stats card shown alongside the app-wide stats in the compare
* view header. Handles the various "no data" states (no route picked yet,
* loading, missing data) inline so the header always occupies a consistent
* slot in the layout.
*/
function RouteStatsCard({
selectedRoute,
sourceDiff,
isAnalyzeLoading,
isBaselineAnalyzeLoading,
baselineAnalyzeError,
compressed,
className,
}: {
selectedRoute: string | null
sourceDiff: DiffSummary<SourceDiffRow> | null
isAnalyzeLoading: boolean
isBaselineAnalyzeLoading: boolean
baselineAnalyzeError: unknown | null
compressed: boolean
className?: string
}) {
const isLoading = isAnalyzeLoading || isBaselineAnalyzeLoading
const body = !selectedRoute ? (
<div className="pt-1 text-xs text-muted-foreground">
Select a route above to see per-source changes.
</div>
) : isLoading ? (
<div className="pt-1 text-xs text-muted-foreground">Loading…</div>
) : !sourceDiff ? (
<div className="pt-1 text-xs text-muted-foreground">
No data for this route.
</div>
) : (
<RouteStatsBody
selectedRoute={selectedRoute}
sourceDiff={sourceDiff}
baselineAnalyzeError={baselineAnalyzeError}
compressed={compressed}
/>
)
return (
<div className={cn('flex flex-none flex-col gap-2 px-4 py-3', className)}>
<div className="flex items-center gap-2">
<span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
Route
</span>
<span aria-hidden className="h-px flex-1 bg-border" />
</div>
{body}
</div>
)
}
/**
* Inner body for {@link RouteStatsCard} when source diff data is available.
* Extracted so the stats card can render a placeholder cleanly when no data
* is ready yet without nesting the data-dependent hooks/derivations above.
*/
function RouteStatsBody({
selectedRoute: _selectedRoute,
sourceDiff,
baselineAnalyzeError: _baselineAnalyzeError,
compressed,
}: {
selectedRoute: string
sourceDiff: DiffSummary<SourceDiffRow>
baselineAnalyzeError: unknown | null
compressed: boolean
}) {
const routeSizeA = compressed
? sourceDiff.totalCompressedA
: sourceDiff.totalA
const routeSizeB = compressed
? sourceDiff.totalCompressedB
: sourceDiff.totalB
const routeSizeDelta = routeSizeB - routeSizeA
const sourceCounts = sourceDiff.counts
return (
<>
{/*
Per-route stat strip. Mirrors the layout of the app-wide strip
but at route scope, so the user reads two parallel summaries:
one for the whole build, one drilled into the selected route.
The source-level counters use a different label prefix
("Sources added" vs. the app-wide "Routes added") to make the
unit unambiguous.
*/}
<div className="flex flex-wrap items-stretch gap-2 pt-1">
<StatCard
label="Total size"
a={routeSizeA}
b={routeSizeB}
formatValue={formatBytes}
deltaValue={routeSizeDelta}
formatDeltaValue={(d) => formatDelta(d)}
deltaTone="size"
/>
<CountCard
label="Sources added"
value={sourceCounts.added}
tone="added"
/>
<CountCard
label="Sources removed"
value={sourceCounts.removed}
tone="removed"
/>
<CountCard
label="Sources changed"
value={sourceCounts.changed}
tone="changed"
/>
<CountCard
label="Sources identical"
value={sourceCounts.identical}
tone="identical"
/>
</div>
</>
)
}
/**
* Per-route comparison panel. Shows the diff treemap. Handles missing-route
* states (the route is new in the comparison build, or was removed) with
* friendly messaging.
*/
function ComparePerRoutePanel({
selectedRoute,
sourceDiff,
analyzeData,
baselineAnalyzeData,
isAnalyzeLoading,
isBaselineAnalyzeLoading,
compressed,
compareSelectedKey,
onCompareSelectedKeyChange,
}: {
selectedRoute: string | null
sourceDiff: DiffSummary<SourceDiffRow> | null
analyzeData: AnalyzeData | null
baselineAnalyzeData: AnalyzeData | null
isAnalyzeLoading: boolean
isBaselineAnalyzeLoading: boolean
compressed: boolean
compareSelectedKey: string | null
onCompareSelectedKeyChange: (key: string | null) => void
}) {
if (!selectedRoute) {
return (
<div className="flex flex-1 items-center justify-center p-4 text-sm text-muted-foreground">
Select a route above to see per-source changes.
</div>
)
}
if (isAnalyzeLoading || isBaselineAnalyzeLoading) {
return (
<div className="p-4">
<TreemapSkeleton />
</div>
)
}
if (!sourceDiff) {
return (
<div className="flex flex-1 items-center justify-center p-4 text-sm text-muted-foreground">
No data for this route.
</div>
)
}
return (
<div className="flex flex-1 min-h-0 flex-col">
<DiffTreemap
summary={sourceDiff}
useCompressed={compressed}
analyzeData={analyzeData}
baselineAnalyzeData={baselineAnalyzeData}
selectedKey={compareSelectedKey}
onSelectKey={onCompareSelectedKeyChange}
/>
</div>
)
}
'use client'
import { useMemo, useState } from 'react'
import type { AnalyzeData } from '@/lib/analyze-data'
import type { DiffSummary, SourceDiffRow } from '@/lib/diff'
import { delta, formatDelta } from '@/lib/diff'
import { SizeMode, type LayoutNode } from '@/lib/treemap-layout'
import { TreemapVisualizer } from '@/components/treemap-visualizer'
/**
* Threshold (bytes) below which a row's delta is considered "noise" and the
* row is rendered as neutral grey rather than a directional color. This keeps the
* visualization legible when the build pipeline produces tiny non-deterministic
* size deltas (e.g., source-map paths, comments).
*/
const NEUTRAL_DELTA_THRESHOLD = 4
/** Color-blind-safe blue/amber palette for bundle-size increases/decreases. */
const COLOR_INCREASE = '#2563eb' // blue-600
const COLOR_INCREASE_MUTED = 'rgba(37, 99, 235, 0.6)'
const COLOR_DECREASE = '#d97706' // amber-600
const COLOR_DECREASE_MUTED = 'rgba(217, 119, 6, 0.6)'
const COLOR_NEUTRAL = '#9ca3af' // gray-400
interface DiffTreemapProps {
summary: DiffSummary<SourceDiffRow>
useCompressed: boolean
/**
* Analyze data for comparison side B. Used as the source-of-truth tree
* when present.
*/
analyzeData: AnalyzeData | null
/**
* Analyze data for the baseline ("A") build. Only used when the route was
* removed (no B-side data) so we can still render the removed sources.
*/
baselineAnalyzeData: AnalyzeData | null
/**
* Currently selected diff row (its `key`). Used so the compare sidebar
* and treemap stay in sync when the user clicks elsewhere.
*/
selectedKey?: string | null
/**
* Fires when the user clicks a tile. Receives the diff row's `key`,
* or `null` if the click cleared selection.
*/
onSelectKey?: (key: string | null) => void
}
/**
* A treemap that visualizes a build-to-build diff using the same tile/layout
* engine as the single-build view. Each leaf tile represents one source
* file, and the color encodes the per-file delta:
*
* - bright blue: added in the comparison build
* - bright amber: removed from the comparison build
* - blue tint: same file, grew since the baseline build
* - amber tint: same file, shrank since the baseline build
* - neutral: same size in both builds
*
* Removed files don't exist in comparison build B's source tree so they
* don't appear in the treemap; users can still see them in the table view.
*/
export function DiffTreemap({
summary,
useCompressed,
analyzeData,
baselineAnalyzeData,
selectedKey,
onSelectKey,
}: DiffTreemapProps) {
// Pick the side that drives the source tree. Prefer comparison build B;
// fall back to baseline A for the "removed route" case where there's no
// B-side data.
const data = analyzeData ?? baselineAnalyzeData
// Map from this side's source index to its diff row. Used by the color
// override to look up the per-tile status.
const rowBySourceIndex = useMemo(() => {
const map = new Map<number, SourceDiffRow>()
const side: 'A' | 'B' = analyzeData ? 'B' : 'A'
for (const row of summary.rows) {
const idx = side === 'B' ? row.sourceIndexB : row.sourceIndexA
if (idx != null) map.set(idx, row)
}
return map
}, [summary, analyzeData])
// The AnalyzeData tree can contain the same source path at multiple indices
// (e.g. one file included in several chunks). In the diff treemap we only
// want each unique path to appear once, using the canonical source index
// stored on the diff row. Passing this as `filterSource` removes all
// duplicate instances from the layout so there are no confusing gray tiles
// and clicking always resolves to a diff row.
const canonicalSourceIndices = useMemo(
() => new Set(rowBySourceIndex.keys()),
[rowBySourceIndex]
)
// Reverse lookup so we can map a selected diff key (full source path) back
// to a source index in the active side's tree.
const sourceIndexByKey = useMemo(() => {
const map = new Map<string, number>()
for (const [idx, row] of rowBySourceIndex.entries()) {
map.set(row.key, idx)
}
return map
}, [rowBySourceIndex])
const getFileColorOverride = useMemo(() => {
return (node: LayoutNode): string | undefined => {
if (node.sourceIndex === undefined) return undefined
const row = rowBySourceIndex.get(node.sourceIndex)
if (!row) return COLOR_NEUTRAL
return colorForRow(row, useCompressed)
}
}, [rowBySourceIndex, useCompressed])
// Show size deltas on tiles instead of absolute sizes. Identical files fall
// back to the default (absolute size) since ±0 on every unchanged tile
// would be noise.
const getFileSizeLabel = useMemo(() => {
return (node: LayoutNode): string | undefined => {
if (node.sourceIndex === undefined) return undefined
const row = rowBySourceIndex.get(node.sourceIndex)
if (!row || row.status === 'identical') return undefined
return formatDelta(delta(row, useCompressed))
}
}, [rowBySourceIndex, useCompressed])
// Focus state stays local: it controls drill-in/zoom, which is purely a
// visual concern of the treemap and shouldn't affect the sidebar.
const initialRoot = useMemo(() => {
if (!data) return 0
const roots = data.sourceRoots()
return roots.length > 0 ? roots[0] : 0
}, [data])
const [focusedSourceIndex, setFocusedSourceIndex] =
useState<number>(initialRoot)
// Translate the externally-driven selection key into the side's source
// index. Falls back to the root so the treemap renders something sensible
// when the selection lives on the other side (e.g., a removed file).
const selectedSourceIndex =
(selectedKey != null ? sourceIndexByKey.get(selectedKey) : undefined) ??
initialRoot
const handleSelectSourceIndex = (idx: number) => {
if (!onSelectKey) return
const row = rowBySourceIndex.get(idx)
onSelectKey(row?.key ?? null)
}
if (!data) {
return (
<div className="flex h-full items-center justify-center text-sm text-muted-foreground">
No data for this route.
</div>
)
}
return (
<TreemapVisualizer
analyzeData={data}
sourceIndex={initialRoot}
selectedSourceIndex={selectedSourceIndex}
onSelectSourceIndex={handleSelectSourceIndex}
focusedSourceIndex={focusedSourceIndex}
onFocusSourceIndex={setFocusedSourceIndex}
filterSource={(idx) => canonicalSourceIndices.has(idx)}
getFileSizeLabel={getFileSizeLabel}
sizeMode={useCompressed ? SizeMode.Compressed : SizeMode.Uncompressed}
getFileColorOverride={getFileColorOverride}
overlay={<DiffLegend hasRemoved={summary.counts.removed > 0} />}
/>
)
}
/**
* Picks a fill color for a diff row. Mirrors the previous DiffTreemap's
* scheme: bright blue/amber for added/removed, lighter tints scaled by the
* relative magnitude of the change for grew/shrank, and neutral grey for
* sub-threshold changes.
*/
function colorForRow(row: SourceDiffRow, useCompressed: boolean): string {
if (row.status === 'added') return COLOR_INCREASE
if (row.status === 'removed') return COLOR_DECREASE
const deltaValue = useCompressed
? row.compressedB - row.compressedA
: row.sizeB - row.sizeA
if (Math.abs(deltaValue) <= NEUTRAL_DELTA_THRESHOLD) {
return COLOR_NEUTRAL
}
// For changed rows, scale opacity by relative magnitude so a 1% change is
// less alarming than a 50% change.
const baseline = useCompressed ? row.compressedA : row.sizeA
const ratio =
baseline === 0 ? 1 : Math.min(1, Math.abs(deltaValue) / baseline)
const alpha = 0.35 + ratio * 0.5
return deltaValue > 0
? `rgba(37, 99, 235, ${alpha.toFixed(2)})`
: `rgba(217, 119, 6, ${alpha.toFixed(2)})`
}
/** Static legend overlay so users can decode the color scheme at a glance. */
function DiffLegend({ hasRemoved }: { hasRemoved: boolean }) {
const items: Array<{ label: string; color: string }> = [
{ label: 'Added', color: COLOR_INCREASE },
{ label: 'Grew', color: COLOR_INCREASE_MUTED },
{ label: 'Unchanged', color: COLOR_NEUTRAL },
{ label: 'Shrank', color: COLOR_DECREASE_MUTED },
]
return (
<div className="absolute bottom-2 left-2 flex items-center gap-3 rounded border border-border bg-background/90 px-2 py-1 text-xs text-muted-foreground shadow-sm">
{items.map((item) => (
<span key={item.label} className="flex items-center gap-1.5">
<span
aria-hidden
className="inline-block h-3 w-3 rounded-sm"
style={{ backgroundColor: item.color }}
/>
{item.label}
</span>
))}
{hasRemoved ? (
<span className="border-l border-border pl-3 italic">
Removed sources are listed in the table view.
</span>
) : null}
</div>
)
}
...@@ -125,31 +125,37 @@ function getTitle(level: ChainLevel) { ...@@ -125,31 +125,37 @@ function getTitle(level: ChainLevel) {
return parts.join('\n') return parts.join('\n')
} }
export function ImportChain({ /**
startFileId, * Pure builder for the import chain. Given a starting source and the
analyzeData, * relevant data structures, returns the chain of dependent modules to
modulesData, * render. Extracted from the {@link ImportChain} component so that the
depthMap, * compare view can build chains for both builds and detect when they're
environmentFilter, * identical (and avoid showing redundant tabs).
}: ImportChainProps) { */
// Filter to include only the current route export function buildImportChain(
const [currentRouteOnly, setCurrentRouteOnly] = useState(true) startFileId: number,
analyzeData: AnalyzeData,
modulesData: ModulesData,
depthMap: Map<ModuleIndex, number>,
environmentFilter: 'client' | 'server',
selectedIndices: number[],
currentRouteOnly: boolean
): ChainLevel[] {
const result: ChainLevel[] = []
const visitedModules = new Set<number>()
// Track which dependent is selected at each level const startPath = analyzeData.getFullSourcePath(startFileId)
const [selectedIndices, setSelectedIndices] = useState<number[]>([]) if (!startPath) return result
// Helper function to get module indices from source path
const getModuleIndicesFromSourceIndex = (sourceIndex: number) => { const getModuleIndicesFromSourceIndex = (sourceIndex: number) => {
const path = analyzeData.getFullSourcePath(sourceIndex) const path = analyzeData.getFullSourcePath(sourceIndex)
return modulesData.getModuleIndiciesFromPath(path) return modulesData.getModuleIndiciesFromPath(path)
} }
// Helper function to get source index from module path
const getSourceIndexFromModuleIndex = (moduleIndex: number) => { const getSourceIndexFromModuleIndex = (moduleIndex: number) => {
const module = modulesData.module(moduleIndex) const module = modulesData.module(moduleIndex)
if (!module) return undefined if (!module) return undefined
// Search through all sources to find one with matching path
const modulePath = module.path const modulePath = module.path
for (let i = 0; i < analyzeData.sourceCount(); i++) { for (let i = 0; i < analyzeData.sourceCount(); i++) {
if (analyzeData.getFullSourcePath(i) === modulePath) { if (analyzeData.getFullSourcePath(i) === modulePath) {
...@@ -159,14 +165,6 @@ export function ImportChain({ ...@@ -159,14 +165,6 @@ export function ImportChain({
return undefined return undefined
} }
// Build the import chain based on current selections
const chain = useMemo(() => {
const result: ChainLevel[] = []
const visitedModules = new Set<number>()
const startPath = analyzeData.getFullSourcePath(startFileId)
if (!startPath) return result
// Get all module indices for the starting source // Get all module indices for the starting source
const startModuleIndices = getModuleIndicesFromSourceIndex( const startModuleIndices = getModuleIndicesFromSourceIndex(
startFileId startFileId
...@@ -249,7 +247,6 @@ export function ImportChain({ ...@@ -249,7 +247,6 @@ export function ImportChain({
) )
if (validDependents.length === 0) { if (validDependents.length === 0) {
// No more dependents or all would create cycles
break break
} }
...@@ -271,15 +268,12 @@ export function ImportChain({ ...@@ -271,15 +268,12 @@ export function ImportChain({
// Sort: sync first, async second, then by source presence, then by depth // Sort: sync first, async second, then by source presence, then by depth
dependentsInfo.sort((a, b) => { dependentsInfo.sort((a, b) => {
// Sort by depth (smallest first)
if (a.depth !== b.depth) { if (a.depth !== b.depth) {
return a.depth - b.depth return a.depth - b.depth
} }
// Sort by ident length (shortest first)
if (a.ident.length !== b.ident.length) { if (a.ident.length !== b.ident.length) {
return a.ident.length - b.ident.length return a.ident.length - b.ident.length
} }
// Sort by ident
return a.ident.localeCompare(b.ident) return a.ident.localeCompare(b.ident)
}) })
...@@ -312,7 +306,32 @@ export function ImportChain({ ...@@ -312,7 +306,32 @@ export function ImportChain({
} }
return result return result
// eslint-disable-next-line react-hooks/exhaustive-deps }
export function ImportChain({
startFileId,
analyzeData,
modulesData,
depthMap,
environmentFilter,
}: ImportChainProps) {
// Filter to include only the current route
const [currentRouteOnly, setCurrentRouteOnly] = useState(true)
// Track which dependent is selected at each level
const [selectedIndices, setSelectedIndices] = useState<number[]>([])
// Build the import chain based on current selections
const chain = useMemo(() => {
return buildImportChain(
startFileId,
analyzeData,
modulesData,
depthMap,
environmentFilter,
selectedIndices,
currentRouteOnly
)
}, [ }, [
startFileId, startFileId,
analyzeData, analyzeData,
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
import useSWR from 'swr' import useSWR from 'swr'
import { Check, ChevronsUpDown, Loader, Route } from 'lucide-react' import { Check, ChevronsUpDown, Loader, Route } from 'lucide-react'
import { useEffect, useState } from 'react' import { useEffect, useMemo, useState } from 'react'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { import {
Command, Command,
...@@ -20,15 +20,33 @@ import { ...@@ -20,15 +20,33 @@ import {
import { cn, jsonFetcher } from '@/lib/utils' import { cn, jsonFetcher } from '@/lib/utils'
import { NetworkError } from '@/lib/errors' import { NetworkError } from '@/lib/errors'
import { Kbd } from '@/components/ui/kbd' import { Kbd } from '@/components/ui/kbd'
import {
delta,
formatDelta,
sortByImpact,
type DiffRow,
type DiffSummary,
} from '@/lib/diff'
interface RouteTypeaheadProps { interface RouteTypeaheadProps {
selectedRoute: string | null selectedRoute: string | null
onRouteSelected: (routeName: string) => void onRouteSelected: (routeName: string) => void
/**
* When provided, the picker renders per-route size deltas next to each
* route, sorts by largest impact, and uses the diff's route list as its
* source of truth (so added/removed routes appear with appropriate
* styling).
*/
routeDiff?: DiffSummary | null
/** Whether to use compressed sizes when computing the delta column. */
useCompressed?: boolean
} }
export function RouteTypeahead({ export function RouteTypeahead({
selectedRoute, selectedRoute,
onRouteSelected, onRouteSelected,
routeDiff,
useCompressed = true,
}: RouteTypeaheadProps) { }: RouteTypeaheadProps) {
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
const [shortcutLabel, setShortcutLabel] = useState<string | null>(null) const [shortcutLabel, setShortcutLabel] = useState<string | null>(null)
...@@ -71,6 +89,27 @@ export function RouteTypeahead({ ...@@ -71,6 +89,27 @@ export function RouteTypeahead({
}, },
}) })
// When a route diff is provided, sort routes by largest absolute impact so
// the most-changed route bubbles to the top — matching the rest of the
// compare UI. Without a diff, fall back to the natural routes.json order.
const orderedItems = useMemo<RouteItem[]>(() => {
if (routeDiff) {
const sorted = sortByImpact(routeDiff.rows, useCompressed)
return sorted.map((row) => ({
name: row.key,
row,
}))
}
return (routes ?? []).map((name) => ({ name, row: null }))
}, [routes, routeDiff, useCompressed])
// Find the currently selected route's diff row, used to render a delta
// badge in the trigger button.
const selectedRow = useMemo(() => {
if (!routeDiff || !selectedRoute) return null
return routeDiff.rows.find((r) => r.key === selectedRoute) ?? null
}, [routeDiff, selectedRoute])
if (error) { if (error) {
return ( return (
<div className="flex items-center gap-2 px-3 py-2 rounded-md bg-destructive/10 border border-destructive/20 text-destructive text-sm max-w-full"> <div className="flex items-center gap-2 px-3 py-2 rounded-md bg-destructive/10 border border-destructive/20 text-destructive text-sm max-w-full">
...@@ -84,7 +123,7 @@ export function RouteTypeahead({ ...@@ -84,7 +123,7 @@ export function RouteTypeahead({
) )
} }
let ctaText let ctaText: React.ReactNode
if (isLoading) { if (isLoading) {
ctaText = 'Loading routes...' ctaText = 'Loading routes...'
} else if (selectedRoute != null) { } else if (selectedRoute != null) {
...@@ -104,14 +143,17 @@ export function RouteTypeahead({ ...@@ -104,14 +143,17 @@ export function RouteTypeahead({
disabled={isLoading} disabled={isLoading}
className="flex-grow-1 w-full justify-between font-mono text-sm" className="flex-grow-1 w-full justify-between font-mono text-sm"
> >
<div className="flex items-center"> <div className="flex items-center min-w-0">
{isLoading ? ( {isLoading ? (
<Loader className="mr-2 inline animate-spin" /> <Loader className="mr-2 inline animate-spin" />
) : ( ) : (
<Route className="inline mr-2" /> <Route className="inline mr-2 shrink-0" />
)} )}
{ctaText} <span className="truncate">{ctaText}</span>
{selectedRow ? (
<DeltaBadge row={selectedRow} useCompressed={useCompressed} />
) : null}
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{shortcutLabel && <Kbd>{shortcutLabel}</Kbd>} {shortcutLabel && <Kbd>{shortcutLabel}</Kbd>}
...@@ -125,27 +167,32 @@ export function RouteTypeahead({ ...@@ -125,27 +167,32 @@ export function RouteTypeahead({
<CommandList> <CommandList>
<CommandEmpty>No route found.</CommandEmpty> <CommandEmpty>No route found.</CommandEmpty>
<CommandGroup> <CommandGroup>
{(routes || []).map((route) => { {orderedItems.map(({ name, row }) => (
return (
<CommandItem <CommandItem
key={route} key={name}
value={route} value={name}
onSelect={() => { onSelect={() => {
onRouteSelected(route) onRouteSelected(name)
setOpen(false) setOpen(false)
}} }}
className="font-mono" className="font-mono"
> >
<Check <Check
className={cn( className={cn(
'mr-2 h-4 w-4', 'mr-2 h-4 w-4 shrink-0',
selectedRoute === route ? 'opacity-100' : 'opacity-0' selectedRoute === name ? 'opacity-100' : 'opacity-0'
)} )}
/> />
{route} <span className="truncate">{name}</span>
{row ? (
<DeltaBadge
row={row}
useCompressed={useCompressed}
className="ml-auto"
/>
) : null}
</CommandItem> </CommandItem>
) ))}
})}
</CommandGroup> </CommandGroup>
</CommandList> </CommandList>
</Command> </Command>
...@@ -154,3 +201,51 @@ export function RouteTypeahead({ ...@@ -154,3 +201,51 @@ export function RouteTypeahead({
</div> </div>
) )
} }
interface RouteItem {
name: string
row: DiffRow | null
}
/**
* Compact, color-coded badge showing a route's size delta. Hidden when the
* row has no meaningful change.
*/
function DeltaBadge({
row,
useCompressed,
className,
}: {
row: DiffRow
useCompressed: boolean
className?: string
}) {
if (row.status === 'identical') return null
const d = delta(row, useCompressed)
// For added/removed routes the delta carries the only signal, so always
// render. For changed routes, suppress sub-byte noise.
if (row.status === 'changed' && d === 0) return null
const tone =
row.status === 'added' || d > 0
? 'text-red-600 dark:text-red-400'
: row.status === 'removed' || d < 0
? 'text-green-600 dark:text-green-400'
: 'text-muted-foreground'
return (
<span
className={cn(
'ml-2 shrink-0 text-xs tabular-nums font-sans',
tone,
className
)}
>
{row.status === 'added'
? '+ new'
: row.status === 'removed'
? '− removed'
: formatDelta(d)}
</span>
)
}
'use client' 'use client'
import type React from 'react' import type React from 'react'
import { useState, useMemo } from 'react'
import { CircleHelp } from 'lucide-react' import { CircleHelp } from 'lucide-react'
import { import {
Tooltip, Tooltip,
...@@ -12,8 +13,10 @@ import { ImportChain } from '@/components/import-chain' ...@@ -12,8 +13,10 @@ import { ImportChain } from '@/components/import-chain'
import { Skeleton } from '@/components/ui/skeleton' import { Skeleton } from '@/components/ui/skeleton'
import { AnalyzeData, ModulesData } from '@/lib/analyze-data' import { AnalyzeData, ModulesData } from '@/lib/analyze-data'
import { SpecialModule } from '@/lib/types' import { SpecialModule } from '@/lib/types'
import { getSpecialModuleType } from '@/lib/utils' import { cn, getSpecialModuleType } from '@/lib/utils'
import { Badge } from './ui/badge' import { Badge } from './ui/badge'
import type { DiffSummary, SourceDiffRow } from '@/lib/diff'
import { formatDelta } from '@/lib/diff'
interface SidebarProps { interface SidebarProps {
sidebarWidth: number sidebarWidth: number
...@@ -217,6 +220,181 @@ function SelectionDetails({ ...@@ -217,6 +220,181 @@ function SelectionDetails({
) )
} }
export function CompareSidebar({
selectedKey,
sourceDiff,
analyzeData,
baselineAnalyzeData,
modulesData,
baselineModulesData,
moduleDepthMap,
baselineModuleDepthMap,
environmentFilter,
sidebarWidth,
aLabel,
bLabel,
}: {
selectedKey: string | null
sourceDiff: DiffSummary<SourceDiffRow> | null
analyzeData: AnalyzeData | null
baselineAnalyzeData: AnalyzeData | null
modulesData: ModulesData | null
baselineModulesData: ModulesData | null
moduleDepthMap: Map<number, number>
baselineModuleDepthMap: Map<number, number>
environmentFilter: 'client' | 'server'
sidebarWidth: number
aLabel: string
bLabel: string
}) {
const selectedRow = useMemo(() => {
if (!selectedKey || !sourceDiff) return null
return sourceDiff.rows.find((r) => r.key === selectedKey) ?? null
}, [selectedKey, sourceDiff])
return (
<div
className="flex-none bg-muted border-l border-border overflow-y-auto"
style={{ width: `${sidebarWidth}%` }}
>
{selectedRow ? (
<CompareSidebarContent
key={selectedRow.key}
row={selectedRow}
analyzeData={analyzeData}
baselineAnalyzeData={baselineAnalyzeData}
modulesData={modulesData}
baselineModulesData={baselineModulesData}
moduleDepthMap={moduleDepthMap}
baselineModuleDepthMap={baselineModuleDepthMap}
environmentFilter={environmentFilter}
aLabel={aLabel}
bLabel={bLabel}
/>
) : (
<div className="p-3 text-xs text-muted-foreground">
Click a row or treemap tile to see import details.
</div>
)}
</div>
)
}
function CompareSidebarContent({
row,
analyzeData,
baselineAnalyzeData,
modulesData,
baselineModulesData,
moduleDepthMap,
baselineModuleDepthMap,
environmentFilter,
aLabel,
bLabel,
}: {
row: SourceDiffRow
analyzeData: AnalyzeData | null
baselineAnalyzeData: AnalyzeData | null
modulesData: ModulesData | null
baselineModulesData: ModulesData | null
moduleDepthMap: Map<number, number>
baselineModuleDepthMap: Map<number, number>
environmentFilter: 'client' | 'server'
aLabel: string
bLabel: string
}) {
const hasBoth = row.sourceIndexA != null && row.sourceIndexB != null
const [activeTab, setActiveTab] = useState<'A' | 'B'>(
row.status === 'removed' ? 'A' : 'B'
)
const activeSourceIndex =
activeTab === 'A' ? row.sourceIndexA : row.sourceIndexB
const activeAnalyzeData =
activeTab === 'A' ? baselineAnalyzeData : analyzeData
const activeModulesData =
activeTab === 'A' ? baselineModulesData : modulesData
const activeDepthMap =
activeTab === 'A' ? baselineModuleDepthMap : moduleDepthMap
const compressedDelta = row.compressedB - row.compressedA
return (
<div className="flex-1 p-3 space-y-4 overflow-y-auto">
<div className="space-y-1">
<h2 className="text-s font-semibold text-foreground break-all">
{row.name}
</h2>
<div className="text-xs space-y-0.5">
<div className="flex items-baseline gap-1 flex-wrap">
<span className="text-muted-foreground font-mono">
{formatBytes(row.compressedA)}
</span>
<span className="text-muted-foreground">→</span>
<span className="font-mono">{formatBytes(row.compressedB)}</span>
<span className="text-muted-foreground">compressed</span>
{row.status !== 'identical' && (
<span
className={cn(
'font-mono',
compressedDelta > 0 && 'text-red-600 dark:text-red-400',
compressedDelta < 0 && 'text-green-600 dark:text-green-400',
compressedDelta === 0 && 'text-muted-foreground'
)}
>
{formatDelta(compressedDelta)}
</span>
)}
</div>
</div>
</div>
{hasBoth && (
<div className="flex gap-1">
<button
type="button"
onClick={() => setActiveTab('A')}
className={cn(
'px-2 py-0.5 text-xs rounded transition-colors',
activeTab === 'A'
? 'bg-secondary text-secondary-foreground'
: 'text-muted-foreground hover:text-foreground'
)}
>
{aLabel}
</button>
<button
type="button"
onClick={() => setActiveTab('B')}
className={cn(
'px-2 py-0.5 text-xs rounded transition-colors',
activeTab === 'B'
? 'bg-secondary text-secondary-foreground'
: 'text-muted-foreground hover:text-foreground'
)}
>
{bLabel}
</button>
</div>
)}
{activeSourceIndex != null && activeAnalyzeData && activeModulesData ? (
<ImportChain
startFileId={activeSourceIndex}
analyzeData={activeAnalyzeData}
modulesData={activeModulesData}
depthMap={activeDepthMap}
environmentFilter={environmentFilter}
/>
) : (
<p className="text-xs text-muted-foreground italic">
Import chain not available.
</p>
)}
</div>
)
}
function InlineHelpTooltip({ children }: { children: React.ReactNode }) { function InlineHelpTooltip({ children }: { children: React.ReactNode }) {
return ( return (
<TooltipProvider> <TooltipProvider>
......
import { cn } from '@/lib/utils'
/**
* Inline colored delta rendered next to the `A → B` value. For size deltas,
* positive deltas (regressions) are red and negative (improvements) are
* emerald — matching how regressions are usually framed. Neutral deltas
* (counts) render muted.
*/
export function DeltaChip({
delta,
tone,
render,
}: {
delta: number
tone: 'neutral' | 'size'
render: (delta: number) => string
}) {
const toneClass =
tone === 'size'
? delta > 0
? 'text-red-400'
: delta < 0
? 'text-emerald-400'
: 'text-muted-foreground'
: 'text-muted-foreground'
return (
<span
className={cn(
'shrink-0 whitespace-nowrap font-mono text-xs tabular-nums',
toneClass
)}
>
{render(delta)}
</span>
)
}
/**
* Compact `A → B` card. Used for both counts (Total routes) and sizes
* (Total size). The delta chip is auto-derived from the values unless an
* explicit `deltaValue` is provided (e.g. a precomputed compressed delta).
*/
export function StatCard({
label,
a,
b,
formatValue = (v: number) => String(v),
deltaValue,
formatDeltaValue,
deltaTone,
}: {
label: string
a: number | null
b: number | null
formatValue?: (value: number) => string
deltaValue?: number | null
formatDeltaValue?: (delta: number) => string
deltaTone: 'neutral' | 'size'
}) {
const computedDelta =
deltaValue !== undefined
? deltaValue
: a != null && b != null
? b - a
: null
const renderDelta =
formatDeltaValue ??
((d: number) => (d === 0 ? '±0' : d > 0 ? `+${d}` : `${d}`))
return (
<div className="flex min-w-[112px] flex-1 flex-col gap-1 rounded-md border border-border bg-background/60 px-3 py-2">
<div className="text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
{label}
</div>
<div className="flex flex-wrap items-baseline gap-x-1.5 gap-y-1">
<span className="font-mono text-xs tabular-nums text-foreground">
{a != null ? formatValue(a) : '—'}
</span>
<span aria-hidden className="text-xs text-muted-foreground">
→
</span>
<span className="font-mono text-xs font-semibold tabular-nums text-foreground">
{b != null ? formatValue(b) : '—'}
</span>
{computedDelta != null ? (
<DeltaChip
delta={computedDelta}
tone={deltaTone}
render={renderDelta}
/>
) : null}
</div>
</div>
)
}
/** Single-number card for category counts (Added / Removed / etc). */
export function CountCard({
label,
value,
tone,
}: {
label: string
value: number
tone: 'added' | 'removed' | 'changed' | 'identical'
}) {
const toneClass =
tone === 'added'
? 'text-red-500'
: tone === 'removed'
? 'text-green-500'
: tone === 'changed'
? 'text-amber-500'
: 'text-muted-foreground'
return (
<div className="flex min-w-[80px] flex-col gap-1 rounded-md border border-border bg-background/60 px-3 py-2">
<div className="text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
{label}
</div>
<div
className={cn(
'font-mono text-base font-semibold tabular-nums',
toneClass
)}
>
{value}
</div>
</div>
)
}
'use client'
import { BaselinePicker } from '@/components/baseline-picker'
import { FileSearch } from '@/components/file-search'
import { RouteTypeahead } from '@/components/route-typeahead'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { MultiSelect } from '@/components/ui/multi-select'
import { diffRoutesWithSizes } from '@/lib/diff'
import { type SnapshotMetadata } from '@/lib/snapshot'
import {
Monitor,
Server,
FileCode,
FileJson,
Palette,
Package,
} from 'lucide-react'
export enum Environment {
Client = 'client',
Server = 'server',
}
const typeFilterOptions = [
{
value: 'js',
label: 'JavaScript',
icon: <FileCode className="h-3.5 w-3.5" />,
},
{ value: 'css', label: 'CSS', icon: <Palette className="h-3.5 w-3.5" /> },
{
value: 'json',
label: 'JSON',
icon: <FileJson className="h-3.5 w-3.5" />,
},
{
value: 'asset',
label: 'Asset',
icon: <Package className="h-3.5 w-3.5" />,
},
]
export function ControlDivider() {
return <span className="h-6 w-px bg-muted-foreground/30" />
}
export function TopBar({
selectedRoute,
setSelectedRoute,
environmentFilter,
setEnvironmentFilter,
setSelectedSourceIndex,
setFocusedSourceIndex,
typeFilter,
setTypeFilter,
searchQuery,
setSearchQuery,
baselineSnapshot,
onBaselineChange,
comparisonSnapshot,
onComparisonChange,
routeDiff,
hasSourceData,
}: {
hasSourceData: boolean
selectedRoute: string | null
setSelectedRoute: (route: string | null) => void
environmentFilter: Environment
setEnvironmentFilter: (env: Environment) => void
setSelectedSourceIndex: (index: number | null) => void
setFocusedSourceIndex: (index: number | null) => void
typeFilter: string[]
setTypeFilter: (types: string[]) => void
searchQuery: string
setSearchQuery: (query: string) => void
baselineSnapshot: SnapshotMetadata | null
onBaselineChange: (snapshot: SnapshotMetadata | null) => void
comparisonSnapshot: SnapshotMetadata | null
onComparisonChange: (snapshot: SnapshotMetadata | null) => void
routeDiff: ReturnType<typeof diffRoutesWithSizes> | null
}) {
const isCompareMode = baselineSnapshot != null
return (
<div className="flex-none px-4 py-2 border-b border-border flex items-center gap-3">
<div className="flex-1 flex">
<RouteTypeahead
selectedRoute={selectedRoute}
onRouteSelected={(route) => {
setSelectedRoute(route)
setSelectedSourceIndex(null)
setFocusedSourceIndex(null)
}}
routeDiff={isCompareMode ? routeDiff : null}
useCompressed
/>
</div>
<div className="flex items-center gap-2">
<BaselinePicker
selectedSnapshotId={baselineSnapshot?.id ?? null}
onSelectionChange={onBaselineChange}
excludedSnapshotId={comparisonSnapshot?.id}
prefix="from"
placeholder="Compare from…"
/>
{isCompareMode ? (
<BaselinePicker
selectedSnapshotId={comparisonSnapshot?.id ?? null}
onSelectionChange={onComparisonChange}
excludedSnapshotId={baselineSnapshot?.id}
prefix="to"
placeholder="to Latest"
clearLabel="Compare with latest"
/>
) : null}
{hasSourceData && (
<>
<ControlDivider />
<Select
value={environmentFilter}
onValueChange={(value: Environment) =>
setEnvironmentFilter(value)
}
>
<SelectTrigger className="w-28">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={Environment.Client}>
<div className="flex items-center gap-1.5">
<Monitor className="h-3.5 w-3.5" />
<span className="text-xs">Client</span>
</div>
</SelectItem>
<SelectItem value={Environment.Server}>
<div className="flex items-center gap-1.5">
<Server className="h-3.5 w-3.5" />
<span className="text-xs">Server</span>
</div>
</SelectItem>
</SelectContent>
</Select>
<MultiSelect
options={typeFilterOptions}
value={typeFilter}
onValueChange={setTypeFilter}
selectionName={{ singular: 'file type', plural: 'file types' }}
triggerIcon={<FileCode className="h-3.5 w-3.5" />}
triggerClassName="w-36"
aria-label="Filter by file type"
/>
{!isCompareMode && (
<>
<ControlDivider />
<FileSearch value={searchQuery} onChange={setSearchQuery} />
</>
)}
</>
)}
</div>
</div>
)
}
...@@ -31,6 +31,23 @@ interface TreemapVisualizerProps { ...@@ -31,6 +31,23 @@ interface TreemapVisualizerProps {
isModulePolyfillChunk?: (sourceIndex: number) => boolean isModulePolyfillChunk?: (sourceIndex: number) => boolean
isNoModulePolyfillChunk?: (sourceIndex: number) => boolean isNoModulePolyfillChunk?: (sourceIndex: number) => boolean
sizeMode?: SizeMode sizeMode?: SizeMode
/**
* Optional override for file tile colors. Returning `undefined` falls back
* to the default file-type-based color. Used by the compare view to color
* tiles by diff status (added/removed/grew/shrank) instead of by file type.
*/
getFileColorOverride?: (node: LayoutNode) => string | undefined
/**
* Optional override for the size label shown on a tile. Returning `undefined`
* falls back to `formatBytes(node.size)`. Used by the compare view to show
* size deltas (e.g. "+1.2 KB") instead of absolute sizes.
*/
getFileSizeLabel?: (node: LayoutNode) => string | undefined
/**
* Optional overlay rendered on top of the treemap canvas. Used by the
* compare view to render a red/green legend.
*/
overlay?: React.ReactNode
} }
function getFileColor(node: { function getFileColor(node: {
...@@ -275,6 +292,8 @@ function drawTreemap( ...@@ -275,6 +292,8 @@ function drawTreemap(
searchQuery: string, searchQuery: string,
originalData: LayoutNode, originalData: LayoutNode,
immediateHoveredSourceIndex: number | undefined, immediateHoveredSourceIndex: number | undefined,
getFileColorOverride: ((node: LayoutNode) => string | undefined) | undefined,
getFileSizeLabel: ((node: LayoutNode) => string | undefined) | undefined,
currentPath: string[] = [], currentPath: string[] = [],
parentFadedOut = false, parentFadedOut = false,
insideActiveSubtree = false insideActiveSubtree = false
...@@ -332,6 +351,8 @@ function drawTreemap( ...@@ -332,6 +351,8 @@ function drawTreemap(
searchQuery, searchQuery,
originalData, originalData,
immediateHoveredSourceIndex, immediateHoveredSourceIndex,
getFileColorOverride,
getFileSizeLabel,
path, path,
parentFadedOut, parentFadedOut,
insideActiveSubtree insideActiveSubtree
...@@ -395,7 +416,7 @@ function drawTreemap( ...@@ -395,7 +416,7 @@ function drawTreemap(
sourceIndex !== undefined && sourceIndex === immediateHoveredSourceIndex sourceIndex !== undefined && sourceIndex === immediateHoveredSourceIndex
if (type === 'file') { if (type === 'file') {
let color = getFileColor(node) let color = getFileColorOverride?.(node) ?? getFileColor(node)
// Apply brightness boost to immediately hovered node // Apply brightness boost to immediately hovered node
if (isImmediateHovered) { if (isImmediateHovered) {
...@@ -418,7 +439,7 @@ function drawTreemap( ...@@ -418,7 +439,7 @@ function drawTreemap(
const maxWidth = rect.width - 8 const maxWidth = rect.width - 8
const sizeText = formatBytes(node.size) const sizeText = getFileSizeLabel?.(node) ?? formatBytes(node.size)
const fontSize = 12 const fontSize = 12
const sizeFontSize = 10 const sizeFontSize = 10
const lineHeight = fontSize + 2 const lineHeight = fontSize + 2
...@@ -617,6 +638,8 @@ function drawTreemap( ...@@ -617,6 +638,8 @@ function drawTreemap(
searchQuery, searchQuery,
originalData, originalData,
immediateHoveredSourceIndex, immediateHoveredSourceIndex,
getFileColorOverride,
getFileSizeLabel,
path, path,
childFadeOut, childFadeOut,
childInsideActiveSubtree childInsideActiveSubtree
...@@ -709,6 +732,9 @@ export function TreemapVisualizer({ ...@@ -709,6 +732,9 @@ export function TreemapVisualizer({
searchQuery = '', searchQuery = '',
filterSource, filterSource,
sizeMode = SizeMode.Compressed, sizeMode = SizeMode.Compressed,
getFileColorOverride,
getFileSizeLabel,
overlay,
}: TreemapVisualizerProps) { }: TreemapVisualizerProps) {
const canvasRef = useRef<HTMLCanvasElement>(null) const canvasRef = useRef<HTMLCanvasElement>(null)
const containerRef = useRef<HTMLDivElement>(null) const containerRef = useRef<HTMLDivElement>(null)
...@@ -872,7 +898,9 @@ export function TreemapVisualizer({ ...@@ -872,7 +898,9 @@ export function TreemapVisualizer({
focusedAncestorChain, focusedAncestorChain,
searchQuery, searchQuery,
layout, layout,
hoveredNode?.sourceIndex hoveredNode?.sourceIndex,
getFileColorOverride,
getFileSizeLabel
) )
}, [ }, [
layout, layout,
...@@ -884,6 +912,8 @@ export function TreemapVisualizer({ ...@@ -884,6 +912,8 @@ export function TreemapVisualizer({
focusedAncestorChain, focusedAncestorChain,
searchQuery, searchQuery,
hoveredNode, hoveredNode,
getFileColorOverride,
getFileSizeLabel,
]) ])
const handleClick = (e: React.MouseEvent<HTMLCanvasElement>) => { const handleClick = (e: React.MouseEvent<HTMLCanvasElement>) => {
...@@ -1009,7 +1039,7 @@ export function TreemapVisualizer({ ...@@ -1009,7 +1039,7 @@ export function TreemapVisualizer({
return ( return (
<div <div
ref={containerRef} ref={containerRef}
className="w-full h-full bg-background border border-border rounded-lg overflow-hidden" className="relative w-full h-full bg-background border border-border rounded-lg overflow-hidden"
> >
<canvas <canvas
ref={canvasRef} ref={canvasRef}
...@@ -1021,6 +1051,7 @@ export function TreemapVisualizer({ ...@@ -1021,6 +1051,7 @@ export function TreemapVisualizer({
onDoubleClick={handleDoubleClick} onDoubleClick={handleDoubleClick}
className="block w-full h-full" className="block w-full h-full"
/> />
{overlay}
</div> </div>
) )
} }
......
import { AnalyzeData, type SourceIndex } from './analyze-data'
import { formatBytes } from './utils'
/**
* Formats a byte delta with an explicit sign (or `±0` for no change). Used
* by the diff table and route picker to render compact change indicators.
*/
export function formatDelta(deltaBytes: number): string {
if (deltaBytes === 0) return '±0'
const sign = deltaBytes > 0 ? '+' : '−'
return `${sign}${formatBytes(Math.abs(deltaBytes))}`
}
/**
* Represents how a row (route, source, etc.) changed between two builds.
*
* - `added`: present in `B` (the latest build) only
* - `removed`: present in `A` (the historical build) only
* - `changed`: present in both, but the size delta is non-zero
* - `identical`: present in both with no size change
*/
export type DiffStatus = 'added' | 'removed' | 'changed' | 'identical'
/**
* Per-row diff entry: one logical thing (a route, a source path) compared
* across two builds.
*
* Sizes are all measured in bytes. We carry both compressed and raw sizes
* because the existing UI exposes both modes — comparison should respect the
* user's choice.
*/
export interface DiffRow {
/** Stable join key (route path or full source path). */
key: string
/** Display label. For routes, same as `key`. For sources, the basename or relative-to-project segment. */
name: string
status: DiffStatus
/** Size in build A (the historical baseline). 0 when added. */
sizeA: number
/** Size in build B (the latest build). 0 when removed. */
sizeB: number
/** Compressed size in build A. */
compressedA: number
/** Compressed size in build B. */
compressedB: number
}
/**
* Aggregate totals + categorized rows for a build comparison.
*/
export interface DiffSummary<Row extends DiffRow = DiffRow> {
rows: Row[]
/** Counts by status, useful for headline badges. */
counts: Record<DiffStatus, number>
/** Sum of `sizeA` over all rows. */
totalA: number
/** Sum of `sizeB` over all rows. */
totalB: number
/** Sum of `compressedA` over all rows. */
totalCompressedA: number
/** Sum of `compressedB` over all rows. */
totalCompressedB: number
}
/** Returns `B - A` for a row. */
export function delta(row: DiffRow, useCompressed: boolean): number {
return useCompressed
? row.compressedB - row.compressedA
: row.sizeB - row.sizeA
}
/** Returns the status for a row given the two sizes. */
function statusFor(
sizeA: number,
sizeB: number,
presentInA: boolean,
presentInB: boolean
): DiffStatus {
if (presentInA && !presentInB) return 'removed'
if (!presentInA && presentInB) return 'added'
if (sizeA === sizeB) return 'identical'
return 'changed'
}
/** Builds an empty {@link DiffSummary}. */
function emptySummary<Row extends DiffRow>(): DiffSummary<Row> {
return {
rows: [],
counts: { added: 0, removed: 0, changed: 0, identical: 0 },
totalA: 0,
totalB: 0,
totalCompressedA: 0,
totalCompressedB: 0,
}
}
/** Adds a row to a summary, updating counts and totals. */
function pushRow<Row extends DiffRow>(
summary: DiffSummary<Row>,
row: Row
): void {
summary.rows.push(row)
summary.counts[row.status] += 1
summary.totalA += row.sizeA
summary.totalB += row.sizeB
summary.totalCompressedA += row.compressedA
summary.totalCompressedB += row.compressedB
}
/**
* Diffs two route lists. Routes are compared by their page path. Without
* per-route data loaded (which would be N round-trips), the size columns are
* left at zero; the table view fills them in lazily as the user expands rows.
*/
export function diffRouteLists(
routesA: string[] | null,
routesB: string[]
): DiffSummary {
const summary = emptySummary()
const setA = new Set(routesA ?? [])
const setB = new Set(routesB)
const all = new Set<string>([...setA, ...setB])
const sorted = Array.from(all).sort()
for (const route of sorted) {
const inA = setA.has(route)
const inB = setB.has(route)
pushRow(summary, {
key: route,
name: route,
status: statusFor(0, 0, inA, inB),
sizeA: 0,
sizeB: 0,
compressedA: 0,
compressedB: 0,
})
}
return summary
}
/**
* Per-route size aggregates contributed by a single side (A or B). When a
* route is missing from the corresponding map entirely, it's treated as
* "not present in that build".
*/
export interface RouteSizeTotals {
size: number
compressedSize: number
}
/**
* Sums the `getOwnSizes` of every leaf source in an {@link AnalyzeData},
* giving a single route's total contribution. This matches what the existing
* route sidebar shows for each route in non-compare mode.
*/
export function totalsFromAnalyzeData(
data: AnalyzeData,
filter?: (sourceIndex: SourceIndex) => boolean
): RouteSizeTotals {
let size = 0
let compressedSize = 0
const count = data.sourceCount()
for (let i = 0; i < count; i++) {
if (data.sourceChildren(i).length > 0) continue
if (filter && !filter(i)) continue
const own = data.getOwnSizes(i)
size += own.size
compressedSize += own.compressedSize
}
return { size, compressedSize }
}
/**
* Size-aware variant of {@link diffRouteLists}. When `sizesA`/`sizesB` are
* provided, routes get real `changed`/`identical` classification based on
* their summed source sizes — not just name-presence.
*
* A route is `added` if it is missing from `sizesA`, `removed` if missing
* from `sizesB`. `sizesA == null` means the baseline is still loading and we
* fall back to the name-only diff (`diffRouteLists`).
*/
export function diffRoutesWithSizes(
routesA: string[] | null,
routesB: string[],
sizesA: ReadonlyMap<string, RouteSizeTotals> | null,
sizesB: ReadonlyMap<string, RouteSizeTotals>
): DiffSummary {
if (!sizesA) return diffRouteLists(routesA, routesB)
const summary = emptySummary()
const setA = new Set(routesA ?? [])
const setB = new Set(routesB)
const all = new Set<string>([...setA, ...setB])
const sorted = Array.from(all).sort()
for (const route of sorted) {
const a = sizesA.get(route)
const b = sizesB.get(route)
const inA = setA.has(route)
const inB = setB.has(route)
const sizeA = a?.size ?? 0
const sizeB = b?.size ?? 0
pushRow(summary, {
key: route,
name: route,
status: statusFor(sizeA, sizeB, inA, inB),
sizeA,
sizeB,
compressedA: a?.compressedSize ?? 0,
compressedB: b?.compressedSize ?? 0,
})
}
return summary
}
/**
* A {@link DiffRow} for a source (file or module), including the indices we
* need to look it back up in either side's {@link AnalyzeData}.
*/
export interface SourceDiffRow extends DiffRow {
sourceIndexA: SourceIndex | null
sourceIndexB: SourceIndex | null
/**
* Whether the source lives in an npm package (`package`) or is part of the
* user's project (`project`). Used by the diff table to pick an icon.
*/
pathKind: 'package' | 'project'
/** Resolved npm package name when `pathKind === 'package'`. */
packageName?: string
/**
* Environment flags reflecting where the leaf is bundled. Mirrors what
* the treemap hover footer already shows. Computed via
* `AnalyzeData.getSourceFlags` at diff time so the table can render
* `client` / `server` badges without re-deriving them per row.
*
* Both flags can be `true` simultaneously (a source can be pulled into
* both client and server bundles).
*/
client: boolean
server: boolean
}
interface SourceDiffOptions {
/** When provided, sources for which `filterSource(side, index) === false` are excluded. */
filterSource?: (side: 'A' | 'B', index: SourceIndex) => boolean
}
/**
* Per-side leaf entry as collected from an {@link AnalyzeData}. The
* `index` points back into that side's data so callers (e.g. the sidebar
* import-chain panel) can resolve the original source.
*/
interface LeafEntry {
index: SourceIndex
size: number
compressedSize: number
/** Bundled into the client environment. */
client: boolean
/** Bundled into the server environment. */
server: boolean
}
/**
* Walks every leaf source in `data` (skipping directory aggregations and
* empty contributions) and returns them keyed by full path.
*/
function collectLeaves(
side: 'A' | 'B',
data: AnalyzeData,
options: SourceDiffOptions
): Map<string, LeafEntry> {
const out = new Map<string, LeafEntry>()
const count = data.sourceCount()
for (let i = 0; i < count; i++) {
// Only include leaf sources (real files, not directory aggregations).
if (data.sourceChildren(i).length > 0) continue
if (options.filterSource && !options.filterSource(side, i)) continue
const fullPath = data.getFullSourcePath(i)
if (!fullPath) continue
const own = data.getOwnSizes(i)
// Skip empty contributions — they aren't really "in" the bundle.
if (own.size === 0 && own.compressedSize === 0) continue
const flags = data.getSourceFlags(i)
out.set(fullPath, {
index: i,
size: own.size,
compressedSize: own.compressedSize,
client: flags.client,
server: flags.server,
})
}
return out
}
/**
* Diffs every source between two analyze datasets, joining by full source
* path (stable across builds modulo file moves).
*
* Directories (sources with children) are excluded — only leaf "files" appear
* in the resulting rows. Their own size is the sum of their {@link
* AnalyzeData.sourceChunkParts} contributions.
*/
export function diffSources(
analyzeA: AnalyzeData | null,
analyzeB: AnalyzeData,
options: SourceDiffOptions = {}
): DiffSummary<SourceDiffRow> {
const summary = emptySummary<SourceDiffRow>()
const leavesA = analyzeA
? collectLeaves('A', analyzeA, options)
: new Map<string, LeafEntry>()
const leavesB = collectLeaves('B', analyzeB, options)
const allKeys = new Set<string>([...leavesA.keys(), ...leavesB.keys()])
for (const key of allKeys) {
const a = leavesA.get(key)
const b = leavesB.get(key)
const pretty = prettifySourcePath(key)
pushRow(summary, {
key,
name: pretty.display,
status: statusFor(
a?.size ?? 0,
b?.size ?? 0,
a !== undefined,
b !== undefined
),
sizeA: a?.size ?? 0,
sizeB: b?.size ?? 0,
compressedA: a?.compressedSize ?? 0,
compressedB: b?.compressedSize ?? 0,
sourceIndexA: a?.index ?? null,
sourceIndexB: b?.index ?? null,
pathKind: pretty.kind,
packageName: pretty.packageName,
// OR-merge env flags across both sides so the badge reflects the
// row's overall environment(s). A source that's client-only in A
// and removed in B is still "client" for the purpose of the row.
client: (a?.client ?? false) || (b?.client ?? false),
server: (a?.server ?? false) || (b?.server ?? false),
})
}
return summary
}
/**
* Returns a short, human-friendly version of a source path for table /
* treemap labels. Source paths look like:
*
* `[project]/app/page.tsx`
* `[client-fs]/node_modules/react/index.js`
* `[turbopack]/...`
*
* For UI purposes the `[bracket]/` prefix is noise — keep the rest.
*/
export function shortenSourcePath(fullPath: string): string {
const pretty = prettifySourcePath(fullPath)
return pretty.display
}
/**
* Result of {@link prettifySourcePath}. Tells the UI both how to render the
* path (`display`) and whether it points into an npm package (so callers can
* add a package icon, etc.).
*/
export interface PrettySourcePath {
/** Discriminator the UI uses to decide on iconography. */
kind: 'package' | 'project'
/** Human-friendly path. For packages: `<pkg>/<rest>`. */
display: string
/** Resolved npm package name, when `kind === 'package'`. */
packageName?: string
}
/**
* Picks a clean, scannable display path for a source. Handles three cases:
*
* 1. **pnpm-encoded paths** like
* `node_modules/.pnpm/react@19.2.4/node_modules/react/index.js` —
* we collapse all the `.pnpm/...` virtual store noise and report
* `react/index.js` as the display path.
* 2. **Plain `node_modules/<pkg>/...` paths** — same treatment, just without
* the virtual store layer.
* 3. **Project-relative paths** (e.g. `app/page.tsx`) — pass through unchanged
* after stripping the `[project]/` prefix that {@link shortenSourcePath}
* used to handle.
*
* The full path is always preserved on the original row's `key` so the UI can
* surface it via `title=` for power-users.
*/
export function prettifySourcePath(fullPath: string): PrettySourcePath {
// Strip Turbopack's `[bracket]/` source-root prefix.
const stripped = fullPath.replace(/^\[[^\]]+\]\//, '') || fullPath
// Walk every `node_modules/<segment>/` occurrence and pick the *last* one —
// that's where the real package name lives. pnpm produces paths shaped like
// `node_modules/.pnpm/<encoded>/node_modules/<pkg>/...`, where the inner
// `node_modules/<pkg>` is the real entry point.
const nm = 'node_modules/'
let lastNmIndex = -1
for (
let idx = stripped.indexOf(nm);
idx !== -1;
idx = stripped.indexOf(nm, idx + nm.length)
) {
lastNmIndex = idx
}
if (lastNmIndex !== -1) {
const after = stripped.slice(lastNmIndex + nm.length)
// The package name is one or two path segments depending on whether it's
// scoped: `@scope/name/...` vs `name/...`. Anything after that is the
// path within the package.
const segments = after.split('/')
if (segments.length > 0 && segments[0]) {
const isScoped = segments[0].startsWith('@')
const pkgSegments = isScoped ? segments.slice(0, 2) : segments.slice(0, 1)
const restSegments = segments.slice(pkgSegments.length)
const packageName = pkgSegments.join('/')
// Skip pnpm's `.pnpm` virtual-store entry — we only treat real packages
// (not the `.pnpm` directory itself) as packages.
if (packageName && packageName !== '.pnpm') {
const display =
restSegments.length > 0
? `${packageName}/${restSegments.join('/')}`
: packageName
return { kind: 'package', display, packageName }
}
}
}
return { kind: 'project', display: stripped }
}
/**
* Sorts diff rows by absolute delta (largest impact first), with a stable
* tiebreaker on key. Identical rows always sort last.
*/
export function sortByImpact<Row extends DiffRow>(
rows: Row[],
useCompressed: boolean
): Row[] {
return [...rows].sort((a, b) => {
if (a.status === 'identical' && b.status !== 'identical') return 1
if (b.status === 'identical' && a.status !== 'identical') return -1
const da = Math.abs(delta(a, useCompressed))
const db = Math.abs(delta(b, useCompressed))
if (da !== db) return db - da
return a.key < b.key ? -1 : 1
})
}
import { useEffect, useState } from 'react'
import { AnalyzeData } from './analyze-data'
import { totalsFromAnalyzeData, type RouteSizeTotals } from './diff'
import { fetchStrict } from './utils'
/**
* Resolve the URL of an `analyze.data` file for a given route, parameterised
* by base directory (`'data'` for the live build, `'history/<id>'` for a
* historical snapshot).
*/
function analyzeDataUrl(route: string, baseDir: string): string {
if (route === '/') return `${baseDir}/analyze.data`
return `${baseDir}/${route.replace(/^\//, '')}/analyze.data`
}
/**
* Result of loading route totals for one side. `totals` is keyed by route.
* Routes whose `analyze.data` failed to load (e.g. deleted between builds)
* are simply absent from the map; callers should treat absence as
* "not present in this build".
*/
export interface RouteTotalsState {
totals: ReadonlyMap<string, RouteSizeTotals> | null
isLoading: boolean
}
/**
* Loads `analyze.data` for every route in `routes` from `baseDir` and
* reduces each to its size totals. Used to power the route-level diff so
* that routes can be classified `changed`/`identical` by real bundle size,
* not just name presence.
*
* The fetch fan-out is parallel; for projects with many routes this can be
* heavy, but typical analyze runs have a small number of routes. Results
* are stored in module-scoped state keyed by `baseDir` to avoid refetching
* across re-renders.
*/
export function useRouteTotals(
routes: string[] | null | undefined,
baseDir: string | null
): RouteTotalsState {
const [state, setState] = useState<RouteTotalsState>({
totals: null,
isLoading: false,
})
useEffect(() => {
if (!routes || !baseDir) {
setState({ totals: null, isLoading: false })
return
}
let cancelled = false
setState((prev) => ({ totals: prev.totals, isLoading: true }))
Promise.all(
routes.map(async (route) => {
try {
const resp = await fetchStrict(analyzeDataUrl(route, baseDir))
const data = new AnalyzeData(await resp.arrayBuffer())
return [route, totalsFromAnalyzeData(data)] as const
} catch {
return null
}
})
).then((results) => {
if (cancelled) return
const totals = new Map<string, RouteSizeTotals>()
for (const result of results) {
if (result) totals.set(result[0], result[1])
}
setState({ totals, isLoading: false })
})
return () => {
cancelled = true
}
}, [routes, baseDir])
return state
}
'use client'
import { useEffect, useState } from 'react'
const MIN_SIDEBAR_WIDTH = 10
const MAX_SIDEBAR_WIDTH = 50
/** Shared mouse-drag behavior for the analyzer's right-hand sidebars. */
export function useSidebarResize(initialWidth = 20) {
const [sidebarWidth, setSidebarWidth] = useState(initialWidth)
const [isResizing, setIsResizing] = useState(false)
useEffect(() => {
if (!isResizing) return
const handleMouseMove = (event: MouseEvent) => {
const width =
((window.innerWidth - event.clientX) / window.innerWidth) * 100
setSidebarWidth(
Math.max(MIN_SIDEBAR_WIDTH, Math.min(MAX_SIDEBAR_WIDTH, width))
)
}
const handleMouseUp = () => setIsResizing(false)
window.addEventListener('mousemove', handleMouseMove)
window.addEventListener('mouseup', handleMouseUp)
return () => {
window.removeEventListener('mousemove', handleMouseMove)
window.removeEventListener('mouseup', handleMouseUp)
}
}, [isResizing])
return {
sidebarWidth,
startResizing: () => setIsResizing(true),
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment