Unverified Commit a742cc64 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

bundle-analyzer: address compare review feedback

Co-authored-by: 's avatarWill Binns-Smith <755844+wbinnssmith@users.noreply.github.com>
parent b998bd8e
This diff is collapsed.
......@@ -33,15 +33,18 @@ import {
} from '@/lib/snapshot'
interface BaselinePickerProps {
/** Selected snapshot id, or null when no comparison is active. */
/** 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 a historical analyze snapshot to
* compare the latest build against. When no snapshot is selected, the
* analyzer behaves as before (single-build view).
* 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`.
......@@ -49,6 +52,10 @@ interface BaselinePickerProps {
export function BaselinePicker({
selectedSnapshotId,
onSelectionChange,
excludedSnapshotId,
prefix = 'vs',
placeholder = 'Compare with…',
clearLabel = 'Stop comparing',
}: BaselinePickerProps) {
const [open, setOpen] = useState(false)
......@@ -79,9 +86,10 @@ export function BaselinePicker({
const allSnapshots = history?.snapshots ?? []
// Filter out the current build's snapshot — comparing to self is a no-op.
const snapshots = currentMetadata
? allSnapshots.filter((s) => s.id !== currentMetadata.id)
: allSnapshots
const snapshots = allSnapshots.filter(
(snapshot) =>
snapshot.id !== currentMetadata?.id && snapshot.id !== excludedSnapshotId
)
const selected =
selectedSnapshotId != null
? snapshots.find((s) => s.id === selectedSnapshotId)
......@@ -102,14 +110,14 @@ export function BaselinePicker({
} else if (selected) {
triggerText = (
<span className="flex items-center gap-1.5 truncate">
<span className="text-muted-foreground text-xs">vs</span>
<span className="text-muted-foreground text-xs">{prefix}</span>
<span className="font-mono truncate">
{formatSnapshotLabel(selected)}
</span>
</span>
)
} else {
triggerText = 'Compare with…'
triggerText = placeholder
}
return (
......@@ -201,7 +209,7 @@ export function BaselinePicker({
<Button
variant="ghost"
size="icon"
aria-label="Stop comparing"
aria-label={clearLabel}
onClick={() => onSelectionChange(null)}
className="h-8 w-8"
>
......
'use client'
import { useState, useEffect } from 'react'
import { useSidebarResize } from '@/lib/use-sidebar-resize'
import { CompareSidebar } from '@/components/sidebar'
import { DiffTreemap } from '@/components/diff-treemap'
import { TreemapSkeleton } from '@/components/ui/skeleton'
......@@ -18,8 +18,9 @@ import { cn, formatBytes } from '@/lib/utils'
export interface CompareLayoutProps {
baselineSnapshot: SnapshotMetadata
comparisonSnapshot: SnapshotMetadata | null
selectedRoute: string | null
currentRouteCount: number | null
comparisonRouteCount: number | null
routeDiff: ReturnType<typeof diffRoutesWithSizes> | null
sourceDiff: DiffSummary<SourceDiffRow> | null
analyzeData: AnalyzeData | null
......@@ -27,7 +28,7 @@ export interface CompareLayoutProps {
isAnalyzeLoading: boolean
isBaselineAnalyzeLoading: boolean
baselineAnalyzeError: unknown | null
useCompressed: boolean
compressed: boolean
compareSelectedKey: string | null
setCompareSelectedKey: (key: string | null) => void
modulesData: ModulesData | null
......@@ -40,7 +41,7 @@ export interface CompareLayoutProps {
/**
* 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 "after" build (B) — the latest one — on the right,
* 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`),
......@@ -48,8 +49,9 @@ export interface CompareLayoutProps {
*/
export function CompareLayout({
baselineSnapshot,
comparisonSnapshot,
selectedRoute,
currentRouteCount,
comparisonRouteCount,
routeDiff,
sourceDiff,
analyzeData,
......@@ -57,7 +59,7 @@ export function CompareLayout({
isAnalyzeLoading,
isBaselineAnalyzeLoading,
baselineAnalyzeError,
useCompressed,
compressed,
compareSelectedKey,
setCompareSelectedKey,
modulesData,
......@@ -66,24 +68,7 @@ export function CompareLayout({
baselineModuleDepthMap,
environmentFilter,
}: CompareLayoutProps) {
const [sidebarWidth, setSidebarWidth] = useState(20)
const [isResizing, setIsResizing] = useState(false)
useEffect(() => {
if (!isResizing) return
const handleMouseMove = (e: MouseEvent) => {
const newWidth =
((window.innerWidth - e.clientX) / window.innerWidth) * 100
setSidebarWidth(Math.max(10, Math.min(50, newWidth)))
}
const handleMouseUp = () => setIsResizing(false)
window.addEventListener('mousemove', handleMouseMove)
window.addEventListener('mouseup', handleMouseUp)
return () => {
window.removeEventListener('mousemove', handleMouseMove)
window.removeEventListener('mouseup', handleMouseUp)
}
}, [isResizing])
const { sidebarWidth, startResizing } = useSidebarResize()
return (
<div className="flex h-full w-full min-w-0 flex-col">
......@@ -102,14 +87,14 @@ export function CompareLayout({
isAnalyzeLoading={isAnalyzeLoading}
isBaselineAnalyzeLoading={isBaselineAnalyzeLoading}
baselineAnalyzeError={baselineAnalyzeError}
useCompressed={useCompressed}
compressed={compressed}
className="xl:min-w-0 xl:flex-1 xl:basis-0 xl:border-r xl:border-border"
/>
<CompareContextStrip
baselineSnapshot={baselineSnapshot}
currentRouteCount={currentRouteCount}
comparisonRouteCount={comparisonRouteCount}
routeDiff={routeDiff}
useCompressed={useCompressed}
compressed={compressed}
className="xl:min-w-0 xl:flex-1 xl:basis-0"
/>
</div>
......@@ -127,7 +112,7 @@ export function CompareLayout({
baselineAnalyzeData={baselineAnalyzeData}
isAnalyzeLoading={isAnalyzeLoading}
isBaselineAnalyzeLoading={isBaselineAnalyzeLoading}
useCompressed={useCompressed}
compressed={compressed}
compareSelectedKey={compareSelectedKey}
onCompareSelectedKeyChange={setCompareSelectedKey}
/>
......@@ -135,7 +120,7 @@ export function CompareLayout({
<button
type="button"
className="flex-none w-1 bg-border hover:bg-primary cursor-col-resize transition-colors"
onMouseDown={() => setIsResizing(true)}
onMouseDown={startResizing}
aria-label="Resize sidebar"
/>
<CompareSidebar
......@@ -150,7 +135,11 @@ export function CompareLayout({
environmentFilter={environmentFilter}
sidebarWidth={sidebarWidth}
aLabel={formatSnapshotLabel(baselineSnapshot)}
bLabel="Latest"
bLabel={
comparisonSnapshot
? formatSnapshotLabel(comparisonSnapshot)
: 'Latest'
}
/>
</div>
</div>
......@@ -168,30 +157,30 @@ export function CompareLayout({
*/
function CompareContextStrip({
baselineSnapshot,
currentRouteCount,
comparisonRouteCount,
routeDiff,
useCompressed,
compressed,
className,
}: {
baselineSnapshot: SnapshotMetadata
currentRouteCount: number | null
comparisonRouteCount: number | null
routeDiff: ReturnType<typeof diffRoutesWithSizes> | null
useCompressed: boolean
compressed: boolean
className?: string
}) {
const baselineRoutes = baselineSnapshot.routeCount
const latestRoutes =
currentRouteCount ??
const comparisonRoutes =
comparisonRouteCount ??
routeDiff?.rows.filter((r) => r.status !== 'removed').length ??
null
const totalA = routeDiff
? useCompressed
? compressed
? routeDiff.totalCompressedA
: routeDiff.totalA
: null
const totalB = routeDiff
? useCompressed
? compressed
? routeDiff.totalCompressedB
: routeDiff.totalB
: null
......@@ -216,7 +205,7 @@ function CompareContextStrip({
<StatCard
label="Total routes"
a={baselineRoutes}
b={latestRoutes}
b={comparisonRoutes}
deltaTone="neutral"
/>
<StatCard
......@@ -265,7 +254,7 @@ function RouteStatsCard({
isAnalyzeLoading,
isBaselineAnalyzeLoading,
baselineAnalyzeError,
useCompressed,
compressed,
className,
}: {
selectedRoute: string | null
......@@ -273,7 +262,7 @@ function RouteStatsCard({
isAnalyzeLoading: boolean
isBaselineAnalyzeLoading: boolean
baselineAnalyzeError: unknown | null
useCompressed: boolean
compressed: boolean
className?: string
}) {
const isLoading = isAnalyzeLoading || isBaselineAnalyzeLoading
......@@ -293,7 +282,7 @@ function RouteStatsCard({
selectedRoute={selectedRoute}
sourceDiff={sourceDiff}
baselineAnalyzeError={baselineAnalyzeError}
useCompressed={useCompressed}
compressed={compressed}
/>
)
......@@ -319,17 +308,17 @@ function RouteStatsBody({
selectedRoute: _selectedRoute,
sourceDiff,
baselineAnalyzeError: _baselineAnalyzeError,
useCompressed,
compressed,
}: {
selectedRoute: string
sourceDiff: DiffSummary<SourceDiffRow>
baselineAnalyzeError: unknown | null
useCompressed: boolean
compressed: boolean
}) {
const routeSizeA = useCompressed
const routeSizeA = compressed
? sourceDiff.totalCompressedA
: sourceDiff.totalA
const routeSizeB = useCompressed
const routeSizeB = compressed
? sourceDiff.totalCompressedB
: sourceDiff.totalB
const routeSizeDelta = routeSizeB - routeSizeA
......@@ -382,7 +371,7 @@ function RouteStatsBody({
/**
* Per-route comparison panel. Shows the diff treemap. Handles missing-route
* states (the route is new in the latest build, or was removed) with
* states (the route is new in the comparison build, or was removed) with
* friendly messaging.
*/
function ComparePerRoutePanel({
......@@ -392,7 +381,7 @@ function ComparePerRoutePanel({
baselineAnalyzeData,
isAnalyzeLoading,
isBaselineAnalyzeLoading,
useCompressed,
compressed,
compareSelectedKey,
onCompareSelectedKeyChange,
}: {
......@@ -402,7 +391,7 @@ function ComparePerRoutePanel({
baselineAnalyzeData: AnalyzeData | null
isAnalyzeLoading: boolean
isBaselineAnalyzeLoading: boolean
useCompressed: boolean
compressed: boolean
compareSelectedKey: string | null
onCompareSelectedKeyChange: (key: string | null) => void
}) {
......@@ -432,7 +421,7 @@ function ComparePerRoutePanel({
<div className="flex flex-1 min-h-0 flex-col">
<DiffTreemap
summary={sourceDiff}
useCompressed={useCompressed}
useCompressed={compressed}
analyzeData={analyzeData}
baselineAnalyzeData={baselineAnalyzeData}
selectedKey={compareSelectedKey}
......
......@@ -10,23 +10,25 @@ 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 red/green. This keeps 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 palette for diff tiles. Red = more bytes (bad), green = fewer bytes (good). */
const COLOR_ADDED = '#dc2626' // red-600 — new bytes in bundle
const COLOR_REMOVED = '#16a34a' // green-600 — bytes removed from bundle
/** 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 the current ("B") build. Used as the source-of-truth
* tree when present.
* Analyze data for comparison side B. Used as the source-of-truth tree
* when present.
*/
analyzeData: AnalyzeData | null
/**
......@@ -51,13 +53,13 @@ interface DiffTreemapProps {
* engine as the single-build view. Each leaf tile represents one source
* file, and the color encodes the per-file delta:
*
* - bright red: added in the latest build (more bytes = bad)
* - bright green: removed in the historical build (fewer bytes = good)
* - red tint: same file, grew since the historical build
* - green tint: same file, shrank since the historical build
* - 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 the current build's source tree so they
* 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({
......@@ -68,8 +70,8 @@ export function DiffTreemap({
selectedKey,
onSelectKey,
}: DiffTreemapProps) {
// Pick the side that drives the source tree. Prefer the current build (B);
// fall back to baseline (A) for the "removed route" case where there's no
// 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
......@@ -177,13 +179,13 @@ export function DiffTreemap({
/**
* Picks a fill color for a diff row. Mirrors the previous DiffTreemap's
* scheme: bright green/red for added/removed, lighter tints scaled by the
* 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_ADDED
if (row.status === 'removed') return COLOR_REMOVED
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
......@@ -197,17 +199,17 @@ function colorForRow(row: SourceDiffRow, useCompressed: boolean): string {
baseline === 0 ? 1 : Math.min(1, Math.abs(deltaValue) / baseline)
const alpha = 0.35 + ratio * 0.5
return deltaValue > 0
? `rgba(220, 38, 38, ${alpha.toFixed(2)})`
: `rgba(22, 163, 74, ${alpha.toFixed(2)})`
? `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_ADDED },
{ label: 'Grew', color: 'rgba(220, 38, 38, 0.6)' },
{ label: 'Added', color: COLOR_INCREASE },
{ label: 'Grew', color: COLOR_INCREASE_MUTED },
{ label: 'Unchanged', color: COLOR_NEUTRAL },
{ label: 'Shrank', color: 'rgba(22, 163, 74, 0.6)' },
{ 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">
......
......@@ -63,6 +63,8 @@ export function TopBar({
setSearchQuery,
baselineSnapshot,
onBaselineChange,
comparisonSnapshot,
onComparisonChange,
routeDiff,
hasSourceData,
}: {
......@@ -79,6 +81,8 @@ export function TopBar({
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
......@@ -101,7 +105,20 @@ export function TopBar({
<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 && (
<>
......
'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