An open source design system that's fully customizable and agent ready
TypeScript
docsite: send /themes a small theme list instead of the package and template registries (#9937)
Cindy Zhang241e1d282fcb
diff --git a/apps/docsite/src/__tests__/docs-nav.test.ts b/apps/docsite/src/__tests__/docs-nav.test.tsindex 71e05f41c9..394da70d69 100644--- a/apps/docsite/src/__tests__/docs-nav.test.ts+++ b/apps/docsite/src/__tests__/docs-nav.test.ts@@ -1,9 +1,10 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Docs nav model: the (docs) layout gives DocsShell a small projection of- * the registries. DocsShell is a client component, so React serializes its- * props into every docs page, and the modules it imports ship to the browser.+ * @file Client data models: the (docs) layout gives DocsShell, and the /themes+ * page gives ThemePackagePage, a small projection of the registries. Both are+ * client components, so React serializes their props into the page, and the+ * modules they import ship to the browser.*/import {readFileSync} from 'node:fs';@@ -11,8 +12,22 @@ import {join} from 'node:path';import {describe, it, expect} from 'vitest';import {packages} from '../generated/packageRegistry';import {docTopics} from '../generated/docsRegistry';+import {templates} from '../generated/templateRegistry';import {flattenComponentSidebarEntries} from '../components/componentSidebarData';import {getDocsNav, type DocsNavItem} from '../components/docsNav';+import {+ getThemeExplorerPackages,+ getThemeShowcaseSource,+} from '../components/themeExplorerData';++function expectOnlyTypeImports(file: string, dataImportPattern: RegExp) {+ const source = readFileSync(join(__dirname, '..', file), 'utf8');+ const dataImports = [...source.matchAll(dataImportPattern)];+ expect(dataImports.length).toBeGreaterThan(0);+ for (const [statement, typeOnly] of dataImports) {+ expect(typeOnly, statement).toBeTruthy();+ }+}function flattenNavEntries(items: DocsNavItem[]) {return items.flatMap(item => (item.type === 'entry' ? [item] : item.entries));@@ -62,18 +77,56 @@ describe('docs nav model', () => {});it('keeps registry modules out of the DocsShell client bundle', () => {- const source = readFileSync(- join(__dirname, '../components/DocsShell.tsx'),- 'utf8',+ expectOnlyTypeImports(+ 'components/DocsShell.tsx',+ /^import\s+(type\s+)?[^;]*?from\s+'(\.\.\/generated\/[^']+|\.\/componentSidebarData|\.\/docsNav)';/gm,+ );+ });+});++describe('theme explorer model', () => {+ const themePackages = getThemeExplorerPackages();++ it('keeps every theme package with only the fields the explorer reads', () => {+ const registryThemes = packages.filter(p =>+ p.name.startsWith('@astryxdesign/theme-'),);- const dataImports = [- ...source.matchAll(- /^import\s+(type\s+)?[^;]*?from\s+'(\.\.\/generated\/[^']+|\.\/componentSidebarData|\.\/docsNav)';/gm,+ expect(themePackages).toHaveLength(registryThemes.length);+ expect(themePackages).toEqual(+ expect.arrayContaining(+ registryThemes.map(({name, displayName}) => ({name, displayName})),),+ );+ });++ it('lists themes in gallery order, then the rest alphabetically', () => {+ const galleryOrder = [+ '@astryxdesign/theme-neutral',+ '@astryxdesign/theme-stone',+ '@astryxdesign/theme-gothic',+ '@astryxdesign/theme-matcha',+ '@astryxdesign/theme-y2k',+ '@astryxdesign/theme-butter',];- expect(dataImports.length).toBeGreaterThan(0);- for (const [statement, typeOnly] of dataImports) {- expect(typeOnly, statement).toBeTruthy();- }+ const names = themePackages.map(p => p.name);+ const ordered = names.filter(name => galleryOrder.includes(name));+ const rest = names.filter(name => !galleryOrder.includes(name));+ expect(ordered).toEqual(galleryOrder.filter(name => names.includes(name)));+ expect(names).toEqual([...ordered, ...rest]);+ expect(rest).toEqual([...rest].sort((a, b) => a.localeCompare(b)));+ });++ it('gives the theme-showcase template source to Open in Playground', () => {+ const showcase = templates.find(t => t.slug === 'theme-showcase');+ expect(showcase?.source).toBeTruthy();+ expect(getThemeShowcaseSource()).toBe(showcase?.source);+ });++ it('keeps package and template registries out of the ThemePackagePage client bundle', () => {+ // The theme objects render every theme preview, so they stay in the bundle.+ expectOnlyTypeImports(+ 'components/ThemePackagePage.tsx',+ /^import\s+(type\s+)?[^;]*?from\s+'(\.\.\/generated\/(?!themeRegistry')[^']+|\.\/themeExplorerData)';/gm,+ );});});diff --git a/apps/docsite/src/app/(site)/themes/page.tsx b/apps/docsite/src/app/(site)/themes/page.tsxindex 2d7236a849..7c960f3dcc 100644--- a/apps/docsite/src/app/(site)/themes/page.tsx+++ b/apps/docsite/src/app/(site)/themes/page.tsx@@ -25,6 +25,10 @@ import {Carousel} from '@astryxdesign/core/Carousel';import {packages} from '../../../generated/packageRegistry';import {themeObjects} from '../../../generated/themeRegistry';import {ThemePackagePage} from '../../../components/ThemePackagePage';+import {+ getThemeExplorerPackages,+ getThemeShowcaseSource,+} from '../../../components/themeExplorerData';import {ThemeHeading} from '../../../components/ThemeHeading';import {ThemeExplorerActions,@@ -121,7 +125,14 @@ async function SeededThemeExplorer({notFound();}- return <ThemePackagePage packageName={seedPkg.name} theme={seedTheme} />;+ return (+ <ThemePackagePage+ packageName={seedPkg.name}+ theme={seedTheme}+ themePackages={getThemeExplorerPackages()}+ showcaseSource={getThemeShowcaseSource()}+ />+ );}/**diff --git a/apps/docsite/src/components/ThemePackagePage.tsx b/apps/docsite/src/components/ThemePackagePage.tsxindex 628fd385ec..9fc32b40a0 100644--- a/apps/docsite/src/components/ThemePackagePage.tsx+++ b/apps/docsite/src/components/ThemePackagePage.tsx@@ -23,9 +23,8 @@ import {Selector} from '@astryxdesign/core/Selector';import {ThemeShowcaseStore} from '../../../../packages/cli/assets/templates/pages/theme-showcase/page';import {getThemeShowcaseContent} from './themeShowcaseContent';import {buildPlaygroundHref} from './playgroundLink';-import {packages} from '../generated/packageRegistry';import {themeObjects} from '../generated/themeRegistry';-import {templates} from '../generated/templateRegistry';+import type {ThemeExplorerPackage} from './themeExplorerData';import {trackCopy, trackOpenPlayground, trackToggle} from '../lib/analytics';import {useThemeMode} from '../app/providers';import {ThemeHeading} from './ThemeHeading';@@ -43,29 +42,9 @@ import {ThemeExplorerSidebarSurface,} from './ThemeExplorerLayout';-// Raw source of the theme-showcase page template (embedded as a string in-// the generated template registry). Used to prepopulate the playground's-// code editor when the user clicks "Open in Playground" from a theme.-const THEME_SHOWCASE_SOURCE =- templates.find(t => t.slug === 'theme-showcase')?.source ?? '';-// Per-theme picker banners are self-hosted under the docsite's /public/images// dir (same location as the showcase product photos).-// Gallery order — themes are listed in the same canonical visual--// closeness order used elsewhere (most restrained → most expressive).-// Lives here so the sidebar's theme list reads in the same order as-// /themes (Neutral → Stone → Gothic → Matcha → Y2K → Butter). Any-// theme not in this list falls to the end alphabetically.-const THEME_ORDER: ReadonlyArray<string> = [- '@astryxdesign/theme-neutral',- '@astryxdesign/theme-stone',- '@astryxdesign/theme-gothic',- '@astryxdesign/theme-matcha',- '@astryxdesign/theme-y2k',- '@astryxdesign/theme-butter',-];-// The package whose selection corresponds to the canonical bare// `/themes` URL (no `?theme=` query string). Must agree with the// `DEFAULT_THEME_PACKAGE` constant in `app/(site)/themes/page.tsx`,@@ -436,9 +415,18 @@ interface ThemePackagePageProps {/** Full npm package name — seeds the initial selected theme. */packageName: string;theme: DefinedTheme;+ /** Theme packages in gallery order. They feed the sidebar and the mobile carousel. */+ themePackages: ThemeExplorerPackage[];+ /** Theme-showcase template source that seeds the playground code editor. */+ showcaseSource: string;}-export function ThemePackagePage({packageName, theme}: ThemePackagePageProps) {+export function ThemePackagePage({+ packageName,+ theme,+ themePackages,+ showcaseSource,+}: ThemePackagePageProps) {// Preview color mode. `siteMode` is the docsite's already-resolved concrete// light/dark — the provider maps its default `system` to the OS preference// (falling back to light on the first paint), so the preview never sees@@ -516,27 +504,6 @@ export function ThemePackagePage({packageName, theme}: ThemePackagePageProps) {[router, pathname],);- // Sorted list of all theme packages — feeds the sidebar list and- // the mobile dropdown. Order matches the /themes overview gallery.- const themePackages = useMemo(() => {- return packages- .filter(p => p.name.startsWith('@astryxdesign/theme-'))- .sort((a, b) => {- const ai = THEME_ORDER.indexOf(a.name);- const bi = THEME_ORDER.indexOf(b.name);- if (ai === -1 && bi === -1) {- return a.name.localeCompare(b.name);- }- if (ai === -1) {- return 1;- }- if (bi === -1) {- return -1;- }- return ai - bi;- });- }, []);-// Resolve the currently-selected theme object. Falls back to the// SSR-seeded prop if the lookup ever misses (shouldn't happen —// the selector only offers options sourced from the same packages@@ -591,7 +558,7 @@ export function ThemePackagePage({packageName, theme}: ThemePackagePageProps) {// the query string), which runs after the navigation has committed the// new URL, so the hash is reliably present when it's read.const customizeHref = buildPlaygroundHref(- THEME_SHOWCASE_SOURCE,+ showcaseSource,packageNameToSlug(selectedPkgName),);diff --git a/apps/docsite/src/components/themeExplorerData.ts b/apps/docsite/src/components/themeExplorerData.tsnew file mode 100644index 0000000000..f478590b8e--- /dev/null+++ b/apps/docsite/src/components/themeExplorerData.ts@@ -0,0 +1,59 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file themeExplorerData.ts+ * @input Generated package and template registries+ * @output The theme picker list and the theme showcase source+ * @position Server-side projection that the /themes page passes to+ * ThemePackagePage+ *+ * SYNC: When ThemePackagePage reads another registry field, add it here.+ */++import {packages, type PackageMeta} from '../generated/packageRegistry';+import {templates} from '../generated/templateRegistry';++export type ThemeExplorerPackage = Pick<PackageMeta, 'name' | 'displayName'>;++// Gallery order, from most restrained to most expressive. A theme that is+// not in this list goes to the end, in alphabetical order.+const THEME_ORDER: ReadonlyArray<string> = [+ '@astryxdesign/theme-neutral',+ '@astryxdesign/theme-stone',+ '@astryxdesign/theme-gothic',+ '@astryxdesign/theme-matcha',+ '@astryxdesign/theme-y2k',+ '@astryxdesign/theme-butter',+];++function compareThemeOrder(a: ThemeExplorerPackage, b: ThemeExplorerPackage) {+ const ai = THEME_ORDER.indexOf(a.name);+ const bi = THEME_ORDER.indexOf(b.name);+ if (ai === -1 && bi === -1) {+ return a.name.localeCompare(b.name);+ }+ if (ai === -1) {+ return 1;+ }+ if (bi === -1) {+ return -1;+ }+ return ai - bi;+}++/**+ * React serializes the props of a client component into the page, and the+ * modules it imports ship to the browser. The package and template registries+ * are megabytes, so the theme explorer gets only the fields it reads.+ */+export function getThemeExplorerPackages(): ThemeExplorerPackage[] {+ return packages+ .filter(p => p.name.startsWith('@astryxdesign/theme-'))+ .map(({name, displayName}) => ({name, displayName}))+ .sort(compareThemeOrder);+}++/** The theme-showcase template source that seeds Open in Playground. */+export function getThemeShowcaseSource(): string {+ return templates.find(t => t.slug === 'theme-showcase')?.source ?? '';+}