Skip to content

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

TypeScript

feat(sandbox): add Table Lab tool for plugin + perf testing (#3634)

Humberto Virtudes88d928125393
diff --git a/apps/sandbox/src/app/(sandbox)/pages/table-lab/page.tsx b/apps/sandbox/src/app/(sandbox)/pages/table-lab/page.tsx
new file mode 100644
index 0000000000..dd6fd224a1
--- /dev/null
+++ b/apps/sandbox/src/app/(sandbox)/pages/table-lab/page.tsx
@@ -0,0 +1,547 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file page.tsx
+ * @input None
+ * @output Table Lab — a tool to test any combination of Table plugins with
+ * live scroll-perf, FPS, dropped-frame, and re-render metrics.
+ * @position Sandbox tool page (/pages/table-lab)
+ *
+ * ADDING A NEW PLUGIN: add one entry to PLUGIN_ORDER + a colocated block in
+ * `useLabPlugins`. Everything else (toggle, perf, config panel) is generic.
+ */
+
+import {
+ useState,
+ useMemo,
+ useRef,
+ useCallback,
+ useEffect,
+ Profiler,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+
+import {VStack, HStack} from '@astryxdesign/core/Layout';
+import {Text, Heading} from '@astryxdesign/core/Text';
+import {Card} from '@astryxdesign/core/Card';
+import {Button} from '@astryxdesign/core/Button';
+import {Badge} from '@astryxdesign/core/Badge';
+import {Switch} from '@astryxdesign/core/Switch';
+import {Divider} from '@astryxdesign/core/Divider';
+import {
+ SegmentedControl,
+ SegmentedControlItem,
+} from '@astryxdesign/core/SegmentedControl';
+
+import {
+ Table,
+ useTableSelection,
+ useTableSelectionState,
+ useTableSortable,
+ useTableSortableState,
+ useTablePagination,
+ paginateData,
+ useTableColumnResize,
+ useTableStickyColumns,
+ useTableRowExpansion,
+ useTableRowExpansionState,
+} from '@astryxdesign/core/Table';
+import type {TablePlugin, TableSortState} from '@astryxdesign/core/Table';
+
+import {generateRows, labColumns, type LabRow} from './tableLabData';
+import {
+ usePerfMetrics,
+ type RenderStats,
+ type ScrollStats,
+} from './usePerfMetrics';
+
+// =============================================================================
+// Plugin registry — the single place that describes toggleable plugins.
+// To add a new one: add an id here + a block in useLabPlugins below.
+// =============================================================================
+
+type PluginId =
+ | 'selection'
+ | 'sortable'
+ | 'pagination'
+ | 'columnResize'
+ | 'stickyColumns'
+ | 'rowExpansion';
+
+interface PluginMeta {
+ id: PluginId;
+ label: string;
+ description: string;
+}
+
+const PLUGIN_REGISTRY: PluginMeta[] = [
+ {
+ id: 'selection',
+ label: 'Selection',
+ description: 'Row checkboxes + select-all',
+ },
+ {id: 'sortable', label: 'Sortable', description: 'Click headers to sort'},
+ {
+ id: 'pagination',
+ label: 'Pagination',
+ description: 'Paginate rows (page size 25)',
+ },
+ {
+ id: 'columnResize',
+ label: 'Column Resize',
+ description: 'Drag column edges to resize',
+ },
+ {
+ id: 'stickyColumns',
+ label: 'Sticky Columns',
+ description: 'Pin Name (start) + Joined (end)',
+ },
+ {
+ id: 'rowExpansion',
+ label: 'Row Expansion',
+ description: 'Expandable tree rows (grouped by team)',
+ },
+];
+
+// =============================================================================
+// Plugin wiring — every hook is called unconditionally (React rules); only the
+// enabled ones are added to the plugins map handed to <Table>.
+// =============================================================================
+
+interface UseLabPluginsArgs {
+ enabled: Record<PluginId, boolean>;
+ baseData: LabRow[];
+}
+
+interface UseLabPluginsResult {
+ data: LabRow[];
+ plugins: Record<string, TablePlugin<LabRow>>;
+ /** Summary chips for the active-plugin state (selected count, page, etc). */
+ summary: string[];
+}
+
+function useLabPlugins({
+ enabled,
+ baseData,
+}: UseLabPluginsArgs): UseLabPluginsResult {
+ const summary: string[] = [];
+
+ // --- selection ---
+ const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
+ const {selectionConfig} = useTableSelectionState<LabRow>({
+ data: baseData,
+ idKey: 'id',
+ selectedKeys,
+ setSelectedKeys,
+ });
+ const selectionPlugin = useTableSelection<LabRow>(selectionConfig);
+ if (enabled.selection) {
+ summary.push(`${selectedKeys.size} selected`);
+ }
+
+ // --- sortable ---
+ const [sort, setSort] = useState<TableSortState>([]);
+ const {sortedData, sortConfig} = useTableSortableState<LabRow>({
+ data: baseData,
+ sort,
+ onSortChange: setSort,
+ });
+ const sortPlugin = useTableSortable<LabRow>(sortConfig);
+ const dataAfterSort = enabled.sortable ? sortedData : baseData;
+ if (enabled.sortable && sort.length > 0) {
+ summary.push(
+ `sorted by ${sort[0].sortKey} ${sort[0].direction === 'ascending' ? '↑' : '↓'}`,
+ );
+ }
+
+ // --- pagination ---
+ const PAGE_SIZE = 25;
+ const [page, setPage] = useState(1);
+ const paginationPlugin = useTablePagination<LabRow>({
+ page,
+ onPageChange: setPage,
+ totalItems: dataAfterSort.length,
+ pageSize: PAGE_SIZE,
+ });
+ const dataAfterPage = enabled.pagination
+ ? paginateData(dataAfterSort, page, PAGE_SIZE)
+ : dataAfterSort;
+ if (enabled.pagination) {
+ const totalPages = Math.max(1, Math.ceil(dataAfterSort.length / PAGE_SIZE));
+ summary.push(`page ${page}/${totalPages}`);
+ }
+
+ // --- column resize ---
+ const columnResizePlugin = useTableColumnResize<LabRow>({});
+
+ // --- sticky columns ---
+ const stickyPlugin = useTableStickyColumns<LabRow>({
+ startKeys: ['name'],
+ endKeys: ['joined'],
+ });
+
+ // --- row expansion (flat rows; no real tree in the synthetic data) ---
+ const [expandedKeys, setExpandedKeys] = useState<Set<string>>(new Set());
+ const {expansionConfig} = useTableRowExpansionState<LabRow>({
+ baseData: dataAfterPage,
+ getChildren: () => [],
+ getRowKey: item => item.id,
+ expandedKeys,
+ setExpandedKeys,
+ });
+ const rowExpansionPlugin = useTableRowExpansion(expansionConfig);
+ if (enabled.rowExpansion) {
+ summary.push(`${expandedKeys.size} expanded`);
+ }
+
+ // Assemble enabled plugins in a stable order.
+ const plugins: Record<string, TablePlugin<LabRow>> = {};
+ if (enabled.sortable) {
+ plugins.sort = sortPlugin;
+ }
+ if (enabled.selection) {
+ plugins.selection = selectionPlugin;
+ }
+ if (enabled.rowExpansion) {
+ plugins.expansion = rowExpansionPlugin;
+ }
+ if (enabled.stickyColumns) {
+ plugins.sticky = stickyPlugin;
+ }
+ if (enabled.columnResize) {
+ plugins.resize = columnResizePlugin;
+ }
+ if (enabled.pagination) {
+ plugins.pagination = paginationPlugin;
+ }
+
+ return {data: dataAfterPage, plugins, summary};
+}
+
+// =============================================================================
+// Data-size presets
+// =============================================================================
+
+const SIZE_PRESETS = [
+ {value: '50', label: '50'},
+ {value: '500', label: '500'},
+ {value: '2000', label: '2k'},
+ {value: '10000', label: '10k'},
+];
+
+// =============================================================================
+// Metric HUD
+// =============================================================================
+
+function Metric({
+ label,
+ value,
+ tone,
+}: {
+ label: string;
+ value: string;
+ tone?: 'good' | 'warn' | 'bad';
+}) {
+ const color =
+ tone === 'good'
+ ? 'var(--color-text-green)'
+ : tone === 'warn'
+ ? 'var(--color-text-orange)'
+ : tone === 'bad'
+ ? 'var(--color-text-red)'
+ : 'var(--color-text-primary)';
+ return (
+ <VStack gap={4} {...stylex.props(styles.metric)}>
+ <Text type="supporting" color="secondary">
+ {label}
+ </Text>
+ <span
+ style={{
+ fontSize: 22,
+ fontWeight: 700,
+ fontVariantNumeric: 'tabular-nums',
+ color,
+ }}>
+ {value}
+ </span>
+ </VStack>
+ );
+}
+
+/**
+ * Isolated perf HUD. Reads live render stats from a ref via its own rAF ticker
+ * (throttled to ~10Hz) and renders in a sibling subtree of the profiled Table,
+ * so its updates never re-render — and therefore never re-profile — the Table.
+ * That's what prevents the Profiler setState → commit → onRender feedback loop.
+ */
+function PerfHud({
+ renderStatsRef,
+ scroll,
+ renderedRows,
+}: {
+ renderStatsRef: React.RefObject<RenderStats>;
+ scroll: ScrollStats;
+ renderedRows: number;
+}) {
+ const [display, setDisplay] = useState<RenderStats>({
+ count: 0,
+ lastMs: null,
+ totalMs: 0,
+ });
+
+ useEffect(() => {
+ let raf = 0;
+ let last = 0;
+ const tick = (now: number) => {
+ raf = requestAnimationFrame(tick);
+ if (now - last > 100) {
+ last = now;
+ const r = renderStatsRef.current;
+ setDisplay(prev =>
+ prev.count === r.count && prev.lastMs === r.lastMs
+ ? prev
+ : {count: r.count, lastMs: r.lastMs, totalMs: r.totalMs},
+ );
+ }
+ };
+ raf = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(raf);
+ }, [renderStatsRef]);
+
+ const fpsTone =
+ scroll.fps == null
+ ? undefined
+ : scroll.fps >= 55
+ ? 'good'
+ : scroll.fps >= 30
+ ? 'warn'
+ : 'bad';
+ const dropTone =
+ scroll.drops === 0 ? 'good' : scroll.drops < 5 ? 'warn' : 'bad';
+
+ return (
+ <Card>
+ <HStack gap={2} wrap="wrap" {...stylex.props(styles.hud)}>
+ <Metric
+ label="Scroll FPS"
+ value={scroll.fps == null ? '—' : String(scroll.fps)}
+ tone={fpsTone}
+ />
+ <Metric
+ label="Frame drops"
+ value={scroll.fps == null ? '—' : String(scroll.drops)}
+ tone={scroll.fps == null ? undefined : dropTone}
+ />
+ <Metric
+ label="Frames sampled"
+ value={scroll.frames ? String(scroll.frames) : '—'}
+ />
+ <Divider orientation="vertical" />
+ <Metric label="Renders" value={String(display.count)} />
+ <Metric
+ label="Last commit"
+ value={
+ display.lastMs == null ? '—' : `${display.lastMs.toFixed(1)}ms`
+ }
+ />
+ <Metric
+ label="Total commit"
+ value={display.totalMs ? `${display.totalMs.toFixed(0)}ms` : '—'}
+ />
+ <Divider orientation="vertical" />
+ <Metric label="Rendered rows" value={String(renderedRows)} />
+ </HStack>
+ </Card>
+ );
+}
+
+// =============================================================================
+// Page
+// =============================================================================
+
+export default function TableLabPage() {
+ const [rowCount, setRowCount] = useState(500);
+ const [enabled, setEnabled] = useState<Record<PluginId, boolean>>({
+ selection: false,
+ sortable: true,
+ pagination: false,
+ columnResize: false,
+ stickyColumns: false,
+ rowExpansion: false,
+ });
+
+ const baseData = useMemo(() => generateRows(rowCount), [rowCount]);
+ const {data, plugins, summary} = useLabPlugins({enabled, baseData});
+
+ const {
+ renderStatsRef,
+ onRender,
+ resetRenders,
+ scroll,
+ runScrollTest,
+ resetScroll,
+ } = usePerfMetrics();
+
+ const scrollWrapRef = useRef<HTMLDivElement>(null);
+ const getScrollContainer = useCallback(() => scrollWrapRef.current, []);
+
+ const togglePlugin = useCallback(
+ (id: PluginId, on: boolean) => {
+ setEnabled(prev => ({...prev, [id]: on}));
+ resetScroll();
+ },
+ [resetScroll],
+ );
+
+ const enabledCount = Object.values(enabled).filter(Boolean).length;
+
+ return (
+ <VStack gap={6} {...stylex.props(styles.root)}>
+ <VStack gap={4}>
+ <Heading level={2}>Table Lab</Heading>
+ <Text color="secondary">
+ Toggle any combination of Table plugins and measure scroll FPS,
+ dropped frames, and React re-renders on datasets up to 10k rows.
+ </Text>
+ </VStack>
+
+ {/* Controls */}
+ <Card>
+ <VStack gap={5} {...stylex.props(styles.controls)}>
+ <HStack gap={3} vAlign="center" justify="between" wrap="wrap">
+ <VStack gap={2}>
+ <Text type="supporting" color="secondary">
+ Rows
+ </Text>
+ <SegmentedControl
+ value={String(rowCount)}
+ onChange={v => {
+ setRowCount(Number(v));
+ resetRenders();
+ resetScroll();
+ }}
+ label="Row count">
+ {SIZE_PRESETS.map(p => (
+ <SegmentedControlItem
+ key={p.value}
+ value={p.value}
+ label={p.label}
+ />
+ ))}
+ </SegmentedControl>
+ </VStack>
+
+ <HStack gap={2} wrap="wrap">
+ <Button
+ variant="primary"
+ label={scroll.isScrolling ? 'Scrolling…' : 'Run scroll test'}
+ onClick={() => runScrollTest(getScrollContainer())}
+ isDisabled={scroll.isScrolling}
+ />
+ <Button
+ variant="secondary"
+ label="Reset renders"
+ onClick={resetRenders}
+ />
+ </HStack>
+ </HStack>
+
+ <Divider />
+
+ {/* Plugin toggles */}
+ <VStack gap={3}>
+ <HStack gap={2} vAlign="center">
+ <Text weight="medium">Plugins</Text>
+ <Badge variant="neutral" label={`${enabledCount} active`} />
+ </HStack>
+ <div {...stylex.props(styles.toggleGrid)}>
+ {PLUGIN_REGISTRY.map(p => (
+ <div key={p.id} {...stylex.props(styles.toggleCell)}>
+ <Switch
+ label={p.label}
+ description={p.description}
+ value={enabled[p.id]}
+ onChange={on => togglePlugin(p.id, on)}
+ />
+ </div>
+ ))}
+ </div>
+ </VStack>
+
+ {summary.length > 0 && (
+ <>
+ <Divider />
+ <HStack gap={2} wrap="wrap">
+ {summary.map(s => (
+ <Badge key={s} variant="neutral" label={s} />
+ ))}
+ </HStack>
+ </>
+ )}
+ </VStack>
+ </Card>
+
+ {/* Perf HUD — self-contained: reads render stats from a ref via its own
+ ticker so its updates never re-render (and re-profile) the Table. */}
+ <PerfHud
+ renderStatsRef={renderStatsRef}
+ scroll={scroll}
+ renderedRows={data.length}
+ />
+
+ {/* The Table under test */}
+ <Card>
+ <div ref={scrollWrapRef} {...stylex.props(styles.tableViewport)}>
+ <Profiler id="table-lab" onRender={onRender}>
+ <Table
+ data={data}
+ columns={labColumns}
+ idKey="id"
+ hasHover
+ isStriped
+ plugins={plugins}
+ />
+ </Profiler>
+ </div>
+ </Card>
+ </VStack>
+ );
+}
+
+const styles = stylex.create({
+ root: {
+ padding: 24,
+ maxWidth: 1200,
+ marginInline: 'auto',
+ width: '100%',
+ },
+ controls: {
+ padding: 16,
+ },
+ hud: {
+ padding: 16,
+ alignItems: 'center',
+ },
+ metric: {
+ minWidth: 90,
+ },
+ toggleGrid: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))',
+ gap: 12,
+ },
+ toggleCell: {
+ padding: 12,
+ borderRadius: 8,
+ backgroundColor: 'var(--color-background-muted)',
+ },
+ tableViewport: {
+ // Fixed-height scroll viewport so the scroll test has something to scroll.
+ height: 480,
+ overflowY: 'auto',
+ overflowX: 'auto',
+ position: 'relative',
+ },
+});
diff --git a/apps/sandbox/src/app/(sandbox)/pages/table-lab/tableLabData.ts b/apps/sandbox/src/app/(sandbox)/pages/table-lab/tableLabData.ts
new file mode 100644
index 0000000000..3491a7046a
--- /dev/null
+++ b/apps/sandbox/src/app/(sandbox)/pages/table-lab/tableLabData.ts
@@ -0,0 +1,143 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file tableLabData.ts
+ * @input Row count
+ * @output Deterministic synthetic dataset + column defs for the Table Lab
+ * @position Table Lab tool; generates stress-test data
+ */
+
+import type {TableColumn} from '@astryxdesign/core/Table';
+import {pixel, proportional} from '@astryxdesign/core/Table';
+
+export interface LabRow extends Record<string, unknown> {
+ id: string;
+ name: string;
+ email: string;
+ team: string;
+ role: string;
+ status: 'Active' | 'Away' | 'Offline';
+ commits: number;
+ reviews: number;
+ score: number;
+ joined: string;
+}
+
+const TEAMS = [
+ 'Core',
+ 'Infra',
+ 'Design',
+ 'Growth',
+ 'Data',
+ 'Mobile',
+ 'Web',
+ 'ML',
+];
+const ROLES = [
+ 'Engineer',
+ 'Senior Eng',
+ 'Staff Eng',
+ 'Manager',
+ 'Designer',
+ 'PM',
+];
+const STATUSES: LabRow['status'][] = ['Active', 'Away', 'Offline'];
+const FIRST = [
+ 'Ava',
+ 'Liam',
+ 'Noah',
+ 'Emma',
+ 'Kai',
+ 'Zoe',
+ 'Max',
+ 'Mia',
+ 'Leo',
+ 'Ivy',
+ 'Sam',
+ 'Ada',
+ 'Rio',
+ 'Ben',
+ 'Uma',
+];
+const LAST = [
+ 'Chen',
+ 'Park',
+ 'Silva',
+ 'Kim',
+ 'Ross',
+ 'Vega',
+ 'Nash',
+ 'Wolf',
+ 'Cole',
+ 'Dune',
+ 'Fox',
+ 'Hale',
+ 'Reed',
+ 'Vale',
+ 'Ono',
+];
+
+/** Small deterministic PRNG so re-renders keep stable data. */
+function mulberry32(seed: number): () => number {
+ let a = seed;
+ return () => {
+ a |= 0;
+ a = (a + 0x6d2b79f5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+export function generateRows(count: number): LabRow[] {
+ const rand = mulberry32(1337);
+ const rows: LabRow[] = [];
+ for (let i = 0; i < count; i++) {
+ const first = FIRST[Math.floor(rand() * FIRST.length)];
+ const last = LAST[Math.floor(rand() * LAST.length)];
+ const name = `${first} ${last}`;
+ rows.push({
+ id: `row-${i}`,
+ name,
+ email: `${first.toLowerCase()}.${last.toLowerCase()}${i}@astryx.dev`,
+ team: TEAMS[Math.floor(rand() * TEAMS.length)],
+ role: ROLES[Math.floor(rand() * ROLES.length)],
+ status: STATUSES[Math.floor(rand() * STATUSES.length)],
+ commits: Math.floor(rand() * 2000),
+ reviews: Math.floor(rand() * 500),
+ score: Math.round(rand() * 1000) / 10,
+ joined: `20${String(18 + Math.floor(rand() * 7)).padStart(2, '0')}-${String(1 + Math.floor(rand() * 12)).padStart(2, '0')}`,
+ });
+ }
+ return rows;
+}
+
+export const labColumns: TableColumn<LabRow>[] = [
+ {key: 'name', header: 'Name', width: proportional(2), sortable: true},
+ {key: 'email', header: 'Email', width: proportional(2), sortable: true},
+ {key: 'team', header: 'Team', width: pixel(110), sortable: true},
+ {key: 'role', header: 'Role', width: pixel(130), sortable: true},
+ {key: 'status', header: 'Status', width: pixel(110), sortable: true},
+ {
+ key: 'commits',
+ header: 'Commits',
+ width: pixel(100),
+ align: 'end',
+ sortable: true,
+ },
+ {
+ key: 'reviews',
+ header: 'Reviews',
+ width: pixel(100),
+ align: 'end',
+ sortable: true,
+ },
+ {
+ key: 'score',
+ header: 'Score',
+ width: pixel(90),
+ align: 'end',
+ sortable: true,
+ },
+ {key: 'joined', header: 'Joined', width: pixel(100), sortable: true},
+];
diff --git a/apps/sandbox/src/app/(sandbox)/pages/table-lab/usePerfMetrics.ts b/apps/sandbox/src/app/(sandbox)/pages/table-lab/usePerfMetrics.ts
new file mode 100644
index 0000000000..5d37ec07b0
--- /dev/null
+++ b/apps/sandbox/src/app/(sandbox)/pages/table-lab/usePerfMetrics.ts
@@ -0,0 +1,176 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file usePerfMetrics.ts
+ * @input React refs to a scrollable container
+ * @output Render stats (in a ref), scroll-test state, and an auto-scroll driver
+ * @position Table Lab tool; measures Table render + scroll performance
+ *
+ * CRITICAL: the React Profiler `onRender` callback must NEVER call setState.
+ * setState → commit → onRender → setState … is an infinite loop. So per-commit
+ * stats (render count, commit time) are written to a REF only. The <PerfHud>
+ * component reads that ref via its own rAF ticker and renders in isolation — it
+ * is a sibling of the profiled <Table>, so its updates never re-render (and
+ * therefore never re-profile) the table. Low-frequency scroll results (fired
+ * a couple of times per test) are plain state and safe.
+ */
+
+import {useCallback, useRef, useState} from 'react';
+
+export interface RenderStats {
+ /** Total React commits of the profiled subtree since last reset. */
+ count: number;
+ /** Duration (ms) of the most recent commit (Profiler actualDuration). */
+ lastMs: number | null;
+ /** Sum of all commit durations since last reset. */
+ totalMs: number;
+}
+
+export interface ScrollStats {
+ /** Measured FPS during the last scroll run. */
+ fps: number | null;
+ /** Frames that took > 20ms (dropped) during the last scroll run. */
+ drops: number;
+ /** Total frames sampled during the last scroll run. */
+ frames: number;
+ /** Whether a scroll test is currently running. */
+ isScrolling: boolean;
+}
+
+const EMPTY_SCROLL: ScrollStats = {
+ fps: null,
+ drops: 0,
+ frames: 0,
+ isScrolling: false,
+};
+
+export function usePerfMetrics() {
+ // Per-commit stats live in a ref (written by onRender, read by PerfHud's
+ // ticker). Never parent state — that would loop through the Profiler.
+ const renderStatsRef = useRef<RenderStats>({
+ count: 0,
+ lastMs: null,
+ totalMs: 0,
+ });
+
+ const onRender = useCallback(
+ (_id: string, _phase: string, actualDuration: number) => {
+ const r = renderStatsRef.current;
+ r.count += 1;
+ r.lastMs = actualDuration;
+ r.totalMs += actualDuration;
+ },
+ [],
+ );
+
+ const resetRenders = useCallback(() => {
+ renderStatsRef.current = {count: 0, lastMs: null, totalMs: 0};
+ }, []);
+
+ // Scroll results — low frequency (start + end of a test), safe as state.
+ const [scroll, setScroll] = useState<ScrollStats>(EMPTY_SCROLL);
+
+ const scrollState = useRef({
+ frames: 0,
+ drops: 0,
+ startTime: 0,
+ rafId: 0,
+ measuring: false,
+ lastFrameTime: 0,
+ });
+
+ const runScrollTest = useCallback(
+ (containerArg: HTMLElement | null, durationMs = 2400) => {
+ if (!containerArg) {
+ return;
+ }
+ const container: HTMLElement = containerArg;
+ const s = scrollState.current;
+ if (s.measuring) {
+ return;
+ }
+
+ const totalScroll = container.scrollHeight - container.clientHeight;
+ if (totalScroll <= 0) {
+ setScroll({...EMPTY_SCROLL});
+ return;
+ }
+
+ container.scrollTop = 0;
+ s.frames = 0;
+ s.drops = 0;
+ s.startTime = performance.now();
+ s.measuring = true;
+ s.lastFrameTime = performance.now();
+ setScroll(prev => ({...prev, isScrolling: true}));
+
+ function tick() {
+ if (!s.measuring) {
+ return;
+ }
+ const now = performance.now();
+ s.frames++;
+ if (now - s.lastFrameTime > 20) {
+ s.drops++;
+ }
+ s.lastFrameTime = now;
+ s.rafId = requestAnimationFrame(tick);
+ }
+ s.rafId = requestAnimationFrame(tick);
+
+ const start = performance.now();
+ const half = durationMs / 2;
+
+ function step() {
+ const elapsed = performance.now() - start;
+ // Down for the first half, back up for the second half.
+ let progress: number;
+ if (elapsed < half) {
+ const p = elapsed / half;
+ progress = 1 - Math.pow(1 - p, 3);
+ } else {
+ const p = Math.min((elapsed - half) / half, 1);
+ progress = 1 - (1 - Math.pow(1 - p, 3));
+ }
+ container.scrollTop = totalScroll * Math.max(0, Math.min(1, progress));
+
+ if (elapsed < durationMs) {
+ requestAnimationFrame(step);
+ } else {
+ requestAnimationFrame(() => {
+ s.measuring = false;
+ cancelAnimationFrame(s.rafId);
+ const totalElapsed = performance.now() - s.startTime;
+ const fps =
+ totalElapsed > 0 && s.frames > 0
+ ? Math.round((s.frames / totalElapsed) * 1000)
+ : null;
+ setScroll({
+ fps,
+ drops: s.drops,
+ frames: s.frames,
+ isScrolling: false,
+ });
+ });
+ }
+ }
+ requestAnimationFrame(step);
+ },
+ [],
+ );
+
+ const resetScroll = useCallback(() => {
+ setScroll({...EMPTY_SCROLL});
+ }, []);
+
+ return {
+ renderStatsRef,
+ onRender,
+ resetRenders,
+ scroll,
+ runScrollTest,
+ resetScroll,
+ };
+}
diff --git a/apps/sandbox/src/app/sandboxPages.ts b/apps/sandbox/src/app/sandboxPages.ts
index 12f1967106..fd7cc4684a 100644
--- a/apps/sandbox/src/app/sandboxPages.ts
+++ b/apps/sandbox/src/app/sandboxPages.ts
@@ -54,7 +54,8 @@ export const categories: SandboxCategory[] = [
{
name: 'Card Examples',
href: '/pages/example-cards/',
- description: 'Astryx components showcased in realistic card compositions',
+ description:
+ 'Astryx components showcased in realistic card compositions',
},
{
name: 'Table Overview',
@@ -158,7 +159,8 @@ export const categories: SandboxCategory[] = [
{
label: 'Tools',
slug: 'tools',
- description: 'Interactive tools for building and exploring Astryx components.',
+ description:
+ 'Interactive tools for building and exploring Astryx components.',
pages: [
{
name: 'Layout DSL',
@@ -171,6 +173,12 @@ export const categories: SandboxCategory[] = [
href: '/pages/codeblock-perf/',
description: 'Compare highlight modes and scroll performance',
},
+ {
+ name: 'Table Lab',
+ href: '/pages/table-lab/',
+ description:
+ 'Test any combination of Table plugins with live scroll FPS, dropped-frame, and re-render metrics',
+ },
{
name: 'Foundations',
href: '/pages/doc-preview/',