diff --git a/.changeset/docs-example-heights.md b/.changeset/docs-example-heights.md
new file mode 100644
index 0000000..c01f596
--- /dev/null
+++ b/.changeset/docs-example-heights.md
@@ -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
`, so a page can hold an example's space before it renders
diff --git a/docs/src/content/guides/docs/cli.md b/docs/src/content/guides/docs/cli.md
index 267000c..de7cd1b 100644
--- a/docs/src/content/guides/docs/cli.md
+++ b/docs/src/content/guides/docs/cli.md
@@ -19,7 +19,7 @@ manually.
"scripts": {
"prebuild": "pnpm generate:api && pnpm generate:stackblitz && pnpm generate:releases",
"generate:api": "layerstack-docs generate-api ../packages//src/lib/components generated/api",
- "generate:catalog": "layerstack-docs generate-catalog ../packages//src/lib/components src/examples/components src/examples/catalog",
+ "generate:catalog": "layerstack-docs generate-catalog ../packages//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/ generated/releases",
@@ -32,11 +32,17 @@ manually.
| Command | Arguments | Generates |
| ---------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------- |
| `generate-api` | ` ` | Per-component prop API JSON (via the TypeScript compiler) |
-| `generate-catalog` | ` ` | Per-component example + cross-usage catalogs |
+| `generate-catalog` | ` [--screenshots]` | Per-component example + cross-usage catalogs |
| `generate-screenshots` | ` [--base-url] [--route-base] [--all]` | Responsive light/dark WebP screenshots (Playwright + sharp) |
| `generate-stackblitz` | ` [remote-sources-file] [--template-dir] [--source] [--remote]` | A StackBlitz/WebContainer file bundle |
| `generate-releases` | ` ` | GitHub releases → frontmatter markdown files |
+`generate-screenshots` also records each example's rendered height (at its 800px viewport) in
+`/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.
diff --git a/packages/docs/src/lib/catalog.ts b/packages/docs/src/lib/catalog.ts
index e7fca9b..66126ed 100644
--- a/packages/docs/src/lib/catalog.ts
+++ b/packages/docs/src/lib/catalog.ts
@@ -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;
}
/**
diff --git a/packages/docs/src/lib/cli.ts b/packages/docs/src/lib/cli.ts
index 7db4bf6..99f81ce 100644
--- a/packages/docs/src/lib/cli.ts
+++ b/packages/docs/src/lib/cli.ts
@@ -4,7 +4,7 @@
*
* Commands:
* generate-api
- * generate-catalog
+ * generate-catalog [--screenshots ]
* generate-screenshots [--base-url ] [--route-base ] [--all]
* generate-stackblitz [remote-sources-file] [--template-dir ] [--source out=src ...] [--remote out=src ...]
* generate-releases
@@ -76,7 +76,7 @@ const HELP = `layerstack-docs [...args]
Commands:
generate-api
- generate-catalog
+ generate-catalog [--screenshots ]
generate-screenshots [--base-url ] [--route-base ] [--all]
generate-stackblitz [remote-sources-file]
[--template-dir ] [--source out=src ...] [--remote out=src ...]
@@ -104,7 +104,13 @@ async function main() {
'Usage: layerstack-docs generate-catalog '
);
}
- await writeExampleCatalogs({ componentsDir, examplesDir, catalogDir });
+ await writeExampleCatalogs({
+ componentsDir,
+ examplesDir,
+ catalogDir,
+ // Example heights from its screenshot index (see `generate-screenshots`)
+ screenshotsDir: optString(options, 'screenshots'),
+ });
break;
}
diff --git a/packages/docs/src/lib/node/example-catalog.js b/packages/docs/src/lib/node/example-catalog.js
index f56b42e..e974ee4 100644
--- a/packages/docs/src/lib/node/example-catalog.js
+++ b/packages/docs/src/lib/node/example-catalog.js
@@ -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
@@ -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);
}
}
@@ -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;
@@ -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
@@ -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 (`/index.json`, written by
+ * `generateScreenshots()`), keyed `/`. `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,
}) {
@@ -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'
@@ -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}`);
diff --git a/packages/docs/src/lib/node/screenshots.js b/packages/docs/src/lib/node/screenshots.js
index 66b0272..ad8cdd4 100644
--- a/packages/docs/src/lib/node/screenshots.js
+++ b/packages/docs/src/lib/node/screenshots.js
@@ -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
@@ -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');
@@ -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;
@@ -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);
@@ -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
@@ -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
@@ -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(() => {});
@@ -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