Files
enricobuehler e9a4d3a996 feat(ui): storybook 10 over the real pages + screenshot harness
Preview imports the mock transport statically and wraps every story in
a fresh RegistryProvider seeded with mock mode + the story's scenario
parameter (dark default, light via toolbar). One story file per page
(Default + FirstRun/Syncing/Errors where meaningful) plus the whole
shell. tools/screenshots.mjs mirrors the console's harness: headless
Chromium over storybook-static, every Pages/* + Shell/* story.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 19:41:59 +02:00

145 lines
4.6 KiB
JavaScript

// Capture page screenshots from the built Storybook — the same harness the console
// uses (punktfunk/web/tools/screenshots.mjs): headless Chromium over storybook-static,
// every Pages/* + Shell/* story, rendered entirely from fixtures. No host required.
//
// bun run build-storybook # produce ./storybook-static
// bun run screenshots # → ./screenshots/<story-id>.png
//
// Env knobs: OUT (output dir), STORYBOOK_STATIC (input dir), SETTLE (ms after the
// page looks ready, default 600), WIDTH/HEIGHT/SCALE (viewport, default 1440x900@2x),
// ONLY (comma-separated story-id substring filter).
import { existsSync } from "node:fs";
import { mkdir, readFile } from "node:fs/promises";
import { createServer } from "node:http";
import { extname, join, normalize, resolve } from "node:path";
import { chromium } from "playwright";
const ROOT = resolve(process.env.STORYBOOK_STATIC ?? "storybook-static");
const OUT = resolve(process.env.OUT ?? "screenshots");
const SETTLE = Number(process.env.SETTLE ?? 600);
const WIDTH = Number(process.env.WIDTH ?? 1440);
const HEIGHT = Number(process.env.HEIGHT ?? 900);
const SCALE = Number(process.env.SCALE ?? 2);
const ONLY = (process.env.ONLY ?? "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
// Only the page-level + shell stories make sense as screenshots.
const TITLE_PREFIXES = ["Pages/", "Shell/"];
const MIME = {
".html": "text/html",
".js": "text/javascript",
".mjs": "text/javascript",
".css": "text/css",
".json": "application/json",
".svg": "image/svg+xml",
".png": "image/png",
".jpg": "image/jpeg",
".woff": "font/woff",
".woff2": "font/woff2",
".ttf": "font/ttf",
".map": "application/json",
".ico": "image/x-icon",
};
function staticServer(rootDir) {
return createServer(async (req, res) => {
try {
const url = new URL(req.url, "http://localhost");
let path = decodeURIComponent(url.pathname);
if (path.endsWith("/")) path += "index.html";
// Contain the path to rootDir (no traversal).
const filePath = normalize(join(rootDir, path));
if (!filePath.startsWith(rootDir)) {
res.writeHead(403).end();
return;
}
const body = await readFile(filePath);
res.writeHead(200, {
"content-type": MIME[extname(filePath)] ?? "application/octet-stream",
});
res.end(body);
} catch {
res.writeHead(404).end();
}
});
}
async function listStories(rootDir) {
const indexPath = join(rootDir, "index.json");
if (!existsSync(indexPath)) {
throw new Error(
`${indexPath} not found — run \`bun run build-storybook\` first`,
);
}
const index = JSON.parse(await readFile(indexPath, "utf8"));
const entries = Object.values(index.entries ?? index.stories ?? {});
return entries
.filter((e) => e.type === "story" || e.type === undefined)
.filter((e) => TITLE_PREFIXES.some((p) => (e.title ?? "").startsWith(p)))
.filter((e) => ONLY.length === 0 || ONLY.some((f) => e.id.includes(f)))
.sort((a, b) => a.id.localeCompare(b.id));
}
async function main() {
if (!existsSync(ROOT)) {
throw new Error(
`${ROOT} not found — run \`bun run build-storybook\` first`,
);
}
const stories = await listStories(ROOT);
if (stories.length === 0)
throw new Error("no Pages/* or Shell/* stories found");
await mkdir(OUT, { recursive: true });
const server = staticServer(ROOT);
await new Promise((r) => server.listen(0, "127.0.0.1", r));
const port = server.address().port;
const browser = await chromium.launch({
args: ["--force-color-profile=srgb"],
});
const context = await browser.newContext({
viewport: { width: WIDTH, height: HEIGHT },
deviceScaleFactor: SCALE,
colorScheme: "dark",
});
let ok = 0;
for (const story of stories) {
const page = await context.newPage();
const url = `http://127.0.0.1:${port}/iframe.html?id=${encodeURIComponent(
story.id,
)}&viewMode=story`;
try {
await page.goto(url, { waitUntil: "networkidle", timeout: 30_000 });
// Story root mounted with real content.
await page.waitForSelector("#storybook-root > *", { timeout: 20_000 });
// Web fonts settled (else text reflows / falls back in the shot).
await page.evaluate(() => document.fonts.ready);
await page.waitForTimeout(SETTLE);
const file = join(OUT, `${story.id}.png`);
await page.screenshot({ path: file });
console.log(`ok ${story.id} -> ${file}`);
ok++;
} catch (e) {
console.warn(`FAIL ${story.id}: ${e.message}`);
} finally {
await page.close();
}
}
await browser.close();
await new Promise((r) => server.close(r));
console.log(`\n${ok}/${stories.length} stories captured -> ${OUT}`);
if (ok === 0) process.exit(1);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});