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

Show async module scope in bundle analyzer (#98918)

### What?

Show source load scope in the bundle analyzer's single-build view: label
async-only and mixed sources in the table, mark them in the treemap with
a legend, and add an **Initial only** filter.

### Why?

Help distinguish sources reachable only behind an async import boundary
from sources reachable through an initial path (or both). This describes
**module-graph reachability**, not when a browser actually requests a
chunk.

### How?

Traverse the route's active-entry module graph, propagating initial,
async, and traced reachability across dependencies. Combine the reached
module scopes for each source, then pass the resulting classification to
the table, treemap, and filter. The new filter and indicators apply to
the single-build view; the comparison view keeps its existing behavior.

**Verification:** Bundle-analyzer typecheck, focused lint/format checks,
and production build passed; all eight combinations of the scope flags
were checked when simplifying the classification logic.

<!-- NEXT_JS_LLM -->


<!-- fleet d4ca0cb7-1e23-4f73-ac4e-5a6271239015 -->

---------
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 b8e22809
...@@ -26,6 +26,12 @@ import { ...@@ -26,6 +26,12 @@ import {
TableSkeleton, TableSkeleton,
TreemapSkeleton, TreemapSkeleton,
} from '@/components/ui/skeleton' } from '@/components/ui/skeleton'
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@/components/ui/tooltip'
import { AnalyzeData, ModulesData } from '@/lib/analyze-data' import { AnalyzeData, ModulesData } from '@/lib/analyze-data'
import { import {
analyzeDataUrl, analyzeDataUrl,
...@@ -37,7 +43,11 @@ import { ...@@ -37,7 +43,11 @@ import {
import { diffRoutesWithSizes, diffSources, type RouteSummary } from '@/lib/diff' import { diffRoutesWithSizes, diffSources, type RouteSummary } from '@/lib/diff'
import { useSidebarResize } from '@/lib/use-sidebar-resize' import { useSidebarResize } from '@/lib/use-sidebar-resize'
import { useAnalyzerRoute } from '@/lib/use-analyzer-route' import { useAnalyzerRoute } from '@/lib/use-analyzer-route'
import { computeActiveEntries, computeModuleDepthMap } from '@/lib/module-graph' import {
computeActiveEntries,
computeModuleDepthMap,
computeSourceLoadScopes,
} 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 { createAnalyzeTreemapSource, SizeMode } from '@/lib/treemap-layout' import { createAnalyzeTreemapSource, SizeMode } from '@/lib/treemap-layout'
...@@ -186,6 +196,7 @@ function useAnalyzerModel(compare: boolean) { ...@@ -186,6 +196,7 @@ function useAnalyzerModel(compare: boolean) {
const [compareSelectedKey, setCompareSelectedKey] = useState<string | null>( const [compareSelectedKey, setCompareSelectedKey] = useState<string | null>(
null null
) )
const [initialLoaded, setInitialLoaded] = useState(false)
// Reset compare selection when the route or either side changes — the // Reset compare selection when the route or either side changes — the
// previous selection is unlikely to exist in the new diff. // previous selection is unlikely to exist in the new diff.
...@@ -218,11 +229,20 @@ function useAnalyzerModel(compare: boolean) { ...@@ -218,11 +229,20 @@ function useAnalyzerModel(compare: boolean) {
// React Compiler currently skips this hook. Keep the graph traversal cached // React Compiler currently skips this hook. Keep the graph traversal cached
// across selection and filter updates until that bailout is resolved. // across selection and filter updates until that bailout is resolved.
const moduleDepthMap = useMemo(() => { const { moduleDepthMap, sourceLoadScopes } = useMemo(() => {
if (!analyzeData) return new Map() if (!analyzeData) {
return { moduleDepthMap: new Map(), sourceLoadScopes: new Map() }
}
const activeEntries = computeActiveEntries(modulesData, analyzeData) const activeEntries = computeActiveEntries(modulesData, analyzeData)
return computeModuleDepthMap(modulesData, activeEntries) return {
moduleDepthMap: computeModuleDepthMap(modulesData, activeEntries),
sourceLoadScopes: computeSourceLoadScopes(
modulesData,
analyzeData,
activeEntries
),
}
}, [modulesData, analyzeData]) }, [modulesData, analyzeData])
// This hook isn't compiled; stable predicate identity keeps the source diff // This hook isn't compiled; stable predicate identity keeps the source diff
...@@ -245,9 +265,20 @@ function useAnalyzerModel(compare: boolean) { ...@@ -245,9 +265,20 @@ function useAnalyzerModel(compare: boolean) {
(typeFilter.includes('json') && flags.json) || (typeFilter.includes('json') && flags.json) ||
(typeFilter.includes('asset') && flags.asset) (typeFilter.includes('asset') && flags.asset)
return hasEnvironment && hasType const hasLoadScope =
!initialLoaded ||
sourceLoadScopes.get(sourceIndex) === 'initial' ||
sourceLoadScopes.get(sourceIndex) === 'mixed'
return hasEnvironment && hasType && hasLoadScope
} }
}, [analyzeData, environmentFilter, typeFilter]) }, [
analyzeData,
environmentFilter,
initialLoaded,
sourceLoadScopes,
typeFilter,
])
// In single-build (non-compare) mode the table view still wants a list // In single-build (non-compare) mode the table view still wants a list
// of every source for the current route. We synthesize this by diffing // of every source for the current route. We synthesize this by diffing
...@@ -300,10 +331,12 @@ function useAnalyzerModel(compare: boolean) { ...@@ -300,10 +331,12 @@ function useAnalyzerModel(compare: boolean) {
filterSource, filterSource,
focusedSourceIndex, focusedSourceIndex,
hoveredNodeInfo, hoveredNodeInfo,
initialLoaded,
isHistoryLoading, isHistoryLoading,
isMouseInTreemap, isMouseInTreemap,
isViewPending, isViewPending,
moduleDepthMap, moduleDepthMap,
sourceLoadScopes,
modulesData, modulesData,
currentRouteTotals, currentRouteTotals,
clientRouteTotals, clientRouteTotals,
...@@ -319,6 +352,7 @@ function useAnalyzerModel(compare: boolean) { ...@@ -319,6 +352,7 @@ function useAnalyzerModel(compare: boolean) {
setEnvironmentFilter: routeState.setEnvironmentFilter, setEnvironmentFilter: routeState.setEnvironmentFilter,
setFocusedSourceIndex, setFocusedSourceIndex,
setHoveredNodeInfo, setHoveredNodeInfo,
setInitialLoaded,
setIsMouseInTreemap, setIsMouseInTreemap,
setSearchQuery: setSearchInput, setSearchQuery: setSearchInput,
setSelectedSourceIndex, setSelectedSourceIndex,
...@@ -389,6 +423,8 @@ function AnalyzerTopBar({ ...@@ -389,6 +423,8 @@ function AnalyzerTopBar({
? model.clientRouteTotals ? model.clientRouteTotals
: model.serverRouteTotals : model.serverRouteTotals
} }
initialLoaded={model.initialLoaded}
onInitialLoadedChange={model.setInitialLoaded}
/> />
) )
} }
...@@ -656,6 +692,11 @@ function SingleAnalyzerContent({ ...@@ -656,6 +692,11 @@ function SingleAnalyzerContent({
useCompressed useCompressed
nameHeading="Source" nameHeading="Source"
mode="single" mode="single"
getLoadScope={(row) =>
row.sourceIndexB == null
? 'unknown'
: (model.sourceLoadScopes.get(row.sourceIndexB) ?? 'unknown')
}
searchQuery={model.searchQuery} searchQuery={model.searchQuery}
emptyState={alternateEnvironmentEmptyState} emptyState={alternateEnvironmentEmptyState}
onRowSelect={(row) => { onRowSelect={(row) => {
...@@ -683,6 +724,10 @@ function SingleAnalyzerContent({ ...@@ -683,6 +724,10 @@ function SingleAnalyzerContent({
searchQuery={model.searchQuery} searchQuery={model.searchQuery}
filterSource={model.filterSource} filterSource={model.filterSource}
sizeMode={SizeMode.Compressed} sizeMode={SizeMode.Compressed}
getFileLoadScope={(sourceIndex) =>
model.sourceLoadScopes.get(sourceIndex) ?? 'unknown'
}
overlay={<AsyncScopeLegend />}
/> />
)} )}
</div> </div>
...@@ -705,6 +750,34 @@ function SingleAnalyzerContent({ ...@@ -705,6 +750,34 @@ function SingleAnalyzerContent({
) )
} }
function AsyncScopeLegend() {
return (
<TooltipProvider>
<div className="absolute bottom-3 left-3 flex items-center gap-3 rounded border border-border bg-background/95 px-2.5 py-1.5 text-xs shadow-sm">
<span className="flex items-center gap-1.5">
<span className="h-3 w-3 border border-foreground/40 bg-[repeating-linear-gradient(135deg,transparent_0,transparent_3px,currentColor_3px,currentColor_4px)] text-foreground/45" />
Behind async boundary
</span>
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
className="flex items-center gap-1.5 rounded-sm text-left focus-visible:outline-2 focus-visible:outline-offset-2"
>
<span className="relative h-3 w-3 border border-foreground/40 after:absolute after:right-0 after:top-0 after:h-0 after:w-0 after:border-l-[5px] after:border-t-[5px] after:border-l-transparent after:border-t-foreground/60" />
Initial + async paths
</button>
</TooltipTrigger>
<TooltipContent side="top">
This file is reachable both during the initial load and behind an
async boundary.
</TooltipContent>
</Tooltip>
</div>
</TooltipProvider>
)
}
function hasEnvironmentSources( function hasEnvironmentSources(
data: AnalyzeData, data: AnalyzeData,
environment: Environment, environment: Environment,
......
...@@ -24,6 +24,7 @@ import { ...@@ -24,6 +24,7 @@ import {
import { formatBytes } from '@/lib/utils' import { formatBytes } from '@/lib/utils'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
import { Badge } from '@/components/ui/badge' import { Badge } from '@/components/ui/badge'
import type { SourceLoadScope } from '@/lib/module-graph'
/** Which column the table is currently sorted by. */ /** Which column the table is currently sorted by. */
type SortColumn = 'name' | 'a' | 'b' | 'delta' type SortColumn = 'name' | 'a' | 'b' | 'delta'
...@@ -75,6 +76,8 @@ interface DiffTableProps<Row extends DiffRow> { ...@@ -75,6 +76,8 @@ interface DiffTableProps<Row extends DiffRow> {
searchQuery?: string searchQuery?: string
/** Empty-state message shown when the active source filters remove all rows. */ /** Empty-state message shown when the active source filters remove all rows. */
emptyState?: ReactNode emptyState?: ReactNode
/** Load-scope attribution for single-build source rows. */
getLoadScope?: (row: Row) => SourceLoadScope
} }
const virtuosoComponents = { const virtuosoComponents = {
...@@ -115,6 +118,7 @@ export function DiffTable<Row extends DiffRow>({ ...@@ -115,6 +118,7 @@ export function DiffTable<Row extends DiffRow>({
mode = 'compare', mode = 'compare',
searchQuery, searchQuery,
emptyState, emptyState,
getLoadScope,
}: DiffTableProps<Row>) { }: DiffTableProps<Row>) {
const isSingle = mode === 'single' const isSingle = mode === 'single'
// Compare mode shows only changed sources by default. In single mode every // Compare mode shows only changed sources by default. In single mode every
...@@ -278,6 +282,7 @@ export function DiffTable<Row extends DiffRow>({ ...@@ -278,6 +282,7 @@ export function DiffTable<Row extends DiffRow>({
onClick={onRowSelect ? () => onRowSelect(item.row) : undefined} onClick={onRowSelect ? () => onRowSelect(item.row) : undefined}
isSelected={selectedKey === item.row.key} isSelected={selectedKey === item.row.key}
mode={mode} mode={mode}
loadScope={isSingle ? getLoadScope?.(item.row) : undefined}
/> />
) )
}} }}
...@@ -514,6 +519,7 @@ function DiffPackageHeaderRow<Row extends DiffRow>({ ...@@ -514,6 +519,7 @@ function DiffPackageHeaderRow<Row extends DiffRow>({
isExpanded, isExpanded,
onToggle, onToggle,
mode = 'compare', mode = 'compare',
loadScope,
}: { }: {
packageName: string packageName: string
rows: Row[] rows: Row[]
...@@ -521,6 +527,7 @@ function DiffPackageHeaderRow<Row extends DiffRow>({ ...@@ -521,6 +527,7 @@ function DiffPackageHeaderRow<Row extends DiffRow>({
isExpanded: boolean isExpanded: boolean
onToggle: () => void onToggle: () => void
mode?: 'compare' | 'single' mode?: 'compare' | 'single'
loadScope?: SourceLoadScope
}) { }) {
const isSingle = mode === 'single' const isSingle = mode === 'single'
const agg = aggregatePackage(rows) const agg = aggregatePackage(rows)
...@@ -777,6 +784,7 @@ function DiffTableRow<Row extends DiffRow>({ ...@@ -777,6 +784,7 @@ function DiffTableRow<Row extends DiffRow>({
indent = false, indent = false,
isSelected = false, isSelected = false,
mode = 'compare', mode = 'compare',
loadScope,
}: { }: {
row: Row row: Row
useCompressed: boolean useCompressed: boolean
...@@ -786,6 +794,7 @@ function DiffTableRow<Row extends DiffRow>({ ...@@ -786,6 +794,7 @@ function DiffTableRow<Row extends DiffRow>({
/** When true, the row is highlighted as the active selection. */ /** When true, the row is highlighted as the active selection. */
isSelected?: boolean isSelected?: boolean
mode?: 'compare' | 'single' mode?: 'compare' | 'single'
loadScope?: SourceLoadScope
}) { }) {
const isSingle = mode === 'single' const isSingle = mode === 'single'
const d = delta(row, useCompressed) const d = delta(row, useCompressed)
...@@ -810,6 +819,7 @@ function DiffTableRow<Row extends DiffRow>({ ...@@ -810,6 +819,7 @@ function DiffTableRow<Row extends DiffRow>({
row={row} row={row}
hidePackageBadge={indent} hidePackageBadge={indent}
hideStatusIcon={isSingle} hideStatusIcon={isSingle}
loadScope={loadScope}
/> />
</td> </td>
{!isSingle ? ( {!isSingle ? (
...@@ -869,6 +879,7 @@ function DiffRowName<Row extends DiffRow>({ ...@@ -869,6 +879,7 @@ function DiffRowName<Row extends DiffRow>({
row, row,
hidePackageBadge = false, hidePackageBadge = false,
hideStatusIcon = false, hideStatusIcon = false,
loadScope,
}: { }: {
row: Row row: Row
/** When true, only render the within-package path (no package chip). Used /** When true, only render the within-package path (no package chip). Used
...@@ -878,6 +889,7 @@ function DiffRowName<Row extends DiffRow>({ ...@@ -878,6 +889,7 @@ function DiffRowName<Row extends DiffRow>({
/** When true, omit the per-status icon (used in single-build mode where /** When true, omit the per-status icon (used in single-build mode where
* every row is `identical` against itself, making the icon noise). */ * every row is `identical` against itself, making the icon noise). */
hideStatusIcon?: boolean hideStatusIcon?: boolean
loadScope?: SourceLoadScope
}) { }) {
// Narrow without dragging SourceDiffRow's typings into the generic table. // Narrow without dragging SourceDiffRow's typings into the generic table.
const pathKind = (row as unknown as { pathKind?: 'package' | 'project' }) const pathKind = (row as unknown as { pathKind?: 'package' | 'project' })
...@@ -897,6 +909,7 @@ function DiffRowName<Row extends DiffRow>({ ...@@ -897,6 +909,7 @@ function DiffRowName<Row extends DiffRow>({
<span className="truncate text-muted-foreground"> <span className="truncate text-muted-foreground">
{rest || packageName} {rest || packageName}
</span> </span>
<LoadScopeBadge scope={loadScope} />
<EnvBadges client={client} server={server} /> <EnvBadges client={client} server={server} />
</span> </span>
) )
...@@ -916,6 +929,7 @@ function DiffRowName<Row extends DiffRow>({ ...@@ -916,6 +929,7 @@ function DiffRowName<Row extends DiffRow>({
<span className="truncate text-muted-foreground">{rest}</span> <span className="truncate text-muted-foreground">{rest}</span>
) : null} ) : null}
</span> </span>
<LoadScopeBadge scope={loadScope} />
<EnvBadges client={client} server={server} /> <EnvBadges client={client} server={server} />
</span> </span>
) )
...@@ -928,11 +942,38 @@ function DiffRowName<Row extends DiffRow>({ ...@@ -928,11 +942,38 @@ function DiffRowName<Row extends DiffRow>({
<span className="truncate" title={row.key}> <span className="truncate" title={row.key}>
{row.name} {row.name}
</span> </span>
<LoadScopeBadge scope={loadScope} />
<EnvBadges client={client} server={server} /> <EnvBadges client={client} server={server} />
</span> </span>
) )
} }
function LoadScopeBadge({ scope }: { scope?: SourceLoadScope }) {
if (scope !== 'async' && scope !== 'mixed') return null
const label = scope === 'async' ? 'async' : 'initial + async'
const title =
scope === 'async'
? 'Reachable only through an async import boundary; it may still be requested during the initial render'
: 'Reachable through both initial and async import paths'
return (
<Badge
variant="outline"
className={cn(
'shrink-0 text-[10px] font-normal',
scope === 'async' &&
'bg-[repeating-linear-gradient(135deg,transparent_0,transparent_3px,currentColor_3px,currentColor_4px)] bg-[length:7px_7px]'
)}
title={title}
>
<span className={scope === 'async' ? 'bg-background/90 px-0.5' : ''}>
{label}
</span>
</Badge>
)
}
/** /**
* Invisible placeholder matching a {@link ChevronRight} icon's footprint. * Invisible placeholder matching a {@link ChevronRight} icon's footprint.
* Used on non-expandable rows so their status icon aligns horizontally * Used on non-expandable rows so their status icon aligns horizontally
......
...@@ -11,6 +11,7 @@ import { ...@@ -11,6 +11,7 @@ import {
SelectValue, SelectValue,
} from '@/components/ui/select' } from '@/components/ui/select'
import { MultiSelect } from '@/components/ui/multi-select' import { MultiSelect } from '@/components/ui/multi-select'
import { Switch } from '@/components/ui/switch'
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'
import { diffRoutesWithSizes, type RouteSizeTotals } from '@/lib/diff' import { diffRoutesWithSizes, type RouteSizeTotals } from '@/lib/diff'
import { type SnapshotMetadata } from '@/lib/snapshot' import { type SnapshotMetadata } from '@/lib/snapshot'
...@@ -84,6 +85,8 @@ export function TopBar({ ...@@ -84,6 +85,8 @@ export function TopBar({
routeTotals, routeTotals,
hasSourceData, hasSourceData,
showViewToggle, showViewToggle,
initialLoaded,
onInitialLoadedChange,
}: { }: {
hasSourceData: boolean hasSourceData: boolean
showViewToggle: boolean showViewToggle: boolean
...@@ -110,6 +113,8 @@ export function TopBar({ ...@@ -110,6 +113,8 @@ export function TopBar({
onCompareViewChange: (view: CompareView) => void onCompareViewChange: (view: CompareView) => void
routeDiff: ReturnType<typeof diffRoutesWithSizes> | null routeDiff: ReturnType<typeof diffRoutesWithSizes> | null
routeTotals?: ReadonlyMap<string, RouteSizeTotals> | null routeTotals?: ReadonlyMap<string, RouteSizeTotals> | null
initialLoaded?: boolean
onInitialLoadedChange?: (value: boolean) => void
}) { }) {
const isCompareMode = baselineSnapshot != null const isCompareMode = baselineSnapshot != null
const routeSelection = getRouteHref const routeSelection = getRouteHref
...@@ -239,6 +244,20 @@ export function TopBar({ ...@@ -239,6 +244,20 @@ export function TopBar({
aria-label="Filter by file type" aria-label="Filter by file type"
/> />
{!isCompareMode && onInitialLoadedChange ? (
<label
className="flex h-8 cursor-pointer items-center gap-2 whitespace-nowrap px-1"
title="Show only modules with an initial synchronous path"
>
<span className="text-xs">Initial load only</span>
<Switch
checked={initialLoaded}
onCheckedChange={onInitialLoadedChange}
aria-label="Show only modules with an initial synchronous path"
/>
</label>
) : null}
<ControlDivider /> <ControlDivider />
<FileSearch value={searchQuery} onChange={setSearchQuery} /> <FileSearch value={searchQuery} onChange={setSearchQuery} />
</> </>
......
...@@ -11,6 +11,7 @@ import { ...@@ -11,6 +11,7 @@ import {
} from '@/lib/treemap-layout' } from '@/lib/treemap-layout'
import { SpecialModule } from '@/lib/types' import { SpecialModule } from '@/lib/types'
import { formatBytes } from '@/lib/utils' import { formatBytes } from '@/lib/utils'
import type { SourceLoadScope } from '@/lib/module-graph'
const UI_FONT = 'system-ui, sans-serif' const UI_FONT = 'system-ui, sans-serif'
...@@ -41,6 +42,7 @@ interface TreemapVisualizerProps { ...@@ -41,6 +42,7 @@ interface TreemapVisualizerProps {
* size deltas (e.g. "+1.2 KB") instead of absolute sizes. * size deltas (e.g. "+1.2 KB") instead of absolute sizes.
*/ */
getFileSizeLabel?: (node: LayoutNode) => string | undefined getFileSizeLabel?: (node: LayoutNode) => string | undefined
getFileLoadScope?: (sourceIndex: number) => SourceLoadScope
/** /**
* 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 blue/amber delta legend. * compare view to render a blue/amber delta legend.
...@@ -292,6 +294,7 @@ function drawTreemap( ...@@ -292,6 +294,7 @@ function drawTreemap(
immediateHoveredSourceIndex: number | undefined, immediateHoveredSourceIndex: number | undefined,
getFileColorOverride: ((node: LayoutNode) => string | undefined) | undefined, getFileColorOverride: ((node: LayoutNode) => string | undefined) | undefined,
getFileSizeLabel: ((node: LayoutNode) => string | undefined) | undefined, getFileSizeLabel: ((node: LayoutNode) => string | undefined) | undefined,
getFileLoadScope: ((sourceIndex: number) => SourceLoadScope) | undefined,
currentPath: string[] = [], currentPath: string[] = [],
parentFadedOut = false, parentFadedOut = false,
insideActiveSubtree = false insideActiveSubtree = false
...@@ -351,6 +354,7 @@ function drawTreemap( ...@@ -351,6 +354,7 @@ function drawTreemap(
immediateHoveredSourceIndex, immediateHoveredSourceIndex,
getFileColorOverride, getFileColorOverride,
getFileSizeLabel, getFileSizeLabel,
getFileLoadScope,
path, path,
parentFadedOut, parentFadedOut,
insideActiveSubtree insideActiveSubtree
...@@ -429,6 +433,37 @@ function drawTreemap( ...@@ -429,6 +433,37 @@ function drawTreemap(
ctx.lineWidth = 1 ctx.lineWidth = 1
ctx.strokeRect(rect.x, rect.y, rect.width, rect.height) ctx.strokeRect(rect.x, rect.y, rect.width, rect.height)
const loadScope =
sourceIndex === undefined ? 'unknown' : getFileLoadScope?.(sourceIndex)
if (loadScope === 'async') {
ctx.save()
ctx.beginPath()
ctx.rect(rect.x, rect.y, rect.width, rect.height)
ctx.clip()
ctx.strokeStyle = readableColor(color)
ctx.globalAlpha = opacity * 0.28
ctx.lineWidth = 1
for (let offset = -rect.height; offset < rect.width; offset += 7) {
ctx.beginPath()
ctx.moveTo(rect.x + offset, rect.y + rect.height)
ctx.lineTo(rect.x + offset + rect.height, rect.y)
ctx.stroke()
}
ctx.restore()
ctx.globalAlpha = opacity
} else if (loadScope === 'mixed') {
const markerSize = Math.min(8, rect.width, rect.height)
ctx.fillStyle = readableColor(color)
ctx.globalAlpha = opacity * 0.65
ctx.beginPath()
ctx.moveTo(rect.x + rect.width - markerSize, rect.y)
ctx.lineTo(rect.x + rect.width, rect.y)
ctx.lineTo(rect.x + rect.width, rect.y + markerSize)
ctx.closePath()
ctx.fill()
ctx.globalAlpha = opacity
}
if (rect.width > 60 && rect.height > 30) { if (rect.width > 60 && rect.height > 30) {
const textColor = readableColor(color) const textColor = readableColor(color)
ctx.fillStyle = textColor ctx.fillStyle = textColor
...@@ -638,6 +673,7 @@ function drawTreemap( ...@@ -638,6 +673,7 @@ function drawTreemap(
immediateHoveredSourceIndex, immediateHoveredSourceIndex,
getFileColorOverride, getFileColorOverride,
getFileSizeLabel, getFileSizeLabel,
getFileLoadScope,
path, path,
childFadeOut, childFadeOut,
childInsideActiveSubtree childInsideActiveSubtree
...@@ -739,6 +775,7 @@ export function TreemapVisualizer({ ...@@ -739,6 +775,7 @@ export function TreemapVisualizer({
sizeMode = SizeMode.Compressed, sizeMode = SizeMode.Compressed,
getFileColorOverride, getFileColorOverride,
getFileSizeLabel, getFileSizeLabel,
getFileLoadScope,
overlay, overlay,
}: TreemapVisualizerProps) { }: TreemapVisualizerProps) {
const selectedSourceIndex = selectedSourceIndexProp ?? source.rootIndex const selectedSourceIndex = selectedSourceIndexProp ?? source.rootIndex
...@@ -876,7 +913,8 @@ export function TreemapVisualizer({ ...@@ -876,7 +913,8 @@ export function TreemapVisualizer({
layout, layout,
hoveredNode?.sourceIndex, hoveredNode?.sourceIndex,
getFileColorOverride, getFileColorOverride,
getFileSizeLabel getFileSizeLabel,
getFileLoadScope
) )
}, [ }, [
layout, layout,
...@@ -891,6 +929,7 @@ export function TreemapVisualizer({ ...@@ -891,6 +929,7 @@ export function TreemapVisualizer({
hoveredNode, hoveredNode,
getFileColorOverride, getFileColorOverride,
getFileSizeLabel, getFileSizeLabel,
getFileLoadScope,
]) ])
const handleClick = (e: React.MouseEvent<HTMLCanvasElement>) => { const handleClick = (e: React.MouseEvent<HTMLCanvasElement>) => {
......
'use client'
import * as React from 'react'
import * as SwitchPrimitive from '@radix-ui/react-switch'
import { cn } from '@/lib/utils'
const Switch = React.forwardRef<
React.ElementRef<typeof SwitchPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SwitchPrimitive.Root>
>(({ className, ...props }, ref) => (
<SwitchPrimitive.Root
className={cn(
'peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent bg-input shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary',
className
)}
{...props}
ref={ref}
>
<SwitchPrimitive.Thumb className="pointer-events-none block h-4 w-4 rounded-full bg-background shadow transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0" />
</SwitchPrimitive.Root>
))
Switch.displayName = SwitchPrimitive.Root.displayName
export { Switch }
import type { AnalyzeData, ModuleIndex, ModulesData } from './analyze-data' import type { AnalyzeData, ModuleIndex, ModulesData } from './analyze-data'
export const enum ModuleLoadScope {
Initial = 1,
Async = 2,
Traced = 4,
}
export type SourceLoadScope =
| 'initial'
| 'async'
| 'mixed'
| 'traced'
| 'unknown'
/** /**
* Compute active entries from the current route's sources. * Compute active entries from the current route's sources.
* *
...@@ -152,3 +165,81 @@ export function computeModuleDepthMap( ...@@ -152,3 +165,81 @@ export function computeModuleDepthMap(
return depthMap return depthMap
} }
/**
* Classify route sources by how they are reachable from the route entries.
* This describes graph boundaries, not when a browser requests a chunk.
*/
export function computeSourceLoadScopes(
modulesData: ModulesData,
analyzeData: AnalyzeData,
activeEntries: ModuleIndex[]
): Map<number, SourceLoadScope> {
const moduleScopes = new Map<ModuleIndex, number>()
const queue: Array<{ moduleIndex: ModuleIndex; scope: ModuleLoadScope }> = []
const enqueue = (moduleIndex: ModuleIndex, scope: ModuleLoadScope) => {
const previousScope = moduleScopes.get(moduleIndex) ?? 0
if ((previousScope & scope) === scope) return
moduleScopes.set(moduleIndex, previousScope | scope)
queue.push({ moduleIndex, scope })
}
for (const moduleIndex of activeEntries) {
enqueue(moduleIndex, ModuleLoadScope.Initial)
}
for (let index = 0; index < queue.length; index++) {
const current = queue[index]
for (const dependency of modulesData.moduleDependencies(
current.moduleIndex
)) {
enqueue(dependency, current.scope)
}
for (const dependency of modulesData.asyncModuleDependencies(
current.moduleIndex
)) {
enqueue(dependency, ModuleLoadScope.Async)
}
for (const dependency of modulesData.tracedModuleDependencies(
current.moduleIndex
)) {
enqueue(dependency, ModuleLoadScope.Traced)
}
}
const sourceScopes = new Map<number, SourceLoadScope>()
for (
let sourceIndex = 0;
sourceIndex < analyzeData.sourceCount();
sourceIndex++
) {
const sourcePath = analyzeData.getFullSourcePath(sourceIndex)
let scope = 0
for (const moduleIndex of modulesData.getModuleIndiciesFromPath(
sourcePath
)) {
scope |= moduleScopes.get(moduleIndex) ?? 0
}
const hasInitial = (scope & ModuleLoadScope.Initial) !== 0
const hasAsync = (scope & ModuleLoadScope.Async) !== 0
let loadScope: SourceLoadScope
if (hasInitial && hasAsync) {
loadScope = 'mixed'
} else if (hasAsync) {
loadScope = 'async'
} else if (hasInitial) {
loadScope = 'initial'
} else if ((scope & ModuleLoadScope.Traced) !== 0) {
loadScope = 'traced'
} else {
loadScope = 'unknown'
}
sourceScopes.set(sourceIndex, loadScope)
}
return sourceScopes
}
...@@ -12,6 +12,7 @@ ...@@ -12,6 +12,7 @@
"@radix-ui/react-popover": "1.1.4", "@radix-ui/react-popover": "1.1.4",
"@radix-ui/react-select": "2.2.6", "@radix-ui/react-select": "2.2.6",
"@radix-ui/react-slot": "1.1.1", "@radix-ui/react-slot": "1.1.1",
"@radix-ui/react-switch": "1.1.1",
"@radix-ui/react-toggle-group": "1.1.1", "@radix-ui/react-toggle-group": "1.1.1",
"@radix-ui/react-tooltip": "1.1.4", "@radix-ui/react-tooltip": "1.1.4",
"autoprefixer": "^10.4.20", "autoprefixer": "^10.4.20",
......
...@@ -658,6 +658,9 @@ importers: ...@@ -658,6 +658,9 @@ importers:
'@radix-ui/react-slot': '@radix-ui/react-slot':
specifier: 1.1.1 specifier: 1.1.1
version: 1.1.1(@types/react@19.2.18)(react@19.3.0-canary-278794d7-20261002) version: 1.1.1(@types/react@19.2.18)(react@19.3.0-canary-278794d7-20261002)
'@radix-ui/react-switch':
specifier: 1.1.1
version: 1.1.1(@types/react-dom@19.2.4(@types/react@19.2.18))(@types/react@19.2.18)(react-dom@19.3.0-canary-278794d7-20261002(react@19.3.0-canary-278794d7-20261002))(react@19.3.0-canary-278794d7-20261002)
'@radix-ui/react-toggle-group': '@radix-ui/react-toggle-group':
specifier: 1.1.1 specifier: 1.1.1
version: 1.1.1(@types/react-dom@19.2.4(@types/react@19.2.18))(@types/react@19.2.18)(react-dom@19.3.0-canary-278794d7-20261002(react@19.3.0-canary-278794d7-20261002))(react@19.3.0-canary-278794d7-20261002) version: 1.1.1(@types/react-dom@19.2.4(@types/react@19.2.18))(@types/react@19.2.18)(react-dom@19.3.0-canary-278794d7-20261002(react@19.3.0-canary-278794d7-20261002))(react@19.3.0-canary-278794d7-20261002)
...@@ -5923,6 +5926,19 @@ packages: ...@@ -5923,6 +5926,19 @@ packages:
'@types/react': '@types/react':
optional: true optional: true
'@radix-ui/react-switch@1.1.1':
resolution: {integrity: sha512-diPqDDoBcZPSicYoMWdWx+bCPuTRH4QSp9J+65IvtdS0Kuzt67bI6n32vCj8q6NZmYW/ah+2orOtMwcX5eQwIg==}
peerDependencies:
'@types/react': 19.2.18
'@types/react-dom': 19.2.4
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@types/react-dom':
optional: true
'@radix-ui/react-toggle-group@1.1.1': '@radix-ui/react-toggle-group@1.1.1':
resolution: {integrity: sha512-OgDLZEA30Ylyz8YSXvnGqIHtERqnUt1KUYTKdw/y8u7Ci6zGiJfXc02jahmcSNK3YcErqioj/9flWC9S1ihfwg==} resolution: {integrity: sha512-OgDLZEA30Ylyz8YSXvnGqIHtERqnUt1KUYTKdw/y8u7Ci6zGiJfXc02jahmcSNK3YcErqioj/9flWC9S1ihfwg==}
peerDependencies: peerDependencies:
...@@ -6043,6 +6059,15 @@ packages: ...@@ -6043,6 +6059,15 @@ packages:
'@types/react': '@types/react':
optional: true optional: true
'@radix-ui/react-use-previous@1.1.0':
resolution: {integrity: sha512-Z/e78qg2YFnnXcW88A4JmTtm4ADckLno6F7OXotmkQfeuCVaKuYzqAATPhVzl3delXE7CxIV8shofPn3jPc5Og==}
peerDependencies:
'@types/react': 19.2.18
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@radix-ui/react-use-previous@1.1.1': '@radix-ui/react-use-previous@1.1.1':
resolution: {integrity: sha512-2dHfToCj/pzca2Ck724OZ5L0EVrr3eHRNsG/b3xQJLA2hZpVCS99bLAX+hm1IHXDEnzU6by5z/5MIY794/a8NQ==} resolution: {integrity: sha512-2dHfToCj/pzca2Ck724OZ5L0EVrr3eHRNsG/b3xQJLA2hZpVCS99bLAX+hm1IHXDEnzU6by5z/5MIY794/a8NQ==}
peerDependencies: peerDependencies:
...@@ -23047,6 +23072,21 @@ snapshots: ...@@ -23047,6 +23072,21 @@ snapshots:
optionalDependencies: optionalDependencies:
'@types/react': 19.2.18 '@types/react': 19.2.18
'@radix-ui/react-switch@1.1.1(@types/react-dom@19.2.4(@types/react@19.2.18))(@types/react@19.2.18)(react-dom@19.3.0-canary-278794d7-20261002(react@19.3.0-canary-278794d7-20261002))(react@19.3.0-canary-278794d7-20261002)':
dependencies:
'@radix-ui/primitive': 1.1.0
'@radix-ui/react-compose-refs': 1.1.0(@types/react@19.2.18)(react@19.3.0-canary-278794d7-20261002)
'@radix-ui/react-context': 1.1.1(@types/react@19.2.18)(react@19.3.0-canary-278794d7-20261002)
'@radix-ui/react-primitive': 2.0.0(@types/react-dom@19.2.4(@types/react@19.2.18))(@types/react@19.2.18)(react-dom@19.3.0-canary-278794d7-20261002(react@19.3.0-canary-278794d7-20261002))(react@19.3.0-canary-278794d7-20261002)
'@radix-ui/react-use-controllable-state': 1.1.0(@types/react@19.2.18)(react@19.3.0-canary-278794d7-20261002)
'@radix-ui/react-use-previous': 1.1.0(@types/react@19.2.18)(react@19.3.0-canary-278794d7-20261002)
'@radix-ui/react-use-size': 1.1.0(@types/react@19.2.18)(react@19.3.0-canary-278794d7-20261002)
react: 19.3.0-canary-278794d7-20261002
react-dom: 19.3.0-canary-278794d7-20261002(react@19.3.0-canary-278794d7-20261002)
optionalDependencies:
'@types/react': 19.2.18
'@types/react-dom': 19.2.4(@types/react@19.2.18)
'@radix-ui/react-toggle-group@1.1.1(@types/react-dom@19.2.4(@types/react@19.2.18))(@types/react@19.2.18)(react-dom@19.3.0-canary-278794d7-20261002(react@19.3.0-canary-278794d7-20261002))(react@19.3.0-canary-278794d7-20261002)': '@radix-ui/react-toggle-group@1.1.1(@types/react-dom@19.2.4(@types/react@19.2.18))(@types/react@19.2.18)(react-dom@19.3.0-canary-278794d7-20261002(react@19.3.0-canary-278794d7-20261002))(react@19.3.0-canary-278794d7-20261002)':
dependencies: dependencies:
'@radix-ui/primitive': 1.1.1 '@radix-ui/primitive': 1.1.1
...@@ -23153,6 +23193,12 @@ snapshots: ...@@ -23153,6 +23193,12 @@ snapshots:
optionalDependencies: optionalDependencies:
'@types/react': 19.2.18 '@types/react': 19.2.18
'@radix-ui/react-use-previous@1.1.0(@types/react@19.2.18)(react@19.3.0-canary-278794d7-20261002)':
dependencies:
react: 19.3.0-canary-278794d7-20261002
optionalDependencies:
'@types/react': 19.2.18
'@radix-ui/react-use-previous@1.1.1(@types/react@19.2.18)(react@19.3.0-canary-278794d7-20261002)': '@radix-ui/react-use-previous@1.1.1(@types/react@19.2.18)(react@19.3.0-canary-278794d7-20261002)':
dependencies: dependencies:
react: 19.3.0-canary-278794d7-20261002 react: 19.3.0-canary-278794d7-20261002
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