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

Reorganize bundle analyzer toolbar (#98920)

## Summary

Split the bundle analyzer toolbar into two rows so route context,
comparison controls, and search remain separate from filtering and view
controls.

Keep the layout usable at narrow viewport widths by wrapping the route
selector and allowing the filter strip to scroll horizontally.

## Verification

- `pnpm --filter @next/bundle-analyzer-ui exec tsc --noEmit`
- `pnpm --filter @next/bundle-analyzer-ui build`
- Checked the analyzer layout at desktop, 900px, and 390px viewport
widths

<!-- NEXT_JS_LLM -->

---------
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 3737d0ff
...@@ -49,6 +49,7 @@ import { ...@@ -49,6 +49,7 @@ import {
computeSourceLoadScopes, computeSourceLoadScopes,
} from '@/lib/module-graph' } from '@/lib/module-graph'
import type { SnapshotMetadata } from '@/lib/snapshot' import type { SnapshotMetadata } from '@/lib/snapshot'
import { NetworkError } from '@/lib/errors'
import { formatBytes } from '@/lib/utils' import { formatBytes } from '@/lib/utils'
import { createAnalyzeTreemapSource, SizeMode } from '@/lib/treemap-layout' import { createAnalyzeTreemapSource, SizeMode } from '@/lib/treemap-layout'
...@@ -99,6 +100,8 @@ function AnalyzerFallback({ view }: { view: CompareView }) { ...@@ -99,6 +100,8 @@ function AnalyzerFallback({ view }: { view: CompareView }) {
} }
function useAnalyzerModel(compare: boolean) { function useAnalyzerModel(compare: boolean) {
// Read the URL before suspense data so static prerendering can bail out.
useSearchParams()
const [routePickerOpen, setRoutePickerOpen] = useState(false) const [routePickerOpen, setRoutePickerOpen] = useState(false)
const [selectedSourceIndex, setSelectedSourceIndex] = useState<number | null>( const [selectedSourceIndex, setSelectedSourceIndex] = useState<number | null>(
null null
...@@ -107,8 +110,20 @@ function useAnalyzerModel(compare: boolean) { ...@@ -107,8 +110,20 @@ function useAnalyzerModel(compare: boolean) {
null null
) )
const { data: history, isLoading: isHistoryLoading } = useHistoryIndex() const {
const routeState = useAnalyzerRoute(compare, history?.snapshots) data: history,
isLoading: isHistoryLoading,
error: historyError,
} = useHistoryIndex()
const latestSnapshot = useSuspenseJsonData<SnapshotMetadata>(
'/data/metadata.json',
{ revalidateOnFocus: false, revalidateOnReconnect: false }
)
const routeState = useAnalyzerRoute(
compare,
history?.snapshots,
latestSnapshot
)
const { const {
baselineSnapshot, baselineSnapshot,
comparisonSnapshot, comparisonSnapshot,
...@@ -142,17 +157,14 @@ function useAnalyzerModel(compare: boolean) { ...@@ -142,17 +157,14 @@ function useAnalyzerModel(compare: boolean) {
const activeView = pendingView ?? compareView const activeView = pendingView ?? compareView
const isViewPending = pendingView != null && pendingView !== compareView const isViewPending = pendingView != null && pendingView !== compareView
const comparisonBaseDir = comparisonSnapshot const comparisonBaseDir = routeState.activeBaseDir
? `/history/${comparisonSnapshot.id}`
: '/data'
const { data: modulesData } = useSWR( const { data: modulesData } = useSWR(
`${comparisonBaseDir}/modules.data`, `${comparisonBaseDir}/modules.data`,
fetchModulesData, fetchModulesData,
{ suspense: true } { suspense: true }
) )
// Routes for comparison side B. This is the live build by default, or an // Routes for the active build, which is also comparison side B.
// independently selected historical snapshot.
const currentRoutes = useSuspenseJsonData<string[]>( const currentRoutes = useSuspenseJsonData<string[]>(
`${comparisonBaseDir}/routes.json`, `${comparisonBaseDir}/routes.json`,
{ revalidateOnFocus: false, revalidateOnReconnect: false } { revalidateOnFocus: false, revalidateOnReconnect: false }
...@@ -202,7 +214,7 @@ function useAnalyzerModel(compare: boolean) { ...@@ -202,7 +214,7 @@ function useAnalyzerModel(compare: boolean) {
// previous selection is unlikely to exist in the new diff. // previous selection is unlikely to exist in the new diff.
useEffect(() => { useEffect(() => {
setCompareSelectedKey(null) setCompareSelectedKey(null)
}, [selectedRoute, baselineSnapshot, comparisonSnapshot]) }, [selectedRoute, routeState.fromId, routeState.toId])
useEffect(() => { useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => { const handleKeyDown = (e: KeyboardEvent) => {
...@@ -321,9 +333,20 @@ function useAnalyzerModel(compare: boolean) { ...@@ -321,9 +333,20 @@ function useAnalyzerModel(compare: boolean) {
return { return {
analyzeData, analyzeData,
baselineSnapshot, baselineSnapshot,
baselineIsLatest: compare && routeState.fromId === 'latest',
compareSelectedKey, compareSelectedKey,
compareView: activeView, compareView: activeView,
comparisonSnapshot, comparisonSnapshot,
historySnapshots: history?.snapshots ?? [],
historyError: historyError instanceof NetworkError,
invalidComparison: routeState.invalidComparison,
latestSnapshot,
isCompareMode: compare,
singleBuildId: routeState.singleBuildId,
singleSnapshot: routeState.singleSnapshot,
fromId: routeState.fromId,
toId: routeState.toId,
activeBaseDir: routeState.activeBaseDir,
currentRoutes, currentRoutes,
routePickerOpen, routePickerOpen,
setRoutePickerOpen, setRoutePickerOpen,
...@@ -411,12 +434,17 @@ function AnalyzerTopBar({ ...@@ -411,12 +434,17 @@ function AnalyzerTopBar({
setTypeFilter={model.setTypeFilter} setTypeFilter={model.setTypeFilter}
searchQuery={model.searchQuery} searchQuery={model.searchQuery}
setSearchQuery={model.setSearchQuery} setSearchQuery={model.setSearchQuery}
baselineSnapshot={model.baselineSnapshot} isCompareMode={model.isCompareMode}
getBaselineHref={model.routeState.getBaselineHref} historySnapshots={model.historySnapshots}
onBaselineChange={model.routeState.setBaselineSnapshot} historyLoading={model.isHistoryLoading}
stopComparisonHref={model.routeState.stopComparisonHref} historyError={model.historyError}
comparisonSnapshot={model.comparisonSnapshot} latestSnapshot={model.latestSnapshot}
onComparisonChange={model.routeState.setComparisonSnapshot} singleBuildId={model.singleBuildId}
fromId={model.fromId}
toId={model.toId}
onSingleBuildChange={model.routeState.setSingleBuild}
onComparisonChange={model.routeState.setComparison}
routesBaseDir={model.activeBaseDir}
routeDiff={routeDiff} routeDiff={routeDiff}
routeTotals={ routeTotals={
model.environmentFilter === Environment.Client model.environmentFilter === Environment.Client
...@@ -439,12 +467,17 @@ function CompareAnalyzerView({ model }: { model: AnalyzerModel }) { ...@@ -439,12 +467,17 @@ function CompareAnalyzerView({ model }: { model: AnalyzerModel }) {
</AnalyzerFrame> </AnalyzerFrame>
) )
} }
if (model.baselineSnapshot) return <ValidComparison model={model} /> if (
model.baselineSnapshot &&
!model.invalidComparison &&
model.fromId !== (model.toId ?? 'latest')
)
return <ValidComparison model={model} />
return ( return (
<AnalyzerFrame topBar={<AnalyzerTopBar model={model} />}> <AnalyzerFrame topBar={<AnalyzerTopBar model={model} />}>
<div className="flex flex-1 items-center justify-center text-sm text-muted-foreground"> <div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">
The baseline snapshot in this URL is unavailable. The builds in this URL are unavailable or identical.
</div> </div>
</AnalyzerFrame> </AnalyzerFrame>
) )
...@@ -466,7 +499,9 @@ function ValidComparisonContent({ ...@@ -466,7 +499,9 @@ function ValidComparisonContent({
model: AnalyzerModel model: AnalyzerModel
baselineSnapshot: SnapshotMetadata baselineSnapshot: SnapshotMetadata
}) { }) {
const baselineBaseDir = `/history/${baselineSnapshot.id}` const baselineBaseDir = model.baselineIsLatest
? '/data'
: `/history/${baselineSnapshot.id}`
const { data: baselineModulesData } = useSWR( const { data: baselineModulesData } = useSWR(
`${baselineBaseDir}/modules.data`, `${baselineBaseDir}/modules.data`,
fetchModulesData, fetchModulesData,
...@@ -498,6 +533,7 @@ function ValidComparisonContent({ ...@@ -498,6 +533,7 @@ function ValidComparisonContent({
) )
const layoutProps = { const layoutProps = {
baselineSnapshot, baselineSnapshot,
baselineIsLatest: model.baselineIsLatest,
comparisonSnapshot: model.comparisonSnapshot, comparisonSnapshot: model.comparisonSnapshot,
comparisonRouteCount: model.currentRoutes.length, comparisonRouteCount: model.currentRoutes.length,
routeDiff, routeDiff,
...@@ -562,6 +598,7 @@ function BaselineRouteComparison({ ...@@ -562,6 +598,7 @@ function BaselineRouteComparison({
type ComparisonLayoutProps = Pick< type ComparisonLayoutProps = Pick<
CompareLayoutModel, CompareLayoutModel,
| 'baselineSnapshot' | 'baselineSnapshot'
| 'baselineIsLatest'
| 'comparisonSnapshot' | 'comparisonSnapshot'
| 'comparisonRouteCount' | 'comparisonRouteCount'
| 'routeDiff' | 'routeDiff'
...@@ -641,6 +678,24 @@ function ComparisonContent({ ...@@ -641,6 +678,24 @@ function ComparisonContent({
} }
function SingleAnalyzerView({ model }: { model: AnalyzerModel }) { function SingleAnalyzerView({ model }: { model: AnalyzerModel }) {
if (model.singleBuildId && model.isHistoryLoading) {
return (
<AnalyzerFrame topBar={<AnalyzerTopBar model={model} />}>
<div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">
Loading build…
</div>
</AnalyzerFrame>
)
}
if (model.singleBuildId && !model.singleSnapshot && !model.isHistoryLoading) {
return (
<AnalyzerFrame topBar={<AnalyzerTopBar model={model} />}>
<div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">
The build in this URL is unavailable.
</div>
</AnalyzerFrame>
)
}
const analyzeData = model.analyzeData const analyzeData = model.analyzeData
const content = analyzeData ? ( const content = analyzeData ? (
<SingleAnalyzerContent model={model} analyzeData={analyzeData} /> <SingleAnalyzerContent model={model} analyzeData={analyzeData} />
......
'use client'
import useSWR from 'swr'
import Link from 'next/link'
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,
CommandLinkItem,
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 { useHistoryIndex } from '@/lib/analyzer-data'
import {
formatRelativeTime,
formatSnapshotLabel,
type SnapshotMetadata,
} from '@/lib/snapshot'
interface BaselinePickerOptions {
/** Selected historical snapshot id, or null for the control's default. */
selectedSnapshotId: string | null
excludedSnapshotId?: string | null
prefix?: string
placeholder?: string
clearLabel?: string
}
type BaselinePickerProps = BaselinePickerOptions &
(
| {
mode: 'link'
getSnapshotHref: (snapshot: SnapshotMetadata) => string
clearHref: string
onSelectionChange?: never
}
| {
mode: 'action'
onSelectionChange: (snapshot: SnapshotMetadata | null) => void
clearHref?: string
getSnapshotHref?: never
}
)
/**
* 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 --analyze`.
*/
export function BaselinePicker(props: BaselinePickerProps) {
const {
selectedSnapshotId,
clearHref,
excludedSnapshotId,
prefix = 'vs',
placeholder = 'Compare with…',
clearLabel = 'Stop comparing',
} = props
const [open, setOpen] = useState(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',
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 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 --analyze
</code>{' '}
to start collecting snapshots.
</div>
</div>
) : (
<CommandEmpty>No snapshots found.</CommandEmpty>
)}
<CommandGroup>
{snapshots.map((snapshot) => {
const value = `${snapshot.id} ${snapshot.gitBranch ?? ''} ${snapshot.gitShortSha ?? ''} ${snapshot.gitMessage ?? ''} ${snapshot.snapshotName ?? ''}`
const content = (
<>
<Check
className={cn(
'mr-2 h-4 w-4',
selectedSnapshotId === snapshot.id
? 'opacity-100'
: 'opacity-0'
)}
/>
<SnapshotRow snapshot={snapshot} />
</>
)
return props.mode === 'link' ? (
<CommandLinkItem
key={snapshot.id}
value={value}
href={props.getSnapshotHref(snapshot)}
>
{content}
</CommandLinkItem>
) : (
<CommandItem
key={snapshot.id}
value={value}
onSelect={() => {
props.onSelectionChange(snapshot)
setOpen(false)
}}
>
{content}
</CommandItem>
)
})}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
{selected != null &&
(clearHref ? (
<Button asChild variant="ghost" size="icon" className="h-8 w-8">
<Link href={clearHref} aria-label={clearLabel}>
<X className="h-3.5 w-3.5" />
</Link>
</Button>
) : props.mode === 'action' ? (
<Button
variant="ghost"
size="icon"
aria-label={clearLabel}
onClick={() => props.onSelectionChange(null)}
className="h-8 w-8"
>
<X className="h-3.5 w-3.5" />
</Button>
) : null)}
</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.
...@@ -28,6 +28,7 @@ export interface CompareLayoutProps { ...@@ -28,6 +28,7 @@ export interface CompareLayoutProps {
export interface CompareLayoutModel { export interface CompareLayoutModel {
baselineSnapshot: SnapshotMetadata baselineSnapshot: SnapshotMetadata
baselineIsLatest: boolean
comparisonSnapshot: SnapshotMetadata | null comparisonSnapshot: SnapshotMetadata | null
comparisonRouteCount: number | null comparisonRouteCount: number | null
routeDiff: ReturnType<typeof diffRoutesWithSizes> | null routeDiff: ReturnType<typeof diffRoutesWithSizes> | null
...@@ -93,6 +94,7 @@ export function CompareLayout({ model, onResizeSidebar }: CompareLayoutProps) { ...@@ -93,6 +94,7 @@ export function CompareLayout({ model, onResizeSidebar }: CompareLayoutProps) {
model.hasAlternateEnvironmentSources model.hasAlternateEnvironmentSources
} }
baselineSnapshot={model.baselineSnapshot} baselineSnapshot={model.baselineSnapshot}
baselineIsLatest={model.baselineIsLatest}
comparisonSnapshot={model.comparisonSnapshot} comparisonSnapshot={model.comparisonSnapshot}
compareSelectedKey={model.selectedKey} compareSelectedKey={model.selectedKey}
onCompareSelectedKeyChange={model.onSelectedKeyChange} onCompareSelectedKeyChange={model.onSelectedKeyChange}
...@@ -116,7 +118,11 @@ export function CompareLayout({ model, onResizeSidebar }: CompareLayoutProps) { ...@@ -116,7 +118,11 @@ export function CompareLayout({ model, onResizeSidebar }: CompareLayoutProps) {
baselineModuleDepthMap={model.baselineModuleDepthMap} baselineModuleDepthMap={model.baselineModuleDepthMap}
environmentFilter={model.environmentFilter} environmentFilter={model.environmentFilter}
sidebarWidth={model.sidebarWidth} sidebarWidth={model.sidebarWidth}
aLabel={formatSnapshotLabel(model.baselineSnapshot)} aLabel={
model.baselineIsLatest
? 'Latest'
: formatSnapshotLabel(model.baselineSnapshot)
}
bLabel={ bLabel={
model.comparisonSnapshot model.comparisonSnapshot
? formatSnapshotLabel(model.comparisonSnapshot) ? formatSnapshotLabel(model.comparisonSnapshot)
...@@ -349,6 +355,7 @@ export function ComparePerRoutePanel({ ...@@ -349,6 +355,7 @@ export function ComparePerRoutePanel({
environmentFilter, environmentFilter,
hasAlternateEnvironmentSources, hasAlternateEnvironmentSources,
baselineSnapshot, baselineSnapshot,
baselineIsLatest,
comparisonSnapshot, comparisonSnapshot,
compareSelectedKey, compareSelectedKey,
onCompareSelectedKeyChange, onCompareSelectedKeyChange,
...@@ -365,6 +372,7 @@ export function ComparePerRoutePanel({ ...@@ -365,6 +372,7 @@ export function ComparePerRoutePanel({
environmentFilter: Environment environmentFilter: Environment
hasAlternateEnvironmentSources: boolean hasAlternateEnvironmentSources: boolean
baselineSnapshot: SnapshotMetadata baselineSnapshot: SnapshotMetadata
baselineIsLatest: boolean
comparisonSnapshot: SnapshotMetadata | null comparisonSnapshot: SnapshotMetadata | null
compareSelectedKey: string | null compareSelectedKey: string | null
onCompareSelectedKeyChange: (key: string | null) => void onCompareSelectedKeyChange: (key: string | null) => void
...@@ -439,7 +447,9 @@ export function ComparePerRoutePanel({ ...@@ -439,7 +447,9 @@ export function ComparePerRoutePanel({
summary={sourceDiff} summary={sourceDiff}
useCompressed={compressed} useCompressed={compressed}
nameHeading="Source" nameHeading="Source"
aHeading={formatSnapshotLabel(baselineSnapshot)} aHeading={
baselineIsLatest ? 'Latest' : formatSnapshotLabel(baselineSnapshot)
}
bHeading={ bHeading={
comparisonSnapshot comparisonSnapshot
? formatSnapshotLabel(comparisonSnapshot) ? formatSnapshotLabel(comparisonSnapshot)
......
...@@ -48,6 +48,7 @@ type PickerOpenState = ...@@ -48,6 +48,7 @@ type PickerOpenState =
interface RouteTypeaheadOptions { interface RouteTypeaheadOptions {
selectedRoute: string | null selectedRoute: string | null
routesBaseDir?: string
/** /**
* When provided, the picker renders per-route size deltas next to each * 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 * route, sorts by largest impact, and uses the diff's route list as its
...@@ -170,7 +171,9 @@ export function RouteTypeaheadContent( ...@@ -170,7 +171,9 @@ export function RouteTypeaheadContent(
} }
) { ) {
const { selectedRoute, routeDiff, useCompressed = true, routeTotals } = props const { selectedRoute, routeDiff, useCompressed = true, routeTotals } = props
const routes = useSuspenseJsonData<string[]>('/data/routes.json') const routes = useSuspenseJsonData<string[]>(
`${props.routesBaseDir ?? '/data'}/routes.json`
)
// When a route diff is provided, sort routes by largest absolute impact so // 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 // the most-changed route bubbles to the top — matching the rest of the
......
'use client' 'use client'
import { BaselinePicker } from '@/components/baseline-picker' import { BuildPicker } from '@/components/build-picker'
import { FileSearch } from '@/components/file-search' import { FileSearch } from '@/components/file-search'
import { RouteTypeahead } from '@/components/route-typeahead' import { RouteTypeahead } from '@/components/route-typeahead'
import { import {
...@@ -55,10 +55,6 @@ const typeFilterOptions = [ ...@@ -55,10 +55,6 @@ const typeFilterOptions = [
}, },
] ]
export function ControlDivider() {
return <span className="h-6 w-px bg-muted-foreground/30" />
}
export function TopBar({ export function TopBar({
selectedRoute, selectedRoute,
routePickerOpen, routePickerOpen,
...@@ -73,12 +69,17 @@ export function TopBar({ ...@@ -73,12 +69,17 @@ export function TopBar({
setTypeFilter, setTypeFilter,
searchQuery, searchQuery,
setSearchQuery, setSearchQuery,
baselineSnapshot, isCompareMode,
getBaselineHref, historySnapshots,
onBaselineChange, historyLoading,
stopComparisonHref, historyError,
comparisonSnapshot, latestSnapshot,
singleBuildId,
fromId,
toId,
onSingleBuildChange,
onComparisonChange, onComparisonChange,
routesBaseDir,
compareView, compareView,
onCompareViewChange, onCompareViewChange,
routeDiff, routeDiff,
...@@ -103,12 +104,17 @@ export function TopBar({ ...@@ -103,12 +104,17 @@ export function TopBar({
setTypeFilter: (types: string[]) => void setTypeFilter: (types: string[]) => void
searchQuery: string searchQuery: string
setSearchQuery: (query: string) => void setSearchQuery: (query: string) => void
baselineSnapshot: SnapshotMetadata | null isCompareMode: boolean
getBaselineHref?: (snapshot: SnapshotMetadata) => string historySnapshots: SnapshotMetadata[]
onBaselineChange: (snapshot: SnapshotMetadata) => void historyLoading: boolean
stopComparisonHref: string historyError: boolean
comparisonSnapshot: SnapshotMetadata | null latestSnapshot: SnapshotMetadata
onComparisonChange: (snapshot: SnapshotMetadata | null) => void singleBuildId: string | null
fromId: string | null
toId: string | null
onSingleBuildChange: (id: string | null) => void
onComparisonChange: (from: string | null, to: string | null) => void
routesBaseDir: string
compareView: CompareView compareView: CompareView
onCompareViewChange: (view: CompareView) => void onCompareViewChange: (view: CompareView) => void
routeDiff: ReturnType<typeof diffRoutesWithSizes> | null routeDiff: ReturnType<typeof diffRoutesWithSizes> | null
...@@ -116,7 +122,6 @@ export function TopBar({ ...@@ -116,7 +122,6 @@ export function TopBar({
initialLoaded?: boolean initialLoaded?: boolean
onInitialLoadedChange?: (value: boolean) => void onInitialLoadedChange?: (value: boolean) => void
}) { }) {
const isCompareMode = baselineSnapshot != null
const routeSelection = getRouteHref const routeSelection = getRouteHref
? ({ mode: 'link', getRouteHref } as const) ? ({ mode: 'link', getRouteHref } as const)
: ({ : ({
...@@ -127,87 +132,68 @@ export function TopBar({ ...@@ -127,87 +132,68 @@ export function TopBar({
setFocusedSourceIndex(null) setFocusedSourceIndex(null)
}, },
} as const) } as const)
const baselineSelection = getBaselineHref
? ({
mode: 'link',
getSnapshotHref: getBaselineHref,
clearHref: stopComparisonHref,
} as const)
: ({
mode: 'action',
onSelectionChange: (snapshot: SnapshotMetadata | null) => {
if (snapshot) onBaselineChange(snapshot)
},
clearHref: stopComparisonHref,
} as const)
return ( return (
<div className="flex-none px-4 py-2 border-b border-border flex items-center gap-3"> <div className="flex-none border-b border-border">
<div className="flex min-w-0 flex-1"> <div className="flex min-w-0 items-center gap-2 overflow-x-auto px-4 py-2">
<RouteTypeahead <div className="flex min-w-48 flex-1 gap-2">
selectedRoute={selectedRoute} <BuildPicker
open={routePickerOpen} compareMode={isCompareMode}
onOpenChange={onRoutePickerOpenChange} historySnapshots={historySnapshots}
{...routeSelection} historyLoading={historyLoading}
routeDiff={isCompareMode ? routeDiff : null} historyError={historyError}
routeTotals={routeTotals} latestSnapshot={latestSnapshot}
useCompressed singleBuildId={singleBuildId}
/> fromId={fromId}
</div> toId={toId}
onSingleBuildChange={onSingleBuildChange}
<div className="flex items-center gap-2"> onComparisonChange={onComparisonChange}
<BaselinePicker
selectedSnapshotId={baselineSnapshot?.id ?? null}
{...baselineSelection}
excludedSnapshotId={comparisonSnapshot?.id}
prefix="from"
placeholder="Compare from…"
/>
{isCompareMode ? (
<BaselinePicker
mode="action"
selectedSnapshotId={comparisonSnapshot?.id ?? null}
onSelectionChange={onComparisonChange}
excludedSnapshotId={baselineSnapshot?.id}
prefix="to"
placeholder="to Latest"
clearLabel="Compare with latest"
/> />
) : null}
{showViewToggle && ( <RouteTypeahead
<ToggleGroup selectedRoute={selectedRoute}
type="single" open={routePickerOpen}
size="sm" onOpenChange={onRoutePickerOpenChange}
value={compareView} {...routeSelection}
onValueChange={(value) => { routeDiff={isCompareMode ? routeDiff : null}
if (value) onCompareViewChange(value as CompareView) routeTotals={routeTotals}
}} routesBaseDir={routesBaseDir}
aria-label="View" useCompressed
> />
<ToggleGroupItem </div>
value={CompareView.Table}
aria-label="Table view"
title="Table view"
className="gap-1.5"
>
<TableIcon className="h-3.5 w-3.5" />
<span className="text-xs">Table</span>
</ToggleGroupItem>
<ToggleGroupItem
value={CompareView.Treemap}
aria-label="Treemap view"
title="Treemap view"
className="gap-1.5"
>
<LayoutGrid className="h-3.5 w-3.5" />
<span className="text-xs">Treemap</span>
</ToggleGroupItem>
</ToggleGroup>
)}
{hasSourceData && ( {hasSourceData && (
<> <div className="flex shrink-0 items-center gap-2">
<ControlDivider /> {showViewToggle && (
<ToggleGroup
type="single"
size="sm"
value={compareView}
onValueChange={(value) => {
if (value) onCompareViewChange(value as CompareView)
}}
aria-label="View"
className="shrink-0"
>
<ToggleGroupItem
value={CompareView.Table}
aria-label="Table view"
title="Table view"
className="gap-1.5"
>
<TableIcon className="h-3.5 w-3.5" />
<span className="text-xs">Table</span>
</ToggleGroupItem>
<ToggleGroupItem
value={CompareView.Treemap}
aria-label="Treemap view"
title="Treemap view"
className="gap-1.5"
>
<LayoutGrid className="h-3.5 w-3.5" />
<span className="text-xs">Treemap</span>
</ToggleGroupItem>
</ToggleGroup>
)}
<Select <Select
value={environmentFilter} value={environmentFilter}
...@@ -258,9 +244,10 @@ export function TopBar({ ...@@ -258,9 +244,10 @@ export function TopBar({
</label> </label>
) : null} ) : null}
<ControlDivider /> {hasSourceData ? (
<FileSearch value={searchQuery} onChange={setSearchQuery} /> <FileSearch value={searchQuery} onChange={setSearchQuery} />
</> ) : null}
</div>
)} )}
</div> </div>
</div> </div>
......
...@@ -4,21 +4,35 @@ import type { SnapshotMetadata } from './snapshot' ...@@ -4,21 +4,35 @@ import type { SnapshotMetadata } from './snapshot'
export function useAnalyzerRoute( export function useAnalyzerRoute(
compare: boolean, compare: boolean,
snapshots: SnapshotMetadata[] | undefined snapshots: SnapshotMetadata[] | undefined,
latestSnapshot: SnapshotMetadata
) { ) {
const router = useRouter() const router = useRouter()
const pathname = usePathname() const pathname = usePathname()
const searchParams = useSearchParams() const searchParams = useSearchParams()
const selectedRoute = searchParams.get('route') const selectedRoute = searchParams.get('route')
const singleBuildId = compare ? null : searchParams.get('build')
const singleSnapshot = singleBuildId
? (snapshots?.find((snapshot) => snapshot.id === singleBuildId) ?? null)
: null
const fromId = compare ? searchParams.get('from') : null
const toParam = compare ? searchParams.get('to') : null
const toId = toParam === 'latest' ? null : toParam
const invalidComparison =
compare &&
toId != null &&
!snapshots?.some((snapshot) => snapshot.id === toId)
const baselineSnapshot = compare const baselineSnapshot = compare
? (snapshots?.find( ? fromId === 'latest'
(snapshot) => snapshot.id === searchParams.get('from') ? latestSnapshot
) ?? null) : (snapshots?.find((snapshot) => snapshot.id === fromId) ?? null)
: null : null
const comparisonSnapshot = compare const comparisonSnapshot = compare
? (snapshots?.find((snapshot) => snapshot.id === searchParams.get('to')) ?? ? (snapshots?.find((snapshot) => snapshot.id === toId) ?? null)
null) : singleSnapshot
: null const activeBaseDir = comparisonSnapshot
? `/history/${comparisonSnapshot.id}`
: '/data'
const viewParam = searchParams.get('view') const viewParam = searchParams.get('view')
const compareView = const compareView =
viewParam === CompareView.Table || viewParam === CompareView.Treemap viewParam === CompareView.Table || viewParam === CompareView.Treemap
...@@ -68,8 +82,14 @@ export function useAnalyzerRoute( ...@@ -68,8 +82,14 @@ export function useAnalyzerRoute(
} }
return { return {
activeBaseDir,
baselineSnapshot, baselineSnapshot,
comparisonSnapshot, comparisonSnapshot,
fromId,
invalidComparison,
singleBuildId,
singleSnapshot,
toId,
compareView, compareView,
environmentFilter, environmentFilter,
searchQuery, searchQuery,
...@@ -82,16 +102,16 @@ export function useAnalyzerRoute( ...@@ -82,16 +102,16 @@ export function useAnalyzerRoute(
pathname === '/' pathname === '/'
? (route: string) => buildHref('/analyze', { route }) ? (route: string) => buildHref('/analyze', { route })
: undefined, : undefined,
getBaselineHref: setSingleBuild: (id: string | null) =>
pathname === '/compare' navigate('/analyze', { build: id, from: null, to: null }, 'push'),
? undefined setComparison: (from: string | null, to: string | null) =>
: (snapshot: SnapshotMetadata) => navigate(
buildHref('/compare', { from: snapshot.id, to: null }), '/compare',
setBaselineSnapshot: (snapshot: SnapshotMetadata) => { from: from ?? 'latest', to, build: null },
navigate('/compare', { from: snapshot.id, to: null }, 'push'), pathname === '/compare' && fromId === (from ?? 'latest')
stopComparisonHref: buildHref('/analyze', { from: null, to: null }), ? 'replace'
setComparisonSnapshot: (snapshot: SnapshotMetadata | null) => : 'push'
navigate(pathname, { to: snapshot?.id ?? null }, 'replace'), ),
setEnvironmentFilter: (environment: Environment) => setEnvironmentFilter: (environment: Environment) =>
replaceSearchParams({ replaceSearchParams({
environment: environment === Environment.Client ? null : environment, environment: environment === Environment.Client ? null : environment,
......
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