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

bundle-analyzer: move comparison state into URL (#98530)

## Summary

Move bundle comparison into a dedicated `/compare` route and persist the
selected baseline, comparison snapshot, route, and view in URL search
parameters. This makes comparison views linkable and separates the App
Router route entries from the shared client implementation.

Use root-relative data URLs and proxy historical snapshots during
development so analyzer data continues to load from nested routes.

Follow-up to review feedback on #93521.

## Verification

- `pnpm --filter=@next/bundle-analyzer-ui build`

<!-- NEXT_JS_LLM -->
parent 91d6d671
import { Suspense } from 'react'
import { CompareAnalyzer } from '@/components/analyzer'
export default function ComparePage() {
return (
<Suspense>
<CompareAnalyzer />
</Suspense>
)
}
This diff is collapsed.
This diff is collapsed.
......@@ -25,10 +25,10 @@ import {
} from '@/components/ui/popover'
import { cn, jsonFetcher } from '@/lib/utils'
import { NetworkError } from '@/lib/errors'
import { useHistoryIndex } from '@/lib/analyzer-data'
import {
formatRelativeTime,
formatSnapshotLabel,
type HistoryIndex,
type SnapshotMetadata,
} from '@/lib/snapshot'
......@@ -59,23 +59,12 @@ export function BaselinePicker({
}: 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,
})
const { data: history, isLoading, error } = useHistoryIndex()
// 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',
'/data/metadata.json',
jsonFetcher,
{
revalidateOnFocus: false,
......
'use client'
import { useSidebarResize } from '@/lib/use-sidebar-resize'
import type { MouseEventHandler } from 'react'
import { CompareSidebar } from '@/components/sidebar'
import { DiffTable } from '@/components/diff-table'
import { DiffTreemap } from '@/components/diff-treemap'
......@@ -18,27 +18,31 @@ import { formatSnapshotLabel, type SnapshotMetadata } from '@/lib/snapshot'
import { cn, formatBytes } from '@/lib/utils'
export interface CompareLayoutProps {
model: CompareLayoutModel
onResizeSidebar: MouseEventHandler<HTMLButtonElement>
}
export interface CompareLayoutModel {
baselineSnapshot: SnapshotMetadata
comparisonSnapshot: SnapshotMetadata | null
compareView: CompareView
selectedRoute: string | null
comparisonRouteCount: number | null
routeDiff: ReturnType<typeof diffRoutesWithSizes> | null
selectedRoute: string | null
sourceDiff: DiffSummary<SourceDiffRow> | null
analyzeData: AnalyzeData | null
baselineAnalyzeData: AnalyzeData | null
isAnalyzeLoading: boolean
isBaselineAnalyzeLoading: boolean
baselineAnalyzeError: unknown | null
compressed: boolean
searchQuery: string
compareSelectedKey: string | null
setCompareSelectedKey: (key: string | null) => void
modulesData: ModulesData | null
baselineModulesData: ModulesData | null
moduleDepthMap: Map<number, number>
baselineModuleDepthMap: Map<number, number>
environmentFilter: Environment
sidebarWidth: number
compareView: CompareView
isAnalyzeLoading: boolean
isBaselineAnalyzeLoading: boolean
searchQuery: string
selectedKey: string | null
onSelectedKeyChange: (key: string | null) => void
}
/**
......@@ -49,103 +53,65 @@ export interface CompareLayoutProps {
* Route selection lives in the top-bar route picker (`RouteTypeahead`),
* which also renders per-route deltas in compare mode.
*/
export function CompareLayout({
baselineSnapshot,
comparisonSnapshot,
compareView,
selectedRoute,
comparisonRouteCount,
routeDiff,
sourceDiff,
analyzeData,
baselineAnalyzeData,
isAnalyzeLoading,
isBaselineAnalyzeLoading,
baselineAnalyzeError,
compressed,
searchQuery,
compareSelectedKey,
setCompareSelectedKey,
modulesData,
baselineModulesData,
moduleDepthMap,
baselineModuleDepthMap,
environmentFilter,
}: CompareLayoutProps) {
const { sidebarWidth, startResizing } = useSidebarResize()
export function CompareLayout({ model, onResizeSidebar }: CompareLayoutProps) {
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}
selectedRoute={model.selectedRoute}
sourceDiff={model.sourceDiff}
isAnalyzeLoading={model.isAnalyzeLoading}
isBaselineAnalyzeLoading={model.isBaselineAnalyzeLoading}
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}
baselineSnapshot={model.baselineSnapshot}
comparisonRouteCount={model.comparisonRouteCount}
routeDiff={model.routeDiff}
compressed
className="xl:min-w-0 xl:flex-1 xl:basis-0"
/>
</div>
{/*
Per-route source diff + sidebar. The sidebar slides in when a row or
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
compareView={compareView}
selectedRoute={selectedRoute}
sourceDiff={sourceDiff}
analyzeData={analyzeData}
baselineAnalyzeData={baselineAnalyzeData}
isAnalyzeLoading={isAnalyzeLoading}
isBaselineAnalyzeLoading={isBaselineAnalyzeLoading}
compressed={compressed}
searchQuery={searchQuery}
baselineSnapshot={baselineSnapshot}
comparisonSnapshot={comparisonSnapshot}
compareSelectedKey={compareSelectedKey}
onCompareSelectedKeyChange={setCompareSelectedKey}
compareView={model.compareView}
selectedRoute={model.selectedRoute}
sourceDiff={model.sourceDiff}
analyzeData={model.analyzeData}
baselineAnalyzeData={model.baselineAnalyzeData}
isAnalyzeLoading={model.isAnalyzeLoading}
isBaselineAnalyzeLoading={model.isBaselineAnalyzeLoading}
compressed
searchQuery={model.searchQuery}
baselineSnapshot={model.baselineSnapshot}
comparisonSnapshot={model.comparisonSnapshot}
compareSelectedKey={model.selectedKey}
onCompareSelectedKeyChange={model.onSelectedKeyChange}
/>
</div>
<button
type="button"
className="flex-none w-1 bg-border hover:bg-primary cursor-col-resize transition-colors"
onMouseDown={startResizing}
onMouseDown={onResizeSidebar}
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)}
selectedKey={model.selectedKey}
sourceDiff={model.sourceDiff}
analyzeData={model.analyzeData}
baselineAnalyzeData={model.baselineAnalyzeData}
modulesData={model.modulesData}
baselineModulesData={model.baselineModulesData}
moduleDepthMap={model.moduleDepthMap}
baselineModuleDepthMap={model.baselineModuleDepthMap}
environmentFilter={model.environmentFilter}
sidebarWidth={model.sidebarWidth}
aLabel={formatSnapshotLabel(model.baselineSnapshot)}
bLabel={
comparisonSnapshot
? formatSnapshotLabel(comparisonSnapshot)
model.comparisonSnapshot
? formatSnapshotLabel(model.comparisonSnapshot)
: 'Latest'
}
/>
......@@ -163,7 +129,7 @@ export function CompareLayout({
*
* A/B label pills below identify which snapshot is which.
*/
function CompareContextStrip({
export function CompareContextStrip({
baselineSnapshot,
comparisonRouteCount,
routeDiff,
......@@ -256,12 +222,11 @@ function CompareContextStrip({
* loading, missing data) inline so the header always occupies a consistent
* slot in the layout.
*/
function RouteStatsCard({
export function RouteStatsCard({
selectedRoute,
sourceDiff,
isAnalyzeLoading,
isBaselineAnalyzeLoading,
baselineAnalyzeError,
compressed,
className,
}: {
......@@ -269,7 +234,6 @@ function RouteStatsCard({
sourceDiff: DiffSummary<SourceDiffRow> | null
isAnalyzeLoading: boolean
isBaselineAnalyzeLoading: boolean
baselineAnalyzeError: unknown | null
compressed: boolean
className?: string
}) {
......@@ -286,12 +250,7 @@ function RouteStatsCard({
No data for this route.
</div>
) : (
<RouteStatsBody
selectedRoute={selectedRoute}
sourceDiff={sourceDiff}
baselineAnalyzeError={baselineAnalyzeError}
compressed={compressed}
/>
<RouteStatsBody sourceDiff={sourceDiff} compressed={compressed} />
)
return (
......@@ -313,14 +272,10 @@ function RouteStatsCard({
* 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
......@@ -382,7 +337,7 @@ function RouteStatsBody({
* controlled by `compareView`. Handles missing-route states (the route is new
* in comparison build B, or was removed) with friendly messaging.
*/
function ComparePerRoutePanel({
export function ComparePerRoutePanel({
compareView,
selectedRoute,
sourceDiff,
......
......@@ -80,7 +80,7 @@ export function RouteTypeahead({
data: routes,
isLoading,
error,
} = useSWR<string[]>('data/routes.json', jsonFetcher, {
} = useSWR<string[]>('/data/routes.json', jsonFetcher, {
onSuccess: (routeNames) => {
// Auto-select first route if none is selected
if (routeNames.length > 0 && selectedRoute == null) {
......
import useSWR from 'swr'
import { AnalyzeData, ModulesData } from './analyze-data'
import type { HistoryIndex } from './snapshot'
import { fetchStrict, jsonFetcher } from './utils'
const staticDataOptions = {
revalidateOnFocus: false,
revalidateOnReconnect: false,
}
export function analyzeDataUrl(baseDir: string, route: string): string {
if (route === '/') return `${baseDir}/analyze.data`
return `${baseDir}/${route.replace(/^\//, '')}/analyze.data`
}
export function useHistoryIndex() {
return useSWR<HistoryIndex>('/history/history.json', jsonFetcher, {
...staticDataOptions,
shouldRetryOnError: false,
})
}
export async function fetchAnalyzeData(url: string): Promise<AnalyzeData> {
const response = await fetchStrict(url)
return new AnalyzeData(await response.arrayBuffer())
}
export async function fetchModulesData(url: string): Promise<ModulesData> {
const response = await fetchStrict(url)
return new ModulesData(await response.arrayBuffer())
}
......@@ -304,7 +304,7 @@ function collectLeaves(
*/
export function diffSources(
analyzeA: AnalyzeData | null,
analyzeB: AnalyzeData,
analyzeB: AnalyzeData | null,
options: SourceDiffOptions = {}
): DiffSummary<SourceDiffRow> {
const summary = emptySummary<SourceDiffRow>()
......@@ -312,7 +312,9 @@ export function diffSources(
const leavesA = analyzeA
? collectLeaves('A', analyzeA, options)
: new Map<string, LeafEntry>()
const leavesB = collectLeaves('B', analyzeB, options)
const leavesB = analyzeB
? collectLeaves('B', analyzeB, options)
: new Map<string, LeafEntry>()
const allKeys = new Set<string>([...leavesA.keys(), ...leavesB.keys()])
for (const key of allKeys) {
......
import { CompareView, Environment } from '@/components/top-bar'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import type { SnapshotMetadata } from './snapshot'
export function useAnalyzerRoute(
compare: boolean,
snapshots: SnapshotMetadata[] | undefined
) {
const router = useRouter()
const pathname = usePathname()
const searchParams = useSearchParams()
const selectedRoute = searchParams.get('route')
const baselineSnapshot = compare
? (snapshots?.find(
(snapshot) => snapshot.id === searchParams.get('from')
) ?? null)
: null
const comparisonSnapshot = compare
? (snapshots?.find((snapshot) => snapshot.id === searchParams.get('to')) ??
null)
: null
const viewParam = searchParams.get('view')
const compareView =
viewParam === CompareView.Table || viewParam === CompareView.Treemap
? viewParam
: compare
? CompareView.Table
: CompareView.Treemap
const environmentParam = searchParams.get('environment')
const environmentFilter =
environmentParam === Environment.Server
? Environment.Server
: Environment.Client
const searchQuery = searchParams.get('query') ?? ''
const typeFilter = parseTypeFilter(searchParams.get('types'))
function navigate(
nextPathname: string,
updates: Record<string, string | null>,
method: 'push' | 'replace'
) {
const nextSearchParams = new URLSearchParams(searchParams.toString())
for (const [key, value] of Object.entries(updates)) {
if (value == null) nextSearchParams.delete(key)
else nextSearchParams.set(key, value)
}
const query = nextSearchParams.toString()
router[method](`${nextPathname}${query ? `?${query}` : ''}`)
}
function replaceSearchParams(updates: Record<string, string | null>) {
const nextSearchParams = new URLSearchParams(searchParams.toString())
for (const [key, value] of Object.entries(updates)) {
if (value == null) nextSearchParams.delete(key)
else nextSearchParams.set(key, value)
}
const query = nextSearchParams.toString()
window.history.replaceState(
null,
'',
`${pathname}${query ? `?${query}` : ''}`
)
}
return {
baselineSnapshot,
comparisonSnapshot,
compareView,
environmentFilter,
searchQuery,
selectedRoute,
typeFilter,
setView: (view: CompareView) => navigate(pathname, { view }, 'replace'),
setRoute: (route: string | null) =>
navigate(pathname, { route }, 'replace'),
startComparison: (snapshot: SnapshotMetadata) =>
navigate('/compare', { from: snapshot.id, to: null, view: null }, 'push'),
stopComparison: () =>
navigate('/', { from: null, to: null, view: null }, 'push'),
setComparisonSnapshot: (snapshot: SnapshotMetadata | null) =>
navigate(pathname, { to: snapshot?.id ?? null }, 'replace'),
setEnvironmentFilter: (environment: Environment) =>
replaceSearchParams({
environment: environment === Environment.Client ? null : environment,
}),
setSearchQuery: (query: string) =>
replaceSearchParams({ query: query || null }),
setTypeFilter: (types: string[]) =>
replaceSearchParams({
types: arraysEqual(types, DEFAULT_TYPE_FILTER)
? null
: normalizeTypeFilter(types).join(','),
}),
}
}
const TYPE_FILTER_VALUES = ['js', 'css', 'json', 'asset'] as const
const DEFAULT_TYPE_FILTER = TYPE_FILTER_VALUES.slice(0, 3)
function normalizeTypeFilter(types: string[]): string[] {
const selected = new Set(types)
const normalized = TYPE_FILTER_VALUES.filter((type) => selected.has(type))
return normalized.length > 0 ? normalized : DEFAULT_TYPE_FILTER
}
function parseTypeFilter(value: string | null): string[] {
return value ? normalizeTypeFilter(value.split(',')) : DEFAULT_TYPE_FILTER
}
function arraysEqual(left: string[], right: string[]): boolean {
return (
left.length === right.length &&
left.every((value, index) => value === right[index])
)
}
import { useEffect, useState } from 'react'
import { AnalyzeData } from './analyze-data'
import { analyzeDataUrl } from './analyzer-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)
......@@ -56,7 +47,7 @@ export function useRouteTotals(
Promise.all(
routes.map(async (route) => {
try {
const resp = await fetchStrict(analyzeDataUrl(route, baseDir))
const resp = await fetchStrict(analyzeDataUrl(baseDir, route))
const data = new AnalyzeData(await resp.arrayBuffer())
return [route, totalsFromAnalyzeData(data)] as const
} catch {
......
......@@ -4,6 +4,10 @@ const developmentRewrites = () => {
source: '/data/:path*',
destination: 'http://localhost:4000/data/:path*',
},
{
source: '/history/:path*',
destination: 'http://localhost:4000/history/:path*',
},
]
}
......
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