Skip to content

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

TypeScript

fix(docsite): prerender the templates gallery (#5940)

Xinzi Zhou9fa8c668f8d8
diff --git a/apps/docsite/src/__tests__/static-shell.test.ts b/apps/docsite/src/__tests__/static-shell.test.ts
index 850dde8480..ae8f5bddfb 100644
--- a/apps/docsite/src/__tests__/static-shell.test.ts
+++ b/apps/docsite/src/__tests__/static-shell.test.ts
@@ -3,17 +3,18 @@
/**
* @file Guards the docsite's query-driven PPR boundaries and global footer.
* @input Reads the relevant docsite source files
- * @output Invariants for narrow Suspense boundaries, named fallbacks, and
- * CSS-driven footer responsiveness
+ * @output Invariants for narrow Suspense boundaries, shaped visible fallbacks,
+ * invisible URL synchronizers, and CSS-driven footer responsiveness
* @position Cross-cutting meta-test; no runtime behavior of its own
*
* The docsite runs with `cacheComponents: true` (Partial Prerendering).
* Request state such as `searchParams` is valid, but everything up to its
- * nearest Suspense boundary becomes a PPR hole. The component detail page and
- * theme explorer deliberately keep their existing deep-link behavior; these
- * tests make sure their boundaries stay narrow and never regress to an empty
- * fallback. The global footer must be CSS-responsive because a JavaScript
- * media query cannot know the viewport during prerendering.
+ * nearest Suspense boundary becomes a PPR hole. The component detail page,
+ * templates gallery, and theme explorer deliberately keep their deep-link
+ * behavior; these tests keep visible content outside the query-dependent hole
+ * or reserve a shaped fallback. An invisible URL synchronizer may render no
+ * fallback because it owns no layout. The global footer must be CSS-responsive
+ * because a JavaScript media query cannot know the viewport during prerendering.
*/
import {describe, it, expect} from 'vitest';
@@ -42,6 +43,28 @@ describe('docsite static shell', () => {
);
});
+ it('keeps the templates gallery outside its URL sync boundary', () => {
+ const templates = source('app/(site)/templates/page.tsx');
+ const galleryStart = templates.indexOf('function TemplatesGallery()');
+ const heading = templates.indexOf('<Heading level={1}', galleryStart);
+ const grid = templates.indexOf('<Grid', heading);
+ const boundary = templates.indexOf(
+ '<Suspense fallback={null}>',
+ galleryStart,
+ );
+ const boundaryEnd = templates.indexOf('</Suspense>', boundary);
+ const boundarySource = templates.slice(boundary, boundaryEnd);
+
+ expect(templates).toContain('function TemplatePreviewURLSync');
+ expect(templates).toContain('const searchParams = useSearchParams()');
+ expect(templates).toContain('return <TemplatesGallery />;');
+ expect(heading).toBeGreaterThan(galleryStart);
+ expect(grid).toBeGreaterThan(heading);
+ expect(boundary).toBeGreaterThan(grid);
+ expect(boundarySource).toContain('<TemplatePreviewURLSync');
+ expect(boundarySource).not.toContain('<TemplatesGallery');
+ });
+
it('reuses the same theme heading in fallback and resolved layouts', () => {
const themes = source('app/(site)/themes/page.tsx');
const themePage = source('components/ThemePackagePage.tsx');
diff --git a/apps/docsite/src/__tests__/template-gallery-performance.test.ts b/apps/docsite/src/__tests__/template-gallery-performance.test.ts
new file mode 100644
index 0000000000..30e4d29ca2
--- /dev/null
+++ b/apps/docsite/src/__tests__/template-gallery-performance.test.ts
@@ -0,0 +1,52 @@
+// 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`.
+ */
+
+import {describe, expect, it} from 'vitest';
+import {readFileSync} from 'node:fs';
+import {join} from 'node:path';
+import {buildTemplatePlaygroundHref} from '../components/playgroundLink';
+
+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)');
+ });
+
+ it('lets the playground resolve the encoded template slug', () => {
+ const playground = source('app/playground/PlaygroundClient.tsx');
+
+ 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/app/(site)/templates/page.tsx b/apps/docsite/src/app/(site)/templates/page.tsx
index 5cb837a792..704f80d7f0 100644
--- a/apps/docsite/src/app/(site)/templates/page.tsx
+++ b/apps/docsite/src/app/(site)/templates/page.tsx
@@ -1,12 +1,15 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * Templates gallery — extracted from craft.
+ * @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.
+ * @position Public `/templates` docsite route.
*/
'use client';
-import {Suspense, useCallback, useMemo, useState} from 'react';
+import {Suspense, useCallback, useEffect, useMemo, useState} from 'react';
import type {CSSProperties} from 'react';
import {useSearchParams, useRouter, usePathname} from 'next/navigation';
import * as stylex from '@stylexjs/stylex';
@@ -21,7 +24,7 @@ import {Overlay} from '@astryxdesign/core/Overlay';
import {ToggleButton, ToggleButtonGroup} from '@astryxdesign/core/ToggleButton';
import {templates} from '../../../generated/templateRegistry';
import {TemplateThumbnail} from '../../../components/TemplateThumbnail';
-import {buildPlaygroundHref} from '../../../components/playgroundLink';
+import {buildTemplatePlaygroundHref} from '../../../components/playgroundLink';
import {TemplatePreviewDialog} from '../../../components/TemplatePreviewDialog';
import type {TemplatePreviewItem} from '../../../components/TemplatePreviewDialog';
import {trackOpenPlayground, trackView} from '../../../lib/analytics';
@@ -92,15 +95,35 @@ interface TemplateItem {
slug: string;
href: string;
category: string;
- source: string;
}
export default function TemplatesPage() {
- return (
- <Suspense fallback={null}>
- <TemplatesGallery />
- </Suspense>
- );
+ return <TemplatesGallery />;
+}
+
+interface TemplatePreviewURLSyncProps {
+ indexBySlug: Map<string, number>;
+ onSlugChange: (slug: string | null) => void;
+}
+
+/**
+ * Keeps `?preview=` authoritative for deep links and soft navigation without
+ * making the visible gallery part of the query-dependent PPR hole.
+ */
+function TemplatePreviewURLSync({
+ indexBySlug,
+ onSlugChange,
+}: TemplatePreviewURLSyncProps) {
+ const searchParams = useSearchParams();
+ const previewSlug = searchParams.get('preview');
+ const openSlug =
+ previewSlug != null && indexBySlug.has(previewSlug) ? previewSlug : null;
+
+ useEffect(() => {
+ onSlugChange(openSlug);
+ }, [onSlugChange, openSlug]);
+
+ return null;
}
function TemplatesGallery() {
@@ -118,7 +141,6 @@ function TemplatesGallery() {
slug: t.slug,
href: `/templates/${t.slug}`,
category: t.category,
- source: t.source,
}))
.sort((a, b) => {
const ga = groupOf(a.category);
@@ -157,7 +179,6 @@ function TemplatesGallery() {
slug: i.slug,
name: i.name,
description: i.description,
- source: i.source,
category: groupOf(i.category),
})),
[filteredItems],
@@ -168,26 +189,26 @@ function TemplatesGallery() {
return m;
}, [flatItems]);
- const searchParams = useSearchParams();
const router = useRouter();
const pathname = usePathname();
-
- const previewSlug = searchParams.get('preview');
+ const [openSlug, setOpenSlug] = useState<string | null>(null);
const openIndex =
- previewSlug != null ? (indexBySlug.get(previewSlug) ?? null) : null;
+ openSlug != null ? (indexBySlug.get(openSlug) ?? null) : null;
const setOpenIndex = useCallback(
(index: number | null) => {
- const params = new URLSearchParams(searchParams.toString());
- if (index !== null && flatItems[index]) {
- params.set('preview', flatItems[index].slug);
+ 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');
}
const qs = params.toString();
router.replace(`${pathname}${qs ? `?${qs}` : ''}`, {scroll: false});
},
- [searchParams, flatItems, router, pathname],
+ [flatItems, router, pathname],
);
const openPreview = useCallback(
@@ -272,21 +293,19 @@ function TemplatesGallery() {
variant="secondary"
onClick={() => openPreview(item.slug)}
/>
- {item.source && (
- <Button
- label="Open in Playground"
- variant="secondary"
- href={buildPlaygroundHref(item.source)}
- onClick={e => {
- e.stopPropagation();
- trackOpenPlayground({
- page: 'templates',
- item: item.slug,
- category: groupOf(item.category),
- });
- }}
- />
- )}
+ <Button
+ label="Open in Playground"
+ variant="secondary"
+ href={buildTemplatePlaygroundHref(item.slug)}
+ onClick={e => {
+ e.stopPropagation();
+ trackOpenPlayground({
+ page: 'templates',
+ item: item.slug,
+ category: groupOf(item.category),
+ });
+ }}
+ />
</HStack>
</VStack>
}>
@@ -299,6 +318,13 @@ function TemplatesGallery() {
</Grid>
</VStack>
+ <Suspense fallback={null}>
+ <TemplatePreviewURLSync
+ indexBySlug={indexBySlug}
+ onSlugChange={setOpenSlug}
+ />
+ </Suspense>
+
<TemplatePreviewDialog
items={flatItems}
index={openIndex ?? 0}
diff --git a/apps/docsite/src/app/playground/PlaygroundClient.tsx b/apps/docsite/src/app/playground/PlaygroundClient.tsx
index 6b778df1d0..a179766570 100644
--- a/apps/docsite/src/app/playground/PlaygroundClient.tsx
+++ b/apps/docsite/src/app/playground/PlaygroundClient.tsx
@@ -2,7 +2,7 @@
/**
* @file PlaygroundClient.tsx
- * @input URL hash (shared code), user edits, knob edits
+ * @input URL hash or template query, user edits, and knob edits
* @output Full-page two-panel playground (editor + live preview)
* @position app/playground — the interactive Astryx code playground.
*
@@ -128,25 +128,38 @@ function getInitialCode(): string {
if (typeof window === 'undefined') {
return DEFAULT_CODE;
}
- const hash = window.location.hash.slice(1);
- if (!hash) {
- return DEFAULT_CODE;
- }
- const params = new URLSearchParams(hash);
- const compressed = params.get('code');
- if (!compressed) {
- return DEFAULT_CODE;
- }
- try {
- return decompressCode(compressed) || DEFAULT_CODE;
- } catch {
- return DEFAULT_CODE;
+
+ const hashParams = new URLSearchParams(window.location.hash.slice(1));
+ const compressed = hashParams.get('code');
+ if (compressed) {
+ try {
+ return decompressCode(compressed) || DEFAULT_CODE;
+ } catch {
+ return DEFAULT_CODE;
+ }
}
+
+ const templateSlug = new URLSearchParams(window.location.search).get(
+ 'template',
+ );
+ const templateSource = templates.find(
+ template => template.slug === templateSlug,
+ )?.source;
+ return templateSource
+ ? stripCodeExampleCopyrightHeader(templateSource)
+ : DEFAULT_CODE;
}
function updateURL(code: string) {
const compressed = compressCode(code);
- window.history.replaceState(null, '', `#code=${compressed}`);
+ const canonicalURL = new URL(window.location.href);
+ canonicalURL.searchParams.delete('template');
+ canonicalURL.hash = `code=${compressed}`;
+ window.history.replaceState(
+ null,
+ '',
+ `${canonicalURL.pathname}${canonicalURL.search}${canonicalURL.hash}`,
+ );
}
type LeftView = 'code' | 'theme';
diff --git a/apps/docsite/src/components/TemplatePreviewDialog.tsx b/apps/docsite/src/components/TemplatePreviewDialog.tsx
index 48eb5f7403..7f08d47831 100644
--- a/apps/docsite/src/components/TemplatePreviewDialog.tsx
+++ b/apps/docsite/src/components/TemplatePreviewDialog.tsx
@@ -8,6 +8,10 @@
* prev/next arrows to move quickly between templates in the gallery's
* display order. Arrow keys (←/→) also navigate; Escape closes.
*
+ * @input Template metadata, selected index, open state, and navigation callbacks.
+ * @output A responsive dialog with live preview and template actions.
+ * @position Shared preview controller for the templates gallery.
+ *
* The header surfaces template metadata (name, description) on
* the left. All controls cluster on the right of the header: a
* copy-to-clipboard CLI scaffold command, an Open in Playground action,
@@ -41,14 +45,13 @@ import {Skeleton} from '@astryxdesign/core/Skeleton';
import {Dialog} from '@astryxdesign/core/Dialog';
import {Tooltip} from '@astryxdesign/core/Tooltip';
import {TemplatePreviewSurface} from './TemplatePreviewSurface';
-import {buildPlaygroundHref} from './playgroundLink';
+import {buildTemplatePlaygroundHref} from './playgroundLink';
import {trackCopy, trackOpenPlayground, trackNavigate} from '../lib/analytics';
export interface TemplatePreviewItem {
slug: string;
name: string;
description?: string;
- source?: string;
category?: string;
}
@@ -146,7 +149,7 @@ function TemplatePreviewHeader({
onCopyCommand,
onClose,
}: TemplatePreviewHeaderProps) {
- const playgroundHref = item.source ? buildPlaygroundHref(item.source) : null;
+ const playgroundHref = buildTemplatePlaygroundHref(item.slug);
const metadata = (
<VStack
@@ -177,7 +180,7 @@ function TemplatePreviewHeader({
</HStack>
);
- const playgroundButton = playgroundHref ? (
+ const playgroundButton = (
<Button
label="Open in Playground"
variant="primary"
@@ -191,7 +194,7 @@ function TemplatePreviewHeader({
});
}}
/>
- ) : null;
+ );
const closeButton = (
<Button
diff --git a/apps/docsite/src/components/playgroundLink.ts b/apps/docsite/src/components/playgroundLink.ts
index af8cfcd94c..6f6e38cff8 100644
--- a/apps/docsite/src/components/playgroundLink.ts
+++ b/apps/docsite/src/components/playgroundLink.ts
@@ -1,5 +1,12 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file Playground URL builders.
+ * @input Accepts authored source code or a generated page-template slug.
+ * @output Produces links that seed the playground without running work eagerly.
+ * @position Shared navigation helper for docs, themes, and templates.
+ */
+
import {compressCode} from '../lib/compress';
import {stripCodeExampleCopyrightHeader} from '../lib/codeExamples';
@@ -16,3 +23,12 @@ export function buildPlaygroundHref(source: string, theme?: string): string {
const query = theme ? `?theme=${encodeURIComponent(theme)}` : '';
return `/playground${query}#code=${compressed}`;
}
+
+/**
+ * Link to a generated page template by slug. The playground already owns the
+ * source registry, so gallery pages can avoid embedding every template's code
+ * in their HTML just to produce a destination URL.
+ */
+export function buildTemplatePlaygroundHref(slug: string): string {
+ return `/playground?template=${encodeURIComponent(slug)}`;
+}