Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/docs-example-heights.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@layerstack/docs': minor
---

feat: Record each example's rendered height in the screenshot index, and add it to the example catalog with `generate-catalog --screenshots <dir>`, so a page can hold an example's space before it renders
10 changes: 8 additions & 2 deletions docs/src/content/guides/docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ manually.
"scripts": {
"prebuild": "pnpm generate:api && pnpm generate:stackblitz && pnpm generate:releases",
"generate:api": "layerstack-docs generate-api ../packages/<pkg>/src/lib/components generated/api",
"generate:catalog": "layerstack-docs generate-catalog ../packages/<pkg>/src/lib/components src/examples/components src/examples/catalog",
"generate:catalog": "layerstack-docs generate-catalog ../packages/<pkg>/src/lib/components src/examples/components src/examples/catalog --screenshots static/screenshots",
"generate:screenshots": "layerstack-docs generate-screenshots src/examples/components static/screenshots",
"generate:stackblitz": "layerstack-docs generate-stackblitz src static/stackblitz-files.json [remote-sources.json]",
"generate:releases": "layerstack-docs generate-releases techniq/<repo> generated/releases",
Expand All @@ -32,11 +32,17 @@ manually.
| Command | Arguments | Generates |
| ---------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------- |
| `generate-api` | `<components-dir> <output-dir>` | Per-component prop API JSON (via the TypeScript compiler) |
| `generate-catalog` | `<components-dir> <examples-dir> <catalog-dir>` | Per-component example + cross-usage catalogs |
| `generate-catalog` | `<components-dir> <examples-dir> <catalog-dir> [--screenshots]` | Per-component example + cross-usage catalogs |
| `generate-screenshots` | `<examples-dir> <screenshots-dir> [--base-url] [--route-base] [--all]` | Responsive light/dark WebP screenshots (Playwright + sharp) |
| `generate-stackblitz` | `<source-dir> <output-file> [remote-sources-file] [--template-dir] [--source] [--remote]` | A StackBlitz/WebContainer file bundle |
| `generate-releases` | `<owner/repo> <output-dir>` | GitHub releases → frontmatter markdown files |

`generate-screenshots` also records each example's rendered height (at its 800px viewport) in
`<screenshots-dir>/index.json`, measuring examples whose screenshots are already up to date without
re-encoding them. Pass that directory to `generate-catalog --screenshots` to add each example's
`height` to its catalog entry, so a page can hold the example's space before it renders. Run
screenshots first.

The output under `generated/api/*` and `generated/releases/*` is picked up automatically by
the `references`/`components`/`releases` collections.

Expand Down
5 changes: 5 additions & 0 deletions packages/docs/src/lib/catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ export interface ExampleInfo {
createdAt?: string;
/** ISO timestamp of the last commit that changed the example file */
updatedAt?: string;
/**
* Rendered height in pixels, measured by the screenshot generator (at its viewport's width). Lets
* a page hold the example's space before it renders.
*/
height?: number;
}

/**
Expand Down
12 changes: 9 additions & 3 deletions packages/docs/src/lib/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
*
* Commands:
* generate-api <components-dir> <output-dir>
* generate-catalog <components-dir> <examples-dir> <catalog-dir>
* generate-catalog <components-dir> <examples-dir> <catalog-dir> [--screenshots <dir>]
* generate-screenshots <examples-dir> <screenshots-dir> [--base-url <url>] [--route-base <path>] [--all]
* generate-stackblitz <source-dir> <output-file> [remote-sources-file] [--template-dir <dir>] [--source out=src ...] [--remote out=src ...]
* generate-releases <owner/repo> <output-dir>
Expand Down Expand Up @@ -76,7 +76,7 @@ const HELP = `layerstack-docs <command> [...args]

Commands:
generate-api <components-dir> <output-dir>
generate-catalog <components-dir> <examples-dir> <catalog-dir>
generate-catalog <components-dir> <examples-dir> <catalog-dir> [--screenshots <dir>]
generate-screenshots <examples-dir> <screenshots-dir> [--base-url <url>] [--route-base <path>] [--all]
generate-stackblitz <source-dir> <output-file> [remote-sources-file]
[--template-dir <dir>] [--source out=src ...] [--remote out=src ...]
Expand Down Expand Up @@ -104,7 +104,13 @@ async function main() {
'Usage: layerstack-docs generate-catalog <components-dir> <examples-dir> <catalog-dir>'
);
}
await writeExampleCatalogs({ componentsDir, examplesDir, catalogDir });
await writeExampleCatalogs({
componentsDir,
examplesDir,
catalogDir,
// Example heights from its screenshot index (see `generate-screenshots`)
screenshotsDir: optString(options, 'screenshots'),
});
break;
}

Expand Down
60 changes: 56 additions & 4 deletions packages/docs/src/lib/node/example-catalog.js
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,13 @@ export function getExampleGitDates(examplesDir) {
* @param existingExamples - examples from the previously generated catalog, used to keep
* existing dates when git history is unavailable (or the file has not been committed yet)
*/
function getComponentExamples(componentName, allComponents, gitDates, existingExamples = []) {
function getComponentExamples(
componentName,
allComponents,
gitDates,
existingExamples = [],
heights = null
) {
const componentExamplesDir = path.join(EXAMPLES_DIR, componentName);
const examples = [];
// Check if the component examples directory exists
Expand Down Expand Up @@ -240,6 +246,13 @@ function getComponentExamples(componentName, allComponents, gitDates, existingEx
if (dates?.updatedAt) {
info.updatedAt = dates.updatedAt;
}
// From the screenshot index when given one, else as the existing catalog has it
const height = heights
? heights.get(`${componentName}/${exampleName}`)
: existingExamples.find((e) => e.name === exampleName)?.height;
if (typeof height === 'number') {
info.height = height;
}
examples.push(info);
}
}
Expand Down Expand Up @@ -308,8 +321,16 @@ function withoutDates(examples) {
*
* @param gitDates - result of `getExampleGitDates()`. When `null`/`undefined`, example
* dates are carried over from the existing catalog file.
* @param heights - result of `getExampleHeights()`. When `null`/`undefined`, example heights
* are carried over from the existing catalog file.
*/
export function generateComponentCatalog(componentName, catalogPath, allComponents, gitDates) {
export function generateComponentCatalog(
componentName,
catalogPath,
allComponents,
gitDates,
heights
) {
console.log(`Processing ${componentName}...`);
// Read existing catalog (if any)
let existingCatalog;
Expand All @@ -324,7 +345,8 @@ export function generateComponentCatalog(componentName, catalogPath, allComponen
componentName,
allComponents,
gitDates,
Array.isArray(existingCatalog?.examples) ? existingCatalog.examples : []
Array.isArray(existingCatalog?.examples) ? existingCatalog.examples : [],
heights
);
const usage = findComponentUsage(componentName);
// Check if content has changed (excluding updatedAt field and example dates, which follow
Expand All @@ -341,10 +363,30 @@ export function generateComponentCatalog(componentName, catalogPath, allComponen
updatedAt: (contentUnchanged && existingCatalog.updatedAt) || new Date().toISOString(),
};
}
/**
* Each example's rendered height from a screenshot index (`<screenshots-dir>/index.json`, written by
* `generateScreenshots()`), keyed `<component>/<example>`. `null` if there's no index.
*/
export function getExampleHeights(screenshotsDir) {
const indexPath = path.join(screenshotsDir, 'index.json');
if (!fs.existsSync(indexPath)) return null;
const heights = new Map();
const index = JSON.parse(fs.readFileSync(indexPath, 'utf-8'));
for (const group of index.components ?? []) {
for (const example of group.examples ?? []) {
if (typeof example.height === 'number') {
heights.set(`${group.component}/${example.name}`, example.height);
}
}
}
return heights;
}

export async function writeExampleCatalogs({
componentsDir,
examplesDir,
catalogDir,
screenshotsDir,
title = 'Example Catalog Generator',
logger = console,
}) {
Expand All @@ -358,6 +400,10 @@ export async function writeExampleCatalogs({
const components = getComponents(componentsDir);
logger.log(`Found ${components.length} components\n`);
const gitDates = getExampleGitDates(examplesDir);
const heights = screenshotsDir ? getExampleHeights(screenshotsDir) : null;
if (screenshotsDir && !heights) {
logger.log(`No screenshot index in ${screenshotsDir}, keeping existing example heights\n`);
}
if (!gitDates) {
logger.log(
'Git history unavailable (no git or shallow clone), keeping existing example dates\n'
Expand All @@ -370,7 +416,13 @@ export async function writeExampleCatalogs({
for (const componentName of components) {
// Write catalog file
const catalogPath = path.join(catalogDir, `${componentName}.json`);
const catalog = generateComponentCatalog(componentName, catalogPath, components, gitDates);
const catalog = generateComponentCatalog(
componentName,
catalogPath,
components,
gitDates,
heights
);
fs.writeFileSync(catalogPath, JSON.stringify(catalog, null, 2));
logger.log(` ✓ Examples: ${catalog.examples.length}`);
logger.log(` ✓ Usages: ${catalog.usage.length}`);
Expand Down
101 changes: 76 additions & 25 deletions packages/docs/src/lib/node/screenshots.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,32 +60,35 @@ function calculateChecksum(filePath) {
return crypto.createHash('md5').update(content).digest('hex');
}
/**
* Load checksums from index.json file (inline in examples)
* Load checksums and heights from index.json file (inline in examples)
*/
function loadChecksums() {
function loadIndex() {
const checksums = {};
const heights = {};
if (fs.existsSync(INDEX_FILE)) {
try {
const content = fs.readFileSync(INDEX_FILE, 'utf-8');
const indexData = JSON.parse(content);
const checksums = {};
// Extract checksums from inline example entries
// Extract checksums and heights from inline example entries
if (indexData.components) {
for (const componentGroup of indexData.components) {
for (const example of componentGroup.examples || []) {
const key = `${componentGroup.component}/${example.name}`;
if (example.checksum) {
const key = `${componentGroup.component}/${example.name}`;
checksums[key] = example.checksum;
}
if (typeof example.height === 'number') {
heights[key] = example.height;
}
}
}
}
return checksums;
} catch (error) {
console.warn('Failed to load checksums from index.json, starting fresh');
return {};
console.warn('Failed to load index.json, starting fresh');
return { checksums: {}, heights: {} };
}
}
return {};
return { checksums, heights };
}
/**
* Check if example file has changed since last screenshot
Expand Down Expand Up @@ -149,24 +152,45 @@ function screenshotExists(componentName, exampleName, mode) {
return fs.existsSync(screenshotPath);
});
}
/**
* Open an example on the screenshot route and wait for it to be ready
*/
async function openExample(page, componentName, exampleName) {
const url = `${BASE_URL}${SCREENSHOT_ROUTE_BASE}/${componentName}/${exampleName}`;
await page.goto(url, { waitUntil: 'networkidle' });
// wait for the page to be ready
await page.waitForLoadState('domcontentloaded');
// wait if the lazy-loaded element found
if ((await page.locator('.screenshot-delay').count()) > 0) {
await page.waitForTimeout(2000);
}
}

/**
* The example's rendered height in pixels (its `.example` element, at the screenshot viewport's
* width), so a docs page can hold its space before it renders. Read before controls are hidden,
* as they take up space on the page. `undefined` if there's no `.example`.
*/
async function measureHeight(page) {
const example = page.locator('.example').first();
if ((await example.count()) === 0) return undefined;
const height = await example.evaluate((el) => el.getBoundingClientRect().height);
return height > 0 ? Math.round(height) : undefined;
}

/**
* Generate screenshots for an example in both light and dark modes
* Outputs WebP format in multiple sizes for responsive loading
*
* @returns the example's height (see `measureHeight`)
*/
async function captureScreenshots(page, componentName, exampleName, modes) {
const url = `${BASE_URL}${SCREENSHOT_ROUTE_BASE}/${componentName}/${exampleName}`;
const screenshotDir = path.join(SCREENSHOTS_DIR, componentName);
// Ensure directory exists
ensureDir(screenshotDir);
try {
// Navigate to the example
await page.goto(url, { waitUntil: 'networkidle' });
// wait for the page to be ready
await page.waitForLoadState('domcontentloaded');
// wait if the lazy-loaded element found
if ((await page.locator('.screenshot-delay').count()) > 0) {
await page.waitForTimeout(2000);
}
await openExample(page, componentName, exampleName);
const height = await measureHeight(page);
// Hide example controls before taking screenshots
await page.evaluate(() => {
const controls = document.querySelectorAll('.screenshot-hidden');
Expand Down Expand Up @@ -208,6 +232,7 @@ async function captureScreenshots(page, componentName, exampleName, modes) {
}
console.log(` ✓ ${mode}: ${sizes.join(', ')}`);
}
return height;
} catch (error) {
console.error(` ✗ failed:`, error instanceof Error ? error.message : error);
throw error;
Expand Down Expand Up @@ -315,9 +340,10 @@ export async function generateScreenshots(options) {
console.log(`Found ${examples.length} examples`);
// Clean up orphaned screenshots before processing
cleanupOrphanedScreenshots(examples);
// Load existing checksums
const checksums = loadChecksums();
// Load existing checksums and heights
const { checksums, heights } = loadIndex();
const updatedChecksums = {};
const updatedHeights = {};
// Limit for testing
if (TEST_LIMIT !== undefined) {
examples = examples.slice(0, TEST_LIMIT);
Expand Down Expand Up @@ -356,10 +382,25 @@ export async function generateScreenshots(options) {
const darkExists = screenshotExists(component, exampleName, 'dark');
// Skip if both screenshots exist and file hasn't changed (unless --all flag is used)
if (lightExists && darkExists && !fileChanged && !FORCE_ALL) {
console.log(' ⊘ Skipped (unchanged)');
skippedCount += 2;
const key = `${component}/${exampleName}`;
// Keep existing checksum
updatedChecksums[`${component}/${exampleName}`] = checksums[`${component}/${exampleName}`];
updatedChecksums[key] = checksums[key];
if (heights[key] !== undefined) {
console.log(' ⊘ Skipped (unchanged)');
updatedHeights[key] = heights[key];
} else {
// Screenshots from before heights were recorded: measure it, leaving the images be
try {
await openExample(page, component, exampleName);
updatedHeights[key] = await measureHeight(page);
console.log(` ⊘ Skipped (unchanged), measured height: ${updatedHeights[key]}px`);
} catch (error) {
console.error(` ✗ Height:`, error instanceof Error ? error.message : error);
await page.close().catch(() => {});
page = await newPage();
}
}
skippedCount += 2;
continue;
}
// Show reason for regeneration
Expand All @@ -385,7 +426,12 @@ export async function generateScreenshots(options) {
}
// Capture screenshots if any modes need to be processed
if (modesToCapture.length > 0) {
await captureScreenshots(page, component, exampleName, modesToCapture);
updatedHeights[`${component}/${exampleName}`] = await captureScreenshots(
page,
component,
exampleName,
modesToCapture
);
processedCount += modesToCapture.length;
}
// Update checksum after successful capture
Expand All @@ -394,10 +440,13 @@ export async function generateScreenshots(options) {
console.error(` ✗ Error:`, error instanceof Error ? error.message : error);
errorCount++;
failedExamples.push(`${component}/${exampleName}`);
// Keep old checksum on error to retry next time
// Keep old checksum (and height) on error to retry next time
if (checksums[`${component}/${exampleName}`]) {
updatedChecksums[`${component}/${exampleName}`] = checksums[`${component}/${exampleName}`];
}
if (heights[`${component}/${exampleName}`] !== undefined) {
updatedHeights[`${component}/${exampleName}`] = heights[`${component}/${exampleName}`];
}
// Start the next example on a fresh page, as one left busy (or mid-navigation) would
// fail the examples after it too
await page.close().catch(() => {});
Expand All @@ -414,10 +463,12 @@ export async function generateScreenshots(options) {
examplesByComponent.set(example.component, []);
}
const checksumKey = `${example.component}/${example.example}`;
const height = updatedHeights[checksumKey];
examplesByComponent.get(example.component).push({
name: example.example,
path: `/example/${example.component}/${example.example}`,
checksum: updatedChecksums[checksumKey] || '',
...(height !== undefined ? { height } : {}),
});
}
// Convert to array and sort
Expand Down
Loading