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

bundle-analyzer: use Rust React compiler (#98695)

## Summary

Enable the Rust React compiler when building the bundle analyzer UI.
Update its pinned Next.js version to one that supports the compiler
option.

## Verification

- `pnpm --filter @next/bundle-analyzer-ui build`

<!-- 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 8c1f5501
# Bundle analyzer UI
This app enables the Rust React Compiler (`reactCompiler` and `turbopackRustReactCompiler` in `next.config.mjs`). When adding or reviewing UI code:
- Prefer plain derived values and functions over `useMemo`, `useCallback`, or `memo` used only to cache renders or stabilize props; the compiler handles ordinary memoization. Review new instances in every bundle-analyzer change.
- Even expensive pure calculations generally need no manual memo in a component the compiler optimizes. Before keeping one, check compiled output: keep it if the compiler skips that component, if an imperative API needs stable identity, or if measurements show the compiler misses a costly path. Explain the exception in the code.
- Keep **correct dependencies** for effects, subscriptions, and imperative hooks. Do not remove an effect dependency array just to eliminate memoization; dependencies describe behavior, not merely an optimization.
- Verify affected code with the app's typecheck and a production build (`pnpm --filter=@next/bundle-analyzer-ui exec tsc --noEmit` and `pnpm --filter=@next/bundle-analyzer-ui build`) so the compiler actually runs.
......@@ -245,7 +245,8 @@ function useAnalyzerModel(compare: boolean) {
return () => window.removeEventListener('keydown', handleKeyDown)
}, [analyzeData])
// Compute module depth map from active entries
// React Compiler currently skips this hook. Keep the graph traversal cached
// across selection and filter updates until that bailout is resolved.
const moduleDepthMap = useMemo(() => {
if (!analyzeData) return new Map()
......@@ -253,6 +254,8 @@ function useAnalyzerModel(compare: boolean) {
return computeModuleDepthMap(modulesData, activeEntries)
}, [modulesData, analyzeData])
// This hook isn't compiled; stable predicate identity keeps the source diff
// and treemap layout below cached.
const filterSource = useMemo(() => {
if (!analyzeData) return () => true
......@@ -279,7 +282,8 @@ function useAnalyzerModel(compare: boolean) {
// of every source for the current route. We synthesize this by diffing
// the build against itself, which produces an all-`identical` summary
// that we feed into `<DiffTable mode="single">`. This keeps a single
// sources-listing implementation regardless of mode.
// sources-listing implementation regardless of mode. Diffing walks every
// source, so keep this cached while this hook isn't compiled.
const singleSourceListing = useMemo(() => {
if (!analyzeData || baselineSnapshot) return null
return diffSources(analyzeData, analyzeData, {
......@@ -444,20 +448,14 @@ function ValidComparisonContent({
baselineRoutes,
baselineBaseDir
)
const routeDiff = useMemo(() => {
if (!model.currentRouteTotals) return null
return diffRoutesWithSizes(
baselineRoutes,
model.currentRoutes,
baselineRouteTotals,
model.currentRouteTotals
)
}, [
baselineRoutes,
model.currentRoutes,
baselineRouteTotals,
model.currentRouteTotals,
])
const routeDiff = model.currentRouteTotals
? diffRoutesWithSizes(
baselineRoutes,
model.currentRoutes,
baselineRouteTotals,
model.currentRouteTotals
)
: null
const layoutProps = {
baselineSnapshot,
comparisonSnapshot: model.comparisonSnapshot,
......@@ -538,55 +536,43 @@ function ComparisonContent({
baselineAnalyzeData: AnalyzeData | null
layoutProps: ComparisonLayoutProps
}) {
const baselineModuleDepthMap = useMemo(() => {
if (!baselineAnalyzeData) return new Map()
const activeEntries = computeActiveEntries(
layoutProps.baselineModulesData,
baselineAnalyzeData
)
return computeModuleDepthMap(layoutProps.baselineModulesData, activeEntries)
}, [layoutProps.baselineModulesData, baselineAnalyzeData])
const compareFilterSource = useMemo(() => {
return (side: 'A' | 'B', sourceIndex: number): boolean => {
const data = side === 'A' ? baselineAnalyzeData : model.analyzeData
if (!data) return false
const flags = data.getSourceFlags(sourceIndex)
const hasEnvironment =
(model.environmentFilter === Environment.Client && flags.client) ||
(model.environmentFilter === Environment.Server && flags.server)
const hasType =
(model.typeFilter.includes('js') && flags.js) ||
(model.typeFilter.includes('css') && flags.css) ||
(model.typeFilter.includes('json') && flags.json) ||
(model.typeFilter.includes('asset') && flags.asset)
return hasEnvironment && hasType
}
}, [
baselineAnalyzeData,
model.analyzeData,
model.environmentFilter,
model.typeFilter,
])
const sourceDiff = useMemo(() => {
if (!model.analyzeData && !baselineAnalyzeData) return null
return diffSources(baselineAnalyzeData, model.analyzeData ?? null, {
filterSource: compareFilterSource,
})
}, [model.analyzeData, baselineAnalyzeData, compareFilterSource])
const baselineModuleDepthMap = baselineAnalyzeData
? computeModuleDepthMap(
layoutProps.baselineModulesData,
computeActiveEntries(
layoutProps.baselineModulesData,
baselineAnalyzeData
)
)
: new Map<number, number>()
function compareFilterSource(side: 'A' | 'B', sourceIndex: number): boolean {
const data = side === 'A' ? baselineAnalyzeData : model.analyzeData
if (!data) return false
const flags = data.getSourceFlags(sourceIndex)
const hasEnvironment =
(model.environmentFilter === Environment.Client && flags.client) ||
(model.environmentFilter === Environment.Server && flags.server)
const hasType =
(model.typeFilter.includes('js') && flags.js) ||
(model.typeFilter.includes('css') && flags.css) ||
(model.typeFilter.includes('json') && flags.json) ||
(model.typeFilter.includes('asset') && flags.asset)
return hasEnvironment && hasType
}
const sourceDiff =
model.analyzeData || baselineAnalyzeData
? diffSources(baselineAnalyzeData, model.analyzeData ?? null, {
filterSource: compareFilterSource,
})
: null
const alternateEnvironment = getAlternateEnvironment(model.environmentFilter)
const hasAlternateEnvironmentSources = useMemo(
() =>
[model.analyzeData, baselineAnalyzeData].some(
(data) =>
data &&
hasEnvironmentSources(data, alternateEnvironment, model.typeFilter)
),
[
model.analyzeData,
baselineAnalyzeData,
alternateEnvironment,
model.typeFilter,
]
const hasAlternateEnvironmentSources = [
model.analyzeData,
baselineAnalyzeData,
].some(
(data) =>
data &&
hasEnvironmentSources(data, alternateEnvironment, model.typeFilter)
)
const compareModel: CompareLayoutModel = {
...layoutProps,
......
'use client'
import { useMemo, useState, type ComponentProps, type ReactNode } from 'react'
import { useState, type ComponentProps, type ReactNode } from 'react'
import { TableVirtuoso } from 'react-virtuoso'
import {
ArrowDown,
......@@ -142,9 +142,11 @@ export function DiffTable<Row extends DiffRow>({
})
}
const sorted = useMemo(
() => sortRows(summary.rows, sortColumn, sortDirection, useCompressed),
[summary.rows, sortColumn, sortDirection, useCompressed]
const sorted = sortRows(
summary.rows,
sortColumn,
sortDirection,
useCompressed
)
const onHeaderClick = (column: SortColumn) => {
......@@ -158,38 +160,34 @@ export function DiffTable<Row extends DiffRow>({
}
}
const filtered = useMemo(() => {
const q = searchQuery?.trim().toLowerCase() ?? ''
return sorted.filter((row) => {
if (!isSingle && statusFilter !== 'all') {
if (statusFilter === 'changes' && row.status === 'identical')
return false
if (statusFilter !== 'changes' && row.status !== statusFilter) {
return false
}
const q = searchQuery?.trim().toLowerCase() ?? ''
const filtered = sorted.filter((row) => {
if (!isSingle && statusFilter !== 'all') {
if (statusFilter === 'changes' && row.status === 'identical') return false
if (statusFilter !== 'changes' && row.status !== statusFilter) {
return false
}
if (q !== '') {
const key = row.key.toLowerCase()
const name = row.name.toLowerCase()
if (!key.includes(q) && !name.includes(q)) return false
}
return true
})
}, [sorted, isSingle, statusFilter, searchQuery])
}
if (q !== '') {
const key = row.key.toLowerCase()
const name = row.name.toLowerCase()
if (!key.includes(q) && !name.includes(q)) return false
}
return true
})
// Group filtered rows by package, preserving the user's chosen sort order.
// Groups themselves are sorted by their aggregate using the same column +
// direction so ranking is consistent whether you look at the package roll-up
// or its contents. Rows without a `packageName` (project-relative paths)
// render flat as before.
const renderItems = useMemo(
() => buildRenderItems(filtered, sortColumn, sortDirection, useCompressed),
[filtered, sortColumn, sortDirection, useCompressed]
)
const visibleItems = useMemo(
() => expandRenderItems(renderItems, expandedPackages),
[renderItems, expandedPackages]
const renderItems = buildRenderItems(
filtered,
sortColumn,
sortDirection,
useCompressed
)
const visibleItems = expandRenderItems(renderItems, expandedPackages)
const totalDelta = useCompressed
? summary.totalCompressedB - summary.totalCompressedA
......
'use client'
import { useMemo, useState } from 'react'
import { useState } from 'react'
import type { AnalyzeData } from '@/lib/analyze-data'
import type { DiffSummary, SourceDiffRow } from '@/lib/diff'
......@@ -75,17 +75,13 @@ export function DiffTreemap({
// B-side data.
const data = analyzeData ?? baselineAnalyzeData
// Map from this side's source index to its diff row. Used by the color
// override to look up the per-tile status.
const rowBySourceIndex = useMemo(() => {
const map = 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) map.set(idx, row)
}
return map
}, [summary, analyzeData])
// 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
......@@ -93,49 +89,35 @@ export function DiffTreemap({
// 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 = useMemo(
() => new Set(rowBySourceIndex.keys()),
[rowBySourceIndex]
)
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 = useMemo(() => {
const map = new Map<string, number>()
for (const [idx, row] of rowBySourceIndex.entries()) {
map.set(row.key, idx)
}
return map
}, [rowBySourceIndex])
const getFileColorOverride = useMemo(() => {
return (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)
}
}, [rowBySourceIndex, useCompressed])
const sourceIndexByKey = new Map<string, number>()
for (const [idx, row] of rowBySourceIndex) {
sourceIndexByKey.set(row.key, idx)
}
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)
}
// 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.
const getFileSizeLabel = useMemo(() => {
return (node: LayoutNode): string | undefined => {
if (node.sourceIndex === undefined) return undefined
const row = rowBySourceIndex.get(node.sourceIndex)
if (!row || row.status === 'identical') return undefined
return formatDelta(delta(row, useCompressed))
}
}, [rowBySourceIndex, useCompressed])
function getFileSizeLabel(node: LayoutNode): string | undefined {
if (node.sourceIndex === undefined) return undefined
const row = rowBySourceIndex.get(node.sourceIndex)
if (!row || row.status === 'identical') return undefined
return formatDelta(delta(row, useCompressed))
}
// 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 = useMemo(() => {
if (!data) return 0
const roots = data.sourceRoots()
return roots.length > 0 ? roots[0] : 0
}, [data])
const initialRoot = data?.sourceRoots()[0] ?? 0
const [focusedSourceIndex, setFocusedSourceIndex] =
useState<number>(initialRoot)
......
......@@ -13,7 +13,7 @@ import {
MessageCircleQuestion,
Package,
} from 'lucide-react'
import { useMemo, useState } from 'react'
import { useState } from 'react'
import type {
AnalyzeData,
ModuleIndex,
......@@ -321,26 +321,15 @@ export function ImportChain({
// Track which dependent is selected at each level
const [selectedIndices, setSelectedIndices] = useState<number[]>([])
// Build the import chain based on current selections
const chain = useMemo(() => {
return buildImportChain(
startFileId,
analyzeData,
modulesData,
depthMap,
environmentFilter,
selectedIndices,
currentRouteOnly
)
}, [
const chain = buildImportChain(
startFileId,
analyzeData,
modulesData,
selectedIndices,
currentRouteOnly,
depthMap,
environmentFilter,
])
selectedIndices,
currentRouteOnly
)
const handlePrevious = (levelIndex: number) => {
setSelectedIndices((prev) => {
......
'use client'
import { Check, ChevronsUpDown, Route } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'
import { useSuspenseJsonData } from '@/lib/analyzer-data'
import {
......@@ -87,23 +87,19 @@ export function RouteTypeahead({
// 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
// compare UI. Without a diff, fall back to the natural routes.json order.
const orderedItems = useMemo<RouteItem[]>(() => {
if (routeDiff) {
const sorted = sortByImpact(routeDiff.rows, useCompressed)
return sorted.map((row) => ({
const orderedItems: RouteItem[] = routeDiff
? sortByImpact(routeDiff.rows, useCompressed).map((row) => ({
name: row.key,
row,
}))
}
return routes.map((name) => ({ name, row: null }))
}, [routes, routeDiff, useCompressed])
: routes.map((name) => ({ name, row: null }))
// Find the currently selected route's diff row, used to render a delta
// badge in the trigger button.
const selectedRow = useMemo(() => {
if (!routeDiff || !selectedRoute) return null
return routeDiff.rows.find((r) => r.key === selectedRoute) ?? null
}, [routeDiff, selectedRoute])
const selectedRow =
routeDiff && selectedRoute
? (routeDiff.rows.find((row) => row.key === selectedRoute) ?? null)
: null
const ctaText = selectedRoute ?? 'Select route...'
......
'use client'
import type React from 'react'
import { useState, useMemo } from 'react'
import { useState } from 'react'
import { CircleHelp } from 'lucide-react'
import {
Tooltip,
......@@ -210,10 +210,10 @@ export function CompareSidebar({
aLabel: string
bLabel: string
}) {
const selectedRow = useMemo(() => {
if (!selectedKey || !sourceDiff) return null
return sourceDiff.rows.find((r) => r.key === selectedKey) ?? null
}, [selectedKey, sourceDiff])
const selectedRow =
selectedKey && sourceDiff
? (sourceDiff.rows.find((row) => row.key === selectedKey) ?? null)
: null
return (
<div
......
......@@ -756,7 +756,9 @@ export function TreemapVisualizer({
})
const [, _setTheme] = useState<'light' | 'dark'>('light')
// Build ancestor chain for focused source (list of source indices from root to focused)
// 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
......@@ -772,7 +774,7 @@ export function TreemapVisualizer({
}, [analyzeData, focusedSourceIndex])
// Build ancestor chain for selected source
const selectedAncestorChain = useMemo(() => {
const selectedAncestorChain = (() => {
const chain: number[] = []
let currentIndex = selectedSourceIndex
......@@ -784,10 +786,10 @@ export function TreemapVisualizer({
}
return chain
}, [analyzeData, selectedSourceIndex])
})()
// Build ancestor chain for hovered node (only used for dimming)
const hoveredAncestorChain = useMemo(() => {
const hoveredAncestorChain = (() => {
if (
!shouldDimOthers ||
!hoveredNode ||
......@@ -806,7 +808,7 @@ export function TreemapVisualizer({
}
return chain
}, [analyzeData, hoveredNode, shouldDimOthers])
})()
useEffect(() => {
const container = containerRef.current
......@@ -859,43 +861,33 @@ export function TreemapVisualizer({
}
}, [])
const layout = useMemo(() => {
// Compute layout using the focused source index
const focusedLayout = computeTreemapLayoutFromAnalyze(
analyzeData,
focusedSourceIndex,
{
x: 0,
y: 12 * focusedAncestorChain.length,
width: dimensions.cssWidth,
height: dimensions.cssHeight,
},
filterSource,
sizeMode
)
// If we're not at the root, wrap with ancestor title bars
if (focusedAncestorChain.length > 1) {
return wrapLayoutWithAncestorsUsingIndices(
focusedLayout,
focusedAncestorChain,
analyzeData,
dimensions.cssWidth,
dimensions.cssHeight,
12
)
}
return focusedLayout
}, [
// Layout walks the entire focused subtree; hover and selection redraw it
// in the canvas effect below.
const focusedLayout = computeTreemapLayoutFromAnalyze(
analyzeData,
focusedSourceIndex,
focusedAncestorChain,
dimensions.cssWidth,
dimensions.cssHeight,
{
x: 0,
y: 12 * focusedAncestorChain.length,
width: dimensions.cssWidth,
height: dimensions.cssHeight,
},
filterSource,
sizeMode,
])
sizeMode
)
// If we're not at the root, wrap with ancestor title bars
const layout =
focusedAncestorChain.length > 1
? wrapLayoutWithAncestorsUsingIndices(
focusedLayout,
focusedAncestorChain,
analyzeData,
dimensions.cssWidth,
dimensions.cssHeight,
12
)
: focusedLayout
useLayoutEffect(() => {
const canvas = canvasRef.current
......
......@@ -15,6 +15,10 @@ const developmentRewrites = () => {
const nextConfig = {
output: 'export',
distDir: 'dist',
reactCompiler: true,
experimental: {
turbopackRustReactCompiler: true,
},
rewrites:
process.env.NODE_ENV === 'development' ? developmentRewrites : undefined,
}
......
......@@ -20,7 +20,7 @@
"clsx": "^2.1.1",
"cmdk": "1.0.4",
"lucide-react": "^0.554.0",
"next": "16.2.3",
"next": "16.4.0-canary.31",
"next-themes": "^0.4.6",
"polished": "^4.3.1",
"react": "19.2.0",
......
This diff is collapsed.
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