Skip to content

Commit 0c37946

Browse files
techniqclaude
andauthored
feat(docs): Record example heights in the screenshot index and catalog (#123)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent f785e3e commit 0c37946

6 files changed

Lines changed: 159 additions & 34 deletions

File tree

‎.changeset/docs-example-heights.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@layerstack/docs': minor
3+
---
4+
5+
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

‎docs/src/content/guides/docs/cli.md‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ manually.
1919
"scripts": {
2020
"prebuild": "pnpm generate:api && pnpm generate:stackblitz && pnpm generate:releases",
2121
"generate:api": "layerstack-docs generate-api ../packages/<pkg>/src/lib/components generated/api",
22-
"generate:catalog": "layerstack-docs generate-catalog ../packages/<pkg>/src/lib/components src/examples/components src/examples/catalog",
22+
"generate:catalog": "layerstack-docs generate-catalog ../packages/<pkg>/src/lib/components src/examples/components src/examples/catalog --screenshots static/screenshots",
2323
"generate:screenshots": "layerstack-docs generate-screenshots src/examples/components static/screenshots",
2424
"generate:stackblitz": "layerstack-docs generate-stackblitz src static/stackblitz-files.json [remote-sources.json]",
2525
"generate:releases": "layerstack-docs generate-releases techniq/<repo> generated/releases",
@@ -32,11 +32,17 @@ manually.
3232
| Command | Arguments | Generates |
3333
| ---------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------- |
3434
| `generate-api` | `<components-dir> <output-dir>` | Per-component prop API JSON (via the TypeScript compiler) |
35-
| `generate-catalog` | `<components-dir> <examples-dir> <catalog-dir>` | Per-component example + cross-usage catalogs |
35+
| `generate-catalog` | `<components-dir> <examples-dir> <catalog-dir> [--screenshots]` | Per-component example + cross-usage catalogs |
3636
| `generate-screenshots` | `<examples-dir> <screenshots-dir> [--base-url] [--route-base] [--all]` | Responsive light/dark WebP screenshots (Playwright + sharp) |
3737
| `generate-stackblitz` | `<source-dir> <output-file> [remote-sources-file] [--template-dir] [--source] [--remote]` | A StackBlitz/WebContainer file bundle |
3838
| `generate-releases` | `<owner/repo> <output-dir>` | GitHub releases → frontmatter markdown files |
3939

40+
`generate-screenshots` also records each example's rendered height (at its 800px viewport) in
41+
`<screenshots-dir>/index.json`, measuring examples whose screenshots are already up to date without
42+
re-encoding them. Pass that directory to `generate-catalog --screenshots` to add each example's
43+
`height` to its catalog entry, so a page can hold the example's space before it renders. Run
44+
screenshots first.
45+
4046
The output under `generated/api/*` and `generated/releases/*` is picked up automatically by
4147
the `references`/`components`/`releases` collections.
4248

‎packages/docs/src/lib/catalog.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,11 @@ export interface ExampleInfo {
3737
createdAt?: string;
3838
/** ISO timestamp of the last commit that changed the example file */
3939
updatedAt?: string;
40+
/**
41+
* Rendered height in pixels, measured by the screenshot generator (at its viewport's width). Lets
42+
* a page hold the example's space before it renders.
43+
*/
44+
height?: number;
4045
}
4146

4247
/**

‎packages/docs/src/lib/cli.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
*
55
* Commands:
66
* generate-api <components-dir> <output-dir>
7-
* generate-catalog <components-dir> <examples-dir> <catalog-dir>
7+
* generate-catalog <components-dir> <examples-dir> <catalog-dir> [--screenshots <dir>]
88
* generate-screenshots <examples-dir> <screenshots-dir> [--base-url <url>] [--route-base <path>] [--all]
99
* generate-stackblitz <source-dir> <output-file> [remote-sources-file] [--template-dir <dir>] [--source out=src ...] [--remote out=src ...]
1010
* generate-releases <owner/repo> <output-dir>
@@ -76,7 +76,7 @@ const HELP = `layerstack-docs <command> [...args]
7676
7777
Commands:
7878
generate-api <components-dir> <output-dir>
79-
generate-catalog <components-dir> <examples-dir> <catalog-dir>
79+
generate-catalog <components-dir> <examples-dir> <catalog-dir> [--screenshots <dir>]
8080
generate-screenshots <examples-dir> <screenshots-dir> [--base-url <url>] [--route-base <path>] [--all]
8181
generate-stackblitz <source-dir> <output-file> [remote-sources-file]
8282
[--template-dir <dir>] [--source out=src ...] [--remote out=src ...]
@@ -104,7 +104,13 @@ async function main() {
104104
'Usage: layerstack-docs generate-catalog <components-dir> <examples-dir> <catalog-dir>'
105105
);
106106
}
107-
await writeExampleCatalogs({ componentsDir, examplesDir, catalogDir });
107+
await writeExampleCatalogs({
108+
componentsDir,
109+
examplesDir,
110+
catalogDir,
111+
// Example heights from its screenshot index (see `generate-screenshots`)
112+
screenshotsDir: optString(options, 'screenshots'),
113+
});
108114
break;
109115
}
110116

‎packages/docs/src/lib/node/example-catalog.js‎

Lines changed: 56 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,13 @@ export function getExampleGitDates(examplesDir) {
202202
* @param existingExamples - examples from the previously generated catalog, used to keep
203203
* existing dates when git history is unavailable (or the file has not been committed yet)
204204
*/
205-
function getComponentExamples(componentName, allComponents, gitDates, existingExamples = []) {
205+
function getComponentExamples(
206+
componentName,
207+
allComponents,
208+
gitDates,
209+
existingExamples = [],
210+
heights = null
211+
) {
206212
const componentExamplesDir = path.join(EXAMPLES_DIR, componentName);
207213
const examples = [];
208214
// Check if the component examples directory exists
@@ -240,6 +246,13 @@ function getComponentExamples(componentName, allComponents, gitDates, existingEx
240246
if (dates?.updatedAt) {
241247
info.updatedAt = dates.updatedAt;
242248
}
249+
// From the screenshot index when given one, else as the existing catalog has it
250+
const height = heights
251+
? heights.get(`${componentName}/${exampleName}`)
252+
: existingExamples.find((e) => e.name === exampleName)?.height;
253+
if (typeof height === 'number') {
254+
info.height = height;
255+
}
243256
examples.push(info);
244257
}
245258
}
@@ -308,8 +321,16 @@ function withoutDates(examples) {
308321
*
309322
* @param gitDates - result of `getExampleGitDates()`. When `null`/`undefined`, example
310323
* dates are carried over from the existing catalog file.
324+
* @param heights - result of `getExampleHeights()`. When `null`/`undefined`, example heights
325+
* are carried over from the existing catalog file.
311326
*/
312-
export function generateComponentCatalog(componentName, catalogPath, allComponents, gitDates) {
327+
export function generateComponentCatalog(
328+
componentName,
329+
catalogPath,
330+
allComponents,
331+
gitDates,
332+
heights
333+
) {
313334
console.log(`Processing ${componentName}...`);
314335
// Read existing catalog (if any)
315336
let existingCatalog;
@@ -324,7 +345,8 @@ export function generateComponentCatalog(componentName, catalogPath, allComponen
324345
componentName,
325346
allComponents,
326347
gitDates,
327-
Array.isArray(existingCatalog?.examples) ? existingCatalog.examples : []
348+
Array.isArray(existingCatalog?.examples) ? existingCatalog.examples : [],
349+
heights
328350
);
329351
const usage = findComponentUsage(componentName);
330352
// Check if content has changed (excluding updatedAt field and example dates, which follow
@@ -341,10 +363,30 @@ export function generateComponentCatalog(componentName, catalogPath, allComponen
341363
updatedAt: (contentUnchanged && existingCatalog.updatedAt) || new Date().toISOString(),
342364
};
343365
}
366+
/**
367+
* Each example's rendered height from a screenshot index (`<screenshots-dir>/index.json`, written by
368+
* `generateScreenshots()`), keyed `<component>/<example>`. `null` if there's no index.
369+
*/
370+
export function getExampleHeights(screenshotsDir) {
371+
const indexPath = path.join(screenshotsDir, 'index.json');
372+
if (!fs.existsSync(indexPath)) return null;
373+
const heights = new Map();
374+
const index = JSON.parse(fs.readFileSync(indexPath, 'utf-8'));
375+
for (const group of index.components ?? []) {
376+
for (const example of group.examples ?? []) {
377+
if (typeof example.height === 'number') {
378+
heights.set(`${group.component}/${example.name}`, example.height);
379+
}
380+
}
381+
}
382+
return heights;
383+
}
384+
344385
export async function writeExampleCatalogs({
345386
componentsDir,
346387
examplesDir,
347388
catalogDir,
389+
screenshotsDir,
348390
title = 'Example Catalog Generator',
349391
logger = console,
350392
}) {
@@ -358,6 +400,10 @@ export async function writeExampleCatalogs({
358400
const components = getComponents(componentsDir);
359401
logger.log(`Found ${components.length} components\n`);
360402
const gitDates = getExampleGitDates(examplesDir);
403+
const heights = screenshotsDir ? getExampleHeights(screenshotsDir) : null;
404+
if (screenshotsDir && !heights) {
405+
logger.log(`No screenshot index in ${screenshotsDir}, keeping existing example heights\n`);
406+
}
361407
if (!gitDates) {
362408
logger.log(
363409
'Git history unavailable (no git or shallow clone), keeping existing example dates\n'
@@ -370,7 +416,13 @@ export async function writeExampleCatalogs({
370416
for (const componentName of components) {
371417
// Write catalog file
372418
const catalogPath = path.join(catalogDir, `${componentName}.json`);
373-
const catalog = generateComponentCatalog(componentName, catalogPath, components, gitDates);
419+
const catalog = generateComponentCatalog(
420+
componentName,
421+
catalogPath,
422+
components,
423+
gitDates,
424+
heights
425+
);
374426
fs.writeFileSync(catalogPath, JSON.stringify(catalog, null, 2));
375427
logger.log(` ✓ Examples: ${catalog.examples.length}`);
376428
logger.log(` ✓ Usages: ${catalog.usage.length}`);

‎packages/docs/src/lib/node/screenshots.js‎

Lines changed: 76 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -60,32 +60,35 @@ function calculateChecksum(filePath) {
6060
return crypto.createHash('md5').update(content).digest('hex');
6161
}
6262
/**
63-
* Load checksums from index.json file (inline in examples)
63+
* Load checksums and heights from index.json file (inline in examples)
6464
*/
65-
function loadChecksums() {
65+
function loadIndex() {
66+
const checksums = {};
67+
const heights = {};
6668
if (fs.existsSync(INDEX_FILE)) {
6769
try {
6870
const content = fs.readFileSync(INDEX_FILE, 'utf-8');
6971
const indexData = JSON.parse(content);
70-
const checksums = {};
71-
// Extract checksums from inline example entries
72+
// Extract checksums and heights from inline example entries
7273
if (indexData.components) {
7374
for (const componentGroup of indexData.components) {
7475
for (const example of componentGroup.examples || []) {
76+
const key = `${componentGroup.component}/${example.name}`;
7577
if (example.checksum) {
76-
const key = `${componentGroup.component}/${example.name}`;
7778
checksums[key] = example.checksum;
7879
}
80+
if (typeof example.height === 'number') {
81+
heights[key] = example.height;
82+
}
7983
}
8084
}
8185
}
82-
return checksums;
8386
} catch (error) {
84-
console.warn('Failed to load checksums from index.json, starting fresh');
85-
return {};
87+
console.warn('Failed to load index.json, starting fresh');
88+
return { checksums: {}, heights: {} };
8689
}
8790
}
88-
return {};
91+
return { checksums, heights };
8992
}
9093
/**
9194
* Check if example file has changed since last screenshot
@@ -149,24 +152,45 @@ function screenshotExists(componentName, exampleName, mode) {
149152
return fs.existsSync(screenshotPath);
150153
});
151154
}
155+
/**
156+
* Open an example on the screenshot route and wait for it to be ready
157+
*/
158+
async function openExample(page, componentName, exampleName) {
159+
const url = `${BASE_URL}${SCREENSHOT_ROUTE_BASE}/${componentName}/${exampleName}`;
160+
await page.goto(url, { waitUntil: 'networkidle' });
161+
// wait for the page to be ready
162+
await page.waitForLoadState('domcontentloaded');
163+
// wait if the lazy-loaded element found
164+
if ((await page.locator('.screenshot-delay').count()) > 0) {
165+
await page.waitForTimeout(2000);
166+
}
167+
}
168+
169+
/**
170+
* The example's rendered height in pixels (its `.example` element, at the screenshot viewport's
171+
* width), so a docs page can hold its space before it renders. Read before controls are hidden,
172+
* as they take up space on the page. `undefined` if there's no `.example`.
173+
*/
174+
async function measureHeight(page) {
175+
const example = page.locator('.example').first();
176+
if ((await example.count()) === 0) return undefined;
177+
const height = await example.evaluate((el) => el.getBoundingClientRect().height);
178+
return height > 0 ? Math.round(height) : undefined;
179+
}
180+
152181
/**
153182
* Generate screenshots for an example in both light and dark modes
154183
* Outputs WebP format in multiple sizes for responsive loading
184+
*
185+
* @returns the example's height (see `measureHeight`)
155186
*/
156187
async function captureScreenshots(page, componentName, exampleName, modes) {
157-
const url = `${BASE_URL}${SCREENSHOT_ROUTE_BASE}/${componentName}/${exampleName}`;
158188
const screenshotDir = path.join(SCREENSHOTS_DIR, componentName);
159189
// Ensure directory exists
160190
ensureDir(screenshotDir);
161191
try {
162-
// Navigate to the example
163-
await page.goto(url, { waitUntil: 'networkidle' });
164-
// wait for the page to be ready
165-
await page.waitForLoadState('domcontentloaded');
166-
// wait if the lazy-loaded element found
167-
if ((await page.locator('.screenshot-delay').count()) > 0) {
168-
await page.waitForTimeout(2000);
169-
}
192+
await openExample(page, componentName, exampleName);
193+
const height = await measureHeight(page);
170194
// Hide example controls before taking screenshots
171195
await page.evaluate(() => {
172196
const controls = document.querySelectorAll('.screenshot-hidden');
@@ -208,6 +232,7 @@ async function captureScreenshots(page, componentName, exampleName, modes) {
208232
}
209233
console.log(` ✓ ${mode}: ${sizes.join(', ')}`);
210234
}
235+
return height;
211236
} catch (error) {
212237
console.error(` ✗ failed:`, error instanceof Error ? error.message : error);
213238
throw error;
@@ -315,9 +340,10 @@ export async function generateScreenshots(options) {
315340
console.log(`Found ${examples.length} examples`);
316341
// Clean up orphaned screenshots before processing
317342
cleanupOrphanedScreenshots(examples);
318-
// Load existing checksums
319-
const checksums = loadChecksums();
343+
// Load existing checksums and heights
344+
const { checksums, heights } = loadIndex();
320345
const updatedChecksums = {};
346+
const updatedHeights = {};
321347
// Limit for testing
322348
if (TEST_LIMIT !== undefined) {
323349
examples = examples.slice(0, TEST_LIMIT);
@@ -356,10 +382,25 @@ export async function generateScreenshots(options) {
356382
const darkExists = screenshotExists(component, exampleName, 'dark');
357383
// Skip if both screenshots exist and file hasn't changed (unless --all flag is used)
358384
if (lightExists && darkExists && !fileChanged && !FORCE_ALL) {
359-
console.log(' ⊘ Skipped (unchanged)');
360-
skippedCount += 2;
385+
const key = `${component}/${exampleName}`;
361386
// Keep existing checksum
362-
updatedChecksums[`${component}/${exampleName}`] = checksums[`${component}/${exampleName}`];
387+
updatedChecksums[key] = checksums[key];
388+
if (heights[key] !== undefined) {
389+
console.log(' ⊘ Skipped (unchanged)');
390+
updatedHeights[key] = heights[key];
391+
} else {
392+
// Screenshots from before heights were recorded: measure it, leaving the images be
393+
try {
394+
await openExample(page, component, exampleName);
395+
updatedHeights[key] = await measureHeight(page);
396+
console.log(` ⊘ Skipped (unchanged), measured height: ${updatedHeights[key]}px`);
397+
} catch (error) {
398+
console.error(` ✗ Height:`, error instanceof Error ? error.message : error);
399+
await page.close().catch(() => {});
400+
page = await newPage();
401+
}
402+
}
403+
skippedCount += 2;
363404
continue;
364405
}
365406
// Show reason for regeneration
@@ -385,7 +426,12 @@ export async function generateScreenshots(options) {
385426
}
386427
// Capture screenshots if any modes need to be processed
387428
if (modesToCapture.length > 0) {
388-
await captureScreenshots(page, component, exampleName, modesToCapture);
429+
updatedHeights[`${component}/${exampleName}`] = await captureScreenshots(
430+
page,
431+
component,
432+
exampleName,
433+
modesToCapture
434+
);
389435
processedCount += modesToCapture.length;
390436
}
391437
// Update checksum after successful capture
@@ -394,10 +440,13 @@ export async function generateScreenshots(options) {
394440
console.error(` ✗ Error:`, error instanceof Error ? error.message : error);
395441
errorCount++;
396442
failedExamples.push(`${component}/${exampleName}`);
397-
// Keep old checksum on error to retry next time
443+
// Keep old checksum (and height) on error to retry next time
398444
if (checksums[`${component}/${exampleName}`]) {
399445
updatedChecksums[`${component}/${exampleName}`] = checksums[`${component}/${exampleName}`];
400446
}
447+
if (heights[`${component}/${exampleName}`] !== undefined) {
448+
updatedHeights[`${component}/${exampleName}`] = heights[`${component}/${exampleName}`];
449+
}
401450
// Start the next example on a fresh page, as one left busy (or mid-navigation) would
402451
// fail the examples after it too
403452
await page.close().catch(() => {});
@@ -414,10 +463,12 @@ export async function generateScreenshots(options) {
414463
examplesByComponent.set(example.component, []);
415464
}
416465
const checksumKey = `${example.component}/${example.example}`;
466+
const height = updatedHeights[checksumKey];
417467
examplesByComponent.get(example.component).push({
418468
name: example.example,
419469
path: `/example/${example.component}/${example.example}`,
420470
checksum: updatedChecksums[checksumKey] || '',
471+
...(height !== undefined ? { height } : {}),
421472
});
422473
}
423474
// Convert to array and sort

0 commit comments

Comments
 (0)