shoot.mjs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. #!/usr/bin/env node
  2. /**
  3. * shoot.mjs — screenshot journey for scroll-driven websites
  4. * Usage: node shoot.mjs <url> [--stops 7] [--out shots] [--breakpoints 390,768,1440] [--dpr 1] [--reduced-motion] [--full]
  5. */
  6. import { mkdir, writeFile } from 'fs/promises';
  7. import { existsSync } from 'fs';
  8. import { resolve, join } from 'path';
  9. // --- CLI parsing ---
  10. const args = process.argv.slice(2);
  11. if (!args.length || args[0] === '--help') {
  12. console.log('Usage: node shoot.mjs <url> [<url>...] [--stops 7] [--out shots] [--breakpoints 390,768,1440] [--dpr 1] [--reduced-motion] [--full]');
  13. console.log('Writes: <out>/bp<width>-stop<NN>.png (also bp<width>-rm-stop<NN>.png with --reduced-motion, bp<width>-full.png with --full)');
  14. process.exit(0);
  15. }
  16. // Multi-screen products need every route shot, not a sample — take all leading non-flag args.
  17. const rawTargets = [];
  18. for (const a of args) { if (a.startsWith('--')) break; rawTargets.push(a); }
  19. const get = (flag, def) => {
  20. const i = args.indexOf(flag);
  21. return i !== -1 ? args[i + 1] : def;
  22. };
  23. const has = flag => args.includes(flag);
  24. const stopsCount = parseInt(get('--stops', '7'), 10);
  25. const outDir = resolve(get('--out', 'shots'));
  26. const bpArg = get('--breakpoints', '390,768,1440');
  27. const reducedMotion = has('--reduced-motion');
  28. const fullPage = has('--full');
  29. // Layout bugs read fine at 1x, so that stays the default (30 frames at 2x cost 4x the bytes for
  30. // nothing). Shoot --dpr 2 when the question is rendering rather than layout: hairline borders that
  31. // vanish, text that only looks crisp at 1x, moiré in a fine pattern, an image whose real resolution
  32. // is half what the layout claims.
  33. const dpr = parseFloat(get('--dpr', '1')) || 1;
  34. const breakpoints = bpArg.split(',').map(Number);
  35. const heights = { 390: 844, 768: 1024, 1440: 900 };
  36. const getHeight = w => heights[w] ?? 900;
  37. // Convert local paths → file:// URLs
  38. const toUrl = u => (u.startsWith('http://') || u.startsWith('https://') || u.startsWith('file://'))
  39. ? u
  40. : 'file:///' + resolve(u).replace(/\\/g, '/');
  41. const targets = rawTargets.map(toUrl);
  42. // One route keeps the historical bp<width>-stop<NN>.png names; several get a per-route prefix.
  43. // Truncating the tail collides for routes that share a long suffix and silently overwrites frames,
  44. // so keep the distinguishing end AND an index that cannot repeat.
  45. const labelFor = (u, i) => targets.length === 1 ? '' :
  46. `${String(i).padStart(2, '0')}_${(u.replace(/^https?:\/\//, '').replace(/^file:\/\/\//, '')
  47. .replace(/[^\w]+/g, '_').replace(/^_+|_+$/g, '').slice(-24)) || 'r'}-`;
  48. // --- Dynamic import playwright with friendly error ---
  49. let chromium;
  50. try {
  51. ({ chromium } = await import('playwright'));
  52. } catch {
  53. console.error('playwright not found. Install: npm i -D playwright && npx playwright install chromium');
  54. process.exit(2);
  55. }
  56. // --- Heuristic: is this screenshot likely blank? ---
  57. // Checks byte-entropy of the PNG buffer — a nearly-uniform image compresses to
  58. // a much smaller ratio vs a varied one. ponytail: approximate, not pixel-perfect.
  59. function likelyBlank(buf) {
  60. if (buf.length === 0) return true;
  61. // PNG files with almost all identical pixels compress extremely well.
  62. // Heuristic: if buffer is <2KB for any resolution it's suspicious.
  63. const VERY_SMALL = 2048;
  64. if (buf.length < VERY_SMALL) return true;
  65. // Sample 512 bytes spread across the buffer, count unique byte values.
  66. const samples = new Set();
  67. const step = Math.max(1, Math.floor(buf.length / 512));
  68. for (let i = 33; i < buf.length; i += step) samples.add(buf[i]); // skip PNG header
  69. return samples.size < 8; // fewer than 8 distinct byte values → very uniform
  70. }
  71. // --- Zero-pad helper ---
  72. const pad = (n, len = 2) => String(n).padStart(len, '0');
  73. // --- Main ---
  74. await mkdir(outDir, { recursive: true });
  75. let totalWritten = 0;
  76. let anySucceeded = false;
  77. const summary = [];
  78. for (const [ti, pageUrl] of targets.entries()) {
  79. const prefix = labelFor(pageUrl, ti);
  80. for (const width of breakpoints) {
  81. const vpHeight = getHeight(width);
  82. const bpErrors = [];
  83. const bpFiles = [];
  84. let browser;
  85. try {
  86. browser = await chromium.launch({ headless: true });
  87. const context = await browser.newContext({
  88. viewport: { width, height: vpHeight },
  89. deviceScaleFactor: dpr,
  90. });
  91. const page = await context.newPage();
  92. // Collect page console errors
  93. page.on('console', msg => { if (msg.type() === 'error') bpErrors.push(msg.text()); });
  94. page.on('pageerror', err => bpErrors.push(err.message));
  95. // Navigate with networkidle, fall back to load on timeout
  96. try {
  97. await page.goto(pageUrl, { waitUntil: 'networkidle', timeout: 30_000 });
  98. } catch {
  99. await page.goto(pageUrl, { waitUntil: 'load', timeout: 15_000 });
  100. }
  101. const scrollHeight = await page.evaluate(() => document.documentElement.scrollHeight);
  102. const maxScroll = Math.max(0, scrollHeight - vpHeight);
  103. // Compute evenly spaced stop positions
  104. const stops = Array.from({ length: stopsCount }, (_, i) =>
  105. stopsCount === 1 ? 0 : Math.round((i / (stopsCount - 1)) * maxScroll)
  106. );
  107. // Screenshot each stop (incremental scroll so animations fire)
  108. let currentY = 0;
  109. for (let si = 0; si < stops.length; si++) {
  110. const target = stops[si];
  111. // Scroll incrementally toward target in chunks so IntersectionObserver triggers
  112. const CHUNK = 200;
  113. while (Math.abs(currentY - target) > CHUNK) {
  114. const next = currentY < target ? Math.min(currentY + CHUNK, target) : Math.max(currentY - CHUNK, target);
  115. await page.evaluate(y => window.scrollTo({ top: y, behavior: 'smooth' }), next);
  116. await page.waitForTimeout(120);
  117. currentY = next;
  118. }
  119. await page.evaluate(y => window.scrollTo({ top: y, behavior: 'smooth' }), target);
  120. await page.waitForTimeout(700); // let scroll-triggered animations settle
  121. const fname = `${prefix}bp${width}-stop${pad(si)}.png`;
  122. const fpath = join(outDir, fname);
  123. const buf = await page.screenshot({ path: fpath, fullPage: false });
  124. bpFiles.push(fname);
  125. totalWritten++;
  126. if (likelyBlank(buf)) console.warn(` [warn] ${fname} possibly blank`);
  127. }
  128. // --reduced-motion: redo first + last stop
  129. if (reducedMotion) {
  130. const rmContext = await browser.newContext({
  131. viewport: { width, height: vpHeight },
  132. deviceScaleFactor: dpr,
  133. reducedMotion: 'reduce',
  134. });
  135. const rmPage = await rmContext.newPage();
  136. try {
  137. await rmPage.goto(pageUrl, { waitUntil: 'networkidle', timeout: 30_000 });
  138. } catch {
  139. await rmPage.goto(pageUrl, { waitUntil: 'load', timeout: 15_000 });
  140. }
  141. // Every stop, not just first and last: the peak lives at 40-70% depth, so shooting only the
  142. // ends captures exactly the frames the reduced-motion cut was never going to break.
  143. for (const [idx, stop] of stops.map((s, i) => [i, s])) {
  144. await rmPage.evaluate(y => window.scrollTo({ top: y, behavior: 'smooth' }), stop);
  145. await rmPage.waitForTimeout(700);
  146. const fname = `${prefix}bp${width}-rm-stop${pad(idx)}.png`;
  147. const fpath = join(outDir, fname);
  148. const buf = await rmPage.screenshot({ path: fpath, fullPage: false });
  149. bpFiles.push(fname);
  150. totalWritten++;
  151. if (likelyBlank(buf)) console.warn(` [warn] ${fname} possibly blank`);
  152. }
  153. await rmContext.close();
  154. }
  155. // --full: one full-page screenshot (and its reduced-motion twin when both flags are on)
  156. if (fullPage) {
  157. const fname = `${prefix}bp${width}-full.png`;
  158. const fpath = join(outDir, fname);
  159. const buf = await page.screenshot({ path: fpath, fullPage: true });
  160. bpFiles.push(fname);
  161. totalWritten++;
  162. if (likelyBlank(buf)) console.warn(` [warn] ${fname} possibly blank`);
  163. }
  164. anySucceeded = true;
  165. summary.push({ url: pageUrl, width, scrollHeight, files: bpFiles, errors: bpErrors });
  166. } catch (err) {
  167. console.error(`[${pageUrl} bp ${width}] failed: ${err.message}`);
  168. summary.push({ url: pageUrl, width, failed: true, error: err.message });
  169. } finally {
  170. await browser?.close();
  171. }
  172. }
  173. }
  174. // --- Print summary ---
  175. console.log('\n=== shoot.mjs summary ===');
  176. console.log(`Output dir : ${outDir}`);
  177. console.log(`Files written: ${totalWritten}`);
  178. for (const s of summary) {
  179. const where = targets.length > 1 ? `${s.url} ` : '';
  180. if (s.failed) {
  181. console.log(` ${where}bp${s.width}: FAILED — ${s.error}`);
  182. } else {
  183. console.log(` ${where}bp${s.width}: scrollHeight=${s.scrollHeight}px files=${s.files.length}`);
  184. if (s.errors.length) console.log(` page errors: ${s.errors.join(' | ')}`);
  185. }
  186. }
  187. process.exit(anySucceeded ? 0 : 1);