An open source design system that's fully customizable and agent ready
TypeScript
fix(docsite): server-render the gallery previews above the fold (#5545)
Xinzi Zhouc333a1c7cdb0
diff --git a/apps/docsite/src/__tests__/data-extraction.test.ts b/apps/docsite/src/__tests__/data-extraction.test.tsindex d63ef891dd..2e3f55af9f 100644--- a/apps/docsite/src/__tests__/data-extraction.test.ts+++ b/apps/docsite/src/__tests__/data-extraction.test.ts@@ -21,6 +21,7 @@ import {blocks, blockCount, showcaseCount} from '../generated/blockRegistry';import {templates, templateCount} from '../generated/templateRegistry';import {docTopics, docsCount} from '../generated/docsRegistry';import {showcaseRegistry} from '../generated/showcaseRegistry';+import {eagerShowcases} from '../components/eagerShowcases';import {exampleRegistry} from '../generated/exampleRegistry';const REPO_ROOT = path.resolve(@@ -1025,3 +1026,105 @@ describe('LinkProvider utility page', () => {expect(examples[0].source).toContain('<LinkProvider component=');});});++// ── Gallery Showcase Registry ──────────────────────────────────────────++/**+ * The eagerly imported showcases have to stay in step with what the+ * /components gallery actually renders first — an eager set pointing at+ * tiles further down the page would ship the chunk cost without removing+ * any loading state. These tests recompute the gallery's render order from+ * the same inputs the page uses and pin the eager set to the top of it.+ */+describe('galleryEagerShowcases', () => {+ /**+ * The gallery's category order lives in the page itself. Reading it back+ * out of the source keeps this test honest without putting a second copy+ * of the order anywhere — if the page is reordered, the expectations below+ * follow it, and the eager list is what has to catch up.+ */+ const GALLERY_PAGE = path.join(+ REPO_ROOT,+ 'apps/docsite/src/app/(docs)/components/page.tsx',+ );+ const pageSource = fs.readFileSync(GALLERY_PAGE, 'utf-8');+ const categories = [+ ...pageSource+ .slice(+ pageSource.indexOf('const CATEGORIES = ['),+ pageSource.indexOf('] as const;'),+ )+ .matchAll(/'([^']+)'/g),+ ].map(m => m[1]);++ /** Mirrors the tile filtering in the same page. */+ const isGalleryComponent = (comp: ComponentEntry) =>+ !comp.isHiddenFromOverview &&+ !comp.hidden &&+ !comp.name.startsWith('use') &&+ Boolean(comp.category) &&+ comp.group !== 'Utilities';++ /** Gallery render order: categories in display order, then registry order. */+ const galleryOrder = categories.flatMap(cat =>+ (components['@astryxdesign/core'] ?? []).filter(+ c => c.category === cat && isGalleryComponent(c),+ ),+ );++ it('reads the gallery category order out of the page', () => {+ expect(categories.length).toBeGreaterThan(5);+ expect(categories).toContain('Action');+ expect(galleryOrder.length).toBeGreaterThan(50);+ });++ it('renders every category some component declares', () => {+ const declared = new Set(+ (components['@astryxdesign/core'] ?? [])+ .filter(isGalleryComponent)+ .map(c => c.category),+ );+ for (const cat of declared) {+ expect(+ categories,+ `category "${cat}" has no section on the page`,+ ).toContain(cat);+ }+ });++ /**+ * The point of the eager set is that those tiles are the ones a visitor+ * sees first. If the gallery is reordered and this list isn't, the page+ * pays the chunk cost for tiles that are no longer on top and still shows+ * a skeleton for the ones that are.+ */+ it('eagerly imports exactly the tiles at the top of the gallery', () => {+ const expected = galleryOrder+ .filter(c => showcaseRegistry[c.name] != null)+ .slice(0, Object.keys(eagerShowcases).length)+ .map(c => c.name);+ expect(Object.keys(eagerShowcases)).toEqual(expected);+ });++ it('eager entries are components, not lazy loaders', () => {+ for (const [name, Component] of Object.entries(eagerShowcases)) {+ expect(Component, name).toBeTypeOf('function');+ // A lazy loader would resolve to a promise; an eager showcase is the+ // component itself and must render synchronously on the server.+ expect((Component as {$$typeof?: symbol}).$$typeof).toBeUndefined();+ }+ });++ it('every eager component also has a lazy loader', () => {+ for (const name of Object.keys(eagerShowcases)) {+ expect(showcaseRegistry[name], name).toBeDefined();+ }+ });++ it('keeps the eager set small enough to stay off the critical path', () => {+ // 12 covers a 2560x1440 viewport. Well past that and the page chunk is+ // carrying components nobody sees before they scroll.+ expect(Object.keys(eagerShowcases).length).toBeGreaterThanOrEqual(6);+ expect(Object.keys(eagerShowcases).length).toBeLessThanOrEqual(16);+ });+});diff --git a/apps/docsite/src/app/(docs)/components/page.tsx b/apps/docsite/src/app/(docs)/components/page.tsxindex ee5fbd7590..621e539a08 100644--- a/apps/docsite/src/app/(docs)/components/page.tsx+++ b/apps/docsite/src/app/(docs)/components/page.tsx@@ -20,7 +20,7 @@ import {Popover} from '@astryxdesign/core/Popover';import {Card} from '@astryxdesign/core/Card';import {CodeExampleBlock} from '../../../components/CodeExampleBlock';import {components as componentRegistry} from '../../../generated/componentRegistry';-import {blocks} from '../../../generated/blockRegistry';+import {showcaseRegistry} from '../../../generated/showcaseRegistry';import {ShowcaseThumbnail} from '../../../components/ShowcaseThumbnail';import {layout} from '../../../layout.stylex';@@ -46,10 +46,13 @@ const CATEGORIES = ['Utility',] as const;-/** Map of showcase blocks by component name for thumbnails */-const showcaseMap = new Map(- blocks.filter(b => b.isShowcase).map(b => [b.exampleFor, b]),-);+/**+ * Which components have a showcase to put in their tile.+ *+ * `showcaseRegistry` is a map of lazy loaders, so reading its keys costs+ * nothing — none of the showcase chunks are pulled in by this.+ */+const SHOWCASE_NAMES = new Set(Object.keys(showcaseRegistry));const styles = stylex.create({heroTitle: {@@ -73,8 +76,8 @@ interface CategoryItem {description: string;href: string;category: string;- /** Showcase block for thumbnail, if available */- showcase: (typeof blocks)[number] | undefined;+ /** Whether a showcase block exists to render in this component's tile */+ hasShowcase: boolean;}export default function ComponentsGalleryPage() {@@ -111,7 +114,7 @@ export default function ComponentsGalleryPage() {description: comp.description,href: `/components/${comp.name}`,category: comp.category,- showcase: showcaseMap.get(comp.name),+ hasShowcase: SHOWCASE_NAMES.has(comp.name),});}@@ -219,11 +222,8 @@ export default function ComponentsGalleryPage() {href={item.href}padding={0}variant="transparent">- {item.showcase ? (- <ShowcaseThumbnail- dirName={item.showcase.dirName}- category={item.showcase.category}- />+ {item.hasShowcase ? (+ <ShowcaseThumbnail name={item.name} />) : (<div {...stylex.props(styles.cardImage)} />)}diff --git a/apps/docsite/src/components/ShowcaseThumbnail.tsx b/apps/docsite/src/components/ShowcaseThumbnail.tsxindex c90332523b..dce480ad02 100644--- a/apps/docsite/src/components/ShowcaseThumbnail.tsx+++ b/apps/docsite/src/components/ShowcaseThumbnail.tsx@@ -1,23 +1,36 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file ShowcaseThumbnail.tsx+ *+ * A component's showcase block, cropped and scaled down to a gallery tile.+ *+ * @input name — component name; keys into the generated showcase registries+ * @output a 16:10 tile rendering the showcase at 2x, scaled to 0.5+ * @position rendered by the /components gallery, one per component card+ *+ * The first EAGER_SHOWCASE_COUNT tiles (see scripts/generate-data.mjs) are+ * statically imported, so they are part of the page chunk and server-render+ * into the prerendered HTML — a visitor sees them at first paint rather than+ * after hydration plus a chunk fetch. Everything below the fold still loads+ * on approach.+ */+'use client';-import React, {- lazy,- Suspense,- useRef,- useState,- useEffect,- useCallback,-} from 'react';+import React, {lazy, Suspense, useRef, useState, useEffect} from 'react';import * as stylex from '@stylexjs/stylex';import {Skeleton} from '@astryxdesign/core/Skeleton';import {Text} from '@astryxdesign/core/Text';import {Theme} from '@astryxdesign/core/theme';import {neutralTheme} from '@astryxdesign/theme-neutral/built';import {useThemeMode} from '../app/providers';+import {showcaseRegistry} from '../generated/showcaseRegistry';-const FIXED_SCALE = 0.5;+import {eagerShowcases} from './eagerShowcases';++/** Distance from the viewport at which a lazy tile starts loading. */+const LAZY_ROOT_MARGIN = '400px';const styles = stylex.create({container: {@@ -30,11 +43,17 @@ const styles = stylex.create({contentVisibility: 'auto',containIntrinsicSize: 'auto 300px 187px',},+ // The showcase renders at 2x the tile's width and is scaled back by half,+ // so a 300px tile shows a 600px-wide composition. Expressing that as+ // `200%` + `scale(0.5)` keeps it pure CSS: no measured width, so no+ // ResizeObserver, so the tile can render on the server.scaler: {position: 'absolute' as const,top: 0,left: 0,+ width: '200%',height: '200%',+ transform: 'scale(0.5)',transformOrigin: 'top left',pointerEvents: 'none' as const,overflow: 'hidden',@@ -83,58 +102,69 @@ class ShowcaseErrorBoundary extends React.Component<}}-/**- * Dynamically import a showcase block component.- * Uses webpack's dynamic import with a template literal that includes- * enough static path for webpack to create a chunk group.- */-function lazyShowcase(category: string, dirName: string) {- return lazy(- () =>- import(- /* webpackChunkName: "showcase-[request]" */- `../../../../packages/cli/assets/templates/blocks/${category}/${dirName}`- ),- );-}--const componentCache = new Map<+const lazyComponentCache = new Map<string,React.LazyExoticComponent<React.ComponentType>>();-function getShowcaseComponent(- category: string,- dirName: string,-): React.LazyExoticComponent<React.ComponentType> {- const key = `${category}/${dirName}`;- const cached = componentCache.get(key);+function getLazyShowcase(+ name: string,+): React.LazyExoticComponent<React.ComponentType> | undefined {+ const cached = lazyComponentCache.get(name);if (cached != null) {return cached;}- const component = lazyShowcase(category, dirName);- componentCache.set(key, component);+ const loader = showcaseRegistry[name];+ if (loader == null) {+ return undefined;+ }+ const component = lazy(loader);+ lazyComponentCache.set(name, component);return component;}-export function ShowcaseThumbnail({- dirName,- category,+/**+ * The tile itself: crops and scales whatever preview is placed inside it.+ */+function ThumbnailFrame({+ children,+ containerRef,}: {- dirName: string;- category: string;+ children: React.ReactNode;+ containerRef?: React.Ref<HTMLDivElement>;}) {- const {mode} = useThemeMode();+ // `themeMode`, not `mode`: it stays 'system' until the OS-preference effect+ // resolves, so a server-rendered tile follows the OS scheme through+ // light-dark() rather than flashing light for dark-mode visitors — the same+ // reasoning as the site-level <Theme> in providers.tsx (#2713).+ const {themeMode} = useThemeMode();+ return (+ <div ref={containerRef} {...stylex.props(styles.container)} inert>+ <div {...stylex.props(styles.scaler)}>+ <ShowcaseErrorBoundary>+ <Theme theme={neutralTheme} mode={themeMode}>+ {children}+ </Theme>+ </ShowcaseErrorBoundary>+ </div>+ </div>+ );+}++/** Above the fold: statically imported, rendered on the server, no skeleton. */+function EagerThumbnail({Component}: {Component: React.ComponentType}) {+ return (+ <ThumbnailFrame>+ <Component />+ </ThumbnailFrame>+ );+}++/** Below the fold: the showcase chunk is fetched as the tile nears the viewport. */+function LazyThumbnail({name}: {name: string}) {const containerRef = useRef<HTMLDivElement>(null);- const [renderWidth, setRenderWidth] = useState(0);const [isVisible, setIsVisible] = useState(false);- const updateWidth = useCallback(() => {- if (containerRef.current) {- setRenderWidth(containerRef.current.offsetWidth / FIXED_SCALE);- }- }, []);-useEffect(() => {const el = containerRef.current;if (!el) {@@ -142,45 +172,35 @@ export function ShowcaseThumbnail({}const observer = new IntersectionObserver(([entry]) => setIsVisible(entry.isIntersecting),- {rootMargin: '200px'},+ {rootMargin: LAZY_ROOT_MARGIN},);observer.observe(el);return () => observer.disconnect();}, []);- useEffect(() => {- updateWidth();- const el = containerRef.current;- if (!el) {- return;- }- const ro = new ResizeObserver(updateWidth);- ro.observe(el);- return () => ro.disconnect();- }, [updateWidth]);-- const Component = getShowcaseComponent(category, dirName);+ const Component = getLazyShowcase(name);return (- <div ref={containerRef} {...stylex.props(styles.container)} inert>- {renderWidth > 0 && isVisible && (- <div- {...stylex.props(styles.scaler)}- style={{width: renderWidth, transform: `scale(${FIXED_SCALE})`}}>- <ShowcaseErrorBoundary>- <Suspense- fallback={- <div {...stylex.props(styles.skeleton)}>- <Skeleton width="100%" height="100%" />- </div>- }>- <Theme theme={neutralTheme} mode={mode}>- <Component />- </Theme>- </Suspense>- </ShowcaseErrorBoundary>- </div>- )}- </div>+ <ThumbnailFrame containerRef={containerRef}>+ {isVisible && Component != null ? (+ <Suspense+ fallback={+ <div {...stylex.props(styles.skeleton)}>+ <Skeleton width="100%" height="100%" />+ </div>+ }>+ <Component />+ </Suspense>+ ) : null}+ </ThumbnailFrame>+ );+}++export function ShowcaseThumbnail({name}: {name: string}) {+ const Eager = eagerShowcases[name];+ return Eager != null ? (+ <EagerThumbnail Component={Eager} />+ ) : (+ <LazyThumbnail name={name} />);}diff --git a/apps/docsite/src/components/eagerShowcases.ts b/apps/docsite/src/components/eagerShowcases.tsnew file mode 100644index 0000000000..1d3d1e093c--- /dev/null+++ b/apps/docsite/src/components/eagerShowcases.ts@@ -0,0 +1,58 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file eagerShowcases.ts+ *+ * The showcases for the gallery tiles above the fold, imported statically.+ *+ * @input nothing — hand-authored+ * @output eagerShowcases, keyed by component name+ * @position read by ShowcaseThumbnail; every other tile loads its showcase+ * lazily through the generated showcaseRegistry+ *+ * A static import is the whole point: these land in the /components page+ * chunk, so Next server-renders them into the prerendered HTML and a visitor+ * sees a real preview at first paint instead of after hydration plus a chunk+ * fetch. A dynamic import — however it is spelled — cannot do that.+ *+ * 12 covers everything in the viewport up to a 2560x1440 display (measured:+ * 6 tiles in view at 1440x900, 9 at 1920x1080, 10 at 2560x1440) and lands on+ * a category boundary — all of Action, plus the first two of Chat. Their+ * sources total ~9 KB of TSX. Adding to the list is cheap but not free:+ * every entry pulls the components it uses into the initial page chunk.+ *+ * These have to be the tiles the gallery renders FIRST, which follows from+ * the category order in src/app/(docs)/components/page.tsx. Reorder that and+ * this list has to move with it — the `galleryEagerShowcases` tests fail+ * when the two disagree, and name the list they expect.+ */++import type {ComponentType} from 'react';++import ButtonShowcase from '../generated/showcases/ButtonShowcase';+import ButtonGroupShowcase from '../generated/showcases/ButtonGroupShowcase';+import DropdownMenuShowcase from '../generated/showcases/DropdownMenuShowcase';+import IconButtonShowcase from '../generated/showcases/IconButtonShowcase';+import LinkShowcase from '../generated/showcases/LinkShowcase';+import MoreMenuShowcase from '../generated/showcases/MoreMenuShowcase';+import SegmentedControlShowcase from '../generated/showcases/SegmentedControlShowcase';+import ToggleButtonShowcase from '../generated/showcases/ToggleButtonShowcase';+import ToggleButtonGroupShowcase from '../generated/showcases/ToggleButtonGroupShowcase';+import ToolbarThreeSlot from '../generated/showcases/ToolbarThreeSlot';+import ChatComposerShowcase from '../generated/showcases/ChatComposerShowcase';+import ChatLayoutShowcase from '../generated/showcases/ChatLayoutShowcase';++export const eagerShowcases: Record<string, ComponentType> = {+ Button: ButtonShowcase,+ ButtonGroup: ButtonGroupShowcase,+ DropdownMenu: DropdownMenuShowcase,+ IconButton: IconButtonShowcase,+ Link: LinkShowcase,+ MoreMenu: MoreMenuShowcase,+ SegmentedControl: SegmentedControlShowcase,+ ToggleButton: ToggleButtonShowcase,+ ToggleButtonGroup: ToggleButtonGroupShowcase,+ Toolbar: ToolbarThreeSlot,+ ChatComposer: ChatComposerShowcase,+ ChatLayout: ChatLayoutShowcase,+};