Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(sandbox): DiffViewer performance page for large change sets (#7554)

Cindy Zhang7fe45847bd65
diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json
index 741b5c8783..402c2042a7 100644
--- a/apps/sandbox/scripts/next-export-routes.json
+++ b/apps/sandbox/scripts/next-export-routes.json
@@ -10,6 +10,7 @@
"/pages/color-studio/",
"/pages/component-scores/",
"/pages/dictation-lab/",
+ "/pages/diffviewer-perf/",
"/pages/doc-discover/",
"/pages/doc-docs/",
"/pages/doc-home/",
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/benchmark.test.ts b/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/benchmark.test.ts
new file mode 100644
index 0000000000..feafa0a252
--- /dev/null
+++ b/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/benchmark.test.ts
@@ -0,0 +1,75 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {
+ countLines,
+ createMultiFileWorkload,
+ createSingleFileWorkload,
+ formatMegabytes,
+ MULTI_FILE_WORKLOADS,
+} from './benchmark';
+
+describe('DiffViewer performance workloads', () => {
+ it('builds the same multi-file workload on every call', () => {
+ const first = createMultiFileWorkload(50, 10_000);
+ const second = createMultiFileWorkload(50, 10_000);
+ expect(second).toEqual(first);
+ expect(first.files).toHaveLength(50);
+ expect(new Set(first.files.map(file => file.path)).size).toBe(50);
+ });
+
+ it.each(MULTI_FILE_WORKLOADS)(
+ 'hits about $totalLines lines across $files files, with a realistic mix',
+ ({files, totalLines}) => {
+ const workload = createMultiFileWorkload(files, totalLines);
+ expect(workload.files).toHaveLength(files);
+ expect(workload.totalLines).toBe(countLines(workload.files));
+ expect(
+ Math.abs(workload.totalLines - totalLines) / totalLines,
+ ).toBeLessThan(0.05);
+ const sizes = workload.files
+ .map(
+ file =>
+ (file.newContents ?? file.oldContents ?? '').split('\n').length,
+ )
+ .sort((a, b) => a - b);
+ // Mostly small files, with a few far larger than the median.
+ expect(sizes[Math.floor(files / 2)]).toBeLessThan(400);
+ expect(sizes[files - 1]).toBeGreaterThan(
+ sizes[Math.floor(files / 2)] * 10,
+ );
+ expect(workload.files.some(file => file.oldContents == null)).toBe(true);
+ expect(workload.files.some(file => file.newContents == null)).toBe(true);
+ expect(
+ workload.files.filter(
+ file =>
+ file.oldContents != null &&
+ file.newContents != null &&
+ file.oldContents !== file.newContents,
+ ).length,
+ ).toBeGreaterThan(files * 0.8);
+ },
+ );
+
+ it('builds one file of the requested size, sparse or rewritten', () => {
+ const sparse = createSingleFileWorkload(1000, 'sparse');
+ const rewrite = createSingleFileWorkload(1000, 'rewrite');
+ expect(sparse.files).toHaveLength(1);
+ expect(sparse.files[0].oldContents?.split('\n')).toHaveLength(1000);
+ const oldLines = new Set(rewrite.files[0].oldContents?.split('\n'));
+ const sharedNonBlank = (rewrite.files[0].newContents ?? '')
+ .split('\n')
+ .filter(line => line.trim() !== '' && oldLines.has(line));
+ expect(sharedNonBlank).toEqual([]);
+ const sparseOld = new Set(sparse.files[0].oldContents?.split('\n'));
+ const kept = (sparse.files[0].newContents ?? '')
+ .split('\n')
+ .filter(line => sparseOld.has(line)).length;
+ expect(kept / 1000).toBeGreaterThan(0.9);
+ });
+
+ it('formats heap readings', () => {
+ expect(formatMegabytes(null)).toBe('—');
+ expect(formatMegabytes(3 * 1_048_576)).toBe('3.0 MB');
+ });
+});
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/benchmark.ts b/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/benchmark.ts
new file mode 100644
index 0000000000..0828ef8e7a
--- /dev/null
+++ b/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/benchmark.ts
@@ -0,0 +1,271 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file benchmark.ts
+ * @input A workload id: a multi-file change set or one file of a given size
+ * @output Deterministic old/new file contents, their totals, and small
+ * formatting helpers for the DiffViewer performance sandbox
+ * @position Pure support utilities for the DiffViewer performance sandbox;
+ * no React and no DOM, so any harness can render the same fixtures
+ *
+ * Multi-file workloads mirror a real large change: many small files, some
+ * medium ones, and a few very large generated or vendored files, with sparse
+ * edits, a handful of new and deleted files, and a few full rewrites. Every
+ * value comes from a seeded generator, so a workload is byte-identical on
+ * every run and in every harness.
+ */
+
+export interface DiffBenchmarkFile {
+ readonly path: string;
+ /** Contents before the change; `null` for an added file. */
+ readonly oldContents: string | null;
+ /** Contents after the change; `null` for a deleted file. */
+ readonly newContents: string | null;
+}
+
+export interface DiffBenchmarkWorkload {
+ readonly id: string;
+ readonly label: string;
+ readonly files: ReadonlyArray<DiffBenchmarkFile>;
+ /** Lines across every file's newer side (the older side for a deleted file). */
+ readonly totalLines: number;
+}
+
+/** Multi-file workloads: file count and the total lines they target. */
+export const MULTI_FILE_WORKLOADS = [
+ {files: 50, totalLines: 10_000},
+ {files: 200, totalLines: 50_000},
+ {files: 500, totalLines: 100_000},
+ {files: 1000, totalLines: 150_000},
+] as const;
+
+/** Single-file workloads: line counts, each with sparse edits or a rewrite. */
+export const SINGLE_FILE_LINES = [100, 1000, 5000, 20_000] as const;
+
+export type SingleFileChange = 'sparse' | 'rewrite';
+
+/** Mulberry32: a small, fast, seeded generator; same seed, same sequence. */
+function createRandom(seed: number): () => number {
+ let state = seed >>> 0;
+ return () => {
+ state = (state + 0x6d2b79f5) >>> 0;
+ let t = state;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+function between(random: () => number, min: number, max: number): number {
+ return min + Math.floor(random() * (max - min + 1));
+}
+
+/**
+ * One line of TypeScript-like source, varied by its file and position. A
+ * variant changes every non-blank line, so two variants share no code.
+ */
+function sourceLine(fileIndex: number, line: number, variant = ''): string {
+ const base = baseSourceLine(fileIndex, line, variant);
+ return variant === '' || base === '' ? base : `${base} // ${variant}`;
+}
+
+function baseSourceLine(
+ fileIndex: number,
+ line: number,
+ variant: string,
+): string {
+ const id = `${fileIndex}_${line}${variant}`;
+ switch (line % 12) {
+ case 0:
+ return `export interface Record${id} {`;
+ case 1:
+ return ` id: string; // ${variant || 'stable'} field`;
+ case 2:
+ return ` value: number;`;
+ case 3:
+ return `}`;
+ case 4:
+ return '';
+ case 5:
+ return `export async function load${id}(url: string): Promise<number> {`;
+ case 6:
+ return ` const response = await fetch(url, {cache: 'no-store'});`;
+ case 7:
+ return ` if (!response.ok) throw new Error('HTTP ' + response.status);`;
+ case 8:
+ return ` return (await response.json()).count ?? ${line}; // ${id}`;
+ case 9:
+ return `}`;
+ case 10:
+ return '';
+ default:
+ return `// Section ${Math.floor(line / 12) + 1} of file ${fileIndex}`;
+ }
+}
+
+function fileLines(fileIndex: number, count: number, variant = ''): string[] {
+ return Array.from({length: count}, (_, line) =>
+ sourceLine(fileIndex, line, variant),
+ );
+}
+
+/**
+ * Edit roughly one site per `spacing` lines: each site replaces one to three
+ * lines and sometimes inserts one or two more.
+ */
+function applySparseEdits(
+ lines: ReadonlyArray<string>,
+ random: () => number,
+ spacing: number,
+): string[] {
+ const next: string[] = [];
+ let line = 0;
+ let isFirst = true;
+ while (line < lines.length) {
+ const gap = between(random, Math.floor(spacing / 2), spacing * 2);
+ // A short file still gets one edit: its first site lands inside it.
+ const reach = isFirst ? Math.min(gap, Math.floor(lines.length / 2)) : gap;
+ isFirst = false;
+ next.push(...lines.slice(line, line + reach));
+ line += reach;
+ if (line >= lines.length) {
+ break;
+ }
+ const replaced = between(random, 1, 3);
+ for (let i = 0; i < replaced && line < lines.length; i++, line++) {
+ next.push(`${lines[line]} // updated`);
+ }
+ const inserted = between(random, 0, 2);
+ for (let i = 0; i < inserted; i++) {
+ next.push(` void track('edit-${line}-${i}');`);
+ }
+ }
+ return next;
+}
+
+const DIRECTORIES = [
+ 'src/components',
+ 'src/hooks',
+ 'src/utils',
+ 'src/server/routes',
+ 'src/server/models',
+ 'test/unit',
+ 'test/integration',
+ 'docs/guides',
+ 'generated/schema',
+ 'vendor/parser',
+];
+
+/** File sizes in three tiers, scaled so their sum meets the target. */
+function fileSizes(
+ random: () => number,
+ files: number,
+ totalLines: number,
+): number[] {
+ const raw = Array.from({length: files}, () => {
+ const tier = random();
+ if (tier < 0.85) {
+ return between(random, 30, 160);
+ }
+ if (tier < 0.97) {
+ return between(random, 300, 1500);
+ }
+ return between(random, 3000, 12_000);
+ });
+ const sum = raw.reduce((total, size) => total + size, 0);
+ const scale = totalLines / sum;
+ return raw.map(size => Math.max(12, Math.round(size * scale)));
+}
+
+/**
+ * A change set of `files` files whose sides total about `totalLines` lines.
+ * About 5% of the files are new, 2% deleted and 2% rewritten in full; the
+ * rest carry sparse edits.
+ */
+export function createMultiFileWorkload(
+ files: number,
+ totalLines: number,
+): DiffBenchmarkWorkload {
+ const random = createRandom(files * 7919 + totalLines);
+ const sizes = fileSizes(random, files, totalLines);
+ const result: DiffBenchmarkFile[] = sizes.map((size, index) => {
+ const directory = DIRECTORIES[index % DIRECTORIES.length];
+ const path = `${directory}/module_${String(index).padStart(4, '0')}.ts`;
+ const original = fileLines(index, size);
+ const kind = random();
+ if (kind < 0.05) {
+ return {path, oldContents: null, newContents: original.join('\n')};
+ }
+ if (kind < 0.07) {
+ return {path, oldContents: original.join('\n'), newContents: null};
+ }
+ if (kind < 0.09) {
+ return {
+ path,
+ oldContents: original.join('\n'),
+ newContents: fileLines(index, size, 'v2').join('\n'),
+ };
+ }
+ return {
+ path,
+ oldContents: original.join('\n'),
+ newContents: applySparseEdits(original, random, 40).join('\n'),
+ };
+ });
+ return {
+ id: `files-${files}`,
+ label: `${files.toLocaleString()} files`,
+ files: result,
+ totalLines: countLines(result),
+ };
+}
+
+/** One file of `lines` lines with sparse edits or rewritten in full. */
+export function createSingleFileWorkload(
+ lines: number,
+ change: SingleFileChange,
+): DiffBenchmarkWorkload {
+ const random = createRandom(lines * 31 + (change === 'rewrite' ? 1 : 0));
+ const original = fileLines(0, lines);
+ const next =
+ change === 'rewrite'
+ ? fileLines(0, lines, 'v2')
+ : applySparseEdits(original, random, 40);
+ const files = [
+ {
+ path: 'src/large_module.ts',
+ oldContents: original.join('\n'),
+ newContents: next.join('\n'),
+ },
+ ];
+ return {
+ id: `single-${lines}-${change}`,
+ label: `${lines.toLocaleString()} lines, ${change === 'rewrite' ? 'full rewrite' : 'sparse edits'}`,
+ files,
+ totalLines: countLines(files),
+ };
+}
+
+function lineCount(contents: string | null): number {
+ return contents == null || contents === '' ? 0 : contents.split('\n').length;
+}
+
+export function countLines(files: ReadonlyArray<DiffBenchmarkFile>): number {
+ return files.reduce(
+ (total, file) =>
+ total + lineCount(file.newContents ?? file.oldContents ?? null),
+ 0,
+ );
+}
+
+export function formatDuration(value: number | null): string {
+ return value == null ? '—' : `${value.toFixed(1)} ms`;
+}
+
+export function formatCount(value: number | null): string {
+ return value == null ? '—' : value.toLocaleString();
+}
+
+export function formatMegabytes(bytes: number | null): string {
+ return bytes == null ? '—' : `${(bytes / 1_048_576).toFixed(1)} MB`;
+}
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/page.tsx b/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/page.tsx
new file mode 100644
index 0000000000..1b1bf6da31
--- /dev/null
+++ b/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/page.tsx
@@ -0,0 +1,648 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file page.tsx
+ * @input Deterministic multi-file and single-file diff workloads, view mode,
+ * and syntax highlighting on or off
+ * @output Interactive DiffViewer benchmark: diff-model time, first file on
+ * screen, total render, long tasks, DOM size, heap, scroll frames, and the
+ * cost of collapse, expand, and view switches
+ * @position Fullscreen sandbox tool for evaluating the Lab DiffViewer on large
+ * change sets
+ */
+
+import {memo, useCallback, useMemo, useRef, useState} from 'react';
+import {flushSync} from 'react-dom';
+import {AppShell} from '@astryxdesign/core/AppShell';
+import {Badge} from '@astryxdesign/core/Badge';
+import {Button} from '@astryxdesign/core/Button';
+import {Card} from '@astryxdesign/core/Card';
+import {Grid} from '@astryxdesign/core/Grid';
+import {ScrollableArea} from '@astryxdesign/core/ScrollableArea';
+import {Section} from '@astryxdesign/core/Section';
+import {
+ SegmentedControl,
+ SegmentedControlItem,
+} from '@astryxdesign/core/SegmentedControl';
+import {HStack, VStack} from '@astryxdesign/core/Stack';
+import {Heading, Text} from '@astryxdesign/core/Text';
+import {
+ createDiffFile,
+ DiffViewer,
+ type DiffViewerFile,
+ type DiffViewerViewMode,
+} from '@astryxdesign/lab';
+import {
+ createMultiFileWorkload,
+ createSingleFileWorkload,
+ formatCount,
+ formatDuration,
+ formatMegabytes,
+ MULTI_FILE_WORKLOADS,
+ SINGLE_FILE_LINES,
+ type DiffBenchmarkFile,
+ type SingleFileChange,
+} from './benchmark';
+
+type Scenario = 'multi' | 'single';
+type Syntax = 'on' | 'off';
+
+/** What a run measured, captured when it started so later control changes don't relabel it. */
+interface RunSubject {
+ label: string;
+ totalLines: number;
+ viewMode: DiffViewerViewMode;
+ syntax: Syntax;
+}
+
+interface RunMetrics {
+ subject: RunSubject | null;
+ prepareMs: number | null;
+ firstFileMs: number | null;
+ renderMs: number | null;
+ longTasks: number | null;
+ longTaskMs: number | null;
+ domNodes: number | null;
+ heapBytes: number | null;
+}
+
+/** The view a reading was taken on, kept with it so later switches don't relabel it. */
+interface ViewContext {
+ viewMode: DiffViewerViewMode;
+ syntax: Syntax;
+}
+
+interface ScrollMetrics extends ViewContext {
+ fps: number;
+ droppedFrames: number;
+ longTasks: number | null;
+}
+
+interface Interaction extends ViewContext {
+ label: string;
+ ms: number;
+}
+
+function describeView({viewMode, syntax}: ViewContext): string {
+ return `${viewMode}, ${syntax === 'on' ? 'highlighted' : 'plain'}`;
+}
+
+const EMPTY_RUN: RunMetrics = {
+ subject: null,
+ prepareMs: null,
+ firstFileMs: null,
+ renderMs: null,
+ longTasks: null,
+ longTaskMs: null,
+ domNodes: null,
+ heapBytes: null,
+};
+
+const SCROLL_DURATION_MS = 4000;
+/** Stop looking for the first rendered file after this long. */
+const FIRST_FILE_TIMEOUT_MS = 60_000;
+
+/**
+ * Chrome's non-standard heap reading; absent in other browsers, and coarse in
+ * some (it can stay flat across a run), so callers treat no change as no reading.
+ */
+function usedHeapBytes(): number | null {
+ const memory = (
+ performance as Performance & {memory?: {usedJSHeapSize: number}}
+ ).memory;
+ return memory?.usedJSHeapSize ?? null;
+}
+
+/** Calls `done` with the time from `start` until the next frame has painted. */
+function afterNextPaint(start: number, done: (ms: number) => void) {
+ requestAnimationFrame(() => {
+ setTimeout(() => done(performance.now() - start), 0);
+ });
+}
+
+interface LongTaskReading {
+ count: number;
+ totalMs: number;
+}
+
+/**
+ * Collects long tasks until the returned stop function is called. Returns
+ * null from stop when the browser has no Long Tasks API, so the page shows no
+ * reading rather than a misleading zero.
+ */
+function watchLongTasks(): () => LongTaskReading | null {
+ const isSupported =
+ typeof PerformanceObserver !== 'undefined' &&
+ PerformanceObserver.supportedEntryTypes?.includes('longtask') === true;
+ if (!isSupported) {
+ return () => null;
+ }
+ const entries: PerformanceEntry[] = [];
+ const observer = new PerformanceObserver(list => {
+ for (const entry of list.getEntries()) {
+ entries.push(entry);
+ }
+ });
+ observer.observe({type: 'longtask', buffered: false});
+ return () => {
+ for (const entry of observer.takeRecords()) {
+ entries.push(entry);
+ }
+ observer.disconnect();
+ return {
+ count: entries.length,
+ totalMs: entries.reduce((total, entry) => total + entry.duration, 0),
+ };
+ };
+}
+
+function toDiffFile(file: DiffBenchmarkFile): DiffViewerFile {
+ return createDiffFile({
+ oldValue: file.oldContents ?? '',
+ newValue: file.newContents ?? '',
+ oldPath: file.oldContents == null ? null : file.path,
+ newPath: file.newContents == null ? null : file.path,
+ });
+}
+
+/** Lines across every hunk: a removed and an added line count separately. */
+function diffLineCount(files: ReadonlyArray<DiffViewerFile>): number {
+ let lines = 0;
+ for (const file of files) {
+ for (const hunk of file.hunks) {
+ lines += hunk.lines.length;
+ }
+ }
+ return lines;
+}
+
+const BenchmarkFile = memo(function BenchmarkFile({
+ file,
+ viewMode,
+ language,
+ isCollapsed,
+ onToggle,
+}: {
+ file: DiffViewerFile;
+ viewMode: DiffViewerViewMode;
+ language: string | undefined;
+ isCollapsed: boolean;
+ onToggle: (path: string, isCollapsed: boolean) => void;
+}) {
+ const path = file.newPath ?? file.oldPath ?? '';
+ return (
+ <DiffViewer
+ file={file}
+ viewMode={viewMode}
+ language={language}
+ isCollapsed={isCollapsed}
+ onCollapsedChange={next => onToggle(path, next)}
+ />
+ );
+});
+
+function Metric({label, value}: {label: string; value: string}) {
+ return (
+ <VStack gap={0.5}>
+ <Text type="label">{label}</Text>
+ <Text type="code">{value}</Text>
+ </VStack>
+ );
+}
+
+export default function DiffViewerPerfPage() {
+ const [scenario, setScenario] = useState<Scenario>('multi');
+ const [fileCount, setFileCount] = useState('200');
+ const [lineCount, setLineCount] = useState('5000');
+ const [change, setChange] = useState<SingleFileChange>('sparse');
+ const [viewMode, setViewMode] = useState<DiffViewerViewMode>('unified');
+ const [syntax, setSyntax] = useState<Syntax>('on');
+ const [files, setFiles] = useState<ReadonlyArray<DiffViewerFile>>([]);
+ const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(new Set());
+ const [run, setRun] = useState<RunMetrics>(EMPTY_RUN);
+ const [scroll, setScroll] = useState<ScrollMetrics | null>(null);
+ const [interaction, setInteraction] = useState<Interaction | null>(null);
+ const [isBusy, setIsBusy] = useState(false);
+ const [isScrolling, setIsScrolling] = useState(false);
+ const [runKey, setRunKey] = useState(0);
+ const surfaceRef = useRef<HTMLDivElement>(null);
+
+ const workload = useMemo(() => {
+ if (scenario === 'multi') {
+ const entry =
+ MULTI_FILE_WORKLOADS.find(w => String(w.files) === fileCount) ??
+ MULTI_FILE_WORKLOADS[0];
+ return createMultiFileWorkload(entry.files, entry.totalLines);
+ }
+ return createSingleFileWorkload(Number(lineCount), change);
+ }, [scenario, fileCount, lineCount, change]);
+
+ const language = syntax === 'on' ? undefined : 'plaintext';
+ const diffLines = useMemo(() => diffLineCount(files), [files]);
+
+ const runBenchmark = useCallback(() => {
+ const subject: RunSubject = {
+ label: workload.label,
+ totalLines: workload.totalLines,
+ viewMode,
+ syntax,
+ };
+ setIsBusy(true);
+ setScroll(null);
+ setInteraction(null);
+ setRun(EMPTY_RUN);
+ setFiles([]);
+ setCollapsed(new Set());
+ // Let the previous list unmount and paint before timing the new one.
+ requestAnimationFrame(() => {
+ setTimeout(() => {
+ const heapBefore = usedHeapBytes();
+ const prepareStart = performance.now();
+ const prepared = workload.files.map(toDiffFile);
+ const prepareMs = performance.now() - prepareStart;
+ const stopLongTasks = watchLongTasks();
+ const renderStart = performance.now();
+ // Both readings are taken after a paint; the run is published once
+ // both are known, so a late first file is recorded, not replaced.
+ let firstFileMs: number | null | undefined;
+ let rendered: {
+ renderMs: number;
+ longTasks: LongTaskReading | null;
+ } | null = null;
+ const publish = () => {
+ if (firstFileMs === undefined || rendered == null) {
+ return;
+ }
+ const heapAfter = usedHeapBytes();
+ setRun({
+ subject,
+ prepareMs,
+ firstFileMs,
+ renderMs: rendered.renderMs,
+ longTasks: rendered.longTasks?.count ?? null,
+ longTaskMs: rendered.longTasks?.totalMs ?? null,
+ domNodes: surfaceRef.current?.querySelectorAll('*').length ?? null,
+ heapBytes:
+ heapBefore == null ||
+ heapAfter == null ||
+ heapAfter === heapBefore
+ ? null
+ : heapAfter - heapBefore,
+ });
+ setIsBusy(false);
+ };
+ // Looks for a rendered diff now and then once per frame, so a file
+ // that renders late is caught at the frame it appears.
+ const watchFirstFile = () => {
+ if (surfaceRef.current?.querySelector('table') != null) {
+ afterNextPaint(renderStart, ms => {
+ firstFileMs = ms;
+ publish();
+ });
+ return;
+ }
+ if (performance.now() - renderStart > FIRST_FILE_TIMEOUT_MS) {
+ firstFileMs = null;
+ publish();
+ return;
+ }
+ requestAnimationFrame(watchFirstFile);
+ };
+ // Commit synchronously so the timers below start after this render.
+ flushSync(() => {
+ setFiles(prepared);
+ setRunKey(key => key + 1);
+ });
+ watchFirstFile();
+ afterNextPaint(renderStart, renderMs => {
+ rendered = {renderMs, longTasks: stopLongTasks()};
+ publish();
+ });
+ }, 0);
+ });
+ }, [workload, viewMode, syntax]);
+
+ // `view` is what the timed update leaves on screen, which a switch changes.
+ const timeInteraction = (
+ label: string,
+ view: ViewContext,
+ update: () => void,
+ ) => {
+ const start = performance.now();
+ update();
+ afterNextPaint(start, ms => setInteraction({label, ms, ...view}));
+ };
+
+ const toggleFile = useCallback(
+ (path: string, isCollapsed: boolean) => {
+ const start = performance.now();
+ setCollapsed(current => {
+ const next = new Set(current);
+ if (isCollapsed) {
+ next.add(path);
+ } else {
+ next.delete(path);
+ }
+ return next;
+ });
+ afterNextPaint(start, ms =>
+ setInteraction({
+ label: isCollapsed ? 'Collapse one file' : 'Expand one file',
+ ms,
+ viewMode,
+ syntax,
+ }),
+ );
+ // A view or syntax switch re-renders every file anyway, so a new callback
+ // then costs nothing extra.
+ },
+ [viewMode, syntax],
+ );
+
+ const currentView: ViewContext = {viewMode, syntax};
+ const collapseAll = () =>
+ timeInteraction('Collapse all', currentView, () =>
+ setCollapsed(new Set(files.map(f => f.newPath ?? f.oldPath ?? ''))),
+ );
+ const expandAll = () =>
+ timeInteraction('Expand all', currentView, () => setCollapsed(new Set()));
+
+ const changeViewMode = (next: string) => {
+ const nextMode = next as DiffViewerViewMode;
+ timeInteraction(`Switch to ${next}`, {viewMode: nextMode, syntax}, () =>
+ setViewMode(nextMode),
+ );
+ };
+ const changeSyntax = (next: string) => {
+ const nextSyntax = next as Syntax;
+ timeInteraction(
+ `Syntax ${nextSyntax === 'on' ? 'highlighted' : 'plain'}`,
+ {viewMode, syntax: nextSyntax},
+ () => setSyntax(nextSyntax),
+ );
+ };
+
+ const runScrollTest = () => {
+ const viewport = surfaceRef.current;
+ if (viewport == null) {
+ return;
+ }
+ viewport.scrollTop = 0;
+ setIsScrolling(true);
+ const view = currentView;
+ const stopLongTasks = watchLongTasks();
+ const distance = viewport.scrollHeight - viewport.clientHeight;
+ const start = performance.now();
+ let frames = 0;
+ let dropped = 0;
+ let previous = start;
+ const step = (now: number) => {
+ frames += 1;
+ if (now - previous > 20) {
+ dropped += 1;
+ }
+ previous = now;
+ const progress = Math.min((now - start) / SCROLL_DURATION_MS, 1);
+ viewport.scrollTop = distance * progress;
+ if (progress < 1) {
+ requestAnimationFrame(step);
+ return;
+ }
+ const elapsed = now - start;
+ setScroll({
+ ...view,
+ fps: Math.round((frames / elapsed) * 1000),
+ droppedFrames: dropped,
+ longTasks: stopLongTasks()?.count ?? null,
+ });
+ setIsScrolling(false);
+ };
+ requestAnimationFrame(step);
+ };
+
+ const controlsDisabled = isBusy || isScrolling;
+ // Badges describe the measured run once there is one, else the selection.
+ const shown: RunSubject = run.subject ?? {
+ label: workload.label,
+ totalLines: workload.totalLines,
+ viewMode,
+ syntax,
+ };
+
+ return (
+ <AppShell contentPadding={4} height="fill">
+ <VStack gap={4}>
+ <VStack gap={1}>
+ <Heading level={2}>DiffViewer Performance</Heading>
+ <Text type="body" color="secondary">
+ Render a whole change set, one DiffViewer per file, and measure the
+ diff model, the first file on screen, the full render, long tasks,
+ DOM size and heap, then scroll the list and time collapse, expand
+ and view switches. Multi-file workloads mix many small files with a
+ few very large ones.
+ </Text>
+ </VStack>
+
+ <Section variant="muted" padding={3} dividers={['bottom']}>
+ <HStack gap={4} vAlign="center" wrap="wrap">
+ <SegmentedControl
+ label="Workload"
+ value={scenario}
+ onChange={value => setScenario(value as Scenario)}
+ isDisabled={controlsDisabled}
+ size="sm">
+ <SegmentedControlItem value="multi" label="Many files" />
+ <SegmentedControlItem value="single" label="One file" />
+ </SegmentedControl>
+ {scenario === 'multi' ? (
+ <SegmentedControl
+ label="Files"
+ value={fileCount}
+ onChange={setFileCount}
+ isDisabled={controlsDisabled}
+ size="sm">
+ {MULTI_FILE_WORKLOADS.map(entry => (
+ <SegmentedControlItem
+ key={entry.files}
+ value={String(entry.files)}
+ label={entry.files.toLocaleString()}
+ />
+ ))}
+ </SegmentedControl>
+ ) : (
+ <>
+ <SegmentedControl
+ label="Lines"
+ value={lineCount}
+ onChange={setLineCount}
+ isDisabled={controlsDisabled}
+ size="sm">
+ {SINGLE_FILE_LINES.map(lines => (
+ <SegmentedControlItem
+ key={lines}
+ value={String(lines)}
+ label={lines.toLocaleString()}
+ />
+ ))}
+ </SegmentedControl>
+ <SegmentedControl
+ label="Change"
+ value={change}
+ onChange={value => setChange(value as SingleFileChange)}
+ isDisabled={controlsDisabled}
+ size="sm">
+ <SegmentedControlItem value="sparse" label="Sparse edits" />
+ <SegmentedControlItem value="rewrite" label="Full rewrite" />
+ </SegmentedControl>
+ </>
+ )}
+ <SegmentedControl
+ label="View"
+ value={viewMode}
+ onChange={changeViewMode}
+ isDisabled={controlsDisabled}
+ size="sm">
+ <SegmentedControlItem value="unified" label="Unified" />
+ <SegmentedControlItem value="split" label="Split" />
+ </SegmentedControl>
+ <SegmentedControl
+ label="Syntax"
+ value={syntax}
+ onChange={changeSyntax}
+ isDisabled={controlsDisabled}
+ size="sm">
+ <SegmentedControlItem value="on" label="Highlighted" />
+ <SegmentedControlItem value="off" label="Plain" />
+ </SegmentedControl>
+ <Button
+ label="Run benchmark"
+ onClick={runBenchmark}
+ isDisabled={controlsDisabled}
+ />
+ </HStack>
+ </Section>
+
+ <Grid columns={2} gap={4}>
+ <Card padding={3}>
+ <VStack gap={3}>
+ <Heading level={3}>Run metrics</Heading>
+ <HStack gap={2} wrap="wrap">
+ <Badge label={shown.label} />
+ <Badge
+ label={`${shown.totalLines.toLocaleString()} file lines`}
+ />
+ <Badge label={`${diffLines.toLocaleString()} diff lines`} />
+ <Badge label={shown.viewMode} />
+ <Badge
+ label={shown.syntax === 'on' ? 'highlighted' : 'plain'}
+ />
+ </HStack>
+ <Grid columns={2} gap={3}>
+ <Metric
+ label="Diff model (createDiffFile)"
+ value={formatDuration(run.prepareMs)}
+ />
+ <Metric
+ label="First file on screen"
+ value={formatDuration(run.firstFileMs)}
+ />
+ <Metric
+ label="Full render"
+ value={formatDuration(run.renderMs)}
+ />
+ <Metric
+ label="Long tasks (count / total)"
+ value={
+ run.longTasks == null
+ ? '—'
+ : `${run.longTasks} / ${formatDuration(run.longTaskMs)}`
+ }
+ />
+ <Metric label="DOM nodes" value={formatCount(run.domNodes)} />
+ <Metric
+ label="Heap growth"
+ value={formatMegabytes(run.heapBytes)}
+ />
+ <Metric
+ label={
+ scroll == null
+ ? 'Scroll (fps / dropped / long tasks)'
+ : `Scroll (fps / dropped / long tasks), ${describeView(scroll)}`
+ }
+ value={
+ scroll == null
+ ? '—'
+ : `${scroll.fps} / ${scroll.droppedFrames} / ${scroll.longTasks ?? '—'}`
+ }
+ />
+ <Metric
+ label={
+ interaction == null
+ ? 'Last interaction'
+ : `${interaction.label}, ${describeView(interaction)}`
+ }
+ value={formatDuration(interaction?.ms ?? null)}
+ />
+ </Grid>
+ <HStack gap={2} wrap="wrap">
+ <Button
+ label="Scroll test"
+ variant="secondary"
+ onClick={runScrollTest}
+ isDisabled={files.length === 0 || controlsDisabled}
+ />
+ <Button
+ label="Collapse all"
+ variant="secondary"
+ onClick={collapseAll}
+ isDisabled={files.length === 0 || controlsDisabled}
+ />
+ <Button
+ label="Expand all"
+ variant="secondary"
+ onClick={expandAll}
+ isDisabled={files.length === 0 || controlsDisabled}
+ />
+ </HStack>
+ <Text type="body" color="secondary">
+ Full render runs from the commit to the next painted frame;
+ first file on screen runs from the commit to the paint after a
+ rendered diff first appears. A long task is a main-thread task
+ over 50 ms; a dropped frame is a gap over 20 ms. A reading the
+ browser cannot give (long tasks without the Long Tasks API, a
+ heap reading that does not move) shows as a dash. Badges name
+ the workload the run was measured on; the scroll and interaction
+ readings name the view they were taken in. The scroll test moves
+ the list from top to bottom over four seconds.
+ </Text>
+ </VStack>
+ </Card>
+
+ <ScrollableArea
+ key={runKey}
+ ref={surfaceRef}
+ label="Rendered change set"
+ height={640}>
+ <VStack gap={3}>
+ {files.map(file => {
+ const path = file.newPath ?? file.oldPath ?? '';
+ return (
+ <BenchmarkFile
+ key={path}
+ file={file}
+ viewMode={viewMode}
+ language={language}
+ isCollapsed={collapsed.has(path)}
+ onToggle={toggleFile}
+ />
+ );
+ })}
+ </VStack>
+ </ScrollableArea>
+ </Grid>
+ </VStack>
+ </AppShell>
+ );
+}
diff --git a/apps/sandbox/src/app/sandboxPages.ts b/apps/sandbox/src/app/sandboxPages.ts
index af3f7580c5..4c878d8c46 100644
--- a/apps/sandbox/src/app/sandboxPages.ts
+++ b/apps/sandbox/src/app/sandboxPages.ts
@@ -251,6 +251,12 @@ export const categories: SandboxCategory[] = [
description:
'Compare complete Markdown rendering with bursty streaming performance and animation',
},
+ {
+ name: 'DiffViewer Perf',
+ href: '/pages/diffviewer-perf/',
+ description:
+ 'Render and scroll many files and lines; compare unified and split',
+ },
{
name: 'Table Lab',
href: '/pages/table-lab/',