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

Turbopack: Add bundle analyzer UI to next build --experimental-analyze (#85788)

This adds an interactive Treemap-style bundle analyzer app to the Next.js codebase and writes a copy to disk when `next build --experimental-analyze` is run.

* It's a separate app in `apps/bundle-analyzer` as `@next/bundle-analyzer-ui` that uses `output: 'export'` to export a purely static Next.js app
* These static resources are copied into Next.js's published `dist` directory in the `next` package itself. Users never depend on `@next/bundle-analyzer-ui`
* When users run `next build --experimental-analyze`, these static resources are copied into the user's `.next/diagnostics/analyze` along with the data payloads needed to visualize the user's app

In an upcoming PR, we'll add `next experimental-analyze` that will create analysis files without build artifacts, as well as optionally start a static file server.

Test Plan: Ran `next build --experimental-analyze` in a test app and ran a static file server to run it.
parent 43e989de
# Bundle Analyzer
A Next.js application for visualizing bundle sizes and analyzing dependencies using interactive treemaps.
This package is not published to npm. Instead it's built and vendored into the main `next` package during its build process.
## Features
- 📊 **Interactive Treemap**: Visualize bundle sizes with an interactive treemap interface
- 🎯 **Route-based Analysis**: Analyze bundle data for specific routes in your application
- 🔍 **Dependency Tracking**: View import chains and dependency relationships
- 🎨 **Filter Controls**: Filter by environment (client/server) and file types (JS/CSS/JSON/Assets)
- 🔎 **Search Functionality**: Search through files in your bundle
@import 'tailwindcss';
@import 'tw-animate-css';
@custom-variant dark (&:is(.dark *));
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--destructive-foreground: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--radius: 0.625rem;
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.145 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.145 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.985 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.396 0.141 25.723);
--destructive-foreground: oklch(0.637 0.237 25.331);
--border: oklch(0.269 0 0);
--input: oklch(0.269 0 0);
--ring: oklch(0.439 0 0);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(0.269 0 0);
--sidebar-ring: oklch(0.439 0 0);
}
@theme inline {
--font-sans: 'Geist', 'Geist Fallback';
--font-mono: 'Geist Mono', 'Geist Mono Fallback';
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}
import type { Metadata } from 'next'
import { Geist, Geist_Mono } from 'next/font/google'
import type React from 'react'
import './globals.css'
// These get used as font-sans and font-mono
const _geist = Geist({ subsets: ['latin'] })
const _geistMono = Geist_Mono({ subsets: ['latin'] })
export const metadata: Metadata = {
title: 'Next.js Bundle Analyzer',
description:
'Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis',
}
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html
lang="en"
// Suppress hydration warnings here specifically because we'll modify the
// classname for the theme before React hydates. This is to prevent a flash
// of incorrect theme.
suppressHydrationWarning
>
<head>
<script
// biome-ignore lint/security/noDangerouslySetInnerHtml: Needed to prevent flash of incorrect theme
dangerouslySetInnerHTML={{
__html: `
(function() {
const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
document.documentElement.classList.toggle('dark', theme === 'dark');
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
document.documentElement.classList.toggle('dark', e.matches);
});
})();
`,
}}
/>
</head>
<body className="font-sans antialiased">{children}</body>
</html>
)
}
This diff is collapsed.
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}
This diff is collapsed.
export { ImportChain } from './import-chain'
export { RouteTypeahead } from './route-typeahead'
export { TreemapVisualizer } from './treemap-visualizer'
'use client'
import useSWR from 'swr'
import { Check, ChevronsUpDown, Loader, Route } from 'lucide-react'
import { forwardRef, useImperativeHandle, useState } from 'react'
import { Button } from '@/components/ui/button'
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from '@/components/ui/command'
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover'
import { cn, jsonFetcher } from '@/lib/utils'
interface RouteTypeaheadProps {
selectedRoute: string | null
onRouteSelected: (routeName: string) => void
}
export interface RouteTypeaheadRef {
focus: () => void
}
export const RouteTypeahead = forwardRef<
RouteTypeaheadRef,
RouteTypeaheadProps
>(function RouteTypeahead({ selectedRoute, onRouteSelected }, ref) {
const [open, setOpen] = useState(false)
useImperativeHandle(ref, () => ({
focus: () => {
setOpen(true)
},
}))
const {
data: routes,
isLoading,
error,
} = useSWR<string[]>('data/routes.json', jsonFetcher, {
onSuccess: (routeNames) => {
// Auto-select first route if none is selected
if (routeNames.length > 0 && selectedRoute == null) {
onRouteSelected(routeNames[0])
}
},
})
if (error) {
return (
<div className="flex max-w-full text-red-600">
Failed to load routes manifest: {error.message}
</div>
)
}
let ctaText
if (isLoading) {
ctaText = 'Loading routes...'
} else if (selectedRoute != null) {
ctaText = selectedRoute
} else {
ctaText = 'Select route...'
}
return (
<div className="flex items-center gap-2 min-w-64 max-w-full">
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
disabled={isLoading}
className="flex-grow-1 w-full justify-between font-mono text-sm"
>
<div className="flex items-center">
{isLoading ? (
<Loader className="mr-2 inline animate-spin" />
) : (
<Route className="inline mr-2" />
)}
{ctaText}
</div>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-96 p-0">
<Command>
<CommandInput placeholder="Search routes..." className="h-9" />
<CommandList>
<CommandEmpty>No route found.</CommandEmpty>
<CommandGroup>
{(routes || []).map((route) => {
return (
<CommandItem
key={route}
value={route}
onSelect={() => {
onRouteSelected(route)
setOpen(false)
}}
className="font-mono"
>
<Check
className={cn(
'mr-2 h-4 w-4',
selectedRoute === route ? 'opacity-100' : 'opacity-0'
)}
/>
{route}
</CommandItem>
)
})}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
)
})
'use client'
import {
ThemeProvider as NextThemesProvider,
type ThemeProviderProps,
} from 'next-themes'
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}
This diff is collapsed.
'use client'
import { Slot } from '@radix-ui/react-slot'
import { cva, type VariantProps } from 'class-variance-authority'
import * as React from 'react'
import { cn } from '@/lib/utils'
const buttonVariants = cva(
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
{
variants: {
variant: {
default:
'bg-primary text-primary-foreground shadow hover:bg-primary/90',
destructive:
'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90',
outline:
'border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground',
secondary:
'bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80',
ghost: 'hover:bg-accent hover:text-accent-foreground',
link: 'text-primary underline-offset-4 hover:underline',
},
size: {
default: 'h-9 px-4 py-2',
sm: 'h-8 rounded-md px-3 text-xs',
lg: 'h-10 rounded-md px-8',
icon: 'h-9 w-9',
},
},
defaultVariants: {
variant: 'default',
size: 'default',
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : 'button'
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = 'Button'
export { Button, buttonVariants }
'use client'
import * as React from 'react'
import { Command as CommandPrimitive } from 'cmdk'
import { SearchIcon } from 'lucide-react'
import { cn } from '@/lib/utils'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
function Command({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive>) {
return (
<CommandPrimitive
data-slot="command"
className={cn(
'bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md',
className
)}
{...props}
/>
)
}
function CommandDialog({
title = 'Command Palette',
description = 'Search for a command to run...',
children,
className,
showCloseButton = true,
...props
}: React.ComponentProps<typeof Dialog> & {
title?: string
description?: string
className?: string
showCloseButton?: boolean
}) {
return (
<Dialog {...props}>
<DialogHeader className="sr-only">
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogContent
className={cn('overflow-hidden p-0', className)}
showCloseButton={showCloseButton}
>
<Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
</DialogContent>
</Dialog>
)
}
function CommandInput({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
return (
<div
data-slot="command-input-wrapper"
className="flex h-9 items-center gap-2 border-b px-3"
>
<SearchIcon className="size-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
data-slot="command-input"
className={cn(
'placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50',
className
)}
{...props}
/>
</div>
)
}
function CommandList({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.List>) {
return (
<CommandPrimitive.List
data-slot="command-list"
className={cn(
'max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto',
className
)}
{...props}
/>
)
}
function CommandEmpty({
...props
}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
return (
<CommandPrimitive.Empty
data-slot="command-empty"
className="py-6 text-center text-sm"
{...props}
/>
)
}
function CommandGroup({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
return (
<CommandPrimitive.Group
data-slot="command-group"
className={cn(
'text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium',
className
)}
{...props}
/>
)
}
function CommandSeparator({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
return (
<CommandPrimitive.Separator
data-slot="command-separator"
className={cn('bg-border -mx-1 h-px', className)}
{...props}
/>
)
}
function CommandItem({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
return (
<CommandPrimitive.Item
data-slot="command-item"
className={cn(
"data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function CommandShortcut({
className,
...props
}: React.ComponentProps<'span'>) {
return (
<span
data-slot="command-shortcut"
className={cn(
'text-muted-foreground ml-auto text-xs tracking-widest',
className
)}
{...props}
/>
)
}
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
}
'use client'
import * as React from 'react'
import * as DialogPrimitive from '@radix-ui/react-dialog'
import { XIcon } from 'lucide-react'
import { cn } from '@/lib/utils'
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50',
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
'bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg',
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="dialog-header"
className={cn('flex flex-col gap-2 text-center sm:text-left', className)}
{...props}
/>
)
}
function DialogFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="dialog-footer"
className={cn(
'flex flex-col-reverse gap-2 sm:flex-row sm:justify-end',
className
)}
{...props}
/>
)
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn('text-lg leading-none font-semibold', className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn('text-muted-foreground text-sm', className)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}
import * as React from 'react'
import { cn } from '@/lib/utils'
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50',
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = 'Input'
export { Input }
'use client'
import * as PopoverPrimitive from '@radix-ui/react-popover'
import * as React from 'react'
import { cn } from '@/lib/utils'
const Popover = PopoverPrimitive.Root
const PopoverTrigger = PopoverPrimitive.Trigger
const PopoverAnchor = PopoverPrimitive.Anchor
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = 'center', sideOffset = 4, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
'z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
))
PopoverContent.displayName = PopoverPrimitive.Content.displayName
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }
import { cn } from '@/lib/utils'
export function Skeleton({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
className={cn('animate-pulse rounded-md bg-muted', className)}
{...props}
/>
)
}
export function TreemapSkeleton() {
return (
<div className="h-full w-full grid grid-cols-12 grid-rows-8 gap-2">
{/* Simulate treemap blocks with varying sizes */}
<Skeleton className="col-span-5 row-span-4" />
<Skeleton className="col-span-4 row-span-3" />
<Skeleton className="col-span-3 row-span-3" />
<Skeleton className="col-span-4 row-span-1" />
<Skeleton className="col-span-3 row-span-2" />
<Skeleton className="col-span-3 row-span-4" />
<Skeleton className="col-span-2 row-span-2" />
<Skeleton className="col-span-2 row-span-2" />
<Skeleton className="col-span-3 row-span-2" />
<Skeleton className="col-span-4 row-span-2" />
<Skeleton className="col-span-2 row-span-2" />
<Skeleton className="col-span-3 row-span-2" />
</div>
)
}
'use client'
import * as ToggleGroupPrimitive from '@radix-ui/react-toggle-group'
import * as React from 'react'
import { cn } from '@/lib/utils'
const ToggleGroupContext = React.createContext<{
size?: 'default' | 'sm' | 'lg'
variant?: 'default' | 'outline'
}>({
size: 'default',
variant: 'default',
})
const ToggleGroup = React.forwardRef<
React.ElementRef<typeof ToggleGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Root> & {
size?: 'default' | 'sm' | 'lg'
variant?: 'default' | 'outline'
}
>(
(
{ className, variant = 'default', size = 'default', children, ...props },
ref
) => (
<ToggleGroupPrimitive.Root
ref={ref}
className={cn('flex items-center justify-center gap-1', className)}
{...props}
>
<ToggleGroupContext.Provider value={{ variant, size }}>
{children}
</ToggleGroupContext.Provider>
</ToggleGroupPrimitive.Root>
)
)
ToggleGroup.displayName = ToggleGroupPrimitive.Root.displayName
const ToggleGroupItem = React.forwardRef<
React.ElementRef<typeof ToggleGroupPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Item>
>(({ className, children, ...props }, ref) => {
const context = React.useContext(ToggleGroupContext)
return (
<ToggleGroupPrimitive.Item
ref={ref}
className={cn(
'inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground',
context.size === 'default' && 'h-10 px-3',
context.size === 'sm' && 'h-8 px-2 text-xs',
context.size === 'lg' && 'h-11 px-5',
className
)}
{...props}
>
{children}
</ToggleGroupPrimitive.Item>
)
})
ToggleGroupItem.displayName = ToggleGroupPrimitive.Item.displayName
export { ToggleGroup, ToggleGroupItem }
This diff is collapsed.
import type { LayoutRect } from './treemap-layout'
export function layoutTreemap(sizes: number[], rect: LayoutRect): LayoutRect[] {
if (sizes.length === 0) return []
if (sizes.length === 1) return [rect]
const totalSize = sizes.reduce((a, b) => a + b, 0)
const normalizedSizes = sizes.map(
(s) => (s / totalSize) * rect.width * rect.height
)
const result: LayoutRect[] = []
let remaining = [...normalizedSizes]
let currentRect = { ...rect }
let totalRemaining = remaining.reduce((a, b) => a + b, 0)
while (remaining.length > 1) {
// Decide orientation: vertical if wider, horizontal if taller
const vertical = currentRect.width >= currentRect.height
// Pick items until sum > total / count
const picked: number[] = []
let sum = 0
for (const size of remaining) {
picked.push(size)
sum += size
if (vertical) {
const width = (currentRect.width * sum) / totalRemaining
if (width > (currentRect.height / picked.length) * 0.9) {
break
}
} else {
const height = (currentRect.height * sum) / totalRemaining
if (height > (currentRect.width / picked.length) * 0.9) {
break
}
}
}
// Ensure at least one item is picked
if (picked.length === 0) {
picked.push(remaining[0])
sum = remaining[0]
}
// Calculate the space used by this row/column
const spaceRatio = sum / totalRemaining
totalRemaining -= sum
if (vertical) {
// Items stacked vertically, filling full width
const rowWidth = Math.round(spaceRatio * currentRect.width)
let offsetY = 0
for (let i = 0; i < picked.length; i++) {
const size = picked[i]
const itemHeight =
i === picked.length - 1
? Math.round(currentRect.height - offsetY)
: Math.round((size / sum) * currentRect.height)
result.push({
x: Math.round(currentRect.x),
y: Math.round(currentRect.y + offsetY),
width: rowWidth,
height: itemHeight,
})
offsetY += itemHeight
}
// Update remaining rectangle
currentRect = {
x: Math.round(currentRect.x + rowWidth),
y: Math.round(currentRect.y),
width: Math.round(currentRect.width - rowWidth),
height: Math.round(currentRect.height),
}
} else {
// Items placed horizontally, filling full height
const rowHeight = Math.round(spaceRatio * currentRect.height)
let offsetX = 0
for (let i = 0; i < picked.length; i++) {
const size = picked[i]
const itemWidth =
i === picked.length - 1
? Math.round(currentRect.width - offsetX)
: Math.round((size / sum) * currentRect.width)
result.push({
x: Math.round(currentRect.x + offsetX),
y: Math.round(currentRect.y),
width: itemWidth,
height: rowHeight,
})
offsetX += itemWidth
}
// Update remaining rectangle
currentRect = {
x: Math.round(currentRect.x),
y: Math.round(currentRect.y + rowHeight),
width: Math.round(currentRect.width),
height: Math.round(currentRect.height - rowHeight),
}
}
// Remove picked items from remaining
remaining = remaining.slice(picked.length)
}
// Last item fills remaining space
if (remaining.length === 1) {
result.push(currentRect)
}
return result
}
import type { AnalyzeData } from './analyze-data'
import { layoutTreemap } from './layout-treemap'
export interface LayoutRect {
x: number
y: number
width: number
height: number
}
export interface LayoutNodeInfo {
name: string
server?: boolean
client?: boolean
}
export interface LayoutNode extends LayoutNodeInfo {
size: number
rect: LayoutRect
type: 'file' | 'directory' | 'collapsed-directory'
titleBarHeight?: number
children?: LayoutNode[]
itemCount?: number
traced?: boolean
js?: boolean
css?: boolean
json?: boolean
asset?: boolean
sourceIndex?: number // Track which source this node represents
}
interface SourceMetadata {
filtered: boolean
totalSize: number
}
function precomputeSourceMetadata(
analyzeData: AnalyzeData,
filterSource?: (sourceIndex: number) => boolean
): SourceMetadata[] {
const sourceCount = analyzeData.sourceCount()
const metadata: SourceMetadata[] = new Array(sourceCount)
// Initialize all entries
for (let i = 0; i < sourceCount; i++) {
metadata[i] = { filtered: true, totalSize: 0 }
}
// Bottom-up pass: compute leaf node data
for (let i = sourceCount - 1; i >= 0; i--) {
const children = analyzeData.sourceChildren(i)
const ownSize = analyzeData.getSourceOutputSize(i)
if (children.length === 0) {
// Leaf node (file)
metadata[i].totalSize = ownSize
metadata[i].filtered = filterSource ? !filterSource(i) : false
} else {
// Directory - initialize with own size
metadata[i].totalSize = ownSize
}
}
// Top-down pass: aggregate child sizes and filtered status for directories
function processDirectory(idx: number) {
const children = analyzeData.sourceChildren(idx)
if (children.length === 0) return // Already processed as leaf
let totalSize = metadata[idx].totalSize // Start with own size
let hasVisibleChild = false
for (const childIdx of children) {
processDirectory(childIdx) // Process child first
if (!metadata[childIdx].filtered) {
// Only add size of visible (non-filtered) children
totalSize += metadata[childIdx].totalSize
hasVisibleChild = true
}
}
metadata[idx].totalSize = totalSize
metadata[idx].filtered = !hasVisibleChild // Directory filtered if no visible children
}
// Process from root sources
const roots = analyzeData.sourceRoots()
for (const rootIdx of roots) {
processDirectory(rootIdx)
}
return metadata
}
// Internal function that uses precomputed metadata
function computeTreemapLayoutFromAnalyzeInternal(
analyzeData: AnalyzeData,
sourceIndex: number,
foldedPath: string,
rect: LayoutRect,
metadata: SourceMetadata[],
filterSource?: (sourceIndex: number) => boolean
): LayoutNode {
const source = analyzeData.source(sourceIndex)
if (!source) {
throw new Error(`Source at index ${sourceIndex} not found`)
}
const isDirectory = source.path.endsWith('/') || !source.path
// Get children sources
const childrenIndices = analyzeData.sourceChildren(sourceIndex)
// Fold single-child directories
if (
childrenIndices.length === 1 &&
isDirectory &&
(foldedPath + source.path).length <= 40
) {
const childIndex = childrenIndices[0]
const child = analyzeData.source(childIndex)
if (child?.path.endsWith('/')) {
return computeTreemapLayoutFromAnalyzeInternal(
analyzeData,
childIndex,
foldedPath + source.path,
rect,
metadata,
filterSource
)
}
}
// Use precomputed size
const totalSize = metadata[sourceIndex].totalSize
// If this is a file (no children), create a file node
if (!isDirectory || childrenIndices.length === 0) {
return {
name: source.path,
size: totalSize,
type: 'file',
rect,
sourceIndex,
...analyzeData.getSourceFlags(sourceIndex),
}
}
// This is a directory with children
const titleBarHeight = Math.round(
Math.max(12, Math.min(24, rect.height * 0.1))
)
const isCollapsed = rect.height < 30
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)),
}
if (isCollapsed) {
// Count all descendant files
function countDescendants(idx: number): number {
const children = analyzeData.sourceChildren(idx)
if (children.length === 0) return 1
return children.reduce(
(sum, childIdx) => sum + countDescendants(childIdx),
0
)
}
return {
name: foldedPath + source.path,
size: totalSize,
type: 'collapsed-directory',
rect,
titleBarHeight,
itemCount: countDescendants(sourceIndex),
children: [],
sourceIndex,
}
}
// Recursively build children with their sizes
const childrenData: { index: number; size: number }[] = []
for (const childIndex of childrenIndices) {
const childSource = analyzeData.source(childIndex)
if (!childSource) continue
// Use precomputed filter status
if (metadata[childIndex].filtered) {
continue
}
// Use precomputed size
const childSize = metadata[childIndex].totalSize
childrenData.push({
index: childIndex,
size: childSize || 1, // Fallback to 1 for visibility
})
}
if (childrenData.length === 0) {
return {
name: foldedPath + source.path,
size: totalSize,
type: 'directory',
rect,
titleBarHeight,
children: [],
sourceIndex,
}
}
// Sort by size (descending)
childrenData.sort((a, b) => b.size - a.size)
// Compute layout
const sizes = childrenData.map((c) => c.size)
const childRects = layoutTreemap(sizes, contentRect)
const layoutChildren: LayoutNode[] = childrenData.map((child, i) =>
computeTreemapLayoutFromAnalyzeInternal(
analyzeData,
child.index,
'',
childRects[i],
metadata,
filterSource
)
)
return {
name: foldedPath + source.path,
size: totalSize,
type: 'directory',
rect,
titleBarHeight,
children: layoutChildren,
sourceIndex,
}
}
// Public function that precomputes metadata and calls internal function
export function computeTreemapLayoutFromAnalyze(
analyzeData: AnalyzeData,
sourceIndex: number,
rect: LayoutRect,
filterSource?: (sourceIndex: number) => boolean
): LayoutNode {
// Precompute metadata once for entire tree
const metadata = precomputeSourceMetadata(analyzeData, filterSource)
// Use internal function with precomputed metadata
return computeTreemapLayoutFromAnalyzeInternal(
analyzeData,
sourceIndex,
'',
rect,
metadata,
filterSource
)
}
export interface FileNode {
id: number
name: string
type: 'file'
size: number
outputType: 'code' | 'css' | 'asset'
server: boolean
client: boolean
dependencies: number[]
dependents: number[]
}
export interface DirectoryNode {
id: number
name: string
type: 'directory'
children: TreeNode[]
size?: number
}
export type TreeNode = FileNode | DirectoryNode
interface Route {
page: string
regex: string
routeKeys?: Record<string, string>
namedRegex?: string
}
export interface RouteManifest {
version: number
pages: Record<string, string>
staticRoutes: Array<Route>
dynamicRoutes: Array<Route>
}
import { type ClassValue, clsx } from 'clsx'
import { twMerge } from 'tailwind-merge'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export function jsonFetcher<T>(url: string): Promise<T> {
return fetch(url).then((res) => res.json())
}
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import './.next/types/routes.d.ts'
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'export',
distDir: 'dist',
}
export default nextConfig
{
"name": "@next/bundle-analyzer-ui",
"version": "16.0.2-canary.16",
"private": true,
"scripts": {
"build": "next build --no-mangling",
"dev": "next dev",
"lint": "eslint .",
"start": "next start"
},
"dependencies": {
"@radix-ui/react-dialog": "1.1.4",
"@radix-ui/react-popover": "1.1.4",
"@radix-ui/react-slot": "1.1.1",
"@radix-ui/react-toggle-group": "1.1.1",
"autoprefixer": "^10.4.20",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "1.0.4",
"lucide-react": "^0.454.0",
"next": "16.0.1",
"next-themes": "^0.4.6",
"polished": "^4.3.1",
"react": "19.2.0",
"react-dom": "19.2.0",
"swr": "^2.2.4",
"tailwind-merge": "^2.5.5",
"tailwindcss-animate": "^1.0.7"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.1.9",
"@types/node": "^22",
"@types/react": "^18",
"@types/react-dom": "^18",
"inliner": "1.13.1",
"postcss": "^8.5",
"tailwindcss": "^4.1.9",
"tw-animate-css": "1.3.3",
"typescript": "^5"
}
}
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
'@tailwindcss/postcss': {},
},
}
export default config
@import 'tailwindcss';
@import 'tw-animate-css';
@custom-variant dark (&:is(.dark *));
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--destructive-foreground: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--radius: 0.625rem;
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--popover: oklch(0.145 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.985 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.396 0.141 25.723);
--destructive-foreground: oklch(0.637 0.237 25.331);
--border: oklch(0.269 0 0);
--input: oklch(0.269 0 0);
--ring: oklch(0.439 0 0);
}
@theme inline {
--font-sans: 'Geist', 'Geist Fallback';
--font-mono: 'Geist Mono', 'Geist Mono Fallback';
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"target": "ES6",
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": ["node_modules"]
}
......@@ -64,7 +64,7 @@ async fn get_analyze_data_operation(
.node_root()
.owned()
.await?
.join("diagnostics/analyze")?;
.join("diagnostics/analyze/data")?;
let whole_app_module_graphs = project.whole_app_module_graphs();
let analyze_output_root = &analyze_output_root;
let analyze_data = project
......
......@@ -223,7 +223,7 @@ import {
sortPages,
sortSortableRouteObjects,
} from '../shared/lib/router/utils/sortable-routes'
import { mkdir } from 'fs/promises'
import { cp, mkdir, writeFile } from 'fs/promises'
import {
createRouteTypesManifest,
writeRouteTypesManifest,
......@@ -4321,6 +4321,30 @@ export default async function build(
.traceAsyncFn(() => telemetry.flush())
await shutdownPromise
if (NextBuildContext.analyze) {
await cp(
path.join(__dirname, '../bundle-analyzer'),
path.join(dir, '.next/diagnostics/analyze'),
{ recursive: true }
)
await mkdir(path.join(dir, '.next/diagnostics/analyze/data'), {
recursive: true,
})
// Write an index of routes for the route picker
await writeFile(
path.join(dir, '.next/diagnostics/analyze/data/routes.json'),
JSON.stringify(
routesManifest.dynamicRoutes
.map((r) => r.page)
.concat(routesManifest.staticRoutes.map((r) => r.page)),
null,
2
)
)
}
})
} catch (e) {
const telemetry: Telemetry | undefined = traceGlobals.get('telemetry')
......
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -260,6 +260,13 @@ export async function copy_vercel_og(task, opts) {
)
}
export async function copy_bundle_analyzer_ui(task, opts) {
const bundleAnalyzerPath = join(__dirname, '../../apps/bundle-analyzer/dist')
await task
.source(join(bundleAnalyzerPath, '**/*'))
.target('dist/bundle-analyzer')
}
externals['anser'] = 'next/dist/compiled/anser'
externals['next/dist/compiled/anser'] = 'next/dist/compiled/anser'
export async function ncc_node_anser(task, opts) {
......@@ -2336,6 +2343,7 @@ export async function next_compile(task, opts) {
await task.parallel(
[
'cli',
'copy_bundle_analyzer_ui',
'bin',
'server',
'server_esm',
......
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