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

Show bundle changes in compare treemap (#98837)

## Summary

Size compare-treemap nodes by the absolute module-size delta and use
color to show whether each module grew or shrank.

Build the view from changed modules in both snapshots so removed modules
remain visible. Group generated chunks without usable source mappings
under `Unattributed output` instead of presenting them as source
modules.

## Verification

- `pnpm --filter @next/bundle-analyzer-ui exec eslint
components/diff-treemap.tsx components/treemap-visualizer.tsx
lib/diff-treemap-layout.ts`
- `pnpm --filter @next/bundle-analyzer-ui exec tsc --noEmit`

<!-- 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 014e821c
...@@ -40,7 +40,7 @@ import { useAnalyzerRoute } from '@/lib/use-analyzer-route' ...@@ -40,7 +40,7 @@ import { useAnalyzerRoute } from '@/lib/use-analyzer-route'
import { computeActiveEntries, computeModuleDepthMap } from '@/lib/module-graph' import { computeActiveEntries, computeModuleDepthMap } from '@/lib/module-graph'
import type { SnapshotMetadata } from '@/lib/snapshot' import type { SnapshotMetadata } from '@/lib/snapshot'
import { formatBytes } from '@/lib/utils' import { formatBytes } from '@/lib/utils'
import { SizeMode } from '@/lib/treemap-layout' import { createAnalyzeTreemapSource, SizeMode } from '@/lib/treemap-layout'
export function SingleAnalyzer() { export function SingleAnalyzer() {
return ( return (
...@@ -57,7 +57,7 @@ function SingleAnalyzerController() { ...@@ -57,7 +57,7 @@ function SingleAnalyzerController() {
export function CompareAnalyzer() { export function CompareAnalyzer() {
return ( return (
<AnalyzerBoundary defaultView={CompareView.Table}> <AnalyzerBoundary defaultView={CompareView.Treemap}>
<CompareAnalyzerController /> <CompareAnalyzerController />
</AnalyzerBoundary> </AnalyzerBoundary>
) )
...@@ -89,6 +89,7 @@ function AnalyzerFallback({ view }: { view: CompareView }) { ...@@ -89,6 +89,7 @@ function AnalyzerFallback({ view }: { view: CompareView }) {
} }
function useAnalyzerModel(compare: boolean) { function useAnalyzerModel(compare: boolean) {
const [routePickerOpen, setRoutePickerOpen] = useState(false)
const [selectedSourceIndex, setSelectedSourceIndex] = useState<number | null>( const [selectedSourceIndex, setSelectedSourceIndex] = useState<number | null>(
null null
) )
...@@ -293,6 +294,8 @@ function useAnalyzerModel(compare: boolean) { ...@@ -293,6 +294,8 @@ function useAnalyzerModel(compare: boolean) {
compareView: activeView, compareView: activeView,
comparisonSnapshot, comparisonSnapshot,
currentRoutes, currentRoutes,
routePickerOpen,
setRoutePickerOpen,
environmentFilter, environmentFilter,
filterSource, filterSource,
focusedSourceIndex, focusedSourceIndex,
...@@ -362,6 +365,8 @@ function AnalyzerTopBar({ ...@@ -362,6 +365,8 @@ function AnalyzerTopBar({
compareView={model.compareView} compareView={model.compareView}
onCompareViewChange={model.setCompareView} onCompareViewChange={model.setCompareView}
selectedRoute={model.selectedRoute} selectedRoute={model.selectedRoute}
routePickerOpen={model.routePickerOpen}
onRoutePickerOpenChange={model.setRoutePickerOpen}
getRouteHref={model.routeState.getRouteHref} getRouteHref={model.routeState.getRouteHref}
setSelectedRoute={model.routeState.setRoute} setSelectedRoute={model.routeState.setRoute}
environmentFilter={model.environmentFilter} environmentFilter={model.environmentFilter}
...@@ -591,6 +596,7 @@ function ComparisonContent({ ...@@ -591,6 +596,7 @@ function ComparisonContent({
isViewPending: model.isViewPending, isViewPending: model.isViewPending,
selectedKey: model.compareSelectedKey, selectedKey: model.compareSelectedKey,
onSelectedKeyChange: model.setCompareSelectedKey, onSelectedKeyChange: model.setCompareSelectedKey,
onOpenRoutePicker: () => model.setRoutePickerOpen(true),
} }
return ( return (
...@@ -627,7 +633,8 @@ function SingleAnalyzerContent({ ...@@ -627,7 +633,8 @@ function SingleAnalyzerContent({
model: AnalyzerModel model: AnalyzerModel
analyzeData: AnalyzeData analyzeData: AnalyzeData
}) { }) {
const rootSourceIndex = getRootSourceIndex(analyzeData) const source = createAnalyzeTreemapSource(analyzeData)
const rootSourceIndex = source.rootIndex
const hasAlternateEnvironmentSources = hasEnvironmentSources( const hasAlternateEnvironmentSources = hasEnvironmentSources(
analyzeData, analyzeData,
getAlternateEnvironment(model.environmentFilter), getAlternateEnvironment(model.environmentFilter),
...@@ -665,8 +672,7 @@ function SingleAnalyzerContent({ ...@@ -665,8 +672,7 @@ function SingleAnalyzerContent({
</div> </div>
) : ( ) : (
<TreemapVisualizer <TreemapVisualizer
analyzeData={analyzeData} source={source}
sourceIndex={rootSourceIndex}
selectedSourceIndex={model.selectedSourceIndex ?? rootSourceIndex} selectedSourceIndex={model.selectedSourceIndex ?? rootSourceIndex}
onSelectSourceIndex={model.setSelectedSourceIndex} onSelectSourceIndex={model.setSelectedSourceIndex}
focusedSourceIndex={model.focusedSourceIndex ?? rootSourceIndex} focusedSourceIndex={model.focusedSourceIndex ?? rootSourceIndex}
......
'use client' 'use client'
import { ArrowRight, CircleCheck, Route } from 'lucide-react'
import Link from 'next/link'
import type { MouseEventHandler } from 'react' 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'
...@@ -7,6 +9,7 @@ import { DiffTreemap } from '@/components/diff-treemap' ...@@ -7,6 +9,7 @@ import { DiffTreemap } from '@/components/diff-treemap'
import { StatCard, CountCard } from '@/components/stat-cards' import { StatCard, CountCard } from '@/components/stat-cards'
import { CompareView, Environment } from '@/components/top-bar' import { CompareView, Environment } from '@/components/top-bar'
import { AlternateEnvironmentEmptyState } from '@/components/analyzer' import { AlternateEnvironmentEmptyState } from '@/components/analyzer'
import { Button } from '@/components/ui/button'
import { TableSkeleton, TreemapSkeleton } from '@/components/ui/skeleton' import { TableSkeleton, TreemapSkeleton } from '@/components/ui/skeleton'
import { AnalyzeData, ModulesData } from '@/lib/analyze-data' import { AnalyzeData, ModulesData } from '@/lib/analyze-data'
import { import {
...@@ -45,6 +48,7 @@ export interface CompareLayoutModel { ...@@ -45,6 +48,7 @@ export interface CompareLayoutModel {
searchQuery: string searchQuery: string
selectedKey: string | null selectedKey: string | null
onSelectedKeyChange: (key: string | null) => void onSelectedKeyChange: (key: string | null) => void
onOpenRoutePicker: () => void
} }
/** /**
...@@ -92,6 +96,7 @@ export function CompareLayout({ model, onResizeSidebar }: CompareLayoutProps) { ...@@ -92,6 +96,7 @@ export function CompareLayout({ model, onResizeSidebar }: CompareLayoutProps) {
comparisonSnapshot={model.comparisonSnapshot} comparisonSnapshot={model.comparisonSnapshot}
compareSelectedKey={model.selectedKey} compareSelectedKey={model.selectedKey}
onCompareSelectedKeyChange={model.onSelectedKeyChange} onCompareSelectedKeyChange={model.onSelectedKeyChange}
onOpenRoutePicker={model.onOpenRoutePicker}
/> />
</div> </div>
<button <button
...@@ -347,6 +352,7 @@ export function ComparePerRoutePanel({ ...@@ -347,6 +352,7 @@ export function ComparePerRoutePanel({
comparisonSnapshot, comparisonSnapshot,
compareSelectedKey, compareSelectedKey,
onCompareSelectedKeyChange, onCompareSelectedKeyChange,
onOpenRoutePicker,
}: { }: {
compareView: CompareView compareView: CompareView
isViewPending: boolean isViewPending: boolean
...@@ -362,6 +368,7 @@ export function ComparePerRoutePanel({ ...@@ -362,6 +368,7 @@ export function ComparePerRoutePanel({
comparisonSnapshot: SnapshotMetadata | null comparisonSnapshot: SnapshotMetadata | null
compareSelectedKey: string | null compareSelectedKey: string | null
onCompareSelectedKeyChange: (key: string | null) => void onCompareSelectedKeyChange: (key: string | null) => void
onOpenRoutePicker: () => void
}) { }) {
if (!selectedRoute) { if (!selectedRoute) {
return ( return (
...@@ -394,6 +401,21 @@ export function ComparePerRoutePanel({ ...@@ -394,6 +401,21 @@ export function ComparePerRoutePanel({
) )
} }
const hasNoModuleChanges =
sourceDiff.rows.length > 0 &&
sourceDiff.counts.added === 0 &&
sourceDiff.counts.removed === 0 &&
sourceDiff.counts.changed === 0
if (hasNoModuleChanges) {
return (
<NoModuleChangesState
selectedRoute={selectedRoute}
onOpenRoutePicker={onOpenRoutePicker}
/>
)
}
return ( return (
<div className="flex flex-1 min-h-0 flex-col"> <div className="flex flex-1 min-h-0 flex-col">
{compareView === CompareView.Treemap && {compareView === CompareView.Treemap &&
...@@ -408,6 +430,7 @@ export function ComparePerRoutePanel({ ...@@ -408,6 +430,7 @@ export function ComparePerRoutePanel({
useCompressed={compressed} useCompressed={compressed}
analyzeData={analyzeData} analyzeData={analyzeData}
baselineAnalyzeData={baselineAnalyzeData} baselineAnalyzeData={baselineAnalyzeData}
searchQuery={searchQuery}
selectedKey={compareSelectedKey} selectedKey={compareSelectedKey}
onSelectKey={onCompareSelectedKeyChange} onSelectKey={onCompareSelectedKeyChange}
/> />
...@@ -435,3 +458,42 @@ export function ComparePerRoutePanel({ ...@@ -435,3 +458,42 @@ export function ComparePerRoutePanel({
</div> </div>
) )
} }
function NoModuleChangesState({
selectedRoute,
onOpenRoutePicker,
}: {
selectedRoute: string
onOpenRoutePicker: () => void
}) {
return (
<div className="flex flex-1 items-center justify-center p-6 text-center">
<div className="flex max-w-sm flex-col items-center">
<div className="mb-4 flex h-10 w-10 items-center justify-center rounded-full border border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400">
<CircleCheck className="h-5 w-5" aria-hidden="true" />
</div>
<h2 className="text-base font-semibold text-foreground">
No module changes
</h2>
<p className="mt-1.5 text-sm leading-6 text-muted-foreground">
This route contains the same modules with the same sizes in both
revisions.
</p>
<div className="mt-5 flex flex-wrap items-center justify-center gap-2">
<Button type="button" size="sm" onClick={onOpenRoutePicker}>
<Route aria-hidden="true" />
Choose another route
</Button>
<Button asChild variant="outline" size="sm">
<Link
href={{ pathname: '/analyze', query: { route: selectedRoute } }}
>
View latest analysis
<ArrowRight aria-hidden="true" />
</Link>
</Button>
</div>
</div>
</div>
)
}
'use client' 'use client'
import { useState } from 'react' import { useMemo, useState } from 'react'
import type { AnalyzeData } from '@/lib/analyze-data' import type { AnalyzeData } from '@/lib/analyze-data'
import type { DiffSummary, SourceDiffRow } from '@/lib/diff' import type { DiffSummary, SourceDiffRow } from '@/lib/diff'
import { delta, formatDelta } from '@/lib/diff' import { delta, formatDelta } from '@/lib/diff'
import { createDiffTreemapLayout } from '@/lib/diff-treemap-layout'
import { SizeMode, type LayoutNode } from '@/lib/treemap-layout' import { SizeMode, type LayoutNode } from '@/lib/treemap-layout'
import { TreemapVisualizer } from '@/components/treemap-visualizer' import { TreemapVisualizer } from '@/components/treemap-visualizer'
/**
* Threshold (bytes) below which a row's delta is considered "noise" and the
* row is rendered as neutral grey rather than a directional color. This keeps the
* visualization legible when the build pipeline produces tiny non-deterministic
* size deltas (e.g., source-map paths, comments).
*/
const NEUTRAL_DELTA_THRESHOLD = 4
/** Color-blind-safe blue/amber palette for bundle-size increases/decreases. */ /** Color-blind-safe blue/amber palette for bundle-size increases/decreases. */
const COLOR_INCREASE = '#2563eb' // blue-600 const COLOR_INCREASE = '#2563eb' // blue-600
const COLOR_INCREASE_MUTED = 'rgba(37, 99, 235, 0.6)' const COLOR_INCREASE_MUTED = 'rgba(37, 99, 235, 0.6)'
const COLOR_DECREASE = '#d97706' // amber-600 const COLOR_DECREASE = '#d97706' // amber-600
const COLOR_DECREASE_MUTED = 'rgba(217, 119, 6, 0.6)' const COLOR_DECREASE_MUTED = 'rgba(217, 119, 6, 0.6)'
const COLOR_NEUTRAL = '#9ca3af' // gray-400
interface DiffTreemapProps { interface DiffTreemapProps {
summary: DiffSummary<SourceDiffRow> summary: DiffSummary<SourceDiffRow>
useCompressed: boolean useCompressed: boolean
/** /** Comparison-side data; the synthetic diff tree drives tile layout. */
* Analyze data for comparison side B. Used as the source-of-truth tree
* when present.
*/
analyzeData: AnalyzeData | null analyzeData: AnalyzeData | null
/** /** Baseline data used when the route was removed (no comparison data). */
* Analyze data for the baseline ("A") build. Only used when the route was
* removed (no B-side data) so we can still render the removed sources.
*/
baselineAnalyzeData: AnalyzeData | null baselineAnalyzeData: AnalyzeData | null
searchQuery: string
/** /**
* Currently selected diff row (its `key`). Used so the compare sidebar * Currently selected diff row (its `key`). Used so the compare sidebar
* and treemap stay in sync when the user clicks elsewhere. * and treemap stay in sync when the user clicks elsewhere.
...@@ -57,57 +44,37 @@ interface DiffTreemapProps { ...@@ -57,57 +44,37 @@ interface DiffTreemapProps {
* - bright amber: removed from the comparison build * - bright amber: removed from the comparison build
* - blue tint: same file, grew since the baseline build * - blue tint: same file, grew since the baseline build
* - amber tint: same file, shrank since the baseline build * - amber tint: same file, shrank since the baseline build
* - neutral: same size in both builds * Only changed files are shown; unchanged rows have no delta area.
* *
* Removed files don't exist in comparison build B's source tree so they * Tile area represents the absolute size delta. The tree is synthesized from
* don't appear in the treemap; users can still see them in the table view. * the union of both builds, so additions and removals are both visible.
*/ */
export function DiffTreemap({ export function DiffTreemap({
summary, summary,
useCompressed, useCompressed,
analyzeData, analyzeData,
baselineAnalyzeData, baselineAnalyzeData,
searchQuery,
selectedKey, selectedKey,
onSelectKey, onSelectKey,
}: DiffTreemapProps) { }: DiffTreemapProps) {
// Pick the side that drives the source tree. Prefer comparison build B;
// fall back to baseline A for the "removed route" case where there's no
// B-side data.
const data = analyzeData ?? baselineAnalyzeData const data = analyzeData ?? baselineAnalyzeData
// Index the diff rows by source index for tile lookups during canvas layout. // The React Compiler currently rebuilds this synthetic tree on every render.
const rowBySourceIndex = new Map<number, SourceDiffRow>() // Keep it stable while hover and focus redraw the canvas.
const side: 'A' | 'B' = analyzeData ? 'B' : 'A' const diffLayout = useMemo(
for (const row of summary.rows) { () => createDiffTreemapLayout(summary.rows, useCompressed),
const idx = side === 'B' ? row.sourceIndexB : row.sourceIndexA [summary.rows, useCompressed]
if (idx != null) rowBySourceIndex.set(idx, row) )
} const { rowBySourceIndex, sourceIndexByKey } = diffLayout
// The AnalyzeData tree can contain the same source path at multiple indices
// (e.g. one file included in several chunks). In the diff treemap we only
// want each unique path to appear once, using the canonical source index
// stored on the diff row. Passing this as `filterSource` removes all
// duplicate instances from the layout so there are no confusing gray tiles
// and clicking always resolves to a diff row.
const canonicalSourceIndices = new Set(rowBySourceIndex.keys())
// Reverse lookup so we can map a selected diff key (full source path) back
// to a source index in the active side's tree.
const sourceIndexByKey = new Map<string, number>()
for (const [idx, row] of rowBySourceIndex) {
sourceIndexByKey.set(row.key, idx)
}
function getFileColorOverride(node: LayoutNode): string | undefined { function getFileColorOverride(node: LayoutNode): string | undefined {
if (node.sourceIndex === undefined) return undefined if (node.sourceIndex === undefined) return undefined
const row = rowBySourceIndex.get(node.sourceIndex) const row = rowBySourceIndex.get(node.sourceIndex)
if (!row) return COLOR_NEUTRAL return row ? colorForRow(row, useCompressed) : undefined
return colorForRow(row, useCompressed)
} }
// Show size deltas on tiles instead of absolute sizes. Identical files fall // Show size deltas on changed tiles instead of absolute sizes.
// back to the default (absolute size) since ±0 on every unchanged tile
// would be noise.
function getFileSizeLabel(node: LayoutNode): string | undefined { function getFileSizeLabel(node: LayoutNode): string | undefined {
if (node.sourceIndex === undefined) return undefined if (node.sourceIndex === undefined) return undefined
const row = rowBySourceIndex.get(node.sourceIndex) const row = rowBySourceIndex.get(node.sourceIndex)
...@@ -117,13 +84,12 @@ export function DiffTreemap({ ...@@ -117,13 +84,12 @@ export function DiffTreemap({
// Focus state stays local: it controls drill-in/zoom, which is purely a // Focus state stays local: it controls drill-in/zoom, which is purely a
// visual concern of the treemap and shouldn't affect the sidebar. // visual concern of the treemap and shouldn't affect the sidebar.
const initialRoot = data?.sourceRoots()[0] ?? 0 const initialRoot = diffLayout.rootIndex
const [focusedSourceIndex, setFocusedSourceIndex] = const [focusedSourceIndex, setFocusedSourceIndex] =
useState<number>(initialRoot) useState<number>(initialRoot)
// Translate the externally-driven selection key into the side's source // Translate selection into the synthetic tree's index. If the selected
// index. Falls back to the root so the treemap renders something sensible // path has no size delta, fall back to the root of changed files.
// when the selection lives on the other side (e.g., a removed file).
const selectedSourceIndex = const selectedSourceIndex =
(selectedKey != null ? sourceIndexByKey.get(selectedKey) : undefined) ?? (selectedKey != null ? sourceIndexByKey.get(selectedKey) : undefined) ??
initialRoot initialRoot
...@@ -144,26 +110,24 @@ export function DiffTreemap({ ...@@ -144,26 +110,24 @@ export function DiffTreemap({
return ( return (
<TreemapVisualizer <TreemapVisualizer
analyzeData={data} source={diffLayout}
sourceIndex={initialRoot}
selectedSourceIndex={selectedSourceIndex} selectedSourceIndex={selectedSourceIndex}
onSelectSourceIndex={handleSelectSourceIndex} onSelectSourceIndex={handleSelectSourceIndex}
focusedSourceIndex={focusedSourceIndex} focusedSourceIndex={focusedSourceIndex}
onFocusSourceIndex={setFocusedSourceIndex} onFocusSourceIndex={setFocusedSourceIndex}
filterSource={(idx) => canonicalSourceIndices.has(idx)}
getFileSizeLabel={getFileSizeLabel} getFileSizeLabel={getFileSizeLabel}
sizeMode={useCompressed ? SizeMode.Compressed : SizeMode.Uncompressed} sizeMode={useCompressed ? SizeMode.Compressed : SizeMode.Uncompressed}
getFileColorOverride={getFileColorOverride} getFileColorOverride={getFileColorOverride}
overlay={<DiffLegend hasRemoved={summary.counts.removed > 0} />} searchQuery={searchQuery}
overlay={<DiffLegend />}
/> />
) )
} }
/** /**
* Picks a fill color for a diff row. Mirrors the previous DiffTreemap's * Picks a fill color for a diff row. Mirrors the previous DiffTreemap's
* scheme: bright blue/amber for added/removed, lighter tints scaled by the * scheme: bright blue/amber for added/removed and lighter tints scaled by the
* relative magnitude of the change for grew/shrank, and neutral grey for * relative magnitude of the change for grew/shrank.
* sub-threshold changes.
*/ */
function colorForRow(row: SourceDiffRow, useCompressed: boolean): string { function colorForRow(row: SourceDiffRow, useCompressed: boolean): string {
if (row.status === 'added') return COLOR_INCREASE if (row.status === 'added') return COLOR_INCREASE
...@@ -171,9 +135,6 @@ function colorForRow(row: SourceDiffRow, useCompressed: boolean): string { ...@@ -171,9 +135,6 @@ function colorForRow(row: SourceDiffRow, useCompressed: boolean): string {
const deltaValue = useCompressed const deltaValue = useCompressed
? row.compressedB - row.compressedA ? row.compressedB - row.compressedA
: row.sizeB - row.sizeA : row.sizeB - row.sizeA
if (Math.abs(deltaValue) <= NEUTRAL_DELTA_THRESHOLD) {
return COLOR_NEUTRAL
}
// For changed rows, scale opacity by relative magnitude so a 1% change is // For changed rows, scale opacity by relative magnitude so a 1% change is
// less alarming than a 50% change. // less alarming than a 50% change.
const baseline = useCompressed ? row.compressedA : row.sizeA const baseline = useCompressed ? row.compressedA : row.sizeA
...@@ -186,12 +147,12 @@ function colorForRow(row: SourceDiffRow, useCompressed: boolean): string { ...@@ -186,12 +147,12 @@ function colorForRow(row: SourceDiffRow, useCompressed: boolean): string {
} }
/** Static legend overlay so users can decode the color scheme at a glance. */ /** Static legend overlay so users can decode the color scheme at a glance. */
function DiffLegend({ hasRemoved }: { hasRemoved: boolean }) { function DiffLegend() {
const items: Array<{ label: string; color: string }> = [ const items: Array<{ label: string; color: string }> = [
{ label: 'Added', color: COLOR_INCREASE }, { label: 'Added', color: COLOR_INCREASE },
{ label: 'Grew', color: COLOR_INCREASE_MUTED }, { label: 'Grew', color: COLOR_INCREASE_MUTED },
{ label: 'Unchanged', color: COLOR_NEUTRAL },
{ label: 'Shrank', color: COLOR_DECREASE_MUTED }, { label: 'Shrank', color: COLOR_DECREASE_MUTED },
{ label: 'Removed', color: COLOR_DECREASE },
] ]
return ( return (
<div className="absolute bottom-2 left-2 flex items-center gap-3 rounded border border-border bg-background/90 px-2 py-1 text-xs text-muted-foreground shadow-sm"> <div className="absolute bottom-2 left-2 flex items-center gap-3 rounded border border-border bg-background/90 px-2 py-1 text-xs text-muted-foreground shadow-sm">
...@@ -205,11 +166,6 @@ function DiffLegend({ hasRemoved }: { hasRemoved: boolean }) { ...@@ -205,11 +166,6 @@ function DiffLegend({ hasRemoved }: { hasRemoved: boolean }) {
{item.label} {item.label}
</span> </span>
))} ))}
{hasRemoved ? (
<span className="border-l border-border pl-3 italic">
Removed sources are listed in the table view.
</span>
) : null}
</div> </div>
) )
} }
...@@ -60,6 +60,8 @@ export function ControlDivider() { ...@@ -60,6 +60,8 @@ export function ControlDivider() {
export function TopBar({ export function TopBar({
selectedRoute, selectedRoute,
routePickerOpen,
onRoutePickerOpenChange,
setSelectedRoute, setSelectedRoute,
getRouteHref, getRouteHref,
environmentFilter, environmentFilter,
...@@ -86,6 +88,8 @@ export function TopBar({ ...@@ -86,6 +88,8 @@ export function TopBar({
hasSourceData: boolean hasSourceData: boolean
showViewToggle: boolean showViewToggle: boolean
selectedRoute: string | null selectedRoute: string | null
routePickerOpen: boolean
onRoutePickerOpenChange: (open: boolean) => void
setSelectedRoute: (route: string | null) => void setSelectedRoute: (route: string | null) => void
getRouteHref?: (route: string) => string getRouteHref?: (route: string) => string
environmentFilter: Environment environmentFilter: Environment
...@@ -136,6 +140,8 @@ export function TopBar({ ...@@ -136,6 +140,8 @@ export function TopBar({
<div className="flex min-w-0 flex-1"> <div className="flex min-w-0 flex-1">
<RouteTypeahead <RouteTypeahead
selectedRoute={selectedRoute} selectedRoute={selectedRoute}
open={routePickerOpen}
onOpenChange={onRoutePickerOpenChange}
{...routeSelection} {...routeSelection}
routeDiff={isCompareMode ? routeDiff : null} routeDiff={isCompareMode ? routeDiff : null}
routeTotals={routeTotals} routeTotals={routeTotals}
...@@ -233,12 +239,8 @@ export function TopBar({ ...@@ -233,12 +239,8 @@ export function TopBar({
aria-label="Filter by file type" aria-label="Filter by file type"
/> />
{!isCompareMode && ( <ControlDivider />
<> <FileSearch value={searchQuery} onChange={setSearchQuery} />
<ControlDivider />
<FileSearch value={searchQuery} onChange={setSearchQuery} />
</>
)}
</> </>
)} )}
</div> </div>
......
...@@ -3,11 +3,10 @@ ...@@ -3,11 +3,10 @@
import { darken, lighten, readableColor } from 'polished' import { darken, lighten, readableColor } from 'polished'
import type React from 'react' import type React from 'react'
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import type { AnalyzeData } from '@/lib/analyze-data'
import { import {
computeTreemapLayoutFromAnalyze,
type LayoutNode, type LayoutNode,
type LayoutNodeInfo, type LayoutNodeInfo,
type TreemapSource,
SizeMode, SizeMode,
} from '@/lib/treemap-layout' } from '@/lib/treemap-layout'
import { SpecialModule } from '@/lib/types' import { SpecialModule } from '@/lib/types'
...@@ -16,8 +15,7 @@ import { formatBytes } from '@/lib/utils' ...@@ -16,8 +15,7 @@ import { formatBytes } from '@/lib/utils'
const UI_FONT = 'system-ui, sans-serif' const UI_FONT = 'system-ui, sans-serif'
interface TreemapVisualizerProps { interface TreemapVisualizerProps {
analyzeData: AnalyzeData source: TreemapSource
sourceIndex: number
selectedSourceIndex?: number selectedSourceIndex?: number
onSelectSourceIndex?: (index: number) => void onSelectSourceIndex?: (index: number) => void
focusedSourceIndex?: number focusedSourceIndex?: number
...@@ -45,7 +43,7 @@ interface TreemapVisualizerProps { ...@@ -45,7 +43,7 @@ interface TreemapVisualizerProps {
getFileSizeLabel?: (node: LayoutNode) => string | undefined getFileSizeLabel?: (node: LayoutNode) => string | undefined
/** /**
* Optional overlay rendered on top of the treemap canvas. Used by the * Optional overlay rendered on top of the treemap canvas. Used by the
* compare view to render a red/green legend. * compare view to render a blue/amber delta legend.
*/ */
overlay?: React.ReactNode overlay?: React.ReactNode
} }
...@@ -652,7 +650,7 @@ function drawTreemap( ...@@ -652,7 +650,7 @@ function drawTreemap(
function wrapLayoutWithAncestorsUsingIndices( function wrapLayoutWithAncestorsUsingIndices(
focusedLayout: LayoutNode, focusedLayout: LayoutNode,
focusedAncestorChain: number[], focusedAncestorChain: number[],
analyzeData: AnalyzeData, getSourceName: (sourceIndex: number) => string,
fullWidth: number, fullWidth: number,
fullHeight: number, fullHeight: number,
minTitleBarHeight = 12 minTitleBarHeight = 12
...@@ -668,16 +666,13 @@ function wrapLayoutWithAncestorsUsingIndices( ...@@ -668,16 +666,13 @@ function wrapLayoutWithAncestorsUsingIndices(
// Work backwards from the parent of focused node to the child of root // Work backwards from the parent of focused node to the child of root
for (let i = focusedAncestorChain.length - 2; i >= 1; i--) { for (let i = focusedAncestorChain.length - 2; i >= 1; i--) {
const ancestorIndex = focusedAncestorChain[i] const ancestorIndex = focusedAncestorChain[i]
const ancestorSource = analyzeData.source(ancestorIndex)
if (!ancestorSource) continue
const titleBarHeight = minTitleBarHeight const titleBarHeight = minTitleBarHeight
// This ancestor starts at cumulativeY - titleBarHeight // This ancestor starts at cumulativeY - titleBarHeight
cumulativeY -= titleBarHeight cumulativeY -= titleBarHeight
const ancestorNode: LayoutNode = { const ancestorNode: LayoutNode = {
name: ancestorSource.path, name: getSourceName(ancestorIndex),
type: 'directory', type: 'directory',
size: currentNode.size, size: currentNode.size,
rect: { rect: {
...@@ -698,10 +693,8 @@ function wrapLayoutWithAncestorsUsingIndices( ...@@ -698,10 +693,8 @@ function wrapLayoutWithAncestorsUsingIndices(
cumulativeY -= minTitleBarHeight cumulativeY -= minTitleBarHeight
const rootIndex = focusedAncestorChain[0] const rootIndex = focusedAncestorChain[0]
const rootSource = analyzeData.source(rootIndex)
const rootNode: LayoutNode = { const rootNode: LayoutNode = {
name: rootSource?.path || '', name: getSourceName(rootIndex),
type: 'directory', type: 'directory',
size: currentNode.size, size: currentNode.size,
rect: { rect: {
...@@ -719,12 +712,24 @@ function wrapLayoutWithAncestorsUsingIndices( ...@@ -719,12 +712,24 @@ function wrapLayoutWithAncestorsUsingIndices(
return rootNode return rootNode
} }
function getAncestorChain(
source: TreemapSource,
sourceIndex: number
): number[] {
const chain: number[] = []
let currentIndex: number | null = sourceIndex
while (currentIndex !== null) {
chain.unshift(currentIndex)
currentIndex = source.getParentSourceIndex(currentIndex)
}
return chain
}
export function TreemapVisualizer({ export function TreemapVisualizer({
analyzeData, source,
sourceIndex, selectedSourceIndex: selectedSourceIndexProp,
selectedSourceIndex = sourceIndex,
onSelectSourceIndex = () => {}, onSelectSourceIndex = () => {},
focusedSourceIndex = sourceIndex, focusedSourceIndex: focusedSourceIndexProp,
onFocusSourceIndex = () => {}, onFocusSourceIndex = () => {},
isMouseInTreemap = false, isMouseInTreemap = false,
onHoveredNodeChange, onHoveredNodeChange,
...@@ -736,6 +741,8 @@ export function TreemapVisualizer({ ...@@ -736,6 +741,8 @@ export function TreemapVisualizer({
getFileSizeLabel, getFileSizeLabel,
overlay, overlay,
}: TreemapVisualizerProps) { }: TreemapVisualizerProps) {
const selectedSourceIndex = selectedSourceIndexProp ?? source.rootIndex
const focusedSourceIndex = focusedSourceIndexProp ?? source.rootIndex
const canvasRef = useRef<HTMLCanvasElement>(null) const canvasRef = useRef<HTMLCanvasElement>(null)
const containerRef = useRef<HTMLDivElement>(null) const containerRef = useRef<HTMLDivElement>(null)
const [hoveredNode, setHoveredNode] = useState<LayoutNode | null>(null) const [hoveredNode, setHoveredNode] = useState<LayoutNode | null>(null)
...@@ -756,59 +763,17 @@ export function TreemapVisualizer({ ...@@ -756,59 +763,17 @@ export function TreemapVisualizer({
}) })
const [, _setTheme] = useState<'light' | 'dark'>('light') const [, _setTheme] = useState<'light' | 'dark'>('light')
// React Compiler caches the selected and hovered chains below, but the // The focused chain needs a manual memo: without it the compiler misses
// focused chain needs a manual memo to keep the expensive layout and canvas // the expensive layout and redraws the canvas on unrelated renders.
// draw effect stable across unrelated renders. const focusedAncestorChain = useMemo(
const focusedAncestorChain = useMemo(() => { () => getAncestorChain(source, focusedSourceIndex),
const chain: number[] = [] [source, focusedSourceIndex]
let currentIndex = focusedSourceIndex )
const selectedAncestorChain = getAncestorChain(source, selectedSourceIndex)
while (currentIndex !== undefined && currentIndex !== null) { const hoveredAncestorChain =
chain.unshift(currentIndex) shouldDimOthers && hoveredNode?.sourceIndex !== undefined
const source = analyzeData.source(currentIndex) ? getAncestorChain(source, hoveredNode.sourceIndex)
if (!source || source.parent_source_index === null) break : null
currentIndex = source.parent_source_index
}
return chain
}, [analyzeData, focusedSourceIndex])
// Build ancestor chain for selected source
const selectedAncestorChain = (() => {
const chain: number[] = []
let currentIndex = selectedSourceIndex
while (currentIndex !== undefined && currentIndex !== null) {
chain.unshift(currentIndex)
const source = analyzeData.source(currentIndex)
if (!source || source.parent_source_index === null) break
currentIndex = source.parent_source_index
}
return chain
})()
// Build ancestor chain for hovered node (only used for dimming)
const hoveredAncestorChain = (() => {
if (
!shouldDimOthers ||
!hoveredNode ||
hoveredNode.sourceIndex === undefined
)
return null
const chain: number[] = []
let currentIndex = hoveredNode.sourceIndex
while (currentIndex !== undefined && currentIndex !== null) {
chain.unshift(currentIndex)
const source = analyzeData.source(currentIndex)
if (!source || source.parent_source_index === null) break
currentIndex = source.parent_source_index
}
return chain
})()
useEffect(() => { useEffect(() => {
const container = containerRef.current const container = containerRef.current
...@@ -861,28 +826,27 @@ export function TreemapVisualizer({ ...@@ -861,28 +826,27 @@ export function TreemapVisualizer({
} }
}, []) }, [])
// Layout walks the entire focused subtree; hover and selection redraw it // Layout walks the focused subtree; hover and selection redraw it in the
// in the canvas effect below. // canvas effect below. A compare view supplies its own synthetic tree.
const focusedLayout = computeTreemapLayoutFromAnalyze( const layoutRect = {
analyzeData, x: 0,
y: 12 * focusedAncestorChain.length,
width: dimensions.cssWidth,
height: dimensions.cssHeight,
}
const focusedLayout = source.computeLayout(
focusedSourceIndex, focusedSourceIndex,
{ layoutRect,
x: 0,
y: 12 * focusedAncestorChain.length,
width: dimensions.cssWidth,
height: dimensions.cssHeight,
},
filterSource, filterSource,
sizeMode sizeMode
) )
// If we're not at the root, wrap with ancestor title bars
const layout = const layout =
focusedAncestorChain.length > 1 focusedAncestorChain.length > 1
? wrapLayoutWithAncestorsUsingIndices( ? wrapLayoutWithAncestorsUsingIndices(
focusedLayout, focusedLayout,
focusedAncestorChain, focusedAncestorChain,
analyzeData, source.getSourceName,
dimensions.cssWidth, dimensions.cssWidth,
dimensions.cssHeight, dimensions.cssHeight,
12 12
...@@ -942,7 +906,7 @@ export function TreemapVisualizer({ ...@@ -942,7 +906,7 @@ export function TreemapVisualizer({
if (node && node.sourceIndex !== undefined) { if (node && node.sourceIndex !== undefined) {
// If this node is already, refocus the root node to undim others // If this node is already, refocus the root node to undim others
if (node.sourceIndex === selectedSourceIndex) { if (node.sourceIndex === selectedSourceIndex) {
onSelectSourceIndex(sourceIndex) onSelectSourceIndex(source.rootIndex)
} else { } else {
onSelectSourceIndex(node.sourceIndex) onSelectSourceIndex(node.sourceIndex)
} }
......
import type { SourceDiffRow } from './diff'
import { delta } from './diff'
import { layoutTreemap } from './layout-treemap'
import type { LayoutNode, LayoutRect, TreemapSource } from './treemap-layout'
interface DiffTreeNode {
index: number
name: string
parentIndex: number | null
size: number
row?: SourceDiffRow
children: DiffTreeNode[]
}
export interface DiffTreemapLayout extends TreemapSource {
rowBySourceIndex: Map<number, SourceDiffRow>
sourceIndexByKey: Map<string, number>
}
export function createDiffTreemapLayout(
rows: SourceDiffRow[],
useCompressed: boolean
): DiffTreemapLayout {
let nextIndex = 0
const root: DiffTreeNode = {
index: nextIndex++,
name: 'All Changed Modules',
parentIndex: null,
size: 0,
children: [],
}
const nodeByIndex = new Map<number, DiffTreeNode>([[root.index, root]])
const directoryByPath = new Map<string, DiffTreeNode>([['', root]])
const rowBySourceIndex = new Map<number, SourceDiffRow>()
const sourceIndexByKey = new Map<string, number>()
for (const row of rows) {
const change = delta(row, useCompressed)
if (change === 0) continue
const parts = isNextBuildOutput(row.key)
? ['Unattributed output', getBasename(row.key)]
: row.key.split('/').filter(Boolean)
let parent = root
let directoryPath = ''
for (const part of parts.slice(0, -1)) {
directoryPath += `/${part}`
let directory = directoryByPath.get(directoryPath)
if (!directory) {
directory = {
index: nextIndex++,
name: `${part}/`,
parentIndex: parent.index,
size: 0,
children: [],
}
parent.children.push(directory)
directoryByPath.set(directoryPath, directory)
nodeByIndex.set(directory.index, directory)
}
parent = directory
}
const leaf: DiffTreeNode = {
index: nextIndex++,
name: parts.at(-1) ?? row.name,
parentIndex: parent.index,
size: Math.abs(change),
row,
children: [],
}
parent.children.push(leaf)
nodeByIndex.set(leaf.index, leaf)
rowBySourceIndex.set(leaf.index, row)
sourceIndexByKey.set(row.key, leaf.index)
}
function aggregateSize(node: DiffTreeNode): number {
if (node.row) return node.size
node.size = node.children.reduce(
(total, child) => total + aggregateSize(child),
0
)
return node.size
}
aggregateSize(root)
function computeLayout(node: DiffTreeNode, rect: LayoutRect): LayoutNode {
if (node.row) {
return {
name: node.name,
size: node.size,
type: 'file',
rect,
sourceIndex: node.index,
specialModuleType: null,
client: node.row.client,
server: node.row.server,
}
}
const titleBarHeight = Math.round(
Math.max(12, Math.min(24, rect.height * 0.1))
)
const isCollapsed = rect.height < 30
if (isCollapsed) {
return {
name: node.name,
size: node.size,
type: 'collapsed-directory',
rect,
titleBarHeight,
children: [],
itemCount: countLeaves(node),
sourceIndex: node.index,
specialModuleType: null,
}
}
const contentRect: LayoutRect = {
x: Math.round(rect.x),
y: Math.round(rect.y + titleBarHeight),
width: Math.max(0, Math.round(rect.width - 2)),
height: Math.max(0, Math.round(rect.height - titleBarHeight - 2)),
}
const children = [...node.children].sort((a, b) => b.size - a.size)
const childRects = layoutTreemap(
children.map((child) => child.size),
contentRect
)
return {
name: node.name,
size: node.size,
type: 'directory',
rect,
titleBarHeight,
children: children.map((child, index) =>
computeLayout(child, childRects[index])
),
sourceIndex: node.index,
specialModuleType: null,
}
}
return {
rootIndex: root.index,
rowBySourceIndex,
sourceIndexByKey,
getParentSourceIndex(sourceIndex) {
return nodeByIndex.get(sourceIndex)?.parentIndex ?? null
},
getSourceName(sourceIndex) {
return nodeByIndex.get(sourceIndex)?.name ?? ''
},
computeLayout(sourceIndex, rect) {
return computeLayout(nodeByIndex.get(sourceIndex) ?? root, rect)
},
}
}
function countLeaves(node: DiffTreeNode): number {
if (node.row) return 1
return node.children.reduce((total, child) => total + countLeaves(child), 0)
}
function isNextBuildOutput(sourcePath: string): boolean {
return sourcePath.startsWith('[project]/.next/')
}
function getBasename(sourcePath: string): string {
return sourcePath.slice(sourcePath.lastIndexOf('/') + 1)
}
...@@ -44,6 +44,42 @@ export enum SizeMode { ...@@ -44,6 +44,42 @@ export enum SizeMode {
Uncompressed = 'uncompressed', Uncompressed = 'uncompressed',
} }
/** One tree source for the canvas, whether it represents a build or a diff. */
export interface TreemapSource {
rootIndex: SourceIndex
getParentSourceIndex(sourceIndex: SourceIndex): SourceIndex | null
getSourceName(sourceIndex: SourceIndex): string
computeLayout(
sourceIndex: SourceIndex,
rect: LayoutRect,
filterSource: ((sourceIndex: SourceIndex) => boolean) | undefined,
sizeMode: SizeMode
): LayoutNode
}
export function createAnalyzeTreemapSource(
analyzeData: AnalyzeData
): TreemapSource {
return {
rootIndex: analyzeData.sourceRoots()[0] ?? 0,
getParentSourceIndex(sourceIndex) {
return analyzeData.source(sourceIndex)?.parent_source_index ?? null
},
getSourceName(sourceIndex) {
return analyzeData.source(sourceIndex)?.path ?? ''
},
computeLayout(sourceIndex, rect, filterSource, sizeMode) {
return computeTreemapLayoutFromAnalyze(
analyzeData,
sourceIndex,
rect,
filterSource,
sizeMode
)
},
}
}
function precomputeSourceMetadata( function precomputeSourceMetadata(
analyzeData: AnalyzeData, analyzeData: AnalyzeData,
filterSource?: (sourceIndex: SourceIndex) => boolean filterSource?: (sourceIndex: SourceIndex) => boolean
......
...@@ -23,9 +23,7 @@ export function useAnalyzerRoute( ...@@ -23,9 +23,7 @@ export function useAnalyzerRoute(
const compareView = const compareView =
viewParam === CompareView.Table || viewParam === CompareView.Treemap viewParam === CompareView.Table || viewParam === CompareView.Treemap
? viewParam ? viewParam
: compare : CompareView.Treemap
? CompareView.Table
: CompareView.Treemap
const environmentParam = searchParams.get('environment') const environmentParam = searchParams.get('environment')
const environmentFilter = const environmentFilter =
environmentParam === Environment.Server environmentParam === Environment.Server
...@@ -88,14 +86,10 @@ export function useAnalyzerRoute( ...@@ -88,14 +86,10 @@ export function useAnalyzerRoute(
pathname === '/compare' pathname === '/compare'
? undefined ? undefined
: (snapshot: SnapshotMetadata) => : (snapshot: SnapshotMetadata) =>
buildHref('/compare', { from: snapshot.id, to: null, view: null }), buildHref('/compare', { from: snapshot.id, to: null }),
setBaselineSnapshot: (snapshot: SnapshotMetadata) => setBaselineSnapshot: (snapshot: SnapshotMetadata) =>
navigate('/compare', { from: snapshot.id, to: null, view: null }, 'push'), navigate('/compare', { from: snapshot.id, to: null }, 'push'),
stopComparisonHref: buildHref('/analyze', { stopComparisonHref: buildHref('/analyze', { from: null, to: null }),
from: null,
to: null,
view: null,
}),
setComparisonSnapshot: (snapshot: SnapshotMetadata | null) => setComparisonSnapshot: (snapshot: SnapshotMetadata | null) =>
navigate(pathname, { to: snapshot?.id ?? null }, 'replace'), navigate(pathname, { to: snapshot?.id ?? null }, 'replace'),
setEnvironmentFilter: (environment: Environment) => setEnvironmentFilter: (environment: 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