An open source design system that's fully customizable and agent ready
TypeScript
perf(docsite): defer template gallery payloads and rendering (#6275)
Kenton Quatman819816f39ada
diff --git a/apps/docsite/package.json b/apps/docsite/package.jsonindex 454da0340a..2c17ae13b0 100644--- a/apps/docsite/package.json+++ b/apps/docsite/package.json@@ -6,7 +6,7 @@"build:theme": "astryx theme build src/themes/astryxTheme.ts --out src/themes/astryx.css","generate": "node scripts/check-workspace-build.mjs && pnpm build:theme && node scripts/generate-data.mjs && node scripts/generate-scope.mjs && node scripts/generate-playground-types.mjs && node scripts/copy-vendor.mjs","dev": "pnpm generate && next dev --webpack",- "build": "pnpm generate && next build --webpack",+ "build": "pnpm generate && next build --webpack && node scripts/check-template-gallery-bundle.mjs","start": "next start","typecheck": "tsc --noEmit","test": "vitest run",diff --git a/apps/docsite/scripts/check-template-gallery-bundle.mjs b/apps/docsite/scripts/check-template-gallery-bundle.mjsnew file mode 100644index 0000000000..b564fda96e--- /dev/null+++ b/apps/docsite/scripts/check-template-gallery-bundle.mjs@@ -0,0 +1,55 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Verifies that the production templates route does not eagerly ship code that+ * only live previews or the playground need.+ */++import {readFileSync, statSync} from 'node:fs';+import {join} from 'node:path';+import {fileURLToPath} from 'node:url';++const appRoot = join(fileURLToPath(new URL('.', import.meta.url)), '..');+const htmlPath = join(appRoot, '.next/server/app/templates.html');+const chunksRoot = join(appRoot, '.next/static/chunks');+const html = readFileSync(htmlPath, 'utf8');+const chunkPattern = /<script[^>]+src="\/_next\/static\/chunks\/([^"?]+\.js)/g;+const chunkPaths = [+ ...new Set([...html.matchAll(chunkPattern)].map(match => match[1])),+];++if (chunkPaths.length === 0) {+ throw new Error(`No initial script chunks found in ${htmlPath}`);+}++const forbiddenMarkers = [+ ['full template source', 'activeUsersData'],+ ['live preview dialog', 'Copy Astryx command'],+ ['Recharts runtime', 'ResponsiveContainer'],+];+const violations = [];+let totalBytes = 0;++for (const relativePath of chunkPaths) {+ const chunkPath = join(chunksRoot, relativePath);+ const source = readFileSync(chunkPath, 'utf8');+ totalBytes += statSync(chunkPath).size;+ for (const [label, marker] of forbiddenMarkers) {+ if (source.includes(marker)) {+ violations.push(`${label} (${marker}) in ${relativePath}`);+ }+ }+}++if (violations.length > 0) {+ throw new Error(+ `The templates route eagerly ships deferred preview code:\n${violations+ .map(violation => `- ${violation}`)+ .join('\n')}`,+ );+}++console.log(+ `Template gallery bundle check passed: ${chunkPaths.length} initial chunks, ${totalBytes} uncompressed bytes`,+);diff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjsindex f8b21f1714..926b015b3c 100644--- a/apps/docsite/scripts/generate-data.mjs+++ b/apps/docsite/scripts/generate-data.mjs@@ -14,7 +14,8 @@* - packageRegistry.ts — metadata for every distributable package* - componentRegistry.ts — component listings per package (from .doc.mjs)* - blockRegistry.ts — showcases + example blocks from CLI templates- * - templateRegistry.ts — page-level templates from CLI templates+ * - templateRegistry.ts — page templates including playground source+ * - templateMetadataRegistry.ts — lightweight page-template metadata* - docsRegistry.ts — long-form documentation topics from CLI docs/*/@@ -1561,6 +1562,10 @@ async function generateTemplateRegistry() {'templateRegistry.ts',`// Auto-generated — no templates found\nexport const templates = [];\nexport const templateCount = 0;\n`,);+ writeRegistry(+ 'templateMetadataRegistry.ts',+ `// Auto-generated — no templates found\nexport const templateMetadata = [];\nexport const templateMetadataCount = 0;\n`,+ );return {templates: [], templateCount: 0};}@@ -1635,6 +1640,31 @@ export const templates: TemplateEntry[] = ${JSON.stringify(templates, null, 2)};export const templateCount = ${templates.length};`;writeRegistry('templateRegistry.ts', content);++ const templateMetadata = templates.map(+ ({source: _source, ...metadata}) => metadata,+ );+ const metadataContent = `// Auto-generated by scripts/generate-data.mjs — do not edit++export interface TemplateMetadataEntry {+ slug: string;+ name: string;+ description: string;+ isReady: boolean;+ /** Functional category, e.g. 'Dashboard - Analytics'. Empty when untagged.+ * The overview groups by the part before ' - '. */+ category: string;+ /** When true, hide from the Templates overview gallery (still CLI-available). */+ isHiddenFromOverview: boolean;+ registry: {slug?: string; aliases?: string[]} | null;+}++export const templateMetadata: TemplateMetadataEntry[] = ${JSON.stringify(templateMetadata, null, 2)};++export const templateMetadataCount = ${templateMetadata.length};+`;+ writeRegistry('templateMetadataRegistry.ts', metadataContent);+return {templates, templateCount: templates.length};}diff --git a/apps/docsite/src/__tests__/data-extraction.test.ts b/apps/docsite/src/__tests__/data-extraction.test.tsindex d0d2c6995e..90633fc1fc 100644--- a/apps/docsite/src/__tests__/data-extraction.test.ts+++ b/apps/docsite/src/__tests__/data-extraction.test.ts@@ -20,6 +20,10 @@ import {} from '../generated/componentRegistry';import {blocks, blockCount, showcaseCount} from '../generated/blockRegistry';import {templates, templateCount} from '../generated/templateRegistry';+import {+ templateMetadata,+ templateMetadataCount,+} from '../generated/templateMetadataRegistry';import {docTopics, docsCount} from '../generated/docsRegistry';import {showcaseRegistry} from '../generated/showcaseRegistry';import {externalComponentPreviews} from '../generated/componentPreviewRegistry';@@ -974,6 +978,17 @@ describe('templateRegistry', () => {it('discovers page templates', () => {expect(templateCount).toBeGreaterThan(10);expect(templates.length).toBe(templateCount);+ expect(templateMetadataCount).toBe(templateCount);+ expect(templateMetadata).toHaveLength(templateCount);+ });++ it('keeps source out of the metadata-only registry', () => {+ expect(templateMetadata.map(template => template.slug)).toEqual(+ templates.map(template => template.slug),+ );+ for (const template of templateMetadata) {+ expect(template).not.toHaveProperty('source');+ }});it('templates have required fields', () => {diff --git a/apps/docsite/src/__tests__/search-palette.test.ts b/apps/docsite/src/__tests__/search-palette.test.tsindex 4de9bc0f8a..7dcc7c8f28 100644--- a/apps/docsite/src/__tests__/search-palette.test.ts+++ b/apps/docsite/src/__tests__/search-palette.test.ts@@ -11,7 +11,7 @@ import {describe, it, expect} from 'vitest';import {components} from '../generated/componentRegistry';import {packages} from '../generated/packageRegistry';import {docTopics} from '../generated/docsRegistry';-import {templates} from '../generated/templateRegistry';+import {templateMetadata as templates} from '../generated/templateMetadataRegistry';import {flattenComponentSidebarEntries,getComponentSidebarData,diff --git a/apps/docsite/src/__tests__/shared-top-nav-search.test.tsx b/apps/docsite/src/__tests__/shared-top-nav-search.test.tsxnew file mode 100644index 0000000000..5e638c52aa--- /dev/null+++ b/apps/docsite/src/__tests__/shared-top-nav-search.test.tsx@@ -0,0 +1,129 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++// @vitest-environment jsdom++import type {ReactNode} from 'react';+import {useLayoutEffect, useRef} from 'react';+import {render, screen, waitFor} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {describe, expect, it, vi} from 'vitest';++vi.mock('next/navigation', () => ({+ usePathname: () => '/templates',+ useRouter: () => ({push: vi.fn()}),+}));++vi.mock('@stylexjs/stylex', () => ({+ create: <T,>(styles: T) => styles,+ props: () => ({}),+}));++vi.mock('@astryxdesign/core/AppShell', () => ({+ useAppShellMobile: () => ({+ isMobileNavEnabled: false,+ closeMobileNav: vi.fn(),+ }),+}));++vi.mock('@astryxdesign/core/TopNav', () => ({+ TopNav: ({heading, centerContent, endContent}: Record<string, ReactNode>) => (+ <nav>+ {heading}+ {centerContent}+ {endContent}+ </nav>+ ),+ TopNavHeading: ({logo}: {logo: ReactNode}) => <>{logo}</>,+ TopNavItem: ({label}: {label: string}) => <a href="#">{label}</a>,+ TopNavRenderContext: ({children}: {children: ReactNode}) => <>{children}</>,+ useTopNavRenderMode: () => 'topnav',+}));++vi.mock('@astryxdesign/core/Button', () => ({+ Button: ({+ label,+ onClick,+ href,+ }: {+ label: string;+ onClick?: () => void;+ href?: string;+ }) =>+ href ? (+ <a href={href}>{label}</a>+ ) : (+ <button onClick={onClick}>{label}</button>+ ),+}));++vi.mock('@astryxdesign/core/Layout', () => ({+ HStack: ({children}: {children: ReactNode}) => <>{children}</>,+}));++vi.mock('@astryxdesign/core/MobileNav', () => ({+ MobileNav: ({children}: {children: ReactNode}) => <>{children}</>,+}));++vi.mock('../app/providers', () => ({+ useThemeMode: () => ({+ mode: 'light',+ themeMode: 'light',+ toggleMode: vi.fn(),+ }),+}));++vi.mock('../components/logos', () => ({+ AstryxIcon: () => <svg aria-label="Astryx" />,+}));++vi.mock('../lib/analytics', () => ({+ trackSearch: vi.fn(),+ trackClickCta: vi.fn(),+}));++vi.mock('../components/SearchPalette', () => ({+ SearchPalette: ({+ isOpen,+ onOpenChange,+ }: {+ isOpen: boolean;+ onOpenChange: (open: boolean) => void;+ }) => {+ const returnFocusRef = useRef<HTMLElement | null>(null);+ useLayoutEffect(() => {+ if (isOpen) {+ returnFocusRef.current = document.activeElement as HTMLElement;+ } else {+ returnFocusRef.current?.focus();+ }+ }, [isOpen]);++ return (+ <div data-testid="search-palette">+ {isOpen ? (+ <button onClick={() => onOpenChange(false)}>Close Search</button>+ ) : (+ <span>Search closed</span>+ )}+ </div>+ );+ },+}));++import {SharedTopNav} from '../components/SharedTopNav';++describe('SharedTopNav search lifecycle', () => {+ it('keeps Search mounted through close so focus returns to its trigger', async () => {+ const user = userEvent.setup();+ render(<SharedTopNav />);+ const trigger = screen.getByRole('button', {name: 'Search'});++ await user.click(trigger);+ await user.click(await screen.findByRole('button', {name: 'Close Search'}));++ await waitFor(() => expect(document.activeElement).toBe(trigger));+ expect(screen.getByTestId('search-palette').textContent).toContain(+ 'Search closed',+ );+ });+});diff --git a/apps/docsite/src/__tests__/sitemap.test.ts b/apps/docsite/src/__tests__/sitemap.test.tsindex c7c4a85336..f673b55158 100644--- a/apps/docsite/src/__tests__/sitemap.test.ts+++ b/apps/docsite/src/__tests__/sitemap.test.ts@@ -21,7 +21,7 @@ import {SITE_URL} from '../lib/siteConfig';import {flattenComponentSidebarEntries} from '../components/componentSidebarData';import {docTopics} from '../generated/docsRegistry';import {packages} from '../generated/packageRegistry';-import {templates} from '../generated/templateRegistry';+import {templateMetadata as templates} from '../generated/templateMetadataRegistry';import {blogPosts} from '../generated/blogRegistry';const entries = await sitemap();diff --git a/apps/docsite/src/__tests__/template-gallery-performance.test.ts b/apps/docsite/src/__tests__/template-gallery-performance.test.tsindex 30e4d29ca2..3c1a8277b6 100644--- a/apps/docsite/src/__tests__/template-gallery-performance.test.ts+++ b/apps/docsite/src/__tests__/template-gallery-performance.test.ts@@ -1,52 +1,30 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Guards the templates gallery's lightweight playground handoff.- * @input Reads gallery, dialog, and playground source plus the URL helper.- * @output Invariants that keep raw template source out of gallery HTML.- * @position Docsite performance regression test for `/templates`.+ * @file Tests observable template-gallery data and navigation contracts.+ * @input Uses generated registries and the template playground URL helper.+ * @output Verifies source isolation and slug-based playground navigation.+ * @position Docsite regression coverage for `/templates` data boundaries.*/import {describe, expect, it} from 'vitest';-import {readFileSync} from 'node:fs';-import {join} from 'node:path';import {buildTemplatePlaygroundHref} from '../components/playgroundLink';+import {templateMetadata} from '../generated/templateMetadataRegistry';+import {templates} from '../generated/templateRegistry';-const SRC_DIR = join(__dirname, '..');--function source(path: string): string {- return readFileSync(join(SRC_DIR, path), 'utf8');-}--describe('template gallery playground links', () => {- it('links by slug instead of serializing every template source', () => {- const gallery = source('app/(site)/templates/page.tsx');- const dialog = source('components/TemplatePreviewDialog.tsx');-- expect(gallery).toContain('buildTemplatePlaygroundHref(item.slug)');- expect(dialog).toContain('buildTemplatePlaygroundHref(item.slug)');- expect(gallery).not.toMatch(/source:\s*[ti]\.source/);- expect(gallery).not.toContain('buildPlaygroundHref(item.source)');+describe('template gallery data boundaries', () => {+ it('keeps source out of the metadata consumed by browse and search surfaces', () => {+ expect(templateMetadata.map(template => template.slug)).toEqual(+ templates.map(template => template.slug),+ );+ for (const template of templateMetadata) {+ expect(template).not.toHaveProperty('source');+ }});- it('lets the playground resolve the encoded template slug', () => {- const playground = source('app/playground/PlaygroundClient.tsx');-+ it('links to the playground by encoded template slug', () => {expect(buildTemplatePlaygroundHref('table inbox')).toBe('/playground?template=table%20inbox',);- expect(playground).toMatch(- /new URLSearchParams\(window\.location\.search\)\.get\(\s*'template',?\s*\)/,- );- expect(playground).toContain('template => template.slug === templateSlug');- expect(playground).toContain(- "canonicalURL.searchParams.delete('template')",- );- expect(playground).toContain(- '`${canonicalURL.pathname}${canonicalURL.search}${canonicalURL.hash}`',- );- expect(playground).toContain(- 'stripCodeExampleCopyrightHeader(templateSource)',- );});});diff --git a/apps/docsite/src/__tests__/template-preview-url.test.ts b/apps/docsite/src/__tests__/template-preview-url.test.tsnew file mode 100644index 0000000000..9ce31a484a--- /dev/null+++ b/apps/docsite/src/__tests__/template-preview-url.test.ts@@ -0,0 +1,22 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {buildTemplatePreviewHref} from '../components/templatePreviewUrl';++describe('buildTemplatePreviewHref', () => {+ it('sets an encoded preview slug while preserving other parameters', () => {+ expect(+ buildTemplatePreviewHref('/templates', 'theme=dark', 'table inbox'),+ ).toBe('/templates?theme=dark&preview=table+inbox');+ });++ it('removes an invalid or closed preview while preserving other parameters', () => {+ expect(+ buildTemplatePreviewHref(+ '/templates',+ 'preview=missing&theme=dark',+ null,+ ),+ ).toBe('/templates?theme=dark');+ });+});diff --git a/apps/docsite/src/__tests__/template-thumbnail-loading.test.tsx b/apps/docsite/src/__tests__/template-thumbnail-loading.test.tsxnew file mode 100644index 0000000000..2cb2c0adf6--- /dev/null+++ b/apps/docsite/src/__tests__/template-thumbnail-loading.test.tsx@@ -0,0 +1,255 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++// @vitest-environment jsdom++import type * as ReactModule from 'react';+import type {ReactNode} from 'react';+import {act, cleanup, render, screen, waitFor} from '@testing-library/react';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';++const previewState = vi.hoisted(() => ({renders: [] as string[]}));+const transitionState = vi.hoisted(() => ({+ callbacks: [] as Array<() => void>,+ deferred: false,+}));+const startTransitionMock = vi.hoisted(() =>+ vi.fn((callback: () => void) => {+ if (transitionState.deferred) {+ transitionState.callbacks.push(callback);+ } else {+ callback();+ }+ }),+);++vi.mock('react', async importOriginal => ({+ ...(await importOriginal<typeof ReactModule>()),+ startTransition: startTransitionMock,+}));++vi.mock('@stylexjs/stylex', () => ({+ create: <T,>(styles: T) => styles,+ props: () => ({}),+}));++vi.mock('@astryxdesign/core/Skeleton', () => ({+ Skeleton: () => <div data-testid="skeleton" />,+}));++vi.mock('@astryxdesign/core/theme', () => ({+ Theme: ({children}: {children: ReactNode}) => <>{children}</>,+}));++vi.mock('@astryxdesign/theme-neutral/built', () => ({neutralTheme: {}}));+vi.mock('../app/providers', () => ({useThemeMode: () => ({mode: 'light'})}));+vi.mock('../components/templateComponents', () => ({+ TEMPLATE_COMPONENTS: {+ first: () => {+ previewState.renders.push('first');+ return <div>First preview</div>;+ },+ second: () => {+ previewState.renders.push('second');+ return <div>Second preview</div>;+ },+ },+}));++import {TemplateThumbnail} from '../components/TemplateThumbnail';++type IntersectionCallback = IntersectionObserverCallback;++let intersectionCallbacks: IntersectionCallback[];+let intersectionOptions: Array<IntersectionObserverInit | undefined>;+let idleCallbacks: IdleRequestCallback[];++beforeEach(() => {+ previewState.renders.length = 0;+ startTransitionMock.mockClear();+ transitionState.callbacks.length = 0;+ transitionState.deferred = false;+ intersectionCallbacks = [];+ intersectionOptions = [];+ idleCallbacks = [];++ vi.stubGlobal(+ 'IntersectionObserver',+ class {+ constructor(+ callback: IntersectionCallback,+ options?: IntersectionObserverInit,+ ) {+ intersectionCallbacks.push(callback);+ intersectionOptions.push(options);+ }+ observe() {}+ disconnect() {}+ unobserve() {}+ takeRecords() {+ return [];+ }+ root = null;+ rootMargin = '0px';+ thresholds = [0];+ },+ );+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ constructor(_callback: ResizeObserverCallback) {}+ observe() {}+ disconnect() {}+ unobserve() {}+ },+ );+ Object.defineProperty(HTMLElement.prototype, 'offsetWidth', {+ configurable: true,+ get: () => 360,+ });+ window.requestIdleCallback = vi.fn((callback: IdleRequestCallback) => {+ idleCallbacks.push(callback);+ return idleCallbacks.length;+ });+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++const visibleEntry = {isIntersecting: true} as IntersectionObserverEntry;+const hiddenEntry = {isIntersecting: false} as IntersectionObserverEntry;+const idleDeadline = {+ didTimeout: false,+ timeRemaining: () => 50,+} as IdleDeadline;++describe('TemplateThumbnail loading', () => {+ it('renders visible templates one per idle turn instead of during hydration', async () => {+ render(+ <>+ <TemplateThumbnail slug="first" />+ <TemplateThumbnail slug="second" />+ </>,+ );++ expect(intersectionOptions).toEqual([+ {rootMargin: '0px'},+ {rootMargin: '0px'},+ ]);+ expect(idleCallbacks).toHaveLength(0);+ act(() => {+ for (const callback of intersectionCallbacks) {+ callback([visibleEntry], {} as IntersectionObserver);+ }+ });++ expect(previewState.renders).toEqual([]);+ expect(screen.getAllByTestId('skeleton')).toHaveLength(2);+ expect(idleCallbacks).toHaveLength(1);++ act(() => idleCallbacks.shift()?.(idleDeadline));+ expect(startTransitionMock).toHaveBeenCalledTimes(1);+ await waitFor(() =>+ expect(screen.queryByText('First preview')).not.toBeNull(),+ );+ expect(previewState.renders).toEqual(['first']);++ act(() => idleCallbacks.shift()?.(idleDeadline));+ expect(startTransitionMock).toHaveBeenCalledTimes(2);+ await waitFor(() =>+ expect(screen.queryByText('Second preview')).not.toBeNull(),+ );+ expect(previewState.renders).toEqual(['first', 'second']);+ });++ it('unmounts a loaded preview offscreen and queues it again on re-entry', async () => {+ render(<TemplateThumbnail slug="first" />);++ act(() =>+ intersectionCallbacks[0]?.([visibleEntry], {} as IntersectionObserver),+ );+ act(() => idleCallbacks.shift()?.(idleDeadline));+ await waitFor(() =>+ expect(screen.queryByText('First preview')).not.toBeNull(),+ );++ act(() =>+ intersectionCallbacks[0]?.([hiddenEntry], {} as IntersectionObserver),+ );+ expect(screen.queryByText('First preview')).toBeNull();++ act(() =>+ intersectionCallbacks[0]?.([visibleEntry], {} as IntersectionObserver),+ );+ expect(screen.queryByText('First preview')).toBeNull();+ expect(idleCallbacks).toHaveLength(1);++ act(() => idleCallbacks.shift()?.(idleDeadline));+ await waitFor(() =>+ expect(screen.queryByText('First preview')).not.toBeNull(),+ );+ expect(startTransitionMock).toHaveBeenCalledTimes(2);+ });++ it('cancels queued work when a thumbnail leaves the viewport', () => {+ render(<TemplateThumbnail slug="first" />);++ act(() =>+ intersectionCallbacks[0]?.([visibleEntry], {} as IntersectionObserver),+ );+ expect(idleCallbacks).toHaveLength(1);+ act(() =>+ intersectionCallbacks[0]?.([hiddenEntry], {} as IntersectionObserver),+ );+ act(() => idleCallbacks.shift()?.(idleDeadline));++ expect(startTransitionMock).not.toHaveBeenCalled();+ expect(previewState.renders).toEqual([]);+ });++ it('releases the next thumbnail when an active preview unmounts before commit', async () => {+ transitionState.deferred = true;+ const view = render(+ <>+ <TemplateThumbnail key="first" slug="first" />+ <TemplateThumbnail key="second" slug="second" />+ </>,+ );++ act(() => {+ for (const callback of intersectionCallbacks) {+ callback([visibleEntry], {} as IntersectionObserver);+ }+ });+ act(() => idleCallbacks.shift()?.(idleDeadline));+ expect(startTransitionMock).toHaveBeenCalledOnce();+ expect(transitionState.callbacks).toHaveLength(1);+ expect(idleCallbacks).toHaveLength(0);++ view.rerender(<TemplateThumbnail key="second" slug="second" />);+ await act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ });++ expect(idleCallbacks).toHaveLength(1);+ transitionState.deferred = false;+ act(() => idleCallbacks.shift()?.(idleDeadline));+ expect(startTransitionMock).toHaveBeenCalledTimes(2);+ });++ it('cancels queued work when a thumbnail unmounts', () => {+ const view = render(<TemplateThumbnail slug="first" />);++ act(() =>+ intersectionCallbacks[0]?.([visibleEntry], {} as IntersectionObserver),+ );+ expect(idleCallbacks).toHaveLength(1);+ view.unmount();+ act(() => idleCallbacks.shift()?.(idleDeadline));++ expect(startTransitionMock).not.toHaveBeenCalled();+ expect(previewState.renders).toEqual([]);+ });+});diff --git a/apps/docsite/src/__tests__/thumbnail-render-scheduler.test.ts b/apps/docsite/src/__tests__/thumbnail-render-scheduler.test.tsnew file mode 100644index 0000000000..c0ac12dad2--- /dev/null+++ b/apps/docsite/src/__tests__/thumbnail-render-scheduler.test.ts@@ -0,0 +1,153 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Tests completion-aware template thumbnail scheduling.+ * @input Stubs browser idle callbacks and schedules cancellable async render jobs.+ * @output Verifies idle activation, completion serialization, failures, and cancellation.+ * @position Unit coverage for the template gallery's interaction-first scheduler.+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';++const idleDeadline: IdleDeadline = {+ didTimeout: false,+ timeRemaining: () => 50,+};++let idleCallbacks: IdleRequestCallback[];+let timerCallbacks: Array<() => void>;++async function flushMicrotasks(): Promise<void> {+ await Promise.resolve();+ await Promise.resolve();+}++beforeEach(() => {+ vi.resetModules();+ idleCallbacks = [];+ timerCallbacks = [];+ vi.stubGlobal('window', {+ requestIdleCallback: vi.fn((callback: IdleRequestCallback) => {+ idleCallbacks.push(callback);+ return idleCallbacks.length;+ }),+ cancelIdleCallback: vi.fn(),+ setTimeout: vi.fn((callback: () => void) => {+ timerCallbacks.push(callback);+ return timerCallbacks.length;+ }),+ clearTimeout: vi.fn(),+ });+});++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('scheduleThumbnailRender', () => {+ it('waits for one thumbnail to finish before scheduling the next idle turn', async () => {+ const {scheduleThumbnailRender} =+ await import('../components/thumbnailRenderScheduler');+ const activated: string[] = [];+ let finishFirst: (() => void) | undefined;++ scheduleThumbnailRender(+ () =>+ new Promise<void>(resolve => {+ activated.push('first');+ finishFirst = resolve;+ }),+ );+ scheduleThumbnailRender(() => activated.push('second'));++ expect(idleCallbacks).toHaveLength(1);+ expect(window.requestIdleCallback).toHaveBeenCalledWith(+ expect.any(Function),+ );+ idleCallbacks.shift()?.(idleDeadline);+ expect(activated).toEqual(['first']);+ expect(idleCallbacks).toHaveLength(0);++ finishFirst?.();+ await flushMicrotasks();+ expect(idleCallbacks).toHaveLength(1);++ idleCallbacks.shift()?.(idleDeadline);+ expect(activated).toEqual(['first', 'second']);+ await flushMicrotasks();+ expect(idleCallbacks).toHaveLength(0);+ });++ it('continues after a thumbnail activation fails', async () => {+ const {scheduleThumbnailRender} =+ await import('../components/thumbnailRenderScheduler');+ const activated: string[] = [];++ scheduleThumbnailRender(() => {+ throw new Error('preview failed');+ });+ scheduleThumbnailRender(() => activated.push('second'));++ idleCallbacks.shift()?.(idleDeadline);+ await flushMicrotasks();+ expect(idleCallbacks).toHaveLength(1);+ idleCallbacks.shift()?.(idleDeadline);+ expect(activated).toEqual(['second']);+ });++ it('starts exactly one activation when the starvation timer wins', async () => {+ const {scheduleThumbnailRender} =+ await import('../components/thumbnailRenderScheduler');+ const activated: string[] = [];++ scheduleThumbnailRender(() => activated.push('first'));++ expect(window.setTimeout).toHaveBeenCalledWith(expect.any(Function), 1000);+ timerCallbacks.shift()?.();+ expect(activated).toEqual(['first']);+ await flushMicrotasks();++ idleCallbacks.shift()?.(idleDeadline);+ expect(activated).toEqual(['first']);+ });++ it('uses a timer fallback when requestIdleCallback is unavailable', async () => {+ vi.resetModules();+ const timeoutCallbacks: Array<() => void> = [];+ const setTimeout = vi.fn((callback: () => void) => {+ timeoutCallbacks.push(callback);+ return timeoutCallbacks.length;+ });+ vi.stubGlobal('window', {setTimeout, clearTimeout: vi.fn()});+ const {scheduleThumbnailRender} =+ await import('../components/thumbnailRenderScheduler');+ const activated: string[] = [];++ scheduleThumbnailRender(() => activated.push('fallback'));++ expect(setTimeout).toHaveBeenCalledWith(expect.any(Function), 100);+ expect(activated).toEqual([]);+ timeoutCallbacks.shift()?.();+ expect(activated).toEqual(['fallback']);+ await flushMicrotasks();+ });++ it('skips consecutive cancelled jobs without delaying the next thumbnail', async () => {+ const {scheduleThumbnailRender} =+ await import('../components/thumbnailRenderScheduler');+ const activated: string[] = [];++ const cancelFirst = scheduleThumbnailRender(() => activated.push('first'));+ const cancelSecond = scheduleThumbnailRender(() =>+ activated.push('second'),+ );+ scheduleThumbnailRender(() => activated.push('third'));+ cancelFirst();+ cancelSecond();++ idleCallbacks.shift()?.(idleDeadline);+ expect(activated).toEqual(['third']);+ await flushMicrotasks();+ expect(idleCallbacks).toHaveLength(0);+ });+});diff --git a/apps/docsite/src/app/(site)/templates/[slug]/page.tsx b/apps/docsite/src/app/(site)/templates/[slug]/page.tsxindex f1a27c3c16..df9dc2caf0 100644--- a/apps/docsite/src/app/(site)/templates/[slug]/page.tsx+++ b/apps/docsite/src/app/(site)/templates/[slug]/page.tsx@@ -6,7 +6,7 @@*/import {redirect} from 'next/navigation';-import {templates} from '../../../../generated/templateRegistry';+import {templateMetadata as templates} from '../../../../generated/templateMetadataRegistry';export function generateStaticParams() {return templates.map(t => ({slug: t.slug}));diff --git a/apps/docsite/src/app/(site)/templates/page.tsx b/apps/docsite/src/app/(site)/templates/page.tsxindex d1acb7d9ce..a390114d1a 100644--- a/apps/docsite/src/app/(site)/templates/page.tsx+++ b/apps/docsite/src/app/(site)/templates/page.tsx@@ -2,14 +2,14 @@/*** @file Templates gallery index.- * @input Uses generated template metadata, URL preview state, and live template thumbnails.- * @output Renders the filterable gallery and query-synced preview dialog.+ * @input Uses generated template metadata, URL preview state, live thumbnails, and a lazy preview dialog.+ * @output Renders the filterable gallery and loads the query-synced preview dialog on first open.* @position Public `/templates` docsite route.*/'use client';-import {Suspense, useCallback, useEffect, useMemo, useState} from 'react';+import {Suspense, lazy, useCallback, useEffect, useMemo, useState} from 'react';import type {CSSProperties} from 'react';import {useSearchParams, useRouter, usePathname} from 'next/navigation';import * as stylex from '@stylexjs/stylex';@@ -22,14 +22,20 @@ import {Grid} from '@astryxdesign/core/Grid';import {Button} from '@astryxdesign/core/Button';import {Overlay} from '@astryxdesign/core/Overlay';import {ToggleButton, ToggleButtonGroup} from '@astryxdesign/core/ToggleButton';-import {templates} from '../../../generated/templateRegistry';+import {templateMetadata as templates} from '../../../generated/templateMetadataRegistry';import {TemplateThumbnail} from '../../../components/TemplateThumbnail';import {buildTemplatePlaygroundHref} from '../../../components/playgroundLink';-import {TemplatePreviewDialog} from '../../../components/TemplatePreviewDialog';+import {buildTemplatePreviewHref} from '../../../components/templatePreviewUrl';import type {TemplatePreviewItem} from '../../../components/TemplatePreviewDialog';import {trackOpenPlayground, trackView} from '../../../lib/analytics';import {layout} from '../../../layout.stylex';+const LazyTemplatePreviewDialog = lazy(() =>+ import('../../../components/TemplatePreviewDialog').then(module => ({+ default: module.TemplatePreviewDialog,+ })),+);+const CARD_STYLE: CSSProperties & {'--color-overlay': string} = {'--color-overlay':'color-mix(in srgb, var(--color-on-light) 78%, transparent)',@@ -115,13 +121,21 @@ function TemplatePreviewURLSync({onSlugChange,}: TemplatePreviewURLSyncProps) {const searchParams = useSearchParams();+ const router = useRouter();+ const pathname = usePathname();const previewSlug = searchParams.get('preview');const openSlug =previewSlug != null && indexBySlug.has(previewSlug) ? previewSlug : null;useEffect(() => {onSlugChange(openSlug);- }, [onSlugChange, openSlug]);+ if (previewSlug != null && openSlug == null) {+ router.replace(+ buildTemplatePreviewHref(pathname, searchParams.toString(), null),+ {scroll: false},+ );+ }+ }, [onSlugChange, openSlug, pathname, previewSlug, router, searchParams]);return null;}@@ -192,21 +206,27 @@ function TemplatesGallery() {const router = useRouter();const pathname = usePathname();const [openSlug, setOpenSlug] = useState<string | null>(null);+ const [hasLoadedPreview, setHasLoadedPreview] = useState(false);+ const handlePreviewSlugChange = useCallback((slug: string | null) => {+ if (slug !== null) {+ setHasLoadedPreview(true);+ }+ setOpenSlug(slug);+ }, []);const openIndex =openSlug != null ? (indexBySlug.get(openSlug) ?? null) : null;const setOpenIndex = useCallback((index: number | null) => {const nextSlug = index !== null ? (flatItems[index]?.slug ?? null) : null;- setOpenSlug(nextSlug);- const params = new URLSearchParams(window.location.search);if (nextSlug !== null) {- params.set('preview', nextSlug);- } else {- params.delete('preview');+ setHasLoadedPreview(true);}- const qs = params.toString();- router.replace(`${pathname}${qs ? `?${qs}` : ''}`, {scroll: false});+ setOpenSlug(nextSlug);+ router.replace(+ buildTemplatePreviewHref(pathname, window.location.search, nextSlug),+ {scroll: false},+ );},[flatItems, router, pathname],);@@ -321,22 +341,26 @@ function TemplatesGallery() {<Suspense fallback={null}><TemplatePreviewURLSyncindexBySlug={indexBySlug}- onSlugChange={setOpenSlug}+ onSlugChange={handlePreviewSlugChange}/></Suspense>- <TemplatePreviewDialog- items={flatItems}- index={openIndex ?? 0}- isOpen={openIndex !== null}- onOpenChange={open => {- if (!open) {- setOpenIndex(null);- }- }}- onIndexChange={setOpenIndex}- variant={isMobile ? 'fullscreen' : undefined}- />+ {hasLoadedPreview ? (+ <Suspense fallback={null}>+ <LazyTemplatePreviewDialog+ items={flatItems}+ index={openIndex ?? 0}+ isOpen={openIndex !== null}+ onOpenChange={open => {+ if (!open) {+ setOpenIndex(null);+ }+ }}+ onIndexChange={setOpenIndex}+ variant={isMobile ? 'fullscreen' : undefined}+ />+ </Suspense>+ ) : null}</Section>);}diff --git a/apps/docsite/src/app/sitemap.ts b/apps/docsite/src/app/sitemap.tsindex 69182bebfb..f3e9a978a5 100644--- a/apps/docsite/src/app/sitemap.ts+++ b/apps/docsite/src/app/sitemap.ts@@ -22,7 +22,7 @@ import {CHANGELOG_PAGE_TITLE} from '../lib/pageTitles';import {flattenComponentSidebarEntries} from '../components/componentSidebarData';import {docTopics} from '../generated/docsRegistry';import {packages} from '../generated/packageRegistry';-import {templates} from '../generated/templateRegistry';+import {templateMetadata as templates} from '../generated/templateMetadataRegistry';import {blogPosts} from '../generated/blogRegistry';export type SitemapPage = MetadataRoute.Sitemap[number] & {title: string};diff --git a/apps/docsite/src/components/SearchPalette.tsx b/apps/docsite/src/components/SearchPalette.tsxindex c1d296503e..f65e4dfc22 100644--- a/apps/docsite/src/components/SearchPalette.tsx+++ b/apps/docsite/src/components/SearchPalette.tsx@@ -7,10 +7,10 @@ import {useRouter} from 'next/navigation';import {CommandPalette} from '@astryxdesign/core/CommandPalette';import {Text} from '@astryxdesign/core/Text';import {createStaticSource} from '@astryxdesign/core/Typeahead';-import type {ComponentEntry} from '../generated/componentRegistry';-import type {PackageMeta} from '../generated/packageRegistry';-import type {DocTopic} from '../generated/docsRegistry';-import type {TemplateEntry} from '../generated/templateRegistry';+import {components} from '../generated/componentRegistry';+import {packages} from '../generated/packageRegistry';+import {docTopics} from '../generated/docsRegistry';+import {templateMetadata} from '../generated/templateMetadataRegistry';import {trackSearch} from '../lib/analytics';import {buildSearchPaletteItems,@@ -20,20 +20,9 @@ import {interface SearchPaletteProps {isOpen: boolean;onOpenChange: (open: boolean) => void;- components: Record<string, ComponentEntry[]>;- packages: PackageMeta[];- docTopics: DocTopic[];- templates: TemplateEntry[];}-export function SearchPalette({- isOpen,- onOpenChange,- components,- packages,- docTopics,- templates,-}: SearchPaletteProps) {+export function SearchPalette({isOpen, onOpenChange}: SearchPaletteProps) {const router = useRouter();// Component items come from the same grouped registry as the sidebar so@@ -43,13 +32,13 @@ export function SearchPalette({components,packages,docTopics,- templates,+ templates: templateMetadata,});return createStaticSource(items, {keywords: getSearchItemKeywords,});- }, [components, packages, docTopics, templates]);+ }, []);const handleValueChange = useCallback((value: string) => {diff --git a/apps/docsite/src/components/SharedTopNav.tsx b/apps/docsite/src/components/SharedTopNav.tsxindex 6cf1d1e4f3..5fdf743885 100644--- a/apps/docsite/src/components/SharedTopNav.tsx+++ b/apps/docsite/src/components/SharedTopNav.tsx@@ -2,7 +2,7 @@'use client';-import {useEffect, useState} from 'react';+import {lazy, Suspense, useEffect, useState} from 'react';import {usePathname} from 'next/navigation';import * as stylex from '@stylexjs/stylex';import {@@ -20,14 +20,13 @@ import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';import {Search, HeartHandshake, Sun, Moon, Menu} from 'lucide-react';import {GITHUB_REPO} from '../constants';import {AstryxIcon} from './logos';-import {SearchPalette} from './SearchPalette';-import {components} from '../generated/componentRegistry';-import {packages} from '../generated/packageRegistry';-import {docTopics} from '../generated/docsRegistry';-import {templates} from '../generated/templateRegistry';import {useThemeMode} from '../app/providers';import {trackSearch, trackClickCta} from '../lib/analytics';+const LazySearchPalette = lazy(() =>+ import('./SearchPalette').then(module => ({default: module.SearchPalette})),+);+const GitHubIcon = ({width = 20,height = 20,@@ -106,6 +105,7 @@ const NAV_ITEMS = [export function SharedTopNav() {const [isSearchOpen, setIsSearchOpen] = useState(false);+ const [hasLoadedSearch, setHasLoadedSearch] = useState(false);const [isMenuOpen, setIsMenuOpen] = useState(false);const pathname = usePathname();const {mode, themeMode, toggleMode} = useThemeMode();@@ -127,6 +127,7 @@ export function SharedTopNav() {) {event.preventDefault();trackSearch({target: 'open'});+ setHasLoadedSearch(true);setIsSearchOpen(true);}};@@ -208,6 +209,7 @@ export function SharedTopNav() {icon={<Search size={20} />}onClick={() => {trackSearch({target: 'open'});+ setHasLoadedSearch(true);setIsSearchOpen(true);}}/>@@ -291,14 +293,14 @@ export function SharedTopNav() {</HStack>}/>- <SearchPalette- isOpen={isSearchOpen}- onOpenChange={setIsSearchOpen}- components={components}- packages={packages}- docTopics={docTopics}- templates={templates}- />+ {hasLoadedSearch && (+ <Suspense fallback={null}>+ <LazySearchPalette+ isOpen={isSearchOpen}+ onOpenChange={setIsSearchOpen}+ />+ </Suspense>+ )}{!isMobileNavEnabled && (<MobileNavisOpen={isMenuOpen}diff --git a/apps/docsite/src/components/TemplatePreviewDialog.tsx b/apps/docsite/src/components/TemplatePreviewDialog.tsxindex 37e3f86634..3747f72cab 100644--- a/apps/docsite/src/components/TemplatePreviewDialog.tsx+++ b/apps/docsite/src/components/TemplatePreviewDialog.tsx@@ -481,10 +481,12 @@ export function TemplatePreviewDialog({content={<LayoutContent isScrollable={false} padding={0}><div {...stylex.props(styles.body)} ref={hostRef}>- <TemplatePreviewSurface- key={deferredCurrent.slug}- slug={deferredCurrent.slug}- />+ {isOpen && (+ <TemplatePreviewSurface+ key={deferredCurrent.slug}+ slug={deferredCurrent.slug}+ />+ )}{isPending && (<div {...stylex.props(styles.skeletonOverlay)}><Skeleton width="100%" height="100%" />diff --git a/apps/docsite/src/components/TemplateThumbnail.tsx b/apps/docsite/src/components/TemplateThumbnail.tsxindex 051975cdfc..8a7a5f1686 100644--- a/apps/docsite/src/components/TemplateThumbnail.tsx+++ b/apps/docsite/src/components/TemplateThumbnail.tsx@@ -1,14 +1,29 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file Renders a scaled live template preview inside a gallery tile.+ * @input Uses the template slug, theme mode, visibility, and measured tile size.+ * @output Renders only visible previews and releases the global queue after each committed render.+ * @position Client-side live preview for template gallery cards.+ */+'use client';-import {Suspense, useRef, useState, useEffect, useCallback} from 'react';+import {+ Suspense,+ startTransition,+ useCallback,+ useEffect,+ useRef,+ useState,+} from 'react';import * as stylex from '@stylexjs/stylex';import {Skeleton} from '@astryxdesign/core/Skeleton';import {Theme} from '@astryxdesign/core/theme';import {neutralTheme} from '@astryxdesign/theme-neutral/built';import {useThemeMode} from '../app/providers';import {TEMPLATE_COMPONENTS} from './templateComponents';+import {scheduleThumbnailRender} from './thumbnailRenderScheduler';const FIXED_SCALE = 0.5;@@ -47,6 +62,13 @@ const styles = stylex.create({},});+function ThumbnailRenderSettled({onSettled}: {onSettled: () => void}) {+ useEffect(() => {+ onSettled();+ }, [onSettled]);+ return null;+}+export function TemplateThumbnail({slug,aspectRatio,@@ -74,6 +96,17 @@ export function TemplateThumbnail({const containerRef = useRef<HTMLDivElement>(null);const [tileWidth, setTileWidth] = useState(0);const [isVisible, setIsVisible] = useState(false);+ const [isRenderReady, setIsRenderReady] = useState(false);+ const isVisibleRef = useRef(false);+ const isRenderReadyRef = useRef(false);+ const resolveRenderRef = useRef<(() => void) | null>(null);+ const Component = TEMPLATE_COMPONENTS[slug];++ const settleRender = useCallback(() => {+ const resolve = resolveRenderRef.current;+ resolveRenderRef.current = null;+ resolve?.();+ }, []);const updateWidth = useCallback(() => {if (containerRef.current) {@@ -88,7 +121,8 @@ export function TemplateThumbnail({// Scale so the rendered width fits the tile width.const scale = renderWidth > 0 ? tileWidth / renderWidth : FIXED_SCALE;- // Intersection observer: track visibility for Activity mode+ // Only visible tiles join the activation queue. A zero root margin avoids+ // importing heavy template dependencies before their tiles enter the viewport.useEffect(() => {const el = containerRef.current;if (!el) {@@ -96,13 +130,55 @@ export function TemplateThumbnail({}const observer = new IntersectionObserver(- ([entry]) => setIsVisible(entry.isIntersecting),- {rootMargin: '200px'},+ ([entry]) => {+ const nextIsVisible = entry.isIntersecting;+ isVisibleRef.current = nextIsVisible;+ setIsVisible(nextIsVisible);+ if (!nextIsVisible) {+ isRenderReadyRef.current = false;+ setIsRenderReady(false);+ }+ },+ {rootMargin: '0px'},);observer.observe(el);return () => observer.disconnect();}, []);+ // The queue does not release the next thumbnail until this preview commits.+ // That keeps lazy imports and chart rendering sequential, not just state updates.+ useEffect(() => {+ if (!isVisible || isRenderReadyRef.current || !Component) {+ return;+ }++ let isActive = true;+ const cancel = scheduleThumbnailRender(+ () =>+ new Promise<void>(resolve => {+ if (!isActive || !isVisibleRef.current) {+ resolve();+ return;+ }+ resolveRenderRef.current = resolve;+ startTransition(() => {+ if (isVisibleRef.current) {+ isRenderReadyRef.current = true;+ setIsRenderReady(true);+ } else {+ settleRender();+ }+ });+ }),+ );++ return () => {+ isActive = false;+ cancel();+ settleRender();+ };+ }, [Component, isVisible, settleRender]);+// Measure container width to compute render widthuseEffect(() => {updateWidth();@@ -115,7 +191,6 @@ export function TemplateThumbnail({return () => ro.disconnect();}, [updateWidth]);- const Component = TEMPLATE_COMPONENTS[slug];if (!Component) {return null;}@@ -133,26 +208,33 @@ export function TemplateThumbnail({: undefined}inert>- {tileWidth > 0 && isVisible && (- <div- {...stylex.props(styles.scaler)}- style={{- width: renderWidth,- height: `${100 / scale}%`,- transform: `scale(${scale})`,- }}>- <Suspense- fallback={- <div {...stylex.props(styles.skeleton)}>- <Skeleton width="100%" height="100%" />- </div>- }>- <Theme theme={neutralTheme} mode={mode}>- <Component />- </Theme>- </Suspense>- </div>- )}+ {tileWidth > 0 &&+ isVisible &&+ (isRenderReady ? (+ <div+ {...stylex.props(styles.scaler)}+ style={{+ width: renderWidth,+ height: `${100 / scale}%`,+ transform: `scale(${scale})`,+ }}>+ <Suspense+ fallback={+ <div {...stylex.props(styles.skeleton)}>+ <Skeleton width="100%" height="100%" />+ </div>+ }>+ <Theme theme={neutralTheme} mode={mode}>+ <Component />+ <ThumbnailRenderSettled onSettled={settleRender} />+ </Theme>+ </Suspense>+ </div>+ ) : (+ <div {...stylex.props(styles.skeleton)}>+ <Skeleton width="100%" height="100%" />+ </div>+ ))}</div>);}diff --git a/apps/docsite/src/components/searchPaletteData.ts b/apps/docsite/src/components/searchPaletteData.tsindex 0c58217010..fc0bfc412f 100644--- a/apps/docsite/src/components/searchPaletteData.ts+++ b/apps/docsite/src/components/searchPaletteData.ts@@ -4,7 +4,7 @@ import type {SearchableItem} from '@astryxdesign/core/Typeahead';import type {ComponentEntry} from '../generated/componentRegistry';import type {PackageMeta} from '../generated/packageRegistry';import type {DocTopic} from '../generated/docsRegistry';-import type {TemplateEntry} from '../generated/templateRegistry';+import type {TemplateMetadataEntry} from '../generated/templateMetadataRegistry';import {flattenComponentSidebarEntries} from './componentSidebarData';export interface SearchItemAuxiliaryData {@@ -23,7 +23,7 @@ interface SearchPaletteDataInput {components: Record<string, ComponentEntry[]>;packages: PackageMeta[];docTopics: DocTopic[];- templates: TemplateEntry[];+ templates: TemplateMetadataEntry[];}function uniqueKeywords(keywords: Array<string | null | undefined>): string[] {diff --git a/apps/docsite/src/components/templatePreviewUrl.ts b/apps/docsite/src/components/templatePreviewUrl.tsnew file mode 100644index 0000000000..9b9434b00c--- /dev/null+++ b/apps/docsite/src/components/templatePreviewUrl.ts@@ -0,0 +1,16 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++export function buildTemplatePreviewHref(+ pathname: string,+ search: string,+ slug: string | null,+): string {+ const params = new URLSearchParams(search);+ if (slug == null) {+ params.delete('preview');+ } else {+ params.set('preview', slug);+ }+ const query = params.toString();+ return `${pathname}${query ? `?${query}` : ''}`;+}diff --git a/apps/docsite/src/components/thumbnailRenderScheduler.ts b/apps/docsite/src/components/thumbnailRenderScheduler.tsnew file mode 100644index 0000000000..4922287df9--- /dev/null+++ b/apps/docsite/src/components/thumbnailRenderScheduler.ts@@ -0,0 +1,84 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Serializes live template thumbnail activation during browser idle time.+ * @input Receives cancellable async render jobs from visible gallery tiles.+ * @output Runs one job at a time and waits for it to settle before scheduling the next.+ * @position Client-side scheduling boundary between visibility and heavy preview work.+ */++type ThumbnailRenderJob = {+ cancelled: boolean;+ run: () => Promise<unknown> | unknown;+};++const IDLE_STARVATION_MS = 1000;+const TIMER_FALLBACK_MS = 100;+const jobs: ThumbnailRenderJob[] = [];+let isBusy = false;++function scheduleNext(): void {+ if (isBusy || jobs.length === 0) {+ return;+ }++ isBusy = true;+ let didStart = false;+ let idleId: number | undefined;+ let timerId: number | undefined;++ const runNext = () => {+ if (didStart) {+ return;+ }+ didStart = true;+ if (+ idleId !== undefined &&+ typeof window.cancelIdleCallback === 'function'+ ) {+ window.cancelIdleCallback(idleId);+ }+ if (timerId !== undefined) {+ window.clearTimeout(timerId);+ }++ let job = jobs.shift();+ while (job?.cancelled === true) {+ job = jobs.shift();+ }++ if (job == null) {+ isBusy = false;+ return;+ }++ const execute = async () => {+ try {+ await job.run();+ } finally {+ isBusy = false;+ scheduleNext();+ }+ };+ void execute().catch(() => {});+ };++ if (typeof window.requestIdleCallback === 'function') {+ idleId = window.requestIdleCallback(runNext);+ timerId = window.setTimeout(runNext, IDLE_STARVATION_MS);+ } else {+ timerId = window.setTimeout(runNext, TIMER_FALLBACK_MS);+ }+}++export function scheduleThumbnailRender(+ run: () => Promise<unknown> | unknown,+): () => void {+ const job = {cancelled: false, run};+ jobs.push(job);+ scheduleNext();++ return () => {+ job.cancelled = true;+ };+}diff --git a/apps/docsite/vitest.config.ts b/apps/docsite/vitest.config.tsindex f31e7f2e4f..25fa268298 100644--- a/apps/docsite/vitest.config.ts+++ b/apps/docsite/vitest.config.ts@@ -1,9 +1,18 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+import path from 'node:path';import {defineConfig} from 'vitest/config';export default defineConfig({+ resolve: {+ alias: {+ '@astryxdesign/theme-neutral/built': path.resolve(+ __dirname,+ '../../packages/themes/neutral/src/neutralTheme.ts',+ ),+ },+ },test: {- include: ['src/__tests__/**/*.test.ts'],+ include: ['src/__tests__/**/*.test.{ts,tsx}'],},});