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
This diff is collapsed.
'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>
)
}
This diff is collapsed.
'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>
)
}
...@@ -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={name}
key={route} value={name}
value={route} onSelect={() => {
onSelect={() => { onRouteSelected(name)
onRouteSelected(route) setOpen(false)
setOpen(false) }}
}} className="font-mono"
className="font-mono" >
> <Check
<Check className={cn(
className={cn( 'mr-2 h-4 w-4 shrink-0',
'mr-2 h-4 w-4', selectedRoute === name ? 'opacity-100' : 'opacity-0'
selectedRoute === route ? 'opacity-100' : 'opacity-0' )}
)} />
<span className="truncate">{name}</span>
{row ? (
<DeltaBadge
row={row}
useCompressed={useCompressed}
className="ml-auto"
/> />
{route} ) : 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>
) )
} }
......
This diff is collapsed.
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