Skip to content

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

TypeScript

chore(sandbox): fixed real-Chromium perf scenes and a driver that measures them (#9194)

Cindy Zhang0bd3b3799334
diff --git a/apps/sandbox/perf/measure.ts b/apps/sandbox/perf/measure.ts
new file mode 100644
index 0000000000..96b2b73270
--- /dev/null
+++ b/apps/sandbox/perf/measure.ts
@@ -0,0 +1,146 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file measure.ts
+ * @input A Playwright `Page` on the perf scenes page (Chromium)
+ * @output `measureScene`: one sample of a scene's mount, interaction and
+ * unmount, as the numbers one sample records
+ * @position Driver support for scenes.perf.spec.ts. Rendering counts and long
+ * tasks come from the interaction harness's Chromium trace
+ * (`traceRendering`); heap and listener counts from the DevTools protocol
+ * after a forced garbage collection; interaction latency from the page's
+ * own Event Timing entries, the measurement behind INP.
+ */
+
+import type {CDPSession, Page} from '@playwright/test';
+import {
+ frames,
+ releaseAnimationLog,
+ traceRendering,
+} from '../../../internal/interaction-harness/src/index';
+
+/** One sample of a scene. Every metric is better when lower. */
+export interface SceneSample {
+ /** Total time of the main-thread tasks over 50 ms while the scene mounted. */
+ mountLongTaskMs: number;
+ /** Layouts the main thread ran while the scene mounted. */
+ mountLayouts: number;
+ /** Layouts the main thread ran during the scene's interaction. */
+ interactionLayouts: number;
+ /**
+ * The slowest interaction's input-to-next-paint time (Event Timing
+ * `duration`, 8 ms granularity). 0 when every interaction presented within
+ * 16 ms, the shortest duration the browser reports.
+ */
+ interactionMs: number;
+ /** JS heap after unmount minus before mount, KB, both after collection, on a warm cycle. */
+ heapDeltaKb: number;
+ /** Event listeners after unmount minus before mount. */
+ listenerDelta: number;
+}
+
+/**
+ * Records the page's interactions (Event Timing entries that carry an
+ * interaction id) from its first script on. Installed before navigation.
+ */
+export const EVENT_TIMING_LOG = `(() => {
+ window.__perfInteractions = [];
+ new PerformanceObserver(list => {
+ for (const entry of list.getEntries()) {
+ if (entry.interactionId > 0) window.__perfInteractions.push(entry.duration);
+ }
+ }).observe({type: 'event', durationThreshold: 16, buffered: true});
+})();`;
+
+async function takeInteractions(page: Page): Promise<number[]> {
+ // Entries are queued after the frame that presented them.
+ await frames(page, 3);
+ return page.evaluate(() => {
+ const log = (window as unknown as {__perfInteractions: number[]})
+ .__perfInteractions;
+ return log.splice(0, log.length);
+ });
+}
+
+async function collectedCounts(
+ page: Page,
+ cdp: CDPSession,
+): Promise<{heapBytes: number; listeners: number}> {
+ // The harness's own animation log (filled by waitForRest) keeps the
+ // animations and elements it saw; a count must not include them.
+ await releaseAnimationLog(page);
+ // Two passes: the first can leave objects a finalizer only just released.
+ await cdp.send('HeapProfiler.collectGarbage');
+ await cdp.send('HeapProfiler.collectGarbage');
+ const {metrics} = await cdp.send('Performance.getMetrics');
+ const heap = metrics.find(metric => metric.name === 'JSHeapUsedSize');
+ const counters = await cdp.send('Memory.getDOMCounters');
+ if (heap == null) {
+ throw new Error('Performance.getMetrics reported no JSHeapUsedSize');
+ }
+ return {heapBytes: heap.value, listeners: counters.jsEventListeners};
+}
+
+async function mount(page: Page): Promise<void> {
+ await page.getByRole('button', {name: 'Mount scene', exact: true}).click();
+ await page
+ .locator('html[data-perf-scene="ready"]')
+ .waitFor({state: 'attached'});
+ await frames(page, 2);
+}
+
+async function unmount(page: Page): Promise<void> {
+ await page.getByRole('button', {name: 'Unmount scene', exact: true}).click();
+ await page.locator('html[data-perf-scene]').waitFor({state: 'detached'});
+ await frames(page, 2);
+}
+
+/**
+ * Plays one unmeasured mount, `interact` and unmount, then measures a second
+ * one in the same page and returns that sample. The first cycle pays for
+ * loading and compiling the scene's code and for caches that live past an
+ * unmount, so the sample is a warm mount, and its heap and listener deltas
+ * are what one more cycle leaves behind. The page must be freshly loaded on
+ * `?scene=<id>`.
+ */
+export async function measureScene(
+ page: Page,
+ interact: (page: Page) => Promise<void>,
+): Promise<SceneSample> {
+ await mount(page);
+ await interact(page);
+ await unmount(page);
+
+ const cdp = await page.context().newCDPSession(page);
+ await cdp.send('Performance.enable');
+ try {
+ const before = await collectedCounts(page, cdp);
+
+ const mounted = await traceRendering(page, () => mount(page));
+ // The warm-up's and the mount click's entries are not the interaction's.
+ await takeInteractions(page);
+
+ const interaction = await traceRendering(page, () => interact(page));
+ const durations = await takeInteractions(page);
+
+ await unmount(page);
+ const after = await collectedCounts(page, cdp);
+
+ return {
+ mountLongTaskMs: round(
+ mounted.longTasks.reduce((sum, task) => sum + task.durationMs, 0),
+ ),
+ mountLayouts: mounted.layout,
+ interactionLayouts: interaction.layout,
+ interactionMs: Math.max(0, ...durations),
+ heapDeltaKb: round((after.heapBytes - before.heapBytes) / 1024),
+ listenerDelta: after.listeners - before.listeners,
+ };
+ } finally {
+ await cdp.detach().catch(() => {});
+ }
+}
+
+function round(value: number): number {
+ return Math.round(value * 10) / 10;
+}
diff --git a/apps/sandbox/perf/scenes.perf.spec.ts b/apps/sandbox/perf/scenes.perf.spec.ts
new file mode 100644
index 0000000000..5b9213a42a
--- /dev/null
+++ b/apps/sandbox/perf/scenes.perf.spec.ts
@@ -0,0 +1,174 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file scenes.perf.spec.ts
+ * @input The built Sandbox's perf scenes page (apps/sandbox/out, served here
+ * by the accessibility harness's static server), PERF_SAMPLES (default 5),
+ * PERF_RESULTS_DIR (default test-results/perf)
+ * @output One JSON file per scene: every sample and the per-metric median
+ * @position The perf scenes' measurement driver. Run locally with
+ * `pnpm build && pnpm -F @astryxdesign/sandbox build` then
+ * `pnpm exec playwright test --config playwright.perf.config.ts`.
+ *
+ * Each sample loads the scene in a fresh browser context, so no sample
+ * inherits another's heap, caches or listeners, and inside that context plays
+ * one unmeasured cycle before the measured one (measure.ts): the numbers are a
+ * warm mount and what one more cycle leaves behind.
+ *
+ * SYNC: Scenes come from apps/sandbox/src/app/(raw)/pages/perf-scenes/sceneIds.ts.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {expect, test, type Page} from '@playwright/test';
+import {
+ serveStatic,
+ type StaticServer,
+} from '../../../internal/a11y-spec/src/storybook';
+import {
+ frames,
+ waitForRest,
+} from '../../../internal/interaction-harness/src/index';
+import {
+ PERF_SCENES,
+ type PerfSceneId,
+} from '../src/app/(raw)/pages/perf-scenes/sceneIds';
+import {EVENT_TIMING_LOG, measureScene, type SceneSample} from './measure';
+
+const SAMPLES = positiveInteger('PERF_SAMPLES', 5);
+const RESULTS_DIR = path.resolve(
+ process.env.PERF_RESULTS_DIR ?? 'test-results/perf',
+);
+const OVERLAY_CYCLES = 50;
+const SANDBOX_DIR = 'apps/sandbox/out';
+
+let server: StaticServer | undefined;
+test.beforeAll(async () => {
+ server = await serveStatic(SANDBOX_DIR, {
+ sentinel: 'pages/perf-scenes/index.html',
+ missing: root =>
+ `No built Sandbox with the perf scenes at ${root}. Run \`pnpm build && pnpm -F @astryxdesign/sandbox build\` first.`,
+ });
+});
+test.afterAll(async () => {
+ await server?.close();
+});
+
+function positiveInteger(name: string, fallback: number): number {
+ const raw = process.env[name];
+ const value = raw ? Number(raw) : fallback;
+ if (!Number.isInteger(value) || value < 1) {
+ throw new Error(`${name} must be a positive integer, got "${raw}"`);
+ }
+ return value;
+}
+
+/** Plays one open/close of an overlay with real input. */
+async function openAndClose(
+ page: Page,
+ trigger: string,
+ shown: ReturnType<Page['locator']>,
+): Promise<void> {
+ await page.getByRole('button', {name: trigger, exact: true}).click();
+ await shown.waitFor({state: 'visible'});
+ await page.keyboard.press('Escape');
+ await shown.waitFor({state: 'hidden'});
+}
+
+/** Each scene's interaction, played with real input after it mounted. */
+const INTERACTIONS: Readonly<
+ Record<PerfSceneId, (page: Page) => Promise<void>>
+> = {
+ // Narrow and widen the panel: every truncated row measures again.
+ 'comments-panel': async page => {
+ const resize = page.getByRole('button', {
+ name: 'Resize panel',
+ exact: true,
+ });
+ await resize.click();
+ await frames(page, 2);
+ await resize.click();
+ await frames(page, 2);
+ },
+ // Sort by name, then filter by typing two characters.
+ table: async page => {
+ await page.getByRole('button', {name: /^Name/}).first().click();
+ await frames(page, 2);
+ await page
+ .getByRole('textbox', {name: 'Filter by name', exact: true})
+ .pressSequentially('an', {delay: 50});
+ await frames(page, 2);
+ },
+ // Expand all 50 folders at once and let the layout glide come to rest.
+ 'tree-list': async page => {
+ await page.getByRole('button', {name: 'Expand all', exact: true}).click();
+ await waitForRest(page.getByRole('tree'));
+ },
+ // Append a section to the long document.
+ markdown: async page => {
+ await page
+ .getByRole('button', {name: 'Append section', exact: true})
+ .click();
+ await frames(page, 2);
+ },
+ // Open and close each overlay, OVERLAY_CYCLES times.
+ 'overlay-churn': async page => {
+ const popover = page.getByText('Popover content');
+ const menu = page.getByRole('menuitem', {name: 'Rename', exact: true});
+ const dialog = page.getByRole('dialog', {name: 'Perf dialog', exact: true});
+ for (let cycle = 0; cycle < OVERLAY_CYCLES; cycle++) {
+ await openAndClose(page, 'Open popover', popover);
+ await openAndClose(page, 'Open menu', menu);
+ await openAndClose(page, 'Open dialog', dialog);
+ }
+ },
+};
+
+function median(values: readonly number[]): number {
+ const sorted = [...values].sort((a, b) => a - b);
+ const middle = Math.floor(sorted.length / 2);
+ return sorted.length % 2 === 1
+ ? sorted[middle]
+ : (sorted[middle - 1] + sorted[middle]) / 2;
+}
+
+for (const scene of PERF_SCENES) {
+ test(scene, async ({browser}, testInfo) => {
+ const samples: SceneSample[] = [];
+ for (let run = 0; run < SAMPLES; run++) {
+ const context = await browser.newContext({
+ baseURL: server?.origin,
+ viewport: {width: 1280, height: 800},
+ });
+ try {
+ const page = await context.newPage();
+ await page.addInitScript(EVENT_TIMING_LOG);
+ await page.goto(`/pages/perf-scenes/?scene=${scene}`);
+ await page
+ .locator('html[data-perf-page="interactive"]')
+ .waitFor({state: 'attached'});
+ await page.evaluate(() => document.fonts.ready);
+ samples.push(await measureScene(page, INTERACTIONS[scene]));
+ } finally {
+ await context.close();
+ }
+ }
+
+ const metrics = Object.keys(samples[0]) as (keyof SceneSample)[];
+ const result = {
+ scene,
+ samples,
+ median: Object.fromEntries(
+ metrics.map(metric => [
+ metric,
+ median(samples.map(sample => sample[metric])),
+ ]),
+ ),
+ };
+ fs.mkdirSync(RESULTS_DIR, {recursive: true});
+ const file = path.join(RESULTS_DIR, `${scene}.json`);
+ fs.writeFileSync(file, `${JSON.stringify(result, null, 2)}\n`);
+ await testInfo.attach(`${scene}.json`, {path: file});
+ expect(samples).toHaveLength(SAMPLES);
+ });
+}
diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json
index 09bb9b00dc..2ba661f602 100644
--- a/apps/sandbox/scripts/next-export-routes.json
+++ b/apps/sandbox/scripts/next-export-routes.json
@@ -45,6 +45,7 @@
"/pages/navigation/",
"/pages/neutral-palette/",
"/pages/palette-generator/",
+ "/pages/perf-scenes/",
"/pages/polymorphic-link/",
"/pages/shell-lab/",
"/pages/showcase-components/",
diff --git a/apps/sandbox/src/app/(raw)/pages/perf-scenes/page.tsx b/apps/sandbox/src/app/(raw)/pages/perf-scenes/page.tsx
new file mode 100644
index 0000000000..8187be5b50
--- /dev/null
+++ b/apps/sandbox/src/app/(raw)/pages/perf-scenes/page.tsx
@@ -0,0 +1,71 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file page.tsx
+ * @input `?scene=` (one of the ids in sceneIds.ts; the first by default)
+ * @output A bare page with Mount and Unmount buttons around one perf scene
+ * @position The page the perf driver drives in real Chromium
+ * (apps/sandbox/perf/). It is a raw page, with no sandbox chrome, so the
+ * measurements count only the scene. Also usable by hand: open a scene,
+ * record a DevTools performance profile, press Mount scene.
+ */
+
+import {Suspense, useEffect, useState} from 'react';
+import {useSearchParams} from 'react-router-dom';
+import {Button} from '@astryxdesign/core/Button';
+import {HStack, VStack} from '@astryxdesign/core/Layout';
+import {Link} from '@astryxdesign/core/Link';
+import {Heading, Text} from '@astryxdesign/core/Text';
+import {PerfScene} from './scenes';
+import {PERF_SCENE_LABELS, PERF_SCENES, parsePerfScene} from './sceneIds';
+
+function PerfScenes() {
+ const [searchParams] = useSearchParams();
+ const scene = parsePerfScene(searchParams.get('scene'));
+ const [isMounted, setIsMounted] = useState(false);
+ // The prerendered buttons exist before React owns them; the driver waits
+ // for this mark so its first click is never lost to hydration.
+ useEffect(() => {
+ document.documentElement.dataset.perfPage = 'interactive';
+ }, []);
+ return (
+ <VStack gap={4} padding={4}>
+ <VStack gap={1}>
+ <Heading level={1}>Perf scenes</Heading>
+ <Text color="secondary">{PERF_SCENE_LABELS[scene]}</Text>
+ <HStack gap={3}>
+ {PERF_SCENES.map(id => (
+ <Link key={id} href={`?scene=${id}`}>
+ {id}
+ </Link>
+ ))}
+ </HStack>
+ </VStack>
+ <HStack gap={2}>
+ <Button
+ label="Mount scene"
+ variant="primary"
+ isDisabled={isMounted}
+ onClick={() => setIsMounted(true)}
+ />
+ <Button
+ label="Unmount scene"
+ variant="secondary"
+ isDisabled={!isMounted}
+ onClick={() => setIsMounted(false)}
+ />
+ </HStack>
+ {isMounted ? <PerfScene scene={scene} /> : null}
+ </VStack>
+ );
+}
+
+export default function PerfScenesPage() {
+ return (
+ <Suspense>
+ <PerfScenes />
+ </Suspense>
+ );
+}
diff --git a/apps/sandbox/src/app/(raw)/pages/perf-scenes/sceneIds.ts b/apps/sandbox/src/app/(raw)/pages/perf-scenes/sceneIds.ts
new file mode 100644
index 0000000000..7c45e43a56
--- /dev/null
+++ b/apps/sandbox/src/app/(raw)/pages/perf-scenes/sceneIds.ts
@@ -0,0 +1,37 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file sceneIds.ts
+ * @input None
+ * @output The perf scene ids, their labels, and the parser for `?scene=`
+ * @position Shared by the perf scenes page and the perf driver
+ * (apps/sandbox/perf/), so both name the same scenes.
+ *
+ * SYNC: A new scene needs a component in scenes.tsx and an interaction in
+ * apps/sandbox/perf/scenes.perf.spec.ts.
+ */
+
+export const PERF_SCENES = [
+ 'comments-panel',
+ 'table',
+ 'tree-list',
+ 'markdown',
+ 'overlay-churn',
+] as const;
+
+export type PerfSceneId = (typeof PERF_SCENES)[number];
+
+export const PERF_SCENE_LABELS: Readonly<Record<PerfSceneId, string>> = {
+ 'comments-panel':
+ 'Comments panel: 40 rows of Avatar, truncated Text, Tooltip and a MoreMenu',
+ table: 'Table: 1,000 rows, sort and filter',
+ 'tree-list': 'TreeList: 500 items with animated layout, expand all',
+ markdown: 'Markdown: a long document with tables and code blocks',
+ 'overlay-churn': 'Overlay churn: Popover, DropdownMenu and Dialog',
+};
+
+export function parsePerfScene(value: string | null): PerfSceneId {
+ return (PERF_SCENES as readonly string[]).includes(value ?? '')
+ ? (value as PerfSceneId)
+ : PERF_SCENES[0];
+}
diff --git a/apps/sandbox/src/app/(raw)/pages/perf-scenes/scenes.tsx b/apps/sandbox/src/app/(raw)/pages/perf-scenes/scenes.tsx
new file mode 100644
index 0000000000..37e4713a32
--- /dev/null
+++ b/apps/sandbox/src/app/(raw)/pages/perf-scenes/scenes.tsx
@@ -0,0 +1,286 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file scenes.tsx
+ * @input A scene id
+ * @output The five perf scenes, each a deterministic composition of Core
+ * components that marks the document ready once it has committed
+ * @position The scenes the perf driver measures in Chromium
+ * (apps/sandbox/perf/scenes.perf.spec.ts). Each scene renders the same
+ * content on every run: fixtures come from seeded generators shared with
+ * the hand-run Table Lab and Markdown perf pages.
+ *
+ * The driver mounts a scene with the page's "Mount scene" button, waits for
+ * `html[data-perf-scene="ready"]`, plays the scene's interaction with real
+ * input, then unmounts it and checks what stayed behind.
+ */
+
+import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {Avatar} from '@astryxdesign/core/Avatar';
+import {Button} from '@astryxdesign/core/Button';
+import {Dialog, DialogHeader} from '@astryxdesign/core/Dialog';
+import {DropdownMenu} from '@astryxdesign/core/DropdownMenu';
+import {useAnimatedLayout} from '@astryxdesign/core/hooks';
+import {HStack, VStack} from '@astryxdesign/core/Layout';
+import {Markdown} from '@astryxdesign/core/Markdown';
+import {MoreMenu} from '@astryxdesign/core/MoreMenu';
+import {Popover} from '@astryxdesign/core/Popover';
+import {
+ Table,
+ useTableSortable,
+ useTableSortableState,
+} from '@astryxdesign/core/Table';
+import type {TableSortState} from '@astryxdesign/core/Table';
+import {Text} from '@astryxdesign/core/Text';
+import {TextInput} from '@astryxdesign/core/TextInput';
+import {Tooltip} from '@astryxdesign/core/Tooltip';
+import {TreeList} from '@astryxdesign/core/TreeList';
+import type {TreeListItemData} from '@astryxdesign/core/TreeList';
+import {generateMarkdownFixture} from '../../../(fullscreen)/pages/markdown-perf/benchmark';
+import {
+ generateRows,
+ labColumns,
+ type LabRow,
+} from '../../../(sandbox)/pages/table-lab/tableLabData';
+import type {PerfSceneId} from './sceneIds';
+
+const styles = stylex.create({
+ panelWide: {inlineSize: 560},
+ panelNarrow: {inlineSize: 320},
+ commentBody: {flexGrow: 1, minInlineSize: 0},
+ tableFrame: {blockSize: 560},
+ treeFrame: {maxInlineSize: 480},
+});
+
+/**
+ * Marks the document while the scene is mounted. A parent's effects run
+ * after its children's, so the mark lands once the whole scene committed.
+ */
+function useSceneReady(): void {
+ useEffect(() => {
+ document.documentElement.dataset.perfScene = 'ready';
+ return () => {
+ delete document.documentElement.dataset.perfScene;
+ };
+ }, []);
+}
+
+// ---------------------------------------------------------------------------
+// Comments panel
+// ---------------------------------------------------------------------------
+
+const AUTHORS = ['Ava Chen', 'Liam Okafor', 'Noah Silva', 'Emma Novak'];
+const SENTENCE =
+ 'The rollout looks healthy on the canary, but the retry budget on the read path is close to its limit and the dashboard still reads from the old table, so a second pass before Friday would help.';
+
+const COMMENTS = Array.from({length: 40}, (_, index) => ({
+ id: `comment-${index}`,
+ author: AUTHORS[index % AUTHORS.length],
+ // Every third comment is short, so rows mix truncated and untruncated text.
+ body:
+ index % 3 === 0
+ ? `Looks good, ship it (${index + 1}).`
+ : `${SENTENCE} (${index + 1}) ${SENTENCE}`,
+ date: `October ${(index % 28) + 1}, 2026 at ${(index % 12) + 1}:05 PM`,
+ ago: `${(index % 23) + 1}h`,
+}));
+
+const COMMENT_ACTIONS = [
+ {label: 'Reply'},
+ {label: 'Copy link'},
+ {label: 'Delete', variant: 'destructive' as const},
+];
+
+function CommentsPanelScene() {
+ useSceneReady();
+ const [isNarrow, setIsNarrow] = useState(false);
+ return (
+ <VStack gap={3}>
+ <HStack gap={2}>
+ <Button
+ label="Resize panel"
+ variant="secondary"
+ onClick={() => setIsNarrow(narrow => !narrow)}
+ />
+ </HStack>
+ <VStack gap={3} xstyle={isNarrow ? styles.panelNarrow : styles.panelWide}>
+ {COMMENTS.map(comment => (
+ <HStack key={comment.id} gap={2} vAlign="start">
+ <Avatar name={comment.author} size="sm" />
+ <VStack gap={0.5} xstyle={styles.commentBody}>
+ <HStack gap={2}>
+ <Text weight="semibold" maxLines={1}>
+ {comment.author}
+ </Text>
+ <Tooltip content={comment.date}>
+ <Text type="supporting">{comment.ago}</Text>
+ </Tooltip>
+ </HStack>
+ <Text maxLines={2}>{comment.body}</Text>
+ </VStack>
+ <MoreMenu
+ label="Comment actions"
+ size="sm"
+ items={COMMENT_ACTIONS}
+ />
+ </HStack>
+ ))}
+ </VStack>
+ </VStack>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Table
+// ---------------------------------------------------------------------------
+
+const TABLE_ROWS = generateRows(1000);
+
+function TableScene() {
+ useSceneReady();
+ const [query, setQuery] = useState('');
+ const [sort, setSort] = useState<TableSortState>([]);
+ const filtered = useMemo(() => {
+ const needle = query.trim().toLowerCase();
+ return needle === ''
+ ? TABLE_ROWS
+ : TABLE_ROWS.filter(row => row.name.toLowerCase().includes(needle));
+ }, [query]);
+ const {sortedData, sortConfig} = useTableSortableState<LabRow>({
+ data: filtered,
+ sort,
+ onSortChange: setSort,
+ });
+ const sortPlugin = useTableSortable<LabRow>(sortConfig);
+ return (
+ <VStack gap={3}>
+ <TextInput label="Filter by name" value={query} onChange={setQuery} />
+ <VStack xstyle={styles.tableFrame}>
+ <Table
+ data={sortedData}
+ columns={labColumns}
+ idKey="id"
+ plugins={{sort: sortPlugin}}
+ />
+ </VStack>
+ </VStack>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// TreeList
+// ---------------------------------------------------------------------------
+
+/** 50 folders of 9 files: 500 items. */
+function treeItems(isExpanded: boolean): TreeListItemData[] {
+ return Array.from({length: 50}, (_, folder) => ({
+ id: `folder-${folder}`,
+ label: `Folder ${folder + 1}`,
+ isExpanded,
+ children: Array.from({length: 9}, (_, file) => ({
+ id: `folder-${folder}-file-${file}`,
+ label: `file-${folder + 1}-${file + 1}.tsx`,
+ description: file % 3 === 0 ? 'Modified' : undefined,
+ })),
+ }));
+}
+
+function TreeListScene() {
+ useSceneReady();
+ const containerRef = useRef<HTMLDivElement>(null);
+ const animatedLayout = useAnimatedLayout({containerRef});
+ const [isExpanded, setIsExpanded] = useState(false);
+ const items = useMemo(() => treeItems(isExpanded), [isExpanded]);
+ return (
+ <VStack gap={3}>
+ <HStack gap={2}>
+ <Button
+ label={isExpanded ? 'Collapse all' : 'Expand all'}
+ variant="secondary"
+ onClick={() => setIsExpanded(expanded => !expanded)}
+ />
+ </HStack>
+ <div ref={containerRef}>
+ <TreeList
+ items={items}
+ animatedLayout={animatedLayout}
+ header={<Text weight="semibold">Repository</Text>}
+ xstyle={styles.treeFrame}
+ />
+ </div>
+ </VStack>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Markdown
+// ---------------------------------------------------------------------------
+
+const MARKDOWN_SECTIONS = 120;
+
+function MarkdownScene() {
+ useSceneReady();
+ const [sections, setSections] = useState(MARKDOWN_SECTIONS);
+ const source = useMemo(() => generateMarkdownFixture(sections), [sections]);
+ return (
+ <VStack gap={3}>
+ <HStack gap={2}>
+ <Button
+ label="Append section"
+ variant="secondary"
+ onClick={() => setSections(count => count + 1)}
+ />
+ </HStack>
+ <Markdown>{source}</Markdown>
+ </VStack>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Overlay churn
+// ---------------------------------------------------------------------------
+
+const MENU_ITEMS = [
+ {label: 'Rename'},
+ {label: 'Duplicate'},
+ {label: 'Archive'},
+];
+
+function OverlayChurnScene() {
+ useSceneReady();
+ const [isDialogOpen, setIsDialogOpen] = useState(false);
+ const closeDialog = useCallback((open: boolean) => setIsDialogOpen(open), []);
+ return (
+ <HStack gap={3}>
+ <Popover content={<Text>Popover content</Text>}>
+ <Button label="Open popover" variant="secondary" />
+ </Popover>
+ <DropdownMenu button={{label: 'Open menu'}} items={MENU_ITEMS} />
+ <Button
+ label="Open dialog"
+ variant="secondary"
+ onClick={() => setIsDialogOpen(true)}
+ />
+ <Dialog isOpen={isDialogOpen} onOpenChange={closeDialog}>
+ <DialogHeader title="Perf dialog" onOpenChange={closeDialog} />
+ <Text>Dialog content</Text>
+ </Dialog>
+ </HStack>
+ );
+}
+
+const SCENES: Readonly<Record<PerfSceneId, () => React.ReactNode>> = {
+ 'comments-panel': CommentsPanelScene,
+ table: TableScene,
+ 'tree-list': TreeListScene,
+ markdown: MarkdownScene,
+ 'overlay-churn': OverlayChurnScene,
+};
+
+export function PerfScene({scene}: {scene: PerfSceneId}) {
+ const Scene = SCENES[scene];
+ return <Scene />;
+}
diff --git a/apps/sandbox/src/app/sandboxPages.ts b/apps/sandbox/src/app/sandboxPages.ts
index 4c878d8c46..830fcff70d 100644
--- a/apps/sandbox/src/app/sandboxPages.ts
+++ b/apps/sandbox/src/app/sandboxPages.ts
@@ -257,6 +257,11 @@ export const categories: SandboxCategory[] = [
description:
'Render and scroll many files and lines; compare unified and split',
},
+ {
+ name: 'Perf Scenes',
+ href: '/pages/perf-scenes/',
+ description: 'Fixed performance scenes to mount and profile by hand',
+ },
{
name: 'Table Lab',
href: '/pages/table-lab/',
diff --git a/apps/sandbox/src/hydration-policy.ts b/apps/sandbox/src/hydration-policy.ts
index f7d52dc506..e90e7561bb 100644
--- a/apps/sandbox/src/hydration-policy.ts
+++ b/apps/sandbox/src/hydration-policy.ts
@@ -4,13 +4,20 @@
* @file Decide whether the default static HTML matches the incoming query.
* @input Route and URL search string.
* @output Whether React can safely hydrate instead of client-rendering.
- * @position Prevents mismatches for iframe themes and Shell Lab URL controls.
+ * @position Prevents mismatches for iframe themes and for pages whose first
+ * render reads URL controls (Shell Lab, Perf Scenes).
*/
+/** Pages whose first render reads the query string. */
+const QUERY_RENDERED_PAGES = new Set([
+ '/pages/shell-lab/',
+ '/pages/perf-scenes/',
+]);
+
export function canHydrate(route: string | undefined, search: string): boolean {
const params = new URLSearchParams(search);
return (
params.get('embed') !== '1' &&
- !(route === '/pages/shell-lab/' && search.length > 0)
+ !(route != null && QUERY_RENDERED_PAGES.has(route) && search.length > 0)
);
}
diff --git a/apps/sandbox/src/route-manifest.test.ts b/apps/sandbox/src/route-manifest.test.ts
index 456f70bc2c..22c9fd2f44 100644
--- a/apps/sandbox/src/route-manifest.test.ts
+++ b/apps/sandbox/src/route-manifest.test.ts
@@ -107,6 +107,8 @@ describe('Sandbox static export contract', () => {
);
expect(canHydrate('/pages/component-scores/', '?filter=all')).toBe(true);
expect(canHydrate('/pages/shell-lab/', '')).toBe(true);
+ expect(canHydrate('/pages/perf-scenes/', '?scene=table')).toBe(false);
+ expect(canHydrate('/pages/perf-scenes/', '')).toBe(true);
});
it('does not turn unknown URLs, dynamic segments or traversal into a 200 fallback', () => {
diff --git a/internal/a11y-spec/src/storybook.ts b/internal/a11y-spec/src/storybook.ts
index 070469d576..0f8bc128c6 100644
--- a/internal/a11y-spec/src/storybook.ts
+++ b/internal/a11y-spec/src/storybook.ts
@@ -4,7 +4,8 @@
* @file storybook.ts
* @input Uses node:http, node:fs, node:path
* @output `serveStorybook` — a read-only static server over a built Storybook,
- * for the Chromium lane to drive stories from.
+ * for the Chromium lane to drive stories from — and `serveStatic`, the same
+ * server over any built site (the Sandbox, for the perf scenes).
* @position Binding infrastructure for the Playwright specs. Not part of the
* contract: it decides nothing about accessibility, it just puts checked-in
* stories in front of a real browser.
@@ -33,12 +34,13 @@ const CONTENT_TYPES: Readonly<Record<string, string>> = {
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
+ '.webp': 'image/webp',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
};
export interface StaticServer {
- /** Origin to fetch stories from, e.g. `http://127.0.0.1:53312`. */
+ /** Origin to fetch from, e.g. `http://127.0.0.1:53312`. */
readonly origin: string;
close(): Promise<void>;
}
@@ -46,23 +48,50 @@ export interface StaticServer {
export async function serveStorybook(
directory = DEFAULT_STORYBOOK_DIR,
): Promise<StaticServer> {
- const root = path.resolve(directory);
- if (!fs.existsSync(path.join(root, 'iframe.html'))) {
- throw new Error(
+ return serveStatic(directory, {
+ sentinel: 'iframe.html',
+ missing: root =>
`No built Storybook at ${root}. Run \`pnpm storybook:build\` first, or point ASTRYX_STORYBOOK_DIR at a build.`,
- );
+ });
+}
+
+export interface ServeStaticOptions {
+ /** A file the build always has; its absence means there is no build. */
+ readonly sentinel: string;
+ /** The error message when the sentinel is missing. */
+ readonly missing: (root: string) => string;
+}
+
+/**
+ * Serves a built site read-only on a free local port. A directory serves its
+ * `index.html`, so trailing-slash routes resolve as a static host serves them.
+ */
+export async function serveStatic(
+ directory: string,
+ {sentinel, missing}: ServeStaticOptions,
+): Promise<StaticServer> {
+ const root = path.resolve(directory);
+ if (!fs.existsSync(path.join(root, sentinel))) {
+ throw new Error(missing(root));
}
const server = http.createServer((request, response) => {
const requested = (request.url ?? '/').split('?')[0] ?? '/';
- const resolved = path.resolve(
+ let resolved = path.resolve(
root,
`.${requested === '/' ? '/index.html' : requested}`,
);
- // Never serve outside the built Storybook, whatever the URL asks for.
+ // Never serve outside the build, whatever the URL asks for.
// The separator matters: a bare prefix test would also admit a sibling
// directory whose name merely starts with the root's.
const inside = resolved === root || resolved.startsWith(root + path.sep);
+ if (
+ inside &&
+ fs.existsSync(resolved) &&
+ fs.statSync(resolved).isDirectory()
+ ) {
+ resolved = path.join(resolved, 'index.html');
+ }
if (!inside || !fs.existsSync(resolved)) {
response.writeHead(404).end('not found');
return;
@@ -79,7 +108,7 @@ export async function serveStorybook(
});
const address = server.address();
if (address == null || typeof address === 'string') {
- throw new Error('the Storybook server did not report a port');
+ throw new Error('the static server did not report a port');
}
return {
diff --git a/internal/interaction-harness/README.md b/internal/interaction-harness/README.md
index 55b96ea248..6a170a793b 100644
--- a/internal/interaction-harness/README.md
+++ b/internal/interaction-harness/README.md
@@ -50,7 +50,7 @@ committed: a pull request links or attaches it.
| `busy.ts` | `blockMainThread(page, ms)` and `busyWindowProof(tracked, window)`: frames presented, frames that moved, longest stall, a verdict; `presented` adds the compositor's own frames. |
| `webInput.ts` | `webInputDriver(page)`: `wheel({x, y, dx, dy, ctrl})` and `pen(points)` as real engine input, for proofs across pointers (`spec:AST-100` FR4); `wheel` resolves once the page has the step; read back through the input log. |
| `trace.ts` | `traceRendering(page, body)`: main-thread counts of UpdateLayoutTree / Layout / PrePaint / Paint / Layerize / UpdateLayer / ScrollLayer / HitTest, `countBetween`, long tasks; `installLongTaskLog` / `readLongTasks`; `startCompositorTrace`: when the compositor presents. |
-| `curves.ts` | `holdAnimations`, `seekAnimations`, `sampleCurve` (presented transform / opacity at any t), `waitForAnimation`, `watchAnimations`, `waitForRest`, `releaseAnimations`. |
+| `curves.ts` | `holdAnimations`, `seekAnimations`, `sampleCurve` (presented transform / opacity at any t), `waitForAnimation`, `watchAnimations`, `waitForRest`, `releaseAnimations`, `releaseAnimationLog` (frees what the recorder kept, before a heap or listener count). |
| `math.ts` | Oracles independent of the code under test: `cubicBezier`, `timingFunction`, `springStep` (SwiftUI response / dampingFraction, initial velocity), `projectDecay`, `rubberBand`, `parseTransform`, `compareCurve`, `timeline`. |
| `storyboard.ts` | `animationStoryboard` (seek to t = 0, 16.7, 33.3 … ms), `touchStoryboard` (a frame per scripted event): PNG contact sheet + JSON trace. |
| `output.ts` | `evidenceDir`, `writeEvidence`: where evidence goes and how it is attached to the report. |
diff --git a/internal/interaction-harness/src/curves.ts b/internal/interaction-harness/src/curves.ts
index 18ef2a80c3..486d214dcf 100644
--- a/internal/interaction-harness/src/curves.ts
+++ b/internal/interaction-harness/src/curves.ts
@@ -201,6 +201,12 @@ function animationRecorder(): void {
return armedAt;
},
armedAt: () => armedAt,
+ // Drops every animation the log holds, with the elements and ancestors
+ // they keep alive; later waits record afresh.
+ release: () => {
+ log.length = 0;
+ unstarted = [];
+ },
};
}
@@ -1135,6 +1141,20 @@ export async function waitForAnimation(
}
}
+/**
+ * Empties the page's animation log, so a count taken next (heap size, event
+ * listeners, DOM nodes) reads the page's own objects and not the animations,
+ * elements and ancestors the recorder kept. Waits after it record afresh; a
+ * page the recorder never ran on is left alone.
+ */
+export async function releaseAnimationLog(page: Page): Promise<void> {
+ await page.evaluate(() =>
+ (
+ window as unknown as {__harnessAnimations?: {release: () => void}}
+ ).__harnessAnimations?.release(),
+ );
+}
+
/** Marks now as the point later waits count animations from. */
async function armRecorder(page: Page): Promise<number> {
return page.evaluate(() =>
diff --git a/internal/interaction-harness/src/harness.interaction.browser.spec.ts b/internal/interaction-harness/src/harness.interaction.browser.spec.ts
index 4ab55078bc..e777db1082 100644
--- a/internal/interaction-harness/src/harness.interaction.browser.spec.ts
+++ b/internal/interaction-harness/src/harness.interaction.browser.spec.ts
@@ -80,6 +80,7 @@ import {
traceRendering,
trackMarker,
waitForAnimation,
+ releaseAnimationLog,
waitForRest,
watchAnimations,
webInputDriver,
@@ -2407,6 +2408,53 @@ test.describe('holding', () => {
});
test.describe('animation state', () => {
+ test("releaseAnimationLog frees what the recorder kept, so a count after it reads the page's own objects", async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'forcing a garbage collection needs the DevTools protocol',
+ );
+ await fixture(page);
+ await page.evaluate(() => {
+ const el = document.createElement('div');
+ el.id = 'released';
+ el.style.cssText = 'width:40px;height:40px;background:red';
+ document.body.append(el);
+ });
+ const released = page.locator('#released');
+ await released.evaluate(el => {
+ (el as HTMLElement).style.transition = 'transform 60ms linear';
+ void (el as HTMLElement).offsetWidth;
+ (el as HTMLElement).style.transform = 'translateX(40px)';
+ });
+ await waitForAnimation(released);
+ await waitForRest(released);
+ // The page drops the element; only the recorder's log still holds it.
+ await released.evaluate(el => {
+ (window as unknown as {__released: WeakRef<Element>}).__released =
+ new WeakRef(el);
+ el.remove();
+ });
+ const cdp = await page.context().newCDPSession(page);
+ const alive = async () => {
+ await cdp.send('HeapProfiler.collectGarbage');
+ await cdp.send('HeapProfiler.collectGarbage');
+ return page.evaluate(
+ () =>
+ (
+ window as unknown as {__released: WeakRef<Element>}
+ ).__released.deref() != null,
+ );
+ };
+ // The control: without the release, the log keeps the removed element.
+ expect(await alive()).toBe(true);
+ await releaseAnimationLog(page);
+ expect(await alive()).toBe(false);
+ await cdp.detach();
+ });
+
test('waitForAnimation reports a running transition and waitForRest resolves after it', async ({
page,
}) => {
diff --git a/playwright.perf.config.ts b/playwright.perf.config.ts
new file mode 100644
index 0000000000..a5df7c9b1d
--- /dev/null
+++ b/playwright.perf.config.ts
@@ -0,0 +1,37 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file playwright.perf.config.ts
+ * @input Uses @playwright/test; reads the built Sandbox in apps/sandbox/out
+ * @output The perf scenes, measured in desktop Chromium
+ * @position Run after
+ * `pnpm build && pnpm -F @astryxdesign/sandbox build`. Separate from
+ * playwright.config.ts (accessibility contracts) and
+ * playwright.interaction.config.ts (touch and animation proofs): a perf
+ * sample must not share the CPU with another browser, and its numbers are
+ * trend data, not pass/fail proofs.
+ *
+ * pnpm build && pnpm -F @astryxdesign/sandbox build
+ * pnpm exec playwright install chromium
+ * pnpm exec playwright test --config playwright.perf.config.ts
+ * pnpm exec playwright test --config playwright.perf.config.ts --grep table
+ */
+
+import {defineConfig, devices} from '@playwright/test';
+
+const isCI = (process.env.CI ?? '') !== '';
+
+export default defineConfig({
+ testDir: 'apps/sandbox/perf',
+ testMatch: '**/*.perf.spec.ts',
+ outputDir: 'test-results/perf-output',
+ // Timing data: one browser at a time.
+ workers: 1,
+ fullyParallel: false,
+ // A scene's samples run inside one test, each with a warm-up cycle; overlay
+ // churn plays 150 open/close pairs per cycle.
+ timeout: 6 * 60_000,
+ forbidOnly: isCI,
+ reporter: isCI ? [['list'], ['github']] : [['list']],
+ projects: [{name: 'chromium', use: {...devices['Desktop Chrome']}}],
+});