shoot.mjs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. #!/usr/bin/env node
  2. /**
  3. * scrollcraft verification harness: shoot the page's own scroll.
  4. *
  5. * Walks the page in N evenly spaced scroll positions, waits for the scrub video
  6. * to actually settle at each one, screenshots it, and reports what the engine
  7. * thinks is on screen. Then tiles the frames into one contact sheet, because a
  8. * dead middle only shows up in contiguous frames: any single screenshot is a
  9. * frame the transition may not survive.
  10. *
  11. * node shoot.mjs --url http://localhost:4500 --out lab/shots --steps 12
  12. * node shoot.mjs --url ... --width 375 --height 812 --out lab/mobile
  13. * node shoot.mjs --url ... --reduced-motion --out lab/reduced
  14. *
  15. * Uses the INSTALLED Chrome, not bundled Chromium: Chromium ships without the
  16. * h264 decoder, so every scrub clip would silently fail to paint and the run
  17. * would "pass" against posters.
  18. */
  19. import fs from "node:fs";
  20. import path from "node:path";
  21. import { createRequire } from "node:module";
  22. // The skill lives outside the project it is building, so resolve playwright
  23. // from the BUILD project's node_modules (cwd), not from next to this file.
  24. // Run `npm i playwright-core` in the build project once.
  25. let chromium;
  26. try {
  27. ({ chromium } = createRequire(path.join(process.cwd(), "package.json"))("playwright-core"));
  28. } catch {
  29. console.error("playwright-core not found. Run this in the build project after:\n npm i playwright-core");
  30. process.exit(1);
  31. }
  32. const argv = process.argv.slice(2);
  33. const arg = (n, d) => { const i = argv.indexOf(n); return i > -1 && argv[i + 1] ? argv[i + 1] : d; };
  34. const has = (n) => argv.includes(n);
  35. const URL = arg("--url", "http://localhost:4500");
  36. const OUT = path.resolve(arg("--out", "lab/shots"));
  37. const STEPS = parseInt(arg("--per-act", arg("--steps", "6")), 10); // samples PER ACT
  38. const W = parseInt(arg("--width", "1440"), 10);
  39. const H = parseInt(arg("--height", "900"), 10);
  40. const REDUCED = has("--reduced-motion");
  41. const CHROME = [
  42. process.env.SCROLLCRAFT_CHROME,
  43. // Windows
  44. "C:/Program Files/Google/Chrome/Application/chrome.exe",
  45. "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe",
  46. "C:/Program Files/Microsoft/Edge/Application/msedge.exe",
  47. // macOS
  48. "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
  49. "/Applications/Chromium.app/Contents/MacOS/Chromium",
  50. "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
  51. // Linux
  52. "/usr/bin/google-chrome",
  53. "/usr/bin/google-chrome-stable",
  54. "/usr/bin/chromium",
  55. "/usr/bin/chromium-browser",
  56. "/snap/bin/chromium",
  57. ].find((p) => p && fs.existsSync(p));
  58. if (!CHROME) {
  59. console.error("No installed Chrome found. Set SCROLLCRAFT_CHROME to its path.");
  60. process.exit(1);
  61. }
  62. fs.mkdirSync(OUT, { recursive: true });
  63. const browser = await chromium.launch({ executablePath: CHROME, headless: true });
  64. const page = await browser.newPage({
  65. viewport: { width: W, height: H },
  66. deviceScaleFactor: 2,
  67. reducedMotion: REDUCED ? "reduce" : "no-preference",
  68. });
  69. const consoleErrors = [];
  70. page.on("console", (m) => { if (m.type() === "error") consoleErrors.push(m.text()); });
  71. page.on("pageerror", (e) => consoleErrors.push(String(e)));
  72. const failed = [];
  73. page.on("requestfailed", (r) => failed.push(`${r.failure()?.errorText} ${r.url()}`));
  74. // Not networkidle: the engine keeps clips in flight as you scroll, and a
  75. // webfont connection can stay open, so idle may never arrive. Wait for the
  76. // engine's own ready signal and for the faces to land, since line splitting
  77. // measures real line boxes and is wrong before the real face is applied.
  78. await page.goto(URL, { waitUntil: "domcontentloaded" });
  79. await page.waitForSelector("html.sc-ready", { timeout: 15000 });
  80. await page.evaluate(() => document.fonts.ready);
  81. await page.waitForTimeout(700);
  82. const doc = await page.evaluate(() => {
  83. const world = document.querySelector('[data-sc-mode="worldflight"]');
  84. return {
  85. height: document.body.scrollHeight,
  86. vh: innerHeight,
  87. acts: [...document.querySelectorAll("[data-sc-act]")].map((a) => a.dataset.scAct),
  88. world: world
  89. ? {
  90. seam: parseFloat(world.dataset.scSeam) || 0.12,
  91. segs: [...world.querySelectorAll("[data-sc-segment]")].map((s) => ({
  92. w: parseFloat(s.dataset.scW) || 1.3,
  93. linger: parseFloat(s.dataset.scLinger) || 0,
  94. label: s.dataset.scWaypoint || "",
  95. })),
  96. }
  97. : null,
  98. };
  99. });
  100. const WORLD = doc.world;
  101. const maxScroll = doc.height - doc.vh;
  102. if (WORLD) {
  103. const total = WORLD.segs.reduce((s, g) => s + g.w, 0);
  104. console.log(`page: worldflight, ${WORLD.segs.length} legs over ${total.toFixed(2)}vh ` +
  105. `(track ${(doc.height / doc.vh).toFixed(1)} viewport-heights), seam ${WORLD.seam}vh`);
  106. console.log(` legs: ${WORLD.segs.map((g, i) => `${i}:${g.label || "-"}@${g.w}vh`).join(" ")}`);
  107. } else {
  108. console.log(`page: ${(doc.height / doc.vh).toFixed(1)} viewport-heights, acts: ${doc.acts.join(" > ")}`);
  109. }
  110. // Wait for the playhead to ARRIVE, not merely to stop seeking. The engine lerps
  111. // currentTime toward a target on its own rAF loop, so after any scroll jump
  112. // there is a stretch of ~15 frames during which every clip on the page is
  113. // somewhere it will never be again. Screenshot in that window and the sheet is a
  114. // set of frames the reader is never shown, the dead-scroll comparison runs on
  115. // mid-lerp noise, and the whole run is unrepeatable.
  116. async function settle(timeout = 4000) {
  117. const t0 = Date.now();
  118. let last = null;
  119. for (;;) {
  120. const now = await page.evaluate(() => {
  121. const insts = (window.ScrollCraft && window.ScrollCraft.instances) || [];
  122. const clips = [].concat(...insts.map((i) => i.clips || [])).filter((c) => c.ready);
  123. // Pages on an older engine expose no instances; fall back to watching
  124. // currentTime go quiet, which reaches the same state more slowly.
  125. if (clips.length) {
  126. const arrived = clips.every((c) => Math.abs(c.cur - c.target) < 0.002 && !c.el.seeking);
  127. return arrived ? "arrived" : "moving";
  128. }
  129. return [...document.querySelectorAll("video[data-sc-scrub]")]
  130. .map((v) => (v.seeking ? "seeking" : v.currentTime.toFixed(3))).join("|");
  131. });
  132. if (now === "arrived") return true;
  133. if (now !== "moving" && now === last && !now.includes("seeking")) return true;
  134. if (Date.now() - t0 > timeout) return false;
  135. last = now;
  136. await page.waitForTimeout(60);
  137. }
  138. }
  139. // Sample WITHIN each act, not uniformly down the document. Uniform sampling
  140. // distributes positions by page length, so a short act gets one sample that
  141. // lands wherever it lands, and adding a section elsewhere silently moves every
  142. // sample. That produces "this cue never reaches full opacity" reports that come
  143. // and go with unrelated edits. Per-act sampling hits the same fractions of
  144. // every act every run, so the findings mean something.
  145. //
  146. // A worldflight has no acts to sample within; its unit is the leg, and its
  147. // geometry lives entirely in the weights, so positions are computed from the
  148. // track rather than measured off the DOM. Both sides of every seam are added on
  149. // top: the crossfade is the frame this mode is judged on, and it occupies about
  150. // a tenth of a viewport, so uniform sampling steps straight over it.
  151. const positions = WORLD ? await page.evaluate((perSeg) => {
  152. const root = document.querySelector('[data-sc-mode="worldflight"]');
  153. const segs = [...root.querySelectorAll("[data-sc-segment]")];
  154. const top = root.getBoundingClientRect().top + scrollY;
  155. const seam = parseFloat(root.dataset.scSeam) || 0.12;
  156. const fracs = Array.from({ length: perSeg }, (_, i) => (perSeg === 1 ? 0.5 : i / (perSeg - 1)));
  157. const out = [];
  158. let c = 0;
  159. segs.forEach((s, i) => {
  160. const w = parseFloat(s.dataset.scW) || 1.3;
  161. fracs.forEach((f) => {
  162. const p = 0.02 + f * 0.96;
  163. out.push(Math.round(top + (c + w * p) * innerHeight));
  164. });
  165. c += w;
  166. if (i < segs.length - 1) {
  167. [-0.5, -0.2, 0.2, 0.5].forEach((k) => out.push(Math.round(top + (c + k * seam) * innerHeight)));
  168. }
  169. });
  170. const max = document.body.scrollHeight - innerHeight;
  171. out.push(0, max);
  172. return [...new Set(out.map((y) => Math.max(0, Math.min(max, y))))].sort((a, b) => a - b);
  173. }, Math.max(2, Math.round(STEPS))) : await page.evaluate((perAct) => {
  174. const out = [];
  175. const fracs = Array.from({ length: perAct }, (_, i) => (perAct === 1 ? 0.5 : i / (perAct - 1)));
  176. document.querySelectorAll("[data-sc-act]").forEach((el) => {
  177. const top = el.getBoundingClientRect().top + scrollY;
  178. const h = el.offsetHeight;
  179. const pinned = ["scrub", "pin", "pan"].includes(el.dataset.scAct);
  180. fracs.forEach((f) => {
  181. // Nudge off the exact endpoints: p=0 and p=1 sit on the seam between two
  182. // acts, where which one you are "in" is ambiguous.
  183. const p = 0.02 + f * 0.96;
  184. out.push(Math.round(pinned ? top + (h - innerHeight) * p : top - innerHeight + (h + innerHeight) * p));
  185. });
  186. // A pinned stage is on screen for a viewport BEFORE its pinned travel begins
  187. // and a viewport AFTER it ends, and the loop above samples only inside the
  188. // travel. Those two slides are exactly where a clip mapped to pinned
  189. // progress sits frozen on its first or last frame, so not sampling them is
  190. // why a frozen clip could pass this harness. Sample them.
  191. if (el.dataset.scAct === "scrub") {
  192. // `v` is the fraction of the viewport the stage covers at that position.
  193. // Sample the part of each slide where the stage is still MOSTLY on screen,
  194. // because that is where a frozen frame is conspicuous, and because the
  195. // frozen-clip check needs consecutive samples that are both well past its
  196. // visibility gate before it will call anything.
  197. [0.6, 0.75, 0.9].forEach((v) => {
  198. out.push(Math.round(top - innerHeight * (1 - v))); // sliding in
  199. out.push(Math.round(top + h - innerHeight * v)); // sliding out
  200. });
  201. }
  202. });
  203. const max = document.body.scrollHeight - innerHeight;
  204. out.push(max);
  205. return [...new Set(out.map((y) => Math.max(0, Math.min(max, y))))].sort((a, b) => a - b);
  206. }, Math.max(2, Math.round(STEPS)));
  207. const report = [];
  208. for (let i = 0; i < positions.length; i++) {
  209. const y = positions[i];
  210. const p = maxScroll ? y / maxScroll : 0;
  211. await page.evaluate((y) => scrollTo({ top: y, behavior: "instant" }), y);
  212. await page.waitForTimeout(180);
  213. const settled = await settle();
  214. const state = await page.evaluate(() => {
  215. // A kinetic heading carries its real opacity on the split line units; the
  216. // engine forces the element itself to 1. Reading the element therefore
  217. // reports every kinetic headline as fully present, including on frames
  218. // where every one of its lines is at 0. Take the strongest line instead:
  219. // the heading is "peaked" when at least one unit has arrived.
  220. const cueOpacity = (el) => {
  221. const o = parseFloat(getComputedStyle(el).opacity) || 0;
  222. const units = el.querySelectorAll(".sc-split__i");
  223. if (!units.length) return o;
  224. let m = 0;
  225. units.forEach((u) => { m = Math.max(m, parseFloat(getComputedStyle(u).opacity) || 0); });
  226. return o * m;
  227. };
  228. const vis = [];
  229. // A worldflight's copy blocks are windowed against the whole track rather
  230. // than an act's progress, but they are the same thing to a reader: type that
  231. // has to arrive, hold, and leave. Grade them identically.
  232. document.querySelectorAll("[data-sc-cue],[data-sc-copy]").forEach((el) => {
  233. const o = cueOpacity(el);
  234. if (o <= 0.02) return;
  235. // On screen, not merely non-transparent. An element parked off-viewport
  236. // at opacity 1 is not a visible cue, and counting it produces phantom
  237. // findings that send you chasing a bug the reader never sees.
  238. const r = el.getBoundingClientRect();
  239. if (r.bottom < 0 || r.top > innerHeight || r.right < 0 || r.left > innerWidth) return;
  240. vis.push({ t: (el.textContent || "").trim().replace(/\s+/g, " ").slice(0, 46), o: +o.toFixed(2) });
  241. });
  242. const clips = [...document.querySelectorAll("video[data-sc-scrub]")].map((v) => ({
  243. // A continuous world legitimately keeps its clip chain outside the act
  244. // stack, driven by the page's own scroll value rather than by an act's
  245. // progress. Falling back to the clip's own class keeps that case
  246. // reporting instead of taking the whole run down before it writes
  247. // anything.
  248. painted: (v.closest("[data-sc-act]") ?? v).classList.contains("sc-has-clip"),
  249. t: +(v.currentTime || 0).toFixed(2),
  250. dur: +(v.duration || 0).toFixed(2),
  251. // How much of the viewport this clip's stage actually covers. A frozen
  252. // playhead only matters while the reader can see the stage.
  253. vis: (() => {
  254. const st = v.closest("[data-sc-stage]") || v.parentElement;
  255. if (!st) return 0;
  256. const b = st.getBoundingClientRect();
  257. return +(Math.max(0, Math.min(b.bottom, innerHeight) - Math.max(b.top, 0)) / innerHeight).toFixed(3);
  258. })(),
  259. }));
  260. // Rails and wipes move without changing any cue or clip time, so without
  261. // these a panning section reads as dead scroll.
  262. const rails = [...document.querySelectorAll("[data-sc-pan]")]
  263. .map((r) => Math.round(new DOMMatrixReadOnly(getComputedStyle(r).transform).m41));
  264. const wipes = [...document.querySelectorAll("[data-sc-reveal]")]
  265. .map((r) => getComputedStyle(r).clipPath);
  266. // Which act owns the middle of the viewport right now.
  267. let act = "-";
  268. document.querySelectorAll("[data-sc-act]").forEach((a) => {
  269. const r = a.getBoundingClientRect();
  270. if (r.top <= innerHeight / 2 && r.bottom >= innerHeight / 2) act = a.dataset.scAct;
  271. });
  272. // Where each pinned stage physically sits. Before an act reaches its pin
  273. // point the stage slides up the screen while its progress is still clamped
  274. // to 0, so the clip and cues are frozen and yet the view is very much
  275. // moving. Without this the run-up to every pinned act reads as dead scroll.
  276. const stages = [...document.querySelectorAll("[data-sc-stage]")]
  277. .map((s) => Math.round(s.getBoundingClientRect().top));
  278. // Worldflight legs. Opacity IS the crossfade, so it is state, not styling:
  279. // two samples with the same clip times but different leg opacities are a
  280. // dissolve in progress, not dead scroll.
  281. const segs = [...document.querySelectorAll("[data-sc-segment]")].map((el, i) => {
  282. const v = el.querySelector("video");
  283. return {
  284. i, label: el.dataset.scWaypoint || "",
  285. op: +(parseFloat(getComputedStyle(el).opacity) || 0).toFixed(3),
  286. painted: el.classList.contains("sc-has-clip"),
  287. t: v ? +(v.currentTime || 0).toFixed(3) : null,
  288. };
  289. });
  290. const world = document.querySelector('[data-sc-mode="worldflight"]');
  291. // Bespoke fixed stages can use flow markers for document travel while all
  292. // visible motion happens outside the engine's pin/scrub devices. Those
  293. // pages publish a compact representation of their actual visual state so
  294. // dead-scroll verification does not silently skip the whole experience.
  295. const customEls = [...document.querySelectorAll("[data-sc-verify-state]")];
  296. const custom = customEls.map((el) => el.getAttribute("data-sc-verify-state") || "");
  297. const customHold = customEls.some((el) => el.getAttribute("data-sc-verify-hold") === "true");
  298. return {
  299. cues: vis, clips, rails, wipes, act, stages, segs, custom, customHold,
  300. seg: world ? +(world.style.getPropertyValue("--sc-seg") || -1) : null,
  301. segp: world ? +(world.style.getPropertyValue("--sc-segp") || 0) : null,
  302. bg: getComputedStyle(document.documentElement).getPropertyValue("--sc-canvas").trim(),
  303. };
  304. });
  305. // Flat NN.png so ffmpeg can read the set as a numbered sequence for the
  306. // contact sheet. The scroll offset lives in report.json, not the filename.
  307. const name = `${String(i).padStart(2, "0")}.png`;
  308. await page.screenshot({ path: path.join(OUT, name) });
  309. // Contrast, measured on the COMPOSITED page rather than on the source media.
  310. // Sampling the video directly ignores every scrim, gradient and blend on top
  311. // of it, so a page can read as failing while looking fine, or the reverse.
  312. // Hide the text, shoot the same frame, hand the pixels back to the page, and
  313. // sample the real background under each line. Text over a scrubbing clip is
  314. // the one contrast case a static audit cannot cover: the frame beneath a
  315. // headline changes as you scroll, so it can pass on the poster and fail three
  316. // hundred pixels later. The direction is picked per line: light type fails on
  317. // the brightest patch, dark type on the darkest one.
  318. //
  319. // Fixed chrome is hidden along with the text. A fixed bar paints in FRONT of
  320. // whatever scrolls under it, so its own mark is not the background behind a
  321. // headline passing beneath it, and leaving it in reports a spurious failure
  322. // on an act that is fine.
  323. await page.evaluate(() => {
  324. document.querySelectorAll("body *").forEach((el) => {
  325. if (getComputedStyle(el).position !== "fixed") return;
  326. // A worldflight's stage and copy layer are fixed too, and they are the
  327. // exact opposite case: the stage IS the background behind every line, and
  328. // the copy layer carries the scrim that makes the line legible. Hiding
  329. // them samples the page ground instead of the film and reports the whole
  330. // page as failing while it looks fine.
  331. if (el.closest("[data-sc-world],[data-sc-world-copy]")) return;
  332. el.setAttribute("data-sc-shot-fixed", "");
  333. });
  334. });
  335. await page.addStyleTag({
  336. content: "[data-sc-cue],[data-sc-cue] *,[data-sc-copy],[data-sc-copy] *," +
  337. "[data-sc-shot-fixed]{visibility:hidden!important}",
  338. });
  339. const bare = (await page.screenshot({ type: "jpeg", quality: 80 })).toString("base64");
  340. const contrast = await page.evaluate(async ({ b64, dpr }) => {
  341. const img = new Image();
  342. img.src = "data:image/jpeg;base64," + b64;
  343. await img.decode();
  344. const c = document.createElement("canvas");
  345. const g = c.getContext("2d", { willReadFrequently: true });
  346. const lum = (r, gr, b) => {
  347. const f = (v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
  348. return 0.2126 * f(r) + 0.7152 * f(gr) + 0.0722 * f(b);
  349. };
  350. const ratio = (a, b) => (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
  351. const cueOpacity = (el) => {
  352. const o = parseFloat(getComputedStyle(el).opacity) || 0;
  353. const units = el.querySelectorAll(".sc-split__i");
  354. if (!units.length) return o;
  355. let m = 0;
  356. units.forEach((u) => { m = Math.max(m, parseFloat(getComputedStyle(u).opacity) || 0); });
  357. return o * m;
  358. };
  359. const out = [];
  360. document.querySelectorAll("[data-sc-cue],[data-sc-copy]").forEach((el) => {
  361. if (cueOpacity(el) < 0.85) return;
  362. if (!(el.textContent || "").trim()) return;
  363. const r = el.getBoundingClientRect();
  364. if (r.width < 8 || r.height < 8 || r.bottom < 0 || r.top > innerHeight) return;
  365. // Clamp the sampled rect to the viewport. The part of a pinned act's copy
  366. // that has scrolled above the fold is not on screen, so whatever sits in
  367. // those pixels is not the background behind anything the reader can see.
  368. const vl = Math.max(0, r.left), vt = Math.max(0, r.top);
  369. const vr = Math.min(innerWidth, r.right), vb = Math.min(innerHeight, r.bottom);
  370. if (vr - vl < 8 || vb - vt < 8) return;
  371. const x = vl * dpr, y2 = vt * dpr;
  372. const w = Math.min((vr - vl) * dpr, img.width - x), h = Math.min((vb - vt) * dpr, img.height - y2);
  373. if (w < 2 || h < 2) return;
  374. c.width = 32; c.height = 16;
  375. g.drawImage(img, x, y2, w, h, 0, 0, 32, 16);
  376. const d = g.getImageData(0, 0, 32, 16).data;
  377. let maxL = 0, minL = 1, sum = 0, n = 0;
  378. for (let k = 0; k < d.length; k += 4) {
  379. const L = lum(d[k], d[k + 1], d[k + 2]);
  380. if (L > maxL) maxL = L;
  381. if (L < minL) minL = L;
  382. sum += L; n++;
  383. }
  384. const cs = getComputedStyle(el);
  385. const fg = cs.color.match(/[\d.]+/g).map(Number);
  386. const fl = lum(fg[0], fg[1], fg[2]);
  387. // An element that paints its own opaque background (a button, a chip) is
  388. // an ordinary static contrast case: grade its text against that fill, not
  389. // against whatever the page happens to show behind it. Hiding the element
  390. // to sample the backdrop necessarily hides its background too, so without
  391. // this every solid CTA reports a spurious failure.
  392. const bg = (cs.backgroundColor.match(/[\d.]+/g) || []).map(Number);
  393. const opaqueBg = bg.length >= 3 && (bg.length < 4 || bg[3] > 0.5);
  394. if (opaqueBg) {
  395. const bl = lum(bg[0], bg[1], bg[2]);
  396. out.push({
  397. t: (el.textContent || "").trim().replace(/\s+/g, " ").slice(0, 40),
  398. dir: "own-fill",
  399. worst: +ratio(fl, bl).toFixed(2), mean: +ratio(fl, bl).toFixed(2),
  400. });
  401. return;
  402. }
  403. // Pick the direction from the foreground. Light type on a dark page fails
  404. // on the brightest patch under it; dark type on a light page (a high-key
  405. // world, ink over media) fails on the DARKEST patch, and grading that
  406. // against maxL is the most lenient reading available, so a page can report
  407. // clean over text that is failing. Compare the ink to the mean background
  408. // and grade against whichever extreme is on the ink's own side.
  409. const meanL = sum / n;
  410. const dark = fl < meanL;
  411. out.push({
  412. t: (el.textContent || "").trim().replace(/\s+/g, " ").slice(0, 40),
  413. dir: dark ? "dark-on-light" : "light-on-dark",
  414. worst: +ratio(fl, dark ? minL : maxL).toFixed(2),
  415. mean: +ratio(fl, meanL).toFixed(2),
  416. });
  417. });
  418. return out;
  419. }, { b64: bare, dpr: 2 });
  420. await page.evaluate(() => {
  421. const t = [...document.querySelectorAll("style")].pop();
  422. if (t && t.textContent.includes("data-sc-cue")) t.remove();
  423. document.querySelectorAll("[data-sc-shot-fixed]").forEach((el) => el.removeAttribute("data-sc-shot-fixed"));
  424. });
  425. report.push({ i, y, pct: +(p * 100).toFixed(0), settled, contrast, ...state });
  426. if (WORLD) {
  427. console.log(` ${name} settled=${settled} copy=${state.cues.length} leg=${state.seg}@${state.segp} ` +
  428. `legs=${state.segs.map((g) => `${g.op > 0.002 ? (g.painted ? g.t : "poster") : "-"}${g.op > 0.002 && g.op < 0.998 ? "*" + g.op : ""}`).join(",")}`);
  429. } else {
  430. console.log(` ${name} settled=${settled} cues=${state.cues.length} clips=${state.clips.map((c) => (c.painted ? c.t : "poster")).join(",")}`);
  431. }
  432. }
  433. fs.writeFileSync(path.join(OUT, "report.json"), JSON.stringify({ doc, report, consoleErrors, failed }, null, 2));
  434. if (consoleErrors.length) console.log("\nCONSOLE ERRORS:\n " + consoleErrors.join("\n "));
  435. if (failed.length) console.log("\nFAILED REQUESTS:\n " + failed.join("\n "));
  436. // Dead-scroll detector: consecutive positions where nothing visibly changed.
  437. // This is the failure the eye misses and the reason to shoot contiguously.
  438. // Opacity counts as change: a cue mid-fade is motion, and comparing only which
  439. // cues exist would call a crossfade dead.
  440. const sig = (s) => JSON.stringify([
  441. s.cues.map((c) => c.t + ":" + c.o),
  442. s.clips.map((c) => c.t),
  443. s.rails,
  444. s.wipes,
  445. s.stages,
  446. s.custom || [],
  447. ]);
  448. // Only inside pinned acts. A flow section or a footer that holds still across
  449. // two sample positions is a page behaving correctly, not dead scroll, and
  450. // flagging it trains you to ignore the signal.
  451. const PINNED = new Set(["scrub", "pin", "pan"]);
  452. const dead = [];
  453. if (WORLD) {
  454. // Every pixel of a worldflight track is pinned by construction, so there is
  455. // no "correctly still" region to exclude and the whole page is fair game.
  456. // Three independent things can carry the motion: the film advancing, a leg
  457. // dissolving into the next, and a copy window opening or closing. Dead scroll
  458. // is all three holding at once.
  459. const wsig = (s) => JSON.stringify([
  460. s.segs.map((g) => g.t),
  461. s.segs.map((g) => g.op),
  462. s.cues.map((c) => c.t + ":" + c.o),
  463. ]);
  464. // Not under reduced motion. There the film is deliberately never fetched, so
  465. // the middle of a leg holds a single still frame and every pair of samples in
  466. // it is identical BY DESIGN. Flagging that reports the accessibility path as
  467. // broken every single run, which is how a real finding gets ignored. What
  468. // matters here is whether the story still reads, and the copy-window and
  469. // contrast passes below answer that.
  470. for (let i = 1; !REDUCED && i < report.length; i++) {
  471. const a = report[i - 1], b = report[i];
  472. // Tighter than the act gate: a leg is about one viewport of scroll, so a
  473. // quarter-viewport window would only ever compare four points per leg.
  474. if (b.y - a.y < doc.vh * 0.12) continue;
  475. if (wsig(a) === wsig(b)) {
  476. dead.push(`${a.pct}% -> ${b.pct}% (leg ${a.seg} > ${b.seg})`);
  477. }
  478. }
  479. } else {
  480. for (let i = 1; i < report.length; i++) {
  481. const a = report[i - 1], b = report[i];
  482. const hasCustomState = (a.custom?.length || 0) > 0 || (b.custom?.length || 0) > 0;
  483. if (!PINNED.has(a.act) && !PINNED.has(b.act) && !hasCustomState) continue;
  484. // A page may explicitly declare an authored hold, such as a resolved close
  485. // or the stable accessibility frame under reduced motion. It has to be
  486. // declared by the visible stage; ordinary flow content stays exempt as it
  487. // was before this custom-state path existed.
  488. if (a.customHold && b.customHold) continue;
  489. // Two samples a few dozen pixels apart SHOULD look the same. Only flag a gap
  490. // wide enough that a reader would notice nothing happening in it.
  491. if (b.y - a.y < doc.vh * 0.25) continue;
  492. if (sig(a) === sig(b)) dead.push(`${a.pct}% -> ${b.pct}% (${a.act} > ${b.act})`);
  493. }
  494. }
  495. console.log(dead.length ? `\nDEAD SCROLL between: ${dead.join(", ")}`
  496. : WORLD && REDUCED ? "\ndead-scroll check skipped: reduced motion holds each leg on one still frame by design"
  497. : "\nno dead scroll detected");
  498. // FROZEN CLIP. The reader is scrolling, a scrub stage is on screen, and its
  499. // playhead is not moving: a still photograph sliding up the page. Dead scroll
  500. // cannot see this, because the stage IS moving, which is the whole problem.
  501. //
  502. // A hold on the first or last frame is always a defect. A hold in the middle
  503. // can be an intentional `dwell` settle, so it only counts once it outlasts one.
  504. // Skipped under reduced motion, where no clip is ever fetched on purpose.
  505. if (!REDUCED) {
  506. const nClips = report[0]?.clips?.length || 0;
  507. const VIS = 0.55, EPS = 0.012, MIN = doc.vh * 0.15;
  508. const frozen = [];
  509. for (let c = 0; c < nClips; c++) {
  510. let run = null;
  511. const flush = () => {
  512. if (!run) return;
  513. const kind = run.t < 0.05 ? "entry" : (run.dur && run.t > run.dur - 0.08 ? "exit" : "mid");
  514. const need = kind === "mid" ? doc.vh * 0.5 : MIN;
  515. if (run.to - run.from >= need) frozen.push({ c, kind, ...run });
  516. run = null;
  517. };
  518. for (let i = 1; i < report.length; i++) {
  519. const a = report[i - 1].clips?.[c], b = report[i].clips?.[c];
  520. if (!a || !b) { flush(); continue; }
  521. const seen = a.vis >= VIS && b.vis >= VIS;
  522. const stuck = Math.abs(b.t - a.t) < EPS;
  523. if (seen && stuck && b.painted) {
  524. if (!run) run = { from: report[i - 1].y, to: report[i].y, t: b.t, dur: b.dur };
  525. else run.to = report[i].y;
  526. } else flush();
  527. }
  528. flush();
  529. }
  530. if (frozen.length) {
  531. console.log("\nFROZEN CLIP (still image while the page moves):\n " + frozen.map((f) => {
  532. const px = f.to - f.from;
  533. const where = f.kind === "entry" ? "held on its FIRST frame while the stage slides in"
  534. : f.kind === "exit" ? "held on its LAST frame while the stage slides out"
  535. : `held mid-clip at ${f.t.toFixed(2)}s, longer than a dwell settle`;
  536. return `clip ${f.c}: ${px}px (${(px / doc.vh).toFixed(2)} viewports) ${where}`;
  537. }).join("\n ") + "\n Fix: let the clip map across the stage's whole visible life. That is the\n engine default; data-sc-clip-map=\"travel\" turns it off. See devices.md.");
  538. } else if (nClips) {
  539. console.log(`all ${nClips} scrub clip(s) keep moving whenever they are on screen`);
  540. }
  541. }
  542. // Worldflight findings. A leg that never reaches full opacity is a weight or a
  543. // seam that is wrong: the reader is shown a permanent dissolve between two
  544. // clips and never the leg itself. A leg stuck on its poster is a clip that
  545. // never loaded or never decoded, and it passes every other check on this page
  546. // because a poster looks exactly like a paused film.
  547. if (WORLD) {
  548. const segPeak = {};
  549. report.forEach((s) => (s.segs || []).forEach((g) => {
  550. const k = `${g.i}${g.label ? ' "' + g.label + '"' : ""}`;
  551. segPeak[k] = segPeak[k] || { op: 0, painted: false, hasClip: g.t !== null };
  552. segPeak[k].op = Math.max(segPeak[k].op, g.op);
  553. segPeak[k].painted = segPeak[k].painted || g.painted;
  554. }));
  555. const faint = Object.entries(segPeak).filter(([, v]) => v.op < 0.99);
  556. // Under reduced motion no clip is ever fetched, on purpose. Every leg is
  557. // legitimately on its poster, and reporting that as a fault buries the one
  558. // finding this pass exists for: whether the story still reads without motion.
  559. const posters = REDUCED ? [] : Object.entries(segPeak).filter(([, v]) => v.hasClip && !v.painted);
  560. if (faint.length) console.log("\nLEGS THAT NEVER REACH FULL OPACITY:\n " +
  561. faint.map(([k, v]) => `${v.op.toFixed(2)} leg ${k}`).join("\n "));
  562. if (posters.length) console.log("\nLEGS STUCK ON POSTER (clip never painted):\n " +
  563. posters.map(([k]) => `leg ${k}`).join("\n "));
  564. if (!faint.length && !posters.length)
  565. console.log(`all ${Object.keys(segPeak).length} legs reach full opacity` +
  566. (REDUCED ? " (posters only, as reduced motion requires)" : " and paint a real frame"));
  567. }
  568. // Cues that never reach full strength anywhere on the page. A headline peaking
  569. // at 0.6 is a mis-set cue window, and it is invisible as a bug because the
  570. // element IS there, just never quite arriving.
  571. const peak = {};
  572. report.forEach((s) => s.cues.forEach((c) => { peak[c.t] = Math.max(peak[c.t] || 0, c.o); }));
  573. const weak = Object.entries(peak).filter(([, o]) => o < 0.8);
  574. if (weak.length) console.log("\nCUES THAT NEVER PEAK:\n " + weak.map(([t, o]) => `${o} "${t}"`).join("\n "));
  575. // Contrast over media, graded at the worst frame each line is ever shown on.
  576. const worstBy = {};
  577. report.forEach((s) => (s.contrast || []).forEach((c) => {
  578. if (!worstBy[c.t] || c.worst < worstBy[c.t].worst) worstBy[c.t] = c;
  579. }));
  580. const fails = Object.values(worstBy).filter((c) => c.worst < 3);
  581. const thin = Object.values(worstBy).filter((c) => c.worst >= 3 && c.worst < 4.5);
  582. if (fails.length) console.log("\nCONTRAST FAIL (worst frame < 3:1):\n " +
  583. fails.map((c) => `${c.worst}:1 (mean ${c.mean}) "${c.t}"`).join("\n "));
  584. if (thin.length) console.log("\nCONTRAST THIN (3:1 to 4.5:1, ok for large display type only):\n " +
  585. thin.map((c) => `${c.worst}:1 "${c.t}"`).join("\n "));
  586. if (!fails.length && !thin.length && Object.keys(worstBy).length)
  587. console.log("\ncontrast over media: all cues clear 4.5:1 at their worst frame");
  588. await browser.close();
  589. // Contact sheet. The point of shooting contiguously is to look at the frames
  590. // side by side; a folder of 20 PNGs does not get looked at that way.
  591. const FFMPEG = [
  592. process.env.SCROLLCRAFT_FFMPEG,
  593. ...(fs.existsSync(path.join(process.env.HOME || "", "AppData/Local/Microsoft/WinGet/Packages"))
  594. ? fs.readdirSync(path.join(process.env.HOME, "AppData/Local/Microsoft/WinGet/Packages"))
  595. .filter((d) => d.startsWith("Gyan.FFmpeg"))
  596. .flatMap((d) => {
  597. const base = path.join(process.env.HOME, "AppData/Local/Microsoft/WinGet/Packages", d);
  598. return fs.readdirSync(base).map((v) => path.join(base, v, "bin/ffmpeg.exe"));
  599. })
  600. : []),
  601. "/usr/local/bin/ffmpeg", "/opt/homebrew/bin/ffmpeg", "ffmpeg",
  602. ].find((p) => p && (p === "ffmpeg" || fs.existsSync(p)));
  603. if (FFMPEG) {
  604. const cols = Math.min(5, report.length);
  605. const rows = Math.ceil(report.length / cols);
  606. const { spawnSync } = await import("node:child_process");
  607. const r = spawnSync(FFMPEG, [
  608. "-y", "-v", "error", "-i", path.join(OUT, "%02d.png"),
  609. "-vf", `scale=520:-1,tile=${cols}x${rows}`, "-frames:v", "1",
  610. path.join(OUT, "sheet.png"),
  611. ]);
  612. if (r.status === 0) console.log(`contact sheet: ${path.join(OUT, "sheet.png")}`);
  613. else console.log("contact sheet skipped (needs a full ffmpeg build; scale/tile are missing from stripped ones)");
  614. }
  615. console.log(`\nshots + report.json in ${OUT}`);