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'
import { computeActiveEntries, computeModuleDepthMap } from '@/lib/module-graph'
import type { SnapshotMetadata } from '@/lib/snapshot'
import { formatBytes } from '@/lib/utils'
import { SizeMode } from '@/lib/treemap-layout'
import { createAnalyzeTreemapSource, SizeMode } from '@/lib/treemap-layout'
export function SingleAnalyzer() {
return (
......@@ -57,7 +57,7 @@ function SingleAnalyzerController() {
export function CompareAnalyzer() {
return (
<AnalyzerBoundary defaultView={CompareView.Table}>
<AnalyzerBoundary defaultView={CompareView.Treemap}>
<CompareAnalyzerController />
</AnalyzerBoundary>
)
......@@ -89,6 +89,7 @@ function AnalyzerFallback({ view }: { view: CompareView }) {
}
function useAnalyzerModel(compare: boolean) {
const [routePickerOpen, setRoutePickerOpen] = useState(false)
const [selectedSourceIndex, setSelectedSourceIndex] = useState<number | null>(
null
)
......@@ -293,6 +294,8 @@ function useAnalyzerModel(compare: boolean) {
compareView: activeView,
comparisonSnapshot,
currentRoutes,
routePickerOpen,
setRoutePickerOpen,
environmentFilter,
filterSource,
focusedSourceIndex,
......@@ -362,6 +365,8 @@ function AnalyzerTopBar({
compareView={model.compareView}
onCompareViewChange={model.setCompareView}
selectedRoute={model.selectedRoute}
routePickerOpen={model.routePickerOpen}
onRoutePickerOpenChange={model.setRoutePickerOpen}
getRouteHref={model.routeState.getRouteHref}
setSelectedRoute={model.routeState.setRoute}
environmentFilter={model.environmentFilter}
......@@ -591,6 +596,7 @@ function ComparisonContent({
isViewPending: model.isViewPending,
selectedKey: model.compareSelectedKey,
onSelectedKeyChange: model.setCompareSelectedKey,
onOpenRoutePicker: () => model.setRoutePickerOpen(true),
}
return (
......@@ -627,7 +633,8 @@ function SingleAnalyzerContent({
model: AnalyzerModel
analyzeData: AnalyzeData
}) {
const rootSourceIndex = getRootSourceIndex(analyzeData)
const source = createAnalyzeTreemapSource(analyzeData)
const rootSourceIndex = source.rootIndex
const hasAlternateEnvironmentSources = hasEnvironmentSources(
analyzeData,
getAlternateEnvironment(model.environmentFilter),
......@@ -665,8 +672,7 @@ function SingleAnalyzerContent({
</div>
) : (
<TreemapVisualizer
analyzeData={analyzeData}
sourceIndex={rootSourceIndex}
source={source}
selectedSourceIndex={model.selectedSourceIndex ?? rootSourceIndex}
onSelectSourceIndex={model.setSelectedSourceIndex}
focusedSourceIndex={model.focusedSourceIndex ?? rootSourceIndex}
......
'use client'
import { ArrowRight, CircleCheck, Route } from 'lucide-react'
import Link from 'next/link'
import type { MouseEventHandler } from 'react'
import { CompareSidebar } from '@/components/sidebar'
import { DiffTable } from '@/components/diff-table'
......@@ -7,6 +9,7 @@ import { DiffTreemap } from '@/components/diff-treemap'
import { StatCard, CountCard } from '@/components/stat-cards'
import { CompareView, Environment } from '@/components/top-bar'
import { AlternateEnvironmentEmptyState } from '@/components/analyzer'
import { Button } from '@/components/ui/button'
import { TableSkeleton, TreemapSkeleton } from '@/components/ui/skeleton'
import { AnalyzeData, ModulesData } from '@/lib/analyze-data'
import {
......@@ -45,6 +48,7 @@ export interface CompareLayoutModel {
searchQuery: string
selectedKey: string | null
onSelectedKeyChange: (key: string | null) => void
onOpenRoutePicker: () => void
}
/**
......@@ -92,6 +96,7 @@ export function CompareLayout({ model, onResizeSidebar }: CompareLayoutProps) {
comparisonSnapshot={model.comparisonSnapshot}
compareSelectedKey={model.selectedKey}
onCompareSelectedKeyChange={model.onSelectedKeyChange}
onOpenRoutePicker={model.onOpenRoutePicker}
/>
</div>
<button
......@@ -347,6 +352,7 @@ export function ComparePerRoutePanel({
comparisonSnapshot,
compareSelectedKey,
onCompareSelectedKeyChange,
onOpenRoutePicker,
}: {
compareView: CompareView
isViewPending: boolean
......@@ -362,6 +368,7 @@ export function ComparePerRoutePanel({
comparisonSnapshot: SnapshotMetadata | null
compareSelectedKey: string | null
onCompareSelectedKeyChange: (key: string | null) => void
onOpenRoutePicker: () => void
}) {
if (!selectedRoute) {
return (
......@@ -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 (
<div className="flex flex-1 min-h-0 flex-col">
{compareView === CompareView.Treemap &&
......@@ -408,6 +430,7 @@ export function ComparePerRoutePanel({
useCompressed={compressed}
analyzeData={analyzeData}
baselineAnalyzeData={baselineAnalyzeData}
searchQuery={searchQuery}
selectedKey={compareSelectedKey}
onSelectKey={onCompareSelectedKeyChange}
/>
......@@ -435,3 +458,42 @@ export function ComparePerRoutePanel({
</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'
import { useState } from 'react'
import { useMemo, useState } from 'react'
import type { AnalyzeData } from '@/lib/analyze-data'
import type { DiffSummary, SourceDiffRow } 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 { 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. */
const COLOR_INCREASE = '#2563eb' // blue-600
const COLOR_INCREASE_MUTED = 'rgba(37, 99, 235, 0.6)'
const COLOR_DECREASE = '#d97706' // amber-600
const COLOR_DECREASE_MUTED = 'rgba(217, 119, 6, 0.6)'
const COLOR_NEUTRAL = '#9ca3af' // gray-400
interface DiffTreemapProps {
summary: DiffSummary<SourceDiffRow>
useCompressed: boolean
/**
* Analyze data for comparison side B. Used as the source-of-truth tree
* when present.
*/
/** Comparison-side data; the synthetic diff tree drives tile layout. */
analyzeData: AnalyzeData | null
/**
* 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.
*/
/** Baseline data used when the route was removed (no comparison data). */
baselineAnalyzeData: AnalyzeData | null
searchQuery: string
/**
* Currently selected diff row (its `key`). Used so the compare sidebar
* and treemap stay in sync when the user clicks elsewhere.
......@@ -57,57 +44,37 @@ interface DiffTreemapProps {
* - bright amber: removed from the comparison build
* - blue tint: same file, grew 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
* don't appear in the treemap; users can still see them in the table view.
* Tile area represents the absolute size delta. The tree is synthesized from
* the union of both builds, so additions and removals are both visible.
*/
export function DiffTreemap({
summary,
useCompressed,
analyzeData,
baselineAnalyzeData,
searchQuery,
selectedKey,
onSelectKey,
}: 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
// Index the diff rows by source index for tile lookups during canvas layout.
const rowBySourceIndex = new Map<number, SourceDiffRow>()
const side: 'A' | 'B' = analyzeData ? 'B' : 'A'
for (const row of summary.rows) {
const idx = side === 'B' ? row.sourceIndexB : row.sourceIndexA
if (idx != null) rowBySourceIndex.set(idx, row)
}
// 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)
}
// The React Compiler currently rebuilds this synthetic tree on every render.
// Keep it stable while hover and focus redraw the canvas.
const diffLayout = useMemo(
() => createDiffTreemapLayout(summary.rows, useCompressed),
[summary.rows, useCompressed]
)
const { rowBySourceIndex, sourceIndexByKey } = diffLayout
function getFileColorOverride(node: LayoutNode): string | undefined {
if (node.sourceIndex === undefined) return undefined
const row = rowBySourceIndex.get(node.sourceIndex)
if (!row) return COLOR_NEUTRAL
return colorForRow(row, useCompressed)
return row ? colorForRow(row, useCompressed) : undefined
}
// Show size deltas on tiles instead of absolute sizes. Identical files fall
// back to the default (absolute size) since ±0 on every unchanged tile
// would be noise.
// Show size deltas on changed tiles instead of absolute sizes.
function getFileSizeLabel(node: LayoutNode): string | undefined {
if (node.sourceIndex === undefined) return undefined
const row = rowBySourceIndex.get(node.sourceIndex)
......@@ -117,13 +84,12 @@ export function DiffTreemap({
// Focus state stays local: it controls drill-in/zoom, which is purely a
// visual concern of the treemap and shouldn't affect the sidebar.
const initialRoot = data?.sourceRoots()[0] ?? 0
const initialRoot = diffLayout.rootIndex
const [focusedSourceIndex, setFocusedSourceIndex] =
useState<number>(initialRoot)
// Translate the externally-driven selection key into the side's source
// index. Falls back to the root so the treemap renders something sensible
// when the selection lives on the other side (e.g., a removed file).
// Translate selection into the synthetic tree's index. If the selected
// path has no size delta, fall back to the root of changed files.
const selectedSourceIndex =
(selectedKey != null ? sourceIndexByKey.get(selectedKey) : undefined) ??
initialRoot
......@@ -144,26 +110,24 @@ export function DiffTreemap({
return (
<TreemapVisualizer
analyzeData={data}
sourceIndex={initialRoot}
source={diffLayout}
selectedSourceIndex={selectedSourceIndex}
onSelectSourceIndex={handleSelectSourceIndex}
focusedSourceIndex={focusedSourceIndex}
onFocusSourceIndex={setFocusedSourceIndex}
filterSource={(idx) => canonicalSourceIndices.has(idx)}
getFileSizeLabel={getFileSizeLabel}
sizeMode={useCompressed ? SizeMode.Compressed : SizeMode.Uncompressed}
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
* scheme: bright blue/amber for added/removed, lighter tints scaled by the
* relative magnitude of the change for grew/shrank, and neutral grey for
* sub-threshold changes.
* scheme: bright blue/amber for added/removed and lighter tints scaled by the
* relative magnitude of the change for grew/shrank.
*/
function colorForRow(row: SourceDiffRow, useCompressed: boolean): string {
if (row.status === 'added') return COLOR_INCREASE
......@@ -171,9 +135,6 @@ function colorForRow(row: SourceDiffRow, useCompressed: boolean): string {
const deltaValue = useCompressed
? row.compressedB - row.compressedA
: 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
// less alarming than a 50% change.
const baseline = useCompressed ? row.compressedA : row.sizeA
......@@ -186,12 +147,12 @@ function colorForRow(row: SourceDiffRow, useCompressed: boolean): string {
}
/** 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 }> = [
{ label: 'Added', color: COLOR_INCREASE },
{ label: 'Grew', color: COLOR_INCREASE_MUTED },
{ label: 'Unchanged', color: COLOR_NEUTRAL },
{ label: 'Shrank', color: COLOR_DECREASE_MUTED },
{ label: 'Removed', color: COLOR_DECREASE },
]
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">
......@@ -205,11 +166,6 @@ function DiffLegend({ hasRemoved }: { hasRemoved: boolean }) {
{item.label}
</span>
))}
{hasRemoved ? (
<span className="border-l border-border pl-3 italic">
Removed sources are listed in the table view.
</span>
) : null}
</div>
)
}
......@@ -60,6 +60,8 @@ export function ControlDivider() {
export function TopBar({
selectedRoute,
routePickerOpen,
onRoutePickerOpenChange,
setSelectedRoute,
getRouteHref,
environmentFilter,
......@@ -86,6 +88,8 @@ export function TopBar({
hasSourceData: boolean
showViewToggle: boolean
selectedRoute: string | null
routePickerOpen: boolean
onRoutePickerOpenChange: (open: boolean) => void
setSelectedRoute: (route: string | null) => void
getRouteHref?: (route: string) => string
environmentFilter: Environment
......@@ -136,6 +140,8 @@ export function TopBar({
<div className="flex min-w-0 flex-1">
<RouteTypeahead
selectedRoute={selectedRoute}
open={routePickerOpen}
onOpenChange={onRoutePickerOpenChange}
{...routeSelection}
routeDiff={isCompareMode ? routeDiff : null}
routeTotals={routeTotals}
......@@ -233,12 +239,8 @@ export function TopBar({
aria-label="Filter by file type"
/>
{!isCompareMode && (
<>
<ControlDivider />
<FileSearch value={searchQuery} onChange={setSearchQuery} />
</>
)}
<ControlDivider />
<FileSearch value={searchQuery} onChange={setSearchQuery} />
</>
)}
</div>
......
......@@ -3,11 +3,10 @@
import { darken, lighten, readableColor } from 'polished'
import type React from 'react'
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import type { AnalyzeData } from '@/lib/analyze-data'
import {
computeTreemapLayoutFromAnalyze,
type LayoutNode,
type LayoutNodeInfo,
type TreemapSource,
SizeMode,
} from '@/lib/treemap-layout'
import { SpecialModule } from '@/lib/types'
......@@ -16,8 +15,7 @@ import { formatBytes } from '@/lib/utils'
const UI_FONT = 'system-ui, sans-serif'
interface TreemapVisualizerProps {
analyzeData: AnalyzeData
sourceIndex: number
source: TreemapSource
selectedSourceIndex?: number
onSelectSourceIndex?: (index: number) => void
focusedSourceIndex?: number
......@@ -45,7 +43,7 @@ interface TreemapVisualizerProps {
getFileSizeLabel?: (node: LayoutNode) => string | undefined
/**
* 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
}
......@@ -652,7 +650,7 @@ function drawTreemap(
function wrapLayoutWithAncestorsUsingIndices(
focusedLayout: LayoutNode,
focusedAncestorChain: number[],
analyzeData: AnalyzeData,
getSourceName: (sourceIndex: number) => string,
fullWidth: number,
fullHeight: number,
minTitleBarHeight = 12
......@@ -668,16 +666,13 @@ function wrapLayoutWithAncestorsUsingIndices(
// Work backwards from the parent of focused node to the child of root
for (let i = focusedAncestorChain.length - 2; i >= 1; i--) {
const ancestorIndex = focusedAncestorChain[i]
const ancestorSource = analyzeData.source(ancestorIndex)
if (!ancestorSource) continue
const titleBarHeight = minTitleBarHeight
// This ancestor starts at cumulativeY - titleBarHeight
cumulativeY -= titleBarHeight
const ancestorNode: LayoutNode = {
name: ancestorSource.path,
name: getSourceName(ancestorIndex),
type: 'directory',
size: currentNode.size,
rect: {
......@@ -698,10 +693,8 @@ function wrapLayoutWithAncestorsUsingIndices(
cumulativeY -= minTitleBarHeight
const rootIndex = focusedAncestorChain[0]
const rootSource = analyzeData.source(rootIndex)
const rootNode: LayoutNode = {
name: rootSource?.path || '',
name: getSourceName(rootIndex),
type: 'directory',
size: currentNode.size,
rect: {
......@@ -719,12 +712,24 @@ function wrapLayoutWithAncestorsUsingIndices(
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({
analyzeData,
sourceIndex,
selectedSourceIndex = sourceIndex,
source,
selectedSourceIndex: selectedSourceIndexProp,
onSelectSourceIndex = () => {},
focusedSourceIndex = sourceIndex,
focusedSourceIndex: focusedSourceIndexProp,
onFocusSourceIndex = () => {},
isMouseInTreemap = false,
onHoveredNodeChange,
......@@ -736,6 +741,8 @@ export function TreemapVisualizer({
getFileSizeLabel,
overlay,
}: TreemapVisualizerProps) {
const selectedSourceIndex = selectedSourceIndexProp ?? source.rootIndex
const focusedSourceIndex = focusedSourceIndexProp ?? source.rootIndex
const canvasRef = useRef<HTMLCanvasElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
const [hoveredNode, setHoveredNode] = useState<LayoutNode | null>(null)
......@@ -756,59 +763,17 @@ export function TreemapVisualizer({
})
const [, _setTheme] = useState<'light' | 'dark'>('light')
// React Compiler caches the selected and hovered chains below, but the
// focused chain needs a manual memo to keep the expensive layout and canvas
// draw effect stable across unrelated renders.
const focusedAncestorChain = useMemo(() => {
const chain: number[] = []
let currentIndex = focusedSourceIndex
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
}, [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
})()
// The focused chain needs a manual memo: without it the compiler misses
// the expensive layout and redraws the canvas on unrelated renders.
const focusedAncestorChain = useMemo(
() => getAncestorChain(source, focusedSourceIndex),
[source, focusedSourceIndex]
)
const selectedAncestorChain = getAncestorChain(source, selectedSourceIndex)
const hoveredAncestorChain =
shouldDimOthers && hoveredNode?.sourceIndex !== undefined
? getAncestorChain(source, hoveredNode.sourceIndex)
: null
useEffect(() => {
const container = containerRef.current
......@@ -861,28 +826,27 @@ export function TreemapVisualizer({
}
}, [])
// Layout walks the entire focused subtree; hover and selection redraw it
// in the canvas effect below.
const focusedLayout = computeTreemapLayoutFromAnalyze(
analyzeData,
// Layout walks the focused subtree; hover and selection redraw it in the
// canvas effect below. A compare view supplies its own synthetic tree.
const layoutRect = {
x: 0,
y: 12 * focusedAncestorChain.length,
width: dimensions.cssWidth,
height: dimensions.cssHeight,
}
const focusedLayout = source.computeLayout(
focusedSourceIndex,
{
x: 0,
y: 12 * focusedAncestorChain.length,
width: dimensions.cssWidth,
height: dimensions.cssHeight,
},
layoutRect,
filterSource,
sizeMode
)
// If we're not at the root, wrap with ancestor title bars
const layout =
focusedAncestorChain.length > 1
? wrapLayoutWithAncestorsUsingIndices(
focusedLayout,
focusedAncestorChain,
analyzeData,
source.getSourceName,
dimensions.cssWidth,
dimensions.cssHeight,
12
......@@ -942,7 +906,7 @@ export function TreemapVisualizer({
if (node && node.sourceIndex !== undefined) {
// If this node is already, refocus the root node to undim others
if (node.sourceIndex === selectedSourceIndex) {
onSelectSourceIndex(sourceIndex)
onSelectSourceIndex(source.rootIndex)
} else {
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 {
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(
analyzeData: AnalyzeData,
filterSource?: (sourceIndex: SourceIndex) => boolean
......
......@@ -23,9 +23,7 @@ export function useAnalyzerRoute(
const compareView =
viewParam === CompareView.Table || viewParam === CompareView.Treemap
? viewParam
: compare
? CompareView.Table
: CompareView.Treemap
: CompareView.Treemap
const environmentParam = searchParams.get('environment')
const environmentFilter =
environmentParam === Environment.Server
......@@ -88,14 +86,10 @@ export function useAnalyzerRoute(
pathname === '/compare'
? undefined
: (snapshot: SnapshotMetadata) =>
buildHref('/compare', { from: snapshot.id, to: null, view: null }),
buildHref('/compare', { from: snapshot.id, to: null }),
setBaselineSnapshot: (snapshot: SnapshotMetadata) =>
navigate('/compare', { from: snapshot.id, to: null, view: null }, 'push'),
stopComparisonHref: buildHref('/analyze', {
from: null,
to: null,
view: null,
}),
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'),
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