Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 119 additions & 0 deletions apps/docsite/e2e/home-component-registry.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.

/**
* @file home-component-registry.spec.ts
* @input Production docsite home page and components page, and the generated
* component registry
* @output Regression proof that the home page shows the number of public Core
* components, and loads no script that holds the component registry
* @position Docsite browser tests; only a built page shows which scripts it
* loads
*/

import {expect, test, type Page} from '@playwright/test';
import {components} from '../src/generated/componentRegistry';

const SAMPLE_COUNT = 10;
// A minifier keeps these characters of a string as they are. It can escape a
// quote, a backslash or a dollar sign, and a character outside ASCII.
const PRINTABLE_ASCII = /^[\x20-\x7e]+$/u;
const ESCAPABLE_CHARACTER = /["'`\\$]/u;

/** Component descriptions from the whole registry, as a script holds them. */
function registrySamples(): string[] {
const descriptions = [
...new Set(
Object.values(components)
.flat()
.map(component => component.description)
.filter(
description =>
description.length >= 40 &&
PRINTABLE_ASCII.test(description) &&
!ESCAPABLE_CHARACTER.test(description),
),
),
];
const step = descriptions.length / SAMPLE_COUNT;
return Array.from(
{length: SAMPLE_COUNT},
(_, index) => descriptions[Math.floor(index * step)],
);
}

interface LoadedScript {
path: string;
text: string;
}

/** Each script the page loads before its network is idle. */
async function loadedScripts(
page: Page,
path: string,
): Promise<LoadedScript[]> {
const scripts: Promise<LoadedScript>[] = [];
page.on('response', response => {
if (response.request().resourceType() === 'script' && response.ok()) {
scripts.push(
response
.text()
.then(text => ({path: new URL(response.url()).pathname, text})),
);
}
});
await page.goto(path, {waitUntil: 'networkidle'});
return Promise.all(scripts);
}

/**
* The paths of the scripts that hold the registry. A page can quote one
* description in its own copy. More than half of the samples in one script is
* the registry itself.
*/
function registryScripts(scripts: LoadedScript[], samples: string[]): string[] {
return scripts
.filter(
({text}) =>
samples.filter(sample => text.includes(sample)).length >
samples.length / 2,
)
.map(script => script.path);
}

test('the home page loads no script that holds the component registry', async ({
browser,
}) => {
const samples = registrySamples();
expect(new Set(samples).size).toBe(SAMPLE_COUNT);

// The components page renders from the registry in the browser, so one of
// its scripts holds it. This proves that the samples find the registry.
const componentsPage = await browser.newPage();
const componentsScripts = await loadedScripts(componentsPage, '/components');
await componentsPage.close();
expect(registryScripts(componentsScripts, samples)).not.toEqual([]);

const homePage = await browser.newPage();
const homeScripts = await loadedScripts(homePage, '/');
await homePage.close();
expect(homeScripts.length).toBeGreaterThan(0);
expect(registryScripts(homeScripts, samples)).toEqual([]);
});

// home-component-count.test.tsx pins the rule of the count. This test proves
// that the built page shows that number in both places.
test('the home page shows the count of the registry on the components card and in the closing section', async ({
page,
}) => {
const publicComponents = components['@astryxdesign/core'].filter(
component => !component.hidden && !component.name.startsWith('use'),
).length;
const count = Math.floor(publicComponents / 10) * 10;
expect(count).toBeGreaterThan(0);

await page.goto('/');
await expect(
page.getByRole('heading', {name: `Over ${count} components`}),
).toBeVisible();
await expect(page.getByText(`Browse ${count}+ components`)).toBeVisible();
});
114 changes: 114 additions & 0 deletions apps/docsite/src/__tests__/home-component-count.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.

/**
* @file home-component-count.test.tsx
* @input The home page's server entry, its two sections that show the
* component count, and a component registry fixture
* @output Proof that the server entry counts the public Core components,
* rounded down to the nearest 10, and that each section shows the number it
* receives
* @position Docsite unit tests. e2e/home-component-registry.spec.ts proves
* that the built home page loads no script that holds the registry.
* Run: pnpm -F @astryxdesign/docsite test
*/

import type {ReactNode} from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import {describe, expect, it, vi} from 'vitest';

// 27 public Core components. A wrong filter, package or rounding gives a
// number in another ten.
const registry = vi.hoisted(() => {
const entries = (prefix: string, count: number, hidden = false) =>
Array.from({length: count}, (_, index) => ({
name: `${prefix}${index}`,
hidden,
}));
return {
'@astryxdesign/core': [
...entries('Component', 27),
...entries('Hidden', 9, true),
...entries('useHook', 8),
],
'@astryxdesign/lab': entries('LabComponent', 50),
};
});

// Each mocked component renders its children only, so a test reads the copy
// without the styles and context that the real components need.
const stubs = vi.hoisted(() => ({
passthrough: async (names: string[]) => {
const {createElement} = await import('react');
return Object.fromEntries(
names.map(name => [
name,
({children}: {children?: ReactNode}) =>
createElement('div', null, children),
]),
);
},
}));

vi.mock('@stylexjs/stylex', () => ({
create: (styles: Record<string, unknown>) => styles,
defineConsts: (consts: Record<string, unknown>) => consts,
props: () => ({}),
}));
vi.mock('@astryxdesign/core/Button', () => stubs.passthrough(['Button']));
vi.mock('@astryxdesign/core/Card', () => stubs.passthrough(['Card']));
vi.mock('@astryxdesign/core/Grid', () => stubs.passthrough(['Grid']));
vi.mock('@astryxdesign/core/Layout', () =>
stubs.passthrough(['VStack', 'HStack']),
);
vi.mock('@astryxdesign/core/Link', () => stubs.passthrough(['Link']));
vi.mock('@astryxdesign/core/Text', () =>
stubs.passthrough(['Text', 'Heading']),
);
vi.mock('@astryxdesign/core/theme/tokens.stylex', () => ({spacingVars: {}}));
vi.mock('../components/logos', () => stubs.passthrough(['AstryxLogo']));
vi.mock('../app/(site)/_landing/CliPreview', () =>
stubs.passthrough(['CliPreview']),
);
vi.mock('../app/(site)/_landing/ComponentsPreview', () =>
stubs.passthrough(['ComponentsPreview']),
);
vi.mock('../app/(site)/_landing/ThemesPreview', () =>
stubs.passthrough(['ThemesPreview']),
);
vi.mock('../generated/componentRegistry', () => ({components: registry}));
// The server entry test reads the props that the entry gives the homepage.
vi.mock('../app/(site)/HomePage', () => stubs.passthrough(['HomePage']));
vi.mock('../app/(site)/_landing/FrozenPreview', () =>
stubs.passthrough(['FrozenPreview']),
);
vi.mock('../app/(site)/_landing/TemplatesPreview', () =>
stubs.passthrough(['TemplatesPreview']),
);

import {DiscoverShowcase} from '../app/(site)/_landing/DiscoverShowcase';
import {FeaturesShowcase} from '../app/(site)/_landing/FeaturesShowcase';
import Page from '../app/(site)/page';

describe('home page component count', () => {
it('is the number of public Core components, rounded down to the nearest 10', () => {
expect(Page().props.coreComponentCount).toBe(20);
});

it('shows the number it receives on the components card', () => {
const html = renderToStaticMarkup(
<FeaturesShowcase
coreComponentCount={120}
templatesPreview={null}
themesStore={null}
/>,
);
expect(html).toContain('Over 120 components');
});

it('shows the number it receives in the closing section', () => {
const html = renderToStaticMarkup(
<DiscoverShowcase coreComponentCount={120} />,
);
expect(html.replaceAll('<!-- -->', '')).toContain('Browse 120+ components');
});
});
6 changes: 5 additions & 1 deletion apps/docsite/src/app/(site)/HomePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -282,9 +282,12 @@ function HeroContent({contentRef}: {contentRef: Ref<HTMLElement>}) {
}

export function HomePage({
coreComponentCount,
templatesPreview,
themesStore,
}: {
/** Public Core components, rounded down to the nearest 10. */
coreComponentCount: number;
templatesPreview: ReactNode;
themesStore: ReactNode;
}) {
Expand Down Expand Up @@ -382,12 +385,13 @@ export function HomePage({
</HeroReelProvider>
<VStack ref={showcaseRef} xstyle={styles.showcaseOverlay}>
<FeaturesShowcase
coreComponentCount={coreComponentCount}
templatesPreview={templatesPreview}
themesStore={themesStore}
/>
<AboutShowcase />
<BlogShowcase />
<DiscoverShowcase />
<DiscoverShowcase coreComponentCount={coreComponentCount} />
</VStack>
</div>
);
Expand Down
19 changes: 7 additions & 12 deletions apps/docsite/src/app/(site)/_landing/DiscoverShowcase.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,8 @@ import {Heading, Text} from '@astryxdesign/core/Text';
import {Button} from '@astryxdesign/core/Button';
import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';
import {AstryxLogo} from '../../../components/logos';
import {components} from '../../../generated/componentRegistry';
import {layout} from '../../../layout.stylex';

// Public core component count, rounded down to the nearest 10 for marketing
// copy. Sourced from the generated registry so it stays accurate as the library grows.
const CORE_COMPONENT_COUNT_ROUNDED =
Math.floor(
(components['@astryxdesign/core'] ?? []).filter(
c => !c.hidden && !c.name.startsWith('use'),
).length / 10,
) * 10;

const styles = stylex.create({
section: {
width: '100%',
Expand Down Expand Up @@ -192,7 +182,12 @@ const styles = stylex.create({
},
});

export function DiscoverShowcase() {
export function DiscoverShowcase({
coreComponentCount,
}: {
/** Public Core components, rounded down to the nearest 10. */
coreComponentCount: number;
}) {
const stageRef = useRef<HTMLDivElement | null>(null);
const [spread, setSpread] = useState(false);

Expand Down Expand Up @@ -278,7 +273,7 @@ export function DiscoverShowcase() {
type="body"
color="secondary"
xstyle={styles.supportingText}>
Browse {CORE_COMPONENT_COUNT_ROUNDED}+ components, explore
Browse {coreComponentCount}+ components, explore
production-ready templates, and tune themes to match your brand;
pick a starting point and go.
</Text>
Expand Down
33 changes: 18 additions & 15 deletions apps/docsite/src/app/(site)/_landing/FeaturesShowcase.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,11 @@ import {VStack, HStack} from '@astryxdesign/core/Layout';
import {Heading, Text} from '@astryxdesign/core/Text';
import {Link} from '@astryxdesign/core/Link';
import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';
import {components} from '../../../generated/componentRegistry';
import {layout} from '../../../layout.stylex';
import {ComponentsPreview} from './ComponentsPreview';
import {CliPreview} from './CliPreview';
import {ThemesPreview} from './ThemesPreview';

// Count of public @astryxdesign/core components (excluding hooks and hidden entries).
// Sourced from the generated registry so the number stays accurate as the
// library grows.
const CORE_COMPONENT_COUNT = (components['@astryxdesign/core'] ?? []).filter(
c => !c.hidden && !c.name.startsWith('use'),
).length;
// Round down to the nearest 10 for marketing copy ("Over X components"
// reads better than "Over 87 components" and avoids the displayed number
// going stale every time a single component lands.
const CORE_COMPONENT_COUNT_ROUNDED = Math.floor(CORE_COMPONENT_COUNT / 10) * 10;

const styles = stylex.create({
// Bento CSS-grid layout. Each grid cell holds a full-height
// column wrapper (VStack with height:100%) rather than a
Expand Down Expand Up @@ -355,9 +343,14 @@ type Feature = {
// ordered array because the visual order in the grid is not the
// same as any obvious data order — explicit slot mapping is clearer
// than counting indices.
const features: Record<string, Feature> = {
const features: {
components: Omit<Feature, 'title'>;
themes: Feature;
templates: Feature;
cli: Feature;
} = {
// FeaturesShowcase adds the title: its count comes from the server page.
components: {
title: `Over ${CORE_COMPONENT_COUNT_ROUNDED} components`,
description:
'Accessible and themeable React components with built-in spacing, dark mode, and flexible styling.',
href: '/components',
Expand Down Expand Up @@ -581,9 +574,12 @@ function HeadingBlock() {
}

export function FeaturesShowcase({
coreComponentCount,
templatesPreview,
themesStore,
}: {
/** Public Core components, rounded down to the nearest 10. */
coreComponentCount: number;
/** The templates card preview (TemplatesPreview). */
templatesPreview: ReactNode;
/** The themes card store snapshot (FrozenPreview), rendered on the server. */
Expand Down Expand Up @@ -634,7 +630,14 @@ export function FeaturesShowcase({
/>
</VStack>
<VStack gap={8} width="100%" height="100%" xstyle={styles.column}>
<FeatureCard feature={features.components} isFlex insetImage />
<FeatureCard
feature={{
...features.components,
title: `Over ${coreComponentCount} components`,
}}
isFlex
insetImage
/>
<FeatureCard feature={features.cli} />
</VStack>
<VStack gap={8} width="100%" height="100%" xstyle={styles.column}>
Expand Down
Loading