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 { ...@@ -25,10 +25,10 @@ import {
} from '@/components/ui/popover' } from '@/components/ui/popover'
import { cn, jsonFetcher } from '@/lib/utils' import { cn, jsonFetcher } from '@/lib/utils'
import { NetworkError } from '@/lib/errors' import { NetworkError } from '@/lib/errors'
import { useHistoryIndex } from '@/lib/analyzer-data'
import { import {
formatRelativeTime, formatRelativeTime,
formatSnapshotLabel, formatSnapshotLabel,
type HistoryIndex,
type SnapshotMetadata, type SnapshotMetadata,
} from '@/lib/snapshot' } from '@/lib/snapshot'
...@@ -59,23 +59,12 @@ export function BaselinePicker({ ...@@ -59,23 +59,12 @@ export function BaselinePicker({
}: BaselinePickerProps) { }: BaselinePickerProps) {
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
const { const { data: history, isLoading, error } = useHistoryIndex()
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 // Metadata for the *current* build, so we can exclude its corresponding
// entry from the history picker (you can't compare a build with itself). // entry from the history picker (you can't compare a build with itself).
const { data: currentMetadata } = useSWR<SnapshotMetadata>( const { data: currentMetadata } = useSWR<SnapshotMetadata>(
'data/metadata.json', '/data/metadata.json',
jsonFetcher, jsonFetcher,
{ {
revalidateOnFocus: false, revalidateOnFocus: false,
......
'use client' 'use client'
import { useSidebarResize } from '@/lib/use-sidebar-resize' import type { MouseEventHandler } from 'react'
import { CompareSidebar } from '@/components/sidebar' import { CompareSidebar } from '@/components/sidebar'
import { DiffTable } from '@/components/diff-table' import { DiffTable } from '@/components/diff-table'
import { DiffTreemap } from '@/components/diff-treemap' import { DiffTreemap } from '@/components/diff-treemap'
...@@ -18,27 +18,31 @@ import { formatSnapshotLabel, type SnapshotMetadata } from '@/lib/snapshot' ...@@ -18,27 +18,31 @@ import { formatSnapshotLabel, type SnapshotMetadata } from '@/lib/snapshot'
import { cn, formatBytes } from '@/lib/utils' import { cn, formatBytes } from '@/lib/utils'
export interface CompareLayoutProps { export interface CompareLayoutProps {
model: CompareLayoutModel
onResizeSidebar: MouseEventHandler<HTMLButtonElement>
}
export interface CompareLayoutModel {
baselineSnapshot: SnapshotMetadata baselineSnapshot: SnapshotMetadata
comparisonSnapshot: SnapshotMetadata | null comparisonSnapshot: SnapshotMetadata | null
compareView: CompareView
selectedRoute: string | null
comparisonRouteCount: number | null comparisonRouteCount: number | null
routeDiff: ReturnType<typeof diffRoutesWithSizes> | null routeDiff: ReturnType<typeof diffRoutesWithSizes> | null
selectedRoute: string | null
sourceDiff: DiffSummary<SourceDiffRow> | null sourceDiff: DiffSummary<SourceDiffRow> | null
analyzeData: AnalyzeData | null analyzeData: AnalyzeData | null
baselineAnalyzeData: 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 modulesData: ModulesData | null
baselineModulesData: ModulesData | null baselineModulesData: ModulesData | null
moduleDepthMap: Map<number, number> moduleDepthMap: Map<number, number>
baselineModuleDepthMap: Map<number, number> baselineModuleDepthMap: Map<number, number>
environmentFilter: Environment 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 { ...@@ -49,103 +53,65 @@ export interface CompareLayoutProps {
* Route selection lives in the top-bar route picker (`RouteTypeahead`), * Route selection lives in the top-bar route picker (`RouteTypeahead`),
* which also renders per-route deltas in compare mode. * which also renders per-route deltas in compare mode.
*/ */
export function CompareLayout({ export function CompareLayout({ model, onResizeSidebar }: CompareLayoutProps) {
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()
return ( return (
<div className="flex h-full w-full min-w-0 flex-col"> <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"> <div className="flex flex-none flex-col border-b border-border xl:flex-row xl:items-stretch">
<RouteStatsCard <RouteStatsCard
selectedRoute={selectedRoute} selectedRoute={model.selectedRoute}
sourceDiff={sourceDiff} sourceDiff={model.sourceDiff}
isAnalyzeLoading={isAnalyzeLoading} isAnalyzeLoading={model.isAnalyzeLoading}
isBaselineAnalyzeLoading={isBaselineAnalyzeLoading} isBaselineAnalyzeLoading={model.isBaselineAnalyzeLoading}
baselineAnalyzeError={baselineAnalyzeError} compressed
compressed={compressed}
className="xl:min-w-0 xl:flex-1 xl:basis-0 xl:border-r xl:border-border" className="xl:min-w-0 xl:flex-1 xl:basis-0 xl:border-r xl:border-border"
/> />
<CompareContextStrip <CompareContextStrip
baselineSnapshot={baselineSnapshot} baselineSnapshot={model.baselineSnapshot}
comparisonRouteCount={comparisonRouteCount} comparisonRouteCount={model.comparisonRouteCount}
routeDiff={routeDiff} routeDiff={model.routeDiff}
compressed={compressed} compressed
className="xl:min-w-0 xl:flex-1 xl:basis-0" className="xl:min-w-0 xl:flex-1 xl:basis-0"
/> />
</div> </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-h-0">
<div className="flex flex-1 min-w-0 flex-col"> <div className="flex flex-1 min-w-0 flex-col">
<ComparePerRoutePanel <ComparePerRoutePanel
compareView={compareView} compareView={model.compareView}
selectedRoute={selectedRoute} selectedRoute={model.selectedRoute}
sourceDiff={sourceDiff} sourceDiff={model.sourceDiff}
analyzeData={analyzeData} analyzeData={model.analyzeData}
baselineAnalyzeData={baselineAnalyzeData} baselineAnalyzeData={model.baselineAnalyzeData}
isAnalyzeLoading={isAnalyzeLoading} isAnalyzeLoading={model.isAnalyzeLoading}
isBaselineAnalyzeLoading={isBaselineAnalyzeLoading} isBaselineAnalyzeLoading={model.isBaselineAnalyzeLoading}
compressed={compressed} compressed
searchQuery={searchQuery} searchQuery={model.searchQuery}
baselineSnapshot={baselineSnapshot} baselineSnapshot={model.baselineSnapshot}
comparisonSnapshot={comparisonSnapshot} comparisonSnapshot={model.comparisonSnapshot}
compareSelectedKey={compareSelectedKey} compareSelectedKey={model.selectedKey}
onCompareSelectedKeyChange={setCompareSelectedKey} onCompareSelectedKeyChange={model.onSelectedKeyChange}
/> />
</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={startResizing} onMouseDown={onResizeSidebar}
aria-label="Resize sidebar" aria-label="Resize sidebar"
/> />
<CompareSidebar <CompareSidebar
selectedKey={compareSelectedKey} selectedKey={model.selectedKey}
sourceDiff={sourceDiff} sourceDiff={model.sourceDiff}
analyzeData={analyzeData} analyzeData={model.analyzeData}
baselineAnalyzeData={baselineAnalyzeData} baselineAnalyzeData={model.baselineAnalyzeData}
modulesData={modulesData} modulesData={model.modulesData}
baselineModulesData={baselineModulesData} baselineModulesData={model.baselineModulesData}
moduleDepthMap={moduleDepthMap} moduleDepthMap={model.moduleDepthMap}
baselineModuleDepthMap={baselineModuleDepthMap} baselineModuleDepthMap={model.baselineModuleDepthMap}
environmentFilter={environmentFilter} environmentFilter={model.environmentFilter}
sidebarWidth={sidebarWidth} sidebarWidth={model.sidebarWidth}
aLabel={formatSnapshotLabel(baselineSnapshot)} aLabel={formatSnapshotLabel(model.baselineSnapshot)}
bLabel={ bLabel={
comparisonSnapshot model.comparisonSnapshot
? formatSnapshotLabel(comparisonSnapshot) ? formatSnapshotLabel(model.comparisonSnapshot)
: 'Latest' : 'Latest'
} }
/> />
...@@ -163,7 +129,7 @@ export function CompareLayout({ ...@@ -163,7 +129,7 @@ export function CompareLayout({
* *
* A/B label pills below identify which snapshot is which. * A/B label pills below identify which snapshot is which.
*/ */
function CompareContextStrip({ export function CompareContextStrip({
baselineSnapshot, baselineSnapshot,
comparisonRouteCount, comparisonRouteCount,
routeDiff, routeDiff,
...@@ -256,12 +222,11 @@ function CompareContextStrip({ ...@@ -256,12 +222,11 @@ function CompareContextStrip({
* loading, missing data) inline so the header always occupies a consistent * loading, missing data) inline so the header always occupies a consistent
* slot in the layout. * slot in the layout.
*/ */
function RouteStatsCard({ export function RouteStatsCard({
selectedRoute, selectedRoute,
sourceDiff, sourceDiff,
isAnalyzeLoading, isAnalyzeLoading,
isBaselineAnalyzeLoading, isBaselineAnalyzeLoading,
baselineAnalyzeError,
compressed, compressed,
className, className,
}: { }: {
...@@ -269,7 +234,6 @@ function RouteStatsCard({ ...@@ -269,7 +234,6 @@ function RouteStatsCard({
sourceDiff: DiffSummary<SourceDiffRow> | null sourceDiff: DiffSummary<SourceDiffRow> | null
isAnalyzeLoading: boolean isAnalyzeLoading: boolean
isBaselineAnalyzeLoading: boolean isBaselineAnalyzeLoading: boolean
baselineAnalyzeError: unknown | null
compressed: boolean compressed: boolean
className?: string className?: string
}) { }) {
...@@ -286,12 +250,7 @@ function RouteStatsCard({ ...@@ -286,12 +250,7 @@ function RouteStatsCard({
No data for this route. No data for this route.
</div> </div>
) : ( ) : (
<RouteStatsBody <RouteStatsBody sourceDiff={sourceDiff} compressed={compressed} />
selectedRoute={selectedRoute}
sourceDiff={sourceDiff}
baselineAnalyzeError={baselineAnalyzeError}
compressed={compressed}
/>
) )
return ( return (
...@@ -313,14 +272,10 @@ function RouteStatsCard({ ...@@ -313,14 +272,10 @@ function RouteStatsCard({
* is ready yet without nesting the data-dependent hooks/derivations above. * is ready yet without nesting the data-dependent hooks/derivations above.
*/ */
function RouteStatsBody({ function RouteStatsBody({
selectedRoute: _selectedRoute,
sourceDiff, sourceDiff,
baselineAnalyzeError: _baselineAnalyzeError,
compressed, compressed,
}: { }: {
selectedRoute: string
sourceDiff: DiffSummary<SourceDiffRow> sourceDiff: DiffSummary<SourceDiffRow>
baselineAnalyzeError: unknown | null
compressed: boolean compressed: boolean
}) { }) {
const routeSizeA = compressed const routeSizeA = compressed
...@@ -382,7 +337,7 @@ function RouteStatsBody({ ...@@ -382,7 +337,7 @@ function RouteStatsBody({
* controlled by `compareView`. Handles missing-route states (the route is new * controlled by `compareView`. Handles missing-route states (the route is new
* in comparison build B, or was removed) with friendly messaging. * in comparison build B, or was removed) with friendly messaging.
*/ */
function ComparePerRoutePanel({ export function ComparePerRoutePanel({
compareView, compareView,
selectedRoute, selectedRoute,
sourceDiff, sourceDiff,
......
...@@ -80,7 +80,7 @@ export function RouteTypeahead({ ...@@ -80,7 +80,7 @@ export function RouteTypeahead({
data: routes, data: routes,
isLoading, isLoading,
error, error,
} = useSWR<string[]>('data/routes.json', jsonFetcher, { } = useSWR<string[]>('/data/routes.json', jsonFetcher, {
onSuccess: (routeNames) => { onSuccess: (routeNames) => {
// Auto-select first route if none is selected // Auto-select first route if none is selected
if (routeNames.length > 0 && selectedRoute == null) { 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( ...@@ -304,7 +304,7 @@ function collectLeaves(
*/ */
export function diffSources( export function diffSources(
analyzeA: AnalyzeData | null, analyzeA: AnalyzeData | null,
analyzeB: AnalyzeData, analyzeB: AnalyzeData | null,
options: SourceDiffOptions = {} options: SourceDiffOptions = {}
): DiffSummary<SourceDiffRow> { ): DiffSummary<SourceDiffRow> {
const summary = emptySummary<SourceDiffRow>() const summary = emptySummary<SourceDiffRow>()
...@@ -312,7 +312,9 @@ export function diffSources( ...@@ -312,7 +312,9 @@ export function diffSources(
const leavesA = analyzeA const leavesA = analyzeA
? collectLeaves('A', analyzeA, options) ? collectLeaves('A', analyzeA, options)
: new Map<string, LeafEntry>() : 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()]) const allKeys = new Set<string>([...leavesA.keys(), ...leavesB.keys()])
for (const key of allKeys) { 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 { useEffect, useState } from 'react'
import { AnalyzeData } from './analyze-data' import { AnalyzeData } from './analyze-data'
import { analyzeDataUrl } from './analyzer-data'
import { totalsFromAnalyzeData, type RouteSizeTotals } from './diff' import { totalsFromAnalyzeData, type RouteSizeTotals } from './diff'
import { fetchStrict } from './utils' 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. * 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) * Routes whose `analyze.data` failed to load (e.g. deleted between builds)
...@@ -56,7 +47,7 @@ export function useRouteTotals( ...@@ -56,7 +47,7 @@ export function useRouteTotals(
Promise.all( Promise.all(
routes.map(async (route) => { routes.map(async (route) => {
try { try {
const resp = await fetchStrict(analyzeDataUrl(route, baseDir)) const resp = await fetchStrict(analyzeDataUrl(baseDir, route))
const data = new AnalyzeData(await resp.arrayBuffer()) const data = new AnalyzeData(await resp.arrayBuffer())
return [route, totalsFromAnalyzeData(data)] as const return [route, totalsFromAnalyzeData(data)] as const
} catch { } catch {
......
...@@ -4,6 +4,10 @@ const developmentRewrites = () => { ...@@ -4,6 +4,10 @@ const developmentRewrites = () => {
source: '/data/:path*', source: '/data/:path*',
destination: 'http://localhost:4000/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