An open source design system that's fully customizable and agent ready
TypeScript
sandbox(perf): one shared readings module for the three perf pages (#10921)
Cindy Zhang957d9348bf88
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/animated-layout-perf/page.tsx b/apps/sandbox/src/app/(fullscreen)/pages/animated-layout-perf/page.tsxindex 09e23c8673..9b633b54b1 100644--- a/apps/sandbox/src/app/(fullscreen)/pages/animated-layout-perf/page.tsx+++ b/apps/sandbox/src/app/(fullscreen)/pages/animated-layout-perf/page.tsx@@ -45,11 +45,11 @@ import type {AnimatedLayout} from '@astryxdesign/core/hooks';type Rendering = 'full' | 'virtualized';import {+ formatBenchmarkChange,formatCount,formatDuration,watchLongTasks,-} from '../diffviewer-perf/benchmark';-import {formatBenchmarkChange} from '../markdown-perf/benchmark';+} from '../perfReadings';interface RunMetrics {/** From the change to the glide starting: React's commit and the walk. */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.tsindex 09a2007bd3..bee258494c 100644--- a/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/benchmark.test.ts+++ b/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/benchmark.test.ts@@ -1,6 +1,6 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-import {afterEach, describe, expect, it, vi} from 'vitest';+import {describe, expect, it} from 'vitest';import {createDiffFile} from '../../../../../../../packages/lab/src/DiffViewer/createDiffFile';import {countLines,@@ -10,7 +10,6 @@ import {MULTI_FILE_WORKLOADS,SINGLE_FILE_LINES,type DiffBenchmarkWorkload,- watchLongTasks,} from './benchmark';/** Added plus removed lines in the diff DiffViewer renders, per file. */@@ -135,27 +134,3 @@ describe('DiffViewer performance workloads', () => {expect(formatMegabytes(3 * 1_048_576)).toBe('3.0 MB');});});--describe('watchLongTasks', () => {- afterEach(() => {- vi.unstubAllGlobals();- });-- it('reads no value when the browser has no Long Tasks API', () => {- vi.stubGlobal('PerformanceObserver', undefined);- expect(watchLongTasks()()).toBeNull();- });-- it('counts the long tasks it observed until stopped', () => {- class FakeObserver {- static supportedEntryTypes = ['longtask'];- observe() {}- disconnect() {}- takeRecords() {- return [{duration: 60}, {duration: 90}];- }- }- vi.stubGlobal('PerformanceObserver', FakeObserver);- expect(watchLongTasks()()).toEqual({count: 2, totalMs: 150});- });-});diff --git a/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/benchmark.ts b/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/benchmark.tsindex 032171f7cd..932b631722 100644--- a/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/benchmark.ts+++ b/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/benchmark.ts@@ -5,7 +5,7 @@* @input A workload: a multi-file preset (file count and changed lines) or* one file of a given size* @output Deterministic old/new file contents, their line and changed-line- * totals, and small formatting helpers for the DiffViewer performance sandbox+ * totals, and the megabyte formatter 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*@@ -375,50 +375,6 @@ export function countLines(files: ReadonlyArray<DiffBenchmarkFile>): number {);}-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`;}--export 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 a page shows no- * reading rather than a misleading zero.- */-export 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),- };- };-}diff --git a/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/page.tsx b/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/page.tsxindex c4ce04f03f..3a88eb0d17 100644--- a/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/page.tsx+++ b/apps/sandbox/src/app/(fullscreen)/pages/diffviewer-perf/page.tsx@@ -48,17 +48,19 @@ import {import {createMultiFileWorkload,createSingleFileWorkload,- formatCount,- formatDuration,formatMegabytes,MULTI_FILE_WORKLOADS,SINGLE_FILE_LINES,type DiffBenchmarkFile,type MultiFileWorkloadId,type SingleFileChange,+} from './benchmark';+import {+ formatCount,+ formatDuration,type LongTaskReading,watchLongTasks,-} from './benchmark';+} from '../perfReadings';type Scenario = 'multi' | 'single';type Syntax = 'on' | 'off';diff --git a/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmark.test.ts b/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmark.test.tsindex 7ef7eed4ac..d7b951fd51 100644--- a/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmark.test.ts+++ b/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmark.test.ts@@ -1,11 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import {describe, expect, it} from 'vitest';-import {- formatBenchmarkChange,- generateMarkdownFixture,- nextStreamOffset,-} from './benchmark';+import {generateMarkdownFixture, nextStreamOffset} from './benchmark';describe('Markdown performance fixture', () => {it('generates the requested deterministic section count', () => {@@ -17,23 +13,6 @@ describe('Markdown performance fixture', () => {expect(first).toContain('const section3 = {id: 3, ready: true};');});- it('formats missing, zero, positive, and negative baseline changes', () => {- expect(formatBenchmarkChange(null, 10)).toBe('—');- expect(formatBenchmarkChange(10, null)).toBe('—');- });-- it('shows a caller-supplied empty label when there is no baseline or no value', () => {- const labels = {noBaseline: 'no baseline', noValue: 'baseline saved'};- expect(formatBenchmarkChange(10, null, labels)).toBe('no baseline');- expect(formatBenchmarkChange(null, null, labels)).toBe('no baseline');- expect(formatBenchmarkChange(null, 10, labels)).toBe('baseline saved');- expect(formatBenchmarkChange(12, 10, labels)).toBe('+20.0%');- expect(formatBenchmarkChange(0, 0)).toBe('0.0%');- expect(formatBenchmarkChange(1, 0)).toBe('new');- expect(formatBenchmarkChange(110, 100)).toBe('+10.0%');- expect(formatBenchmarkChange(90, 100)).toBe('-10.0%');- });-it('advances streaming offsets monotonically to the exact source length', () => {const offsets: number[] = [];let offset = 0;diff --git a/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmark.ts b/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmark.tsindex 9d945bf01f..df55bc1d8e 100644--- a/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmark.ts+++ b/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/benchmark.ts@@ -40,32 +40,6 @@ export function generateMarkdownFixture(sectionCount: number): string {].join('\n\n');}-/** What a change shows when it has no value or no baseline to compare. */-export interface BenchmarkChangeEmptyLabels {- /** Shown when no baseline is saved. Defaults to '—'. */- noBaseline?: string;- /** Shown when a baseline is saved but there is no value yet. Defaults to '—'. */- noValue?: string;-}--export function formatBenchmarkChange(- value: number | null,- baseline: number | null,- empty: BenchmarkChangeEmptyLabels = {},-): string {- if (baseline == null) {- return empty.noBaseline ?? '—';- }- if (value == null) {- return empty.noValue ?? '—';- }- if (baseline === 0) {- return value === 0 ? '0.0%' : 'new';- }- const percent = ((value - baseline) / baseline) * 100;- return `${percent >= 0 ? '+' : ''}${percent.toFixed(1)}%`;-}-export function nextStreamOffset(sourceLength: number,currentOffset: number,diff --git a/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/page.tsx b/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/page.tsxindex 5fb50e341d..37f5022688 100644--- a/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/page.tsx+++ b/apps/sandbox/src/app/(fullscreen)/pages/markdown-perf/page.tsx@@ -23,11 +23,12 @@ import {} from '@astryxdesign/core/SegmentedControl';import {HStack, VStack} from '@astryxdesign/core/Stack';import {Heading, Text} from '@astryxdesign/core/Text';+import {generateMarkdownFixture, nextStreamOffset} from './benchmark';import {formatBenchmarkChange,- generateMarkdownFixture,- nextStreamOffset,-} from './benchmark';+ formatCount,+ formatDuration,+} from '../perfReadings';import {getMarkdownBenchmarkPlugins,getMarkdownBenchmarkProfile,@@ -60,14 +61,6 @@ const BURST_OPTIONS = ['64', '256', '1024'];const SETTLE_DELAY_MS = 180;const BURST_INTERVAL_MS = 80;-function formatDuration(value: number | null): string {- return value == null ? '—' : `${value.toFixed(1)} ms`;-}--function formatCount(value: number | null): string {- return value == null ? '—' : value.toLocaleString();-}-function formatFrameCounts(frames: number | null,droppedFrames: number | null,diff --git a/apps/sandbox/src/app/(fullscreen)/pages/perfReadings.test.ts b/apps/sandbox/src/app/(fullscreen)/pages/perfReadings.test.tsnew file mode 100644index 0000000000..4635b059ff--- /dev/null+++ b/apps/sandbox/src/app/(fullscreen)/pages/perfReadings.test.ts@@ -0,0 +1,64 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, describe, expect, it, vi} from 'vitest';+import {+ formatBenchmarkChange,+ formatCount,+ formatDuration,+ watchLongTasks,+} from './perfReadings';++describe('formatDuration and formatCount', () => {+ it('show a dash for no reading', () => {+ expect(formatDuration(null)).toBe('—');+ expect(formatCount(null)).toBe('—');+ });++ it('show a duration to one decimal place and a grouped count', () => {+ expect(formatDuration(12.345)).toBe('12.3 ms');+ expect(formatCount(1234)).toBe((1234).toLocaleString());+ });+});++describe('formatBenchmarkChange', () => {+ it('formats missing, zero, positive, and negative baseline changes', () => {+ expect(formatBenchmarkChange(null, 10)).toBe('—');+ expect(formatBenchmarkChange(10, null)).toBe('—');+ expect(formatBenchmarkChange(0, 0)).toBe('0.0%');+ expect(formatBenchmarkChange(1, 0)).toBe('new');+ expect(formatBenchmarkChange(110, 100)).toBe('+10.0%');+ expect(formatBenchmarkChange(90, 100)).toBe('-10.0%');+ });++ it('shows a caller-supplied empty label when there is no baseline or no value', () => {+ const labels = {noBaseline: 'no baseline', noValue: 'baseline saved'};+ expect(formatBenchmarkChange(10, null, labels)).toBe('no baseline');+ expect(formatBenchmarkChange(null, null, labels)).toBe('no baseline');+ expect(formatBenchmarkChange(null, 10, labels)).toBe('baseline saved');+ expect(formatBenchmarkChange(12, 10, labels)).toBe('+20.0%');+ });+});++describe('watchLongTasks', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('reads no value when the browser has no Long Tasks API', () => {+ vi.stubGlobal('PerformanceObserver', undefined);+ expect(watchLongTasks()()).toBeNull();+ });++ it('counts the long tasks it observed until stopped', () => {+ class FakeObserver {+ static supportedEntryTypes = ['longtask'];+ observe() {}+ disconnect() {}+ takeRecords() {+ return [{duration: 60}, {duration: 90}];+ }+ }+ vi.stubGlobal('PerformanceObserver', FakeObserver);+ expect(watchLongTasks()()).toEqual({count: 2, totalMs: 150});+ });+});diff --git a/apps/sandbox/src/app/(fullscreen)/pages/perfReadings.ts b/apps/sandbox/src/app/(fullscreen)/pages/perfReadings.tsnew file mode 100644index 0000000000..6014168bf3--- /dev/null+++ b/apps/sandbox/src/app/(fullscreen)/pages/perfReadings.ts@@ -0,0 +1,79 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file perfReadings.ts+ * @input Measured values, a saved baseline, and the browser's Long Tasks API+ * @output Duration, count and baseline-change text, and a long-task watcher+ * @position Shared readings for the Sandbox performance pages (Animated Layout+ * Perf, DiffViewer Perf, Markdown Perf), so they show one value the same way+ */++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();+}++/** What a change shows when it has no value or no baseline to compare. */+export interface BenchmarkChangeEmptyLabels {+ /** Shown when no baseline is saved. Defaults to '—'. */+ noBaseline?: string;+ /** Shown when a baseline is saved but there is no value yet. Defaults to '—'. */+ noValue?: string;+}++export function formatBenchmarkChange(+ value: number | null,+ baseline: number | null,+ empty: BenchmarkChangeEmptyLabels = {},+): string {+ if (baseline == null) {+ return empty.noBaseline ?? '—';+ }+ if (value == null) {+ return empty.noValue ?? '—';+ }+ if (baseline === 0) {+ return value === 0 ? '0.0%' : 'new';+ }+ const percent = ((value - baseline) / baseline) * 100;+ return `${percent >= 0 ? '+' : ''}${percent.toFixed(1)}%`;+}++export 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 a page shows no+ * reading rather than a misleading zero.+ */+export 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),+ };+ };+}