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 {
computeSourceLoadScopes,
} from '@/lib/module-graph'
import type { SnapshotMetadata } from '@/lib/snapshot'
import { NetworkError } from '@/lib/errors'
import { formatBytes } from '@/lib/utils'
import { createAnalyzeTreemapSource, SizeMode } from '@/lib/treemap-layout'
......@@ -99,6 +100,8 @@ function AnalyzerFallback({ view }: { view: CompareView }) {
}
function useAnalyzerModel(compare: boolean) {
// Read the URL before suspense data so static prerendering can bail out.
useSearchParams()
const [routePickerOpen, setRoutePickerOpen] = useState(false)
const [selectedSourceIndex, setSelectedSourceIndex] = useState<number | null>(
null
......@@ -107,8 +110,20 @@ function useAnalyzerModel(compare: boolean) {
null
)
const { data: history, isLoading: isHistoryLoading } = useHistoryIndex()
const routeState = useAnalyzerRoute(compare, history?.snapshots)
const {
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 {
baselineSnapshot,
comparisonSnapshot,
......@@ -142,17 +157,14 @@ function useAnalyzerModel(compare: boolean) {
const activeView = pendingView ?? compareView
const isViewPending = pendingView != null && pendingView !== compareView
const comparisonBaseDir = comparisonSnapshot
? `/history/${comparisonSnapshot.id}`
: '/data'
const comparisonBaseDir = routeState.activeBaseDir
const { data: modulesData } = useSWR(
`${comparisonBaseDir}/modules.data`,
fetchModulesData,
{ suspense: true }
)
// Routes for comparison side B. This is the live build by default, or an
// independently selected historical snapshot.
// Routes for the active build, which is also comparison side B.
const currentRoutes = useSuspenseJsonData<string[]>(
`${comparisonBaseDir}/routes.json`,
{ revalidateOnFocus: false, revalidateOnReconnect: false }
......@@ -202,7 +214,7 @@ function useAnalyzerModel(compare: boolean) {
// previous selection is unlikely to exist in the new diff.
useEffect(() => {
setCompareSelectedKey(null)
}, [selectedRoute, baselineSnapshot, comparisonSnapshot])
}, [selectedRoute, routeState.fromId, routeState.toId])
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
......@@ -321,9 +333,20 @@ function useAnalyzerModel(compare: boolean) {
return {
analyzeData,
baselineSnapshot,
baselineIsLatest: compare && routeState.fromId === 'latest',
compareSelectedKey,
compareView: activeView,
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,
routePickerOpen,
setRoutePickerOpen,
......@@ -411,12 +434,17 @@ function AnalyzerTopBar({
setTypeFilter={model.setTypeFilter}
searchQuery={model.searchQuery}
setSearchQuery={model.setSearchQuery}
baselineSnapshot={model.baselineSnapshot}
getBaselineHref={model.routeState.getBaselineHref}
onBaselineChange={model.routeState.setBaselineSnapshot}
stopComparisonHref={model.routeState.stopComparisonHref}
comparisonSnapshot={model.comparisonSnapshot}
onComparisonChange={model.routeState.setComparisonSnapshot}
isCompareMode={model.isCompareMode}
historySnapshots={model.historySnapshots}
historyLoading={model.isHistoryLoading}
historyError={model.historyError}
latestSnapshot={model.latestSnapshot}
singleBuildId={model.singleBuildId}
fromId={model.fromId}
toId={model.toId}
onSingleBuildChange={model.routeState.setSingleBuild}
onComparisonChange={model.routeState.setComparison}
routesBaseDir={model.activeBaseDir}
routeDiff={routeDiff}
routeTotals={
model.environmentFilter === Environment.Client
......@@ -439,12 +467,17 @@ function CompareAnalyzerView({ model }: { model: AnalyzerModel }) {
</AnalyzerFrame>
)
}
if (model.baselineSnapshot) return <ValidComparison model={model} />
if (
model.baselineSnapshot &&
!model.invalidComparison &&
model.fromId !== (model.toId ?? 'latest')
)
return <ValidComparison model={model} />
return (
<AnalyzerFrame topBar={<AnalyzerTopBar model={model} />}>
<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>
</AnalyzerFrame>
)
......@@ -466,7 +499,9 @@ function ValidComparisonContent({
model: AnalyzerModel
baselineSnapshot: SnapshotMetadata
}) {
const baselineBaseDir = `/history/${baselineSnapshot.id}`
const baselineBaseDir = model.baselineIsLatest
? '/data'
: `/history/${baselineSnapshot.id}`
const { data: baselineModulesData } = useSWR(
`${baselineBaseDir}/modules.data`,
fetchModulesData,
......@@ -498,6 +533,7 @@ function ValidComparisonContent({
)
const layoutProps = {
baselineSnapshot,
baselineIsLatest: model.baselineIsLatest,
comparisonSnapshot: model.comparisonSnapshot,
comparisonRouteCount: model.currentRoutes.length,
routeDiff,
......@@ -562,6 +598,7 @@ function BaselineRouteComparison({
type ComparisonLayoutProps = Pick<
CompareLayoutModel,
| 'baselineSnapshot'
| 'baselineIsLatest'
| 'comparisonSnapshot'
| 'comparisonRouteCount'
| 'routeDiff'
......@@ -641,6 +678,24 @@ function ComparisonContent({
}
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 content = 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 {
export interface CompareLayoutModel {
baselineSnapshot: SnapshotMetadata
baselineIsLatest: boolean
comparisonSnapshot: SnapshotMetadata | null
comparisonRouteCount: number | null
routeDiff: ReturnType<typeof diffRoutesWithSizes> | null
......@@ -93,6 +94,7 @@ export function CompareLayout({ model, onResizeSidebar }: CompareLayoutProps) {
model.hasAlternateEnvironmentSources
}
baselineSnapshot={model.baselineSnapshot}
baselineIsLatest={model.baselineIsLatest}
comparisonSnapshot={model.comparisonSnapshot}
compareSelectedKey={model.selectedKey}
onCompareSelectedKeyChange={model.onSelectedKeyChange}
......@@ -116,7 +118,11 @@ export function CompareLayout({ model, onResizeSidebar }: CompareLayoutProps) {
baselineModuleDepthMap={model.baselineModuleDepthMap}
environmentFilter={model.environmentFilter}
sidebarWidth={model.sidebarWidth}
aLabel={formatSnapshotLabel(model.baselineSnapshot)}
aLabel={
model.baselineIsLatest
? 'Latest'
: formatSnapshotLabel(model.baselineSnapshot)
}
bLabel={
model.comparisonSnapshot
? formatSnapshotLabel(model.comparisonSnapshot)
......@@ -349,6 +355,7 @@ export function ComparePerRoutePanel({
environmentFilter,
hasAlternateEnvironmentSources,
baselineSnapshot,
baselineIsLatest,
comparisonSnapshot,
compareSelectedKey,
onCompareSelectedKeyChange,
......@@ -365,6 +372,7 @@ export function ComparePerRoutePanel({
environmentFilter: Environment
hasAlternateEnvironmentSources: boolean
baselineSnapshot: SnapshotMetadata
baselineIsLatest: boolean
comparisonSnapshot: SnapshotMetadata | null
compareSelectedKey: string | null
onCompareSelectedKeyChange: (key: string | null) => void
......@@ -439,7 +447,9 @@ export function ComparePerRoutePanel({
summary={sourceDiff}
useCompressed={compressed}
nameHeading="Source"
aHeading={formatSnapshotLabel(baselineSnapshot)}
aHeading={
baselineIsLatest ? 'Latest' : formatSnapshotLabel(baselineSnapshot)
}
bHeading={
comparisonSnapshot
? formatSnapshotLabel(comparisonSnapshot)
......
......@@ -48,6 +48,7 @@ type PickerOpenState =
interface RouteTypeaheadOptions {
selectedRoute: string | null
routesBaseDir?: string
/**
* 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
......@@ -170,7 +171,9 @@ export function RouteTypeaheadContent(
}
) {
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
// the most-changed route bubbles to the top — matching the rest of the
......
'use client'
import { BaselinePicker } from '@/components/baseline-picker'
import { BuildPicker } from '@/components/build-picker'
import { FileSearch } from '@/components/file-search'
import { RouteTypeahead } from '@/components/route-typeahead'
import {
......@@ -55,10 +55,6 @@ const typeFilterOptions = [
},
]
export function ControlDivider() {
return <span className="h-6 w-px bg-muted-foreground/30" />
}
export function TopBar({
selectedRoute,
routePickerOpen,
......@@ -73,12 +69,17 @@ export function TopBar({
setTypeFilter,
searchQuery,
setSearchQuery,
baselineSnapshot,
getBaselineHref,
onBaselineChange,
stopComparisonHref,
comparisonSnapshot,
isCompareMode,
historySnapshots,
historyLoading,
historyError,
latestSnapshot,
singleBuildId,
fromId,
toId,
onSingleBuildChange,
onComparisonChange,
routesBaseDir,
compareView,
onCompareViewChange,
routeDiff,
......@@ -103,12 +104,17 @@ export function TopBar({
setTypeFilter: (types: string[]) => void
searchQuery: string
setSearchQuery: (query: string) => void
baselineSnapshot: SnapshotMetadata | null
getBaselineHref?: (snapshot: SnapshotMetadata) => string
onBaselineChange: (snapshot: SnapshotMetadata) => void
stopComparisonHref: string
comparisonSnapshot: SnapshotMetadata | null
onComparisonChange: (snapshot: SnapshotMetadata | null) => void
isCompareMode: boolean
historySnapshots: SnapshotMetadata[]
historyLoading: boolean
historyError: boolean
latestSnapshot: SnapshotMetadata
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
onCompareViewChange: (view: CompareView) => void
routeDiff: ReturnType<typeof diffRoutesWithSizes> | null
......@@ -116,7 +122,6 @@ export function TopBar({
initialLoaded?: boolean
onInitialLoadedChange?: (value: boolean) => void
}) {
const isCompareMode = baselineSnapshot != null
const routeSelection = getRouteHref
? ({ mode: 'link', getRouteHref } as const)
: ({
......@@ -127,87 +132,68 @@ export function TopBar({
setFocusedSourceIndex(null)
},
} 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 (
<div className="flex-none px-4 py-2 border-b border-border flex items-center gap-3">
<div className="flex min-w-0 flex-1">
<RouteTypeahead
selectedRoute={selectedRoute}
open={routePickerOpen}
onOpenChange={onRoutePickerOpenChange}
{...routeSelection}
routeDiff={isCompareMode ? routeDiff : null}
routeTotals={routeTotals}
useCompressed
/>
</div>
<div className="flex items-center gap-2">
<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"
<div className="flex-none border-b border-border">
<div className="flex min-w-0 items-center gap-2 overflow-x-auto px-4 py-2">
<div className="flex min-w-48 flex-1 gap-2">
<BuildPicker
compareMode={isCompareMode}
historySnapshots={historySnapshots}
historyLoading={historyLoading}
historyError={historyError}
latestSnapshot={latestSnapshot}
singleBuildId={singleBuildId}
fromId={fromId}
toId={toId}
onSingleBuildChange={onSingleBuildChange}
onComparisonChange={onComparisonChange}
/>
) : null}
{showViewToggle && (
<ToggleGroup
type="single"
size="sm"
value={compareView}
onValueChange={(value) => {
if (value) onCompareViewChange(value as CompareView)
}}
aria-label="View"
>
<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>
)}
<RouteTypeahead
selectedRoute={selectedRoute}
open={routePickerOpen}
onOpenChange={onRoutePickerOpenChange}
{...routeSelection}
routeDiff={isCompareMode ? routeDiff : null}
routeTotals={routeTotals}
routesBaseDir={routesBaseDir}
useCompressed
/>
</div>
{hasSourceData && (
<>
<ControlDivider />
<div className="flex shrink-0 items-center gap-2">
{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
value={environmentFilter}
......@@ -258,9 +244,10 @@ export function TopBar({
</label>
) : null}
<ControlDivider />
<FileSearch value={searchQuery} onChange={setSearchQuery} />
</>
{hasSourceData ? (
<FileSearch value={searchQuery} onChange={setSearchQuery} />
) : null}
</div>
)}
</div>
</div>
......
......@@ -4,21 +4,35 @@ import type { SnapshotMetadata } from './snapshot'
export function useAnalyzerRoute(
compare: boolean,
snapshots: SnapshotMetadata[] | undefined
snapshots: SnapshotMetadata[] | undefined,
latestSnapshot: SnapshotMetadata
) {
const router = useRouter()
const pathname = usePathname()
const searchParams = useSearchParams()
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
? (snapshots?.find(
(snapshot) => snapshot.id === searchParams.get('from')
) ?? null)
? fromId === 'latest'
? latestSnapshot
: (snapshots?.find((snapshot) => snapshot.id === fromId) ?? null)
: null
const comparisonSnapshot = compare
? (snapshots?.find((snapshot) => snapshot.id === searchParams.get('to')) ??
null)
: null
? (snapshots?.find((snapshot) => snapshot.id === toId) ?? null)
: singleSnapshot
const activeBaseDir = comparisonSnapshot
? `/history/${comparisonSnapshot.id}`
: '/data'
const viewParam = searchParams.get('view')
const compareView =
viewParam === CompareView.Table || viewParam === CompareView.Treemap
......@@ -68,8 +82,14 @@ export function useAnalyzerRoute(
}
return {
activeBaseDir,
baselineSnapshot,
comparisonSnapshot,
fromId,
invalidComparison,
singleBuildId,
singleSnapshot,
toId,
compareView,
environmentFilter,
searchQuery,
......@@ -82,16 +102,16 @@ export function useAnalyzerRoute(
pathname === '/'
? (route: string) => buildHref('/analyze', { route })
: undefined,
getBaselineHref:
pathname === '/compare'
? undefined
: (snapshot: SnapshotMetadata) =>
buildHref('/compare', { from: snapshot.id, to: null }),
setBaselineSnapshot: (snapshot: SnapshotMetadata) =>
navigate('/compare', { from: snapshot.id, to: null }, 'push'),
stopComparisonHref: buildHref('/analyze', { from: null, to: null }),
setComparisonSnapshot: (snapshot: SnapshotMetadata | null) =>
navigate(pathname, { to: snapshot?.id ?? null }, 'replace'),
setSingleBuild: (id: string | null) =>
navigate('/analyze', { build: id, from: null, to: null }, 'push'),
setComparison: (from: string | null, to: string | null) =>
navigate(
'/compare',
{ from: from ?? 'latest', to, build: null },
pathname === '/compare' && fromId === (from ?? 'latest')
? 'replace'
: 'push'
),
setEnvironmentFilter: (environment: Environment) =>
replaceSearchParams({
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