@jonandev/longbeard 0.5.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,9 +4,11 @@ A reference is the design from top to bottom. The builder has to take how the **
4
4
 
5
5
  ## Live sites — the script is for a keep
6
6
 
7
- Open as many listings and score pages as the hunt asks. Do not scroll a candidate, and do not screenshot one. Run the script only on a URL you are keeping. That run is the only scroll. Do not screenshot the tab by hand. Do not stitch folds. Stitching is what repeats a sticky hero down the file. A file in `.design/refs/` that is not on the board gets deleted, and only during the whole look that owns that folder. A later hunt keeps its own shots in `.design/hunts/<slug>/refs/`. Do not delete those because the board does not cite them. A file in that folder that its note does not cite gets deleted, and only during that hunt. A loading hunt does not delete a board shot. The whole look does not delete a hunt shot.
7
+ Open as many listings and score pages as the hunt asks. Do not scroll a candidate, and do not screenshot one. **Viewing a listing’s own thumbnails is allowed** — it is not a capture and writes nothing to `refs/`. Use `scripts/contact-sheet.mjs` on a TSV of `label\timageURL` to build labelled grids in a scratch folder (never `.design/`), then open only the shortlist at full size.
8
8
 
9
- From the project root, for the board:
9
+ Run the capture script only on a URL you are keeping. That run is the only scroll. Do not screenshot the tab by hand. Do not stitch folds. Stitching is what repeats a sticky hero down the file. A file in `.design/refs/` that is not on the board gets deleted, and only during the whole look that owns that folder. A later hunt keeps its own shots in `.design/hunts/<slug>/refs/`. Do not delete those because the board does not cite them. A file in that folder that its note does not cite gets deleted, and only during that hunt. A loading hunt does not delete a board shot. The whole look does not delete a hunt shot.
10
+
11
+ From the **project root** (relative `--out` resolves against `git rev-parse --show-toplevel`):
10
12
 
11
13
  ```
12
14
  node <skill>/scripts/capture.mjs https://example.com --out .design/refs/<name>.jpg
@@ -18,9 +20,13 @@ For a later hunt:
18
20
  node <skill>/scripts/capture.mjs https://example.com --out .design/hunts/<slug>/refs/<name>.jpg
19
21
  ```
20
22
 
21
- The script opens Chrome, accepts a cookie button if it can, then scrolls a viewport at a time and pauses so pictures and reveals can finish. It pauses motion. It does not turn animations off, because that puts a revealed section back to blank. Then it unsticks `fixed`/`sticky` and takes **one** JPEG of the document. Node 22+. Chrome, Edge, or Chromium must be installed (`CHROME_PATH` if it is not in the usual place).
23
+ Tall captures (thousands of px) shrink when opened whole until body text is illegible. For reading only, add `--review <scratch>/name-review.jpg`. That writes side-by-side columns about 2,800 px tall; the real capture stays the single tall file in `refs/`. Review files stay in temp or session scratch, never `refs/`.
24
+
25
+ Type specimens (Google Fonts, etc.): use `--clip x,y,w,h` so the shot is the specimen area (name, large sample, text sample), or crop to that area after capture. A type shot may be cropped to the specimen — it is material, not a site.
26
+
27
+ The script opens Chrome, accepts a cookie **button** if the whole label matches (not partial “ok” inside other link text), strips short privacy/cookie dialogs, then scrolls a viewport at a time and pauses so pictures and reveals can finish. If a dismiss click navigates away, it exits non-zero with `navigated away: <url>` — do not keep that file. It pauses motion. It does not turn animations off, because that puts a revealed section back to blank. Then it unsticks `fixed`/`sticky` and takes **one** JPEG of the document. Node 22+. Chrome, Edge, or Chromium must be installed (`CHROME_PATH` if it is not in the usual place). Helpers stay Node with no package dependencies.
22
28
 
23
- Then open the file. Write the hero and what is worth taking from it. A line you could have written without opening it does not count. Invalid if:
29
+ Then open the file (use the review sheet when the capture is tall). Write the hero and what is worth taking from it. A line you could have written without opening it does not count. Invalid if:
24
30
 
25
31
  - the same band of the page appears twice (a stacked face, a repeated headline)
26
32
  - a cookie dialog is still on it
@@ -34,9 +40,9 @@ If it is invalid, delete it and run the script again. If the site will not scrol
34
40
  - Prefer a **live site**. Click through from Awwwards / Godly / Land-book / siteinspire / MaxiBestOf / Recent / Dark Mode Design to the actual URL, then run the script on that URL.
35
41
  - Supahero: the live site behind a hero, or the hero crop itself when the piece is a hero. Not the grid.
36
42
  - Muzli: the original URL. Not the Muzli page.
37
- - Dribbble: open the **shot page** (`/shots/...`). Capture the artwork image only, not `/search`.
38
- - Pinterest: the pin image only, not the board and not search.
39
- - Never capture a search grid, a home feed, or a listing of cards.
43
+ - Dribbble: listing pages are client-rendered; `/shots/...` often returns Human Verification to headless Chrome. Use `scripts/dribbble-cards.mjs` on a popular-search listing URL — it scrolls and prints TSV of `id-slug`, views, image URL, title. Download artwork from `cdn.dribbble.com` (`<url>?resize=1600x1200`). Do not capture `/search`. Run queries one at a time; if a query returns 0 cards, retry once after a pause.
44
+ - Pinterest: the pin image only, not the board and not search. If a login wall appears, see [quality.md](quality.md).
45
+ - Never capture a search grid, a home feed, or a listing of cards (contact sheets of listing thumbnails are fine; they are not refs).
40
46
 
41
47
  ## Dribbble / Behance / Unsplash / Pinterest — not sites
42
48
 
@@ -44,4 +50,8 @@ These are pictures, not pages. Capture the **image** (or the type specimen), no
44
50
 
45
51
  Unsplash and Wikimedia: search the **subject**, not stock category.
46
52
 
53
+ **Unsplash:** `/photos/<id>/download` returns an HTML bot page. On the search page, read `figure a[href*="/photos/"] img`, take its `src` up to the `?`, and download `<that>?w=1600&q=80` from `images.unsplash.com`. Keep the photo page URL as the card’s `url:`.
54
+
55
+ **Wikimedia Commons:** call the API with `-A "<project>-hunt/0.1"`, `prop=imageinfo&iiprop=url&iiurlwidth=1920`, save `thumburl` as the shot, and use `descriptionurl` as the card’s `url:`.
56
+
47
57
  A board entry whose `shot` is a gallery listing, a stitched repeat, or an illustration filed as a website does not count.
@@ -3,10 +3,12 @@
3
3
  // repeat the same fold. Node 22+. Uses an installed Chrome/Edge/Chromium.
4
4
  //
5
5
  // node capture.mjs <url> --out .design/refs/name.jpg
6
- import { spawn } from "node:child_process";
6
+ // node capture.mjs <url> --out .design/refs/name.jpg --review /tmp/name-review.jpg
7
+ // node capture.mjs <url> --out .design/refs/name.jpg --clip x,y,w,h
8
+ import { spawn, execSync } from "node:child_process";
7
9
  import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
8
10
  import { tmpdir } from "node:os";
9
- import { dirname, join, resolve } from "node:path";
11
+ import { dirname, isAbsolute, join, resolve } from "node:path";
10
12
 
11
13
  const args = process.argv.slice(2);
12
14
  const flag = (name, def) => {
@@ -17,12 +19,50 @@ const flag = (name, def) => {
17
19
  return v;
18
20
  };
19
21
  const url = args[0];
20
- const out = resolve(flag("out", "") || "");
21
- if (!url || !/^https?:\/\//.test(url) || !out) {
22
- console.error("usage: node capture.mjs <https://url> --out .design/refs/name.jpg");
22
+ const outArg = flag("out", "") || "";
23
+ const reviewArg = flag("review", "") || "";
24
+ const clipArg = flag("clip", "") || "";
25
+ if (!url || !/^https?:\/\//.test(url) || !outArg) {
26
+ console.error(
27
+ "usage: node capture.mjs <https://url> --out .design/refs/name.jpg [--review /tmp/name-review.jpg] [--clip x,y,w,h]",
28
+ );
23
29
  process.exit(2);
24
30
  }
25
31
 
32
+ function projectRoot() {
33
+ try {
34
+ return execSync("git rev-parse --show-toplevel", { encoding: "utf8" }).trim();
35
+ } catch {
36
+ return process.cwd();
37
+ }
38
+ }
39
+
40
+ function resolveOut(path) {
41
+ if (!path) return "";
42
+ if (isAbsolute(path)) return path;
43
+ return resolve(projectRoot(), path);
44
+ }
45
+
46
+ const out = resolveOut(outArg);
47
+ const reviewOut = resolveOut(reviewArg);
48
+
49
+ function parseClip(s) {
50
+ if (!s) return null;
51
+ const parts = s.split(",").map((n) => Number(n.trim()));
52
+ if (parts.length !== 4 || parts.some((n) => !Number.isFinite(n) || n < 0)) {
53
+ console.error("clip must be x,y,w,h (non-negative numbers)");
54
+ process.exit(2);
55
+ }
56
+ const [x, y, w, h] = parts;
57
+ if (w < 1 || h < 1) {
58
+ console.error("clip width and height must be >= 1");
59
+ process.exit(2);
60
+ }
61
+ return { x, y, width: w, height: h, scale: 1 };
62
+ }
63
+
64
+ const clip = parseClip(clipArg);
65
+
26
66
  function findChrome() {
27
67
  const env = process.env.CHROME_PATH;
28
68
  if (env && existsSync(env)) return env;
@@ -156,19 +196,48 @@ await page("Emulation.setDeviceMetricsOverride", {
156
196
  await page("Page.navigate", { url }, 40000);
157
197
  await sleep(2500);
158
198
 
199
+ const beforeHref = (
200
+ await page("Runtime.evaluate", {
201
+ expression: "location.href",
202
+ returnByValue: true,
203
+ })
204
+ ).result.value;
205
+
159
206
  await page("Runtime.evaluate", {
160
207
  expression: `(() => {
161
- const labels = /accept|agree|ok|got it|allow|i understand|acepto|aceptar/i;
162
- for (const el of document.querySelectorAll("button, [role=button], a")) {
163
- const t = (el.innerText || el.textContent || "").trim();
208
+ const labels = /^(accept( all)?( cookies)?|agree|ok|okay|got it|allow( all)?|i understand|acepto|aceptar)$/i;
209
+ const clickable = document.querySelectorAll("button, [role=button]");
210
+ for (const el of clickable) {
211
+ const t = (el.innerText || el.textContent || "").trim().replace(/\\s+/g, " ");
164
212
  if (t.length < 40 && labels.test(t)) { el.click(); break; }
165
213
  }
214
+ // Strip short privacy/cookie dialogs (e.g. Google Fonts "×" banner).
215
+ const privacy = /uses cookies|privacy and google fonts|cookie settings/i;
216
+ for (const el of [...document.querySelectorAll("div, section, aside, dialog")]) {
217
+ const t = (el.innerText || el.textContent || "").trim();
218
+ if (t.length > 0 && t.length < 300 && privacy.test(t) && el.children.length < 12) {
219
+ el.remove();
220
+ }
221
+ }
166
222
  })()`,
167
223
  awaitPromise: true,
168
224
  returnByValue: true,
169
225
  });
170
226
  await sleep(800);
171
227
 
228
+ const afterHref = (
229
+ await page("Runtime.evaluate", {
230
+ expression: "location.href",
231
+ returnByValue: true,
232
+ })
233
+ ).result.value;
234
+
235
+ if (afterHref !== beforeHref) {
236
+ console.error(`navigated away: ${afterHref}`);
237
+ drop();
238
+ process.exit(1);
239
+ }
240
+
172
241
  await page(
173
242
  "Runtime.evaluate",
174
243
  {
@@ -228,15 +297,25 @@ await sleep(400);
228
297
 
229
298
  const metrics = await page("Page.getLayoutMetrics");
230
299
  const size = metrics.cssContentSize || metrics.contentSize;
231
- const width = Math.max(1, Math.ceil(size.width || 1440));
232
- const height = Math.max(1, Math.min(Math.ceil(size.height || 900), 14000));
300
+ const fullWidth = Math.max(1, Math.ceil(size.width || 1440));
301
+ const fullHeight = Math.max(1, Math.min(Math.ceil(size.height || 900), 14000));
302
+ const shotClip = clip
303
+ ? {
304
+ x: Math.min(clip.x, fullWidth - 1),
305
+ y: Math.min(clip.y, fullHeight - 1),
306
+ width: Math.min(clip.width, fullWidth - Math.min(clip.x, fullWidth - 1)),
307
+ height: Math.min(clip.height, fullHeight - Math.min(clip.y, fullHeight - 1)),
308
+ scale: 1,
309
+ }
310
+ : { x: 0, y: 0, width: fullWidth, height: fullHeight, scale: 1 };
311
+
233
312
  const { data } = await page(
234
313
  "Page.captureScreenshot",
235
314
  {
236
315
  format: "jpeg",
237
316
  quality: 70,
238
317
  captureBeyondViewport: true,
239
- clip: { x: 0, y: 0, width, height, scale: 1 },
318
+ clip: shotClip,
240
319
  },
241
320
  60000,
242
321
  );
@@ -244,5 +323,66 @@ const { data } = await page(
244
323
  mkdirSync(dirname(out), { recursive: true });
245
324
  writeFileSync(out, Buffer.from(data, "base64"));
246
325
  console.log(out);
326
+
327
+ if (reviewOut) {
328
+ // Side-by-side columns ~2800 px tall so a tall capture stays readable.
329
+ // Real capture stays the single tall file; review is scratch only.
330
+ const reviewHtml = `<!doctype html><meta charset=utf-8>
331
+ <canvas id=c></canvas>
332
+ <script>
333
+ const src = "data:image/jpeg;base64,${data}";
334
+ const img = new Image();
335
+ img.onload = () => {
336
+ const colH = 2800;
337
+ const gap = 20;
338
+ const cols = Math.max(1, Math.ceil(img.height / colH));
339
+ const c = document.getElementById("c");
340
+ c.width = cols * img.width + (cols - 1) * gap;
341
+ c.height = Math.min(colH, img.height);
342
+ const ctx = c.getContext("2d");
343
+ ctx.fillStyle = "#111";
344
+ ctx.fillRect(0, 0, c.width, c.height);
345
+ for (let i = 0; i < cols; i++) {
346
+ const sy = i * colH;
347
+ const sh = Math.min(colH, img.height - sy);
348
+ ctx.drawImage(img, 0, sy, img.width, sh, i * (img.width + gap), 0, img.width, sh);
349
+ }
350
+ document.title = "ready";
351
+ };
352
+ img.src = src;
353
+ </script>`;
354
+ const reviewPage = join(dir, "review.html");
355
+ writeFileSync(reviewPage, reviewHtml);
356
+ await page("Page.navigate", { url: `file://${reviewPage}` }, 20000);
357
+ await sleep(400);
358
+ for (let i = 0; i < 40; i++) {
359
+ const title = (
360
+ await page("Runtime.evaluate", { expression: "document.title", returnByValue: true })
361
+ ).result.value;
362
+ if (title === "ready") break;
363
+ await sleep(100);
364
+ }
365
+ const { result: sizeResult } = await page("Runtime.evaluate", {
366
+ expression: `(() => {
367
+ const c = document.getElementById("c");
368
+ return { w: c.width, h: c.height };
369
+ })()`,
370
+ returnByValue: true,
371
+ });
372
+ const { data: reviewData } = await page(
373
+ "Page.captureScreenshot",
374
+ {
375
+ format: "jpeg",
376
+ quality: 75,
377
+ clip: { x: 0, y: 0, width: sizeResult.value.w, height: sizeResult.value.h, scale: 1 },
378
+ captureBeyondViewport: true,
379
+ },
380
+ 60000,
381
+ );
382
+ mkdirSync(dirname(reviewOut), { recursive: true });
383
+ writeFileSync(reviewOut, Buffer.from(reviewData, "base64"));
384
+ console.log(reviewOut);
385
+ }
386
+
247
387
  drop();
248
388
  process.exit(0);
@@ -0,0 +1,247 @@
1
+ #!/usr/bin/env node
2
+ // Build labelled contact sheets from a TSV of label\timageURL.
3
+ // Writes JPEG grids (~36 per sheet) into an output directory (scratch, not .design/).
4
+ // Viewing listing thumbnails is allowed; this is not a capture.
5
+ //
6
+ // node contact-sheet.mjs candidates.tsv --out /tmp/hunt-sheets
7
+ import { spawn } from "node:child_process";
8
+ import {
9
+ existsSync,
10
+ mkdirSync,
11
+ mkdtempSync,
12
+ readFileSync,
13
+ rmSync,
14
+ writeFileSync,
15
+ } from "node:fs";
16
+ import { tmpdir } from "node:os";
17
+ import { join, resolve } from "node:path";
18
+
19
+ const args = process.argv.slice(2);
20
+ const flag = (name, def) => {
21
+ const i = args.indexOf(`--${name}`);
22
+ if (i === -1) return def;
23
+ const v = args[i + 1];
24
+ args.splice(i, 2);
25
+ return v;
26
+ };
27
+ const tsvPath = args[0];
28
+ const outDir = resolve(flag("out", "") || "");
29
+ const perSheet = Math.max(1, Number(flag("per", "36")) || 36);
30
+ if (!tsvPath || !outDir) {
31
+ console.error("usage: node contact-sheet.mjs candidates.tsv --out /tmp/hunt-sheets [--per 36]");
32
+ process.exit(2);
33
+ }
34
+
35
+ const lines = readFileSync(tsvPath, "utf8")
36
+ .split(/\r?\n/)
37
+ .map((l) => l.trim())
38
+ .filter(Boolean)
39
+ .map((l) => {
40
+ const tab = l.indexOf("\t");
41
+ if (tab === -1) return { label: l, url: l };
42
+ return { label: l.slice(0, tab).trim(), url: l.slice(tab + 1).trim() };
43
+ })
44
+ .filter((r) => /^https?:\/\//i.test(r.url));
45
+
46
+ if (!lines.length) {
47
+ console.error("no label\timageURL rows found");
48
+ process.exit(1);
49
+ }
50
+
51
+ function findChrome() {
52
+ const env = process.env.CHROME_PATH;
53
+ if (env && existsSync(env)) return env;
54
+ const home = process.env.HOME || process.env.USERPROFILE || "";
55
+ const local = process.env.LOCALAPPDATA || "";
56
+ const pf = process.env.PROGRAMFILES || "C:\\Program Files";
57
+ const pf86 = process.env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)";
58
+ const candidates = [
59
+ join(pf, "Google/Chrome/Application/chrome.exe"),
60
+ join(pf86, "Google/Chrome/Application/chrome.exe"),
61
+ join(local, "Google/Chrome/Application/chrome.exe"),
62
+ join(pf, "Microsoft/Edge/Application/msedge.exe"),
63
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
64
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
65
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
66
+ join(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
67
+ "/usr/bin/google-chrome",
68
+ "/usr/bin/google-chrome-stable",
69
+ "/usr/bin/chromium",
70
+ "/usr/bin/chromium-browser",
71
+ ];
72
+ return candidates.find((path) => path && existsSync(path)) || null;
73
+ }
74
+
75
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
76
+ const exe = findChrome();
77
+ if (!exe) {
78
+ console.error("No Chrome/Edge/Chromium found. Install one or set CHROME_PATH.");
79
+ process.exit(1);
80
+ }
81
+ if (typeof WebSocket === "undefined") {
82
+ console.error("Node 22+ is required.");
83
+ process.exit(1);
84
+ }
85
+
86
+ const dir = mkdtempSync(join(tmpdir(), "hunt-sheet-"));
87
+ let proc;
88
+ const drop = () => {
89
+ try {
90
+ if (proc?.pid) process.kill(proc.pid, "SIGKILL");
91
+ } catch {}
92
+ try {
93
+ rmSync(dir, { recursive: true, force: true });
94
+ } catch {}
95
+ };
96
+ process.once("exit", drop);
97
+
98
+ proc = spawn(
99
+ exe,
100
+ [
101
+ "--headless=new",
102
+ "--remote-debugging-port=0",
103
+ `--user-data-dir=${dir}`,
104
+ "--no-first-run",
105
+ "--hide-scrollbars",
106
+ "--mute-audio",
107
+ "--force-color-profile=srgb",
108
+ "--window-size=1600,1200",
109
+ "about:blank",
110
+ ],
111
+ { stdio: ["ignore", "ignore", "pipe"] },
112
+ );
113
+
114
+ let buf = "";
115
+ const wsUrl = await new Promise((resolveWs, reject) => {
116
+ const t = setTimeout(() => reject(new Error("Chrome did not start")), 20000);
117
+ proc.stderr.on("data", (d) => {
118
+ buf += d.toString();
119
+ const m = buf.match(/DevTools listening on (ws:\/\/[^\s]+)/);
120
+ if (m) {
121
+ clearTimeout(t);
122
+ resolveWs(m[1]);
123
+ }
124
+ });
125
+ proc.on("exit", (code) => {
126
+ clearTimeout(t);
127
+ reject(new Error(`Chrome exited ${code}`));
128
+ });
129
+ });
130
+
131
+ const ws = new WebSocket(wsUrl);
132
+ await new Promise((res, rej) => {
133
+ ws.onopen = res;
134
+ ws.onerror = () => rej(new Error("CDP socket failed"));
135
+ });
136
+ let nextId = 1;
137
+ const pending = new Map();
138
+ ws.onmessage = (ev) => {
139
+ const msg = JSON.parse(typeof ev.data === "string" ? ev.data : Buffer.from(ev.data).toString());
140
+ if (msg.id && pending.has(msg.id)) {
141
+ const { resolve: ok, reject: bad } = pending.get(msg.id);
142
+ pending.delete(msg.id);
143
+ if (msg.error) bad(new Error(msg.error.message));
144
+ else ok(msg.result);
145
+ }
146
+ };
147
+ const send = (method, params = {}, sessionId, timeoutMs = 30000) => {
148
+ const id = nextId++;
149
+ return new Promise((resolveSend, reject) => {
150
+ const timer = setTimeout(() => {
151
+ pending.delete(id);
152
+ reject(new Error(`CDP timeout: ${method}`));
153
+ }, timeoutMs);
154
+ pending.set(id, {
155
+ resolve: (v) => {
156
+ clearTimeout(timer);
157
+ resolveSend(v);
158
+ },
159
+ reject: (e) => {
160
+ clearTimeout(timer);
161
+ reject(e);
162
+ },
163
+ });
164
+ ws.send(JSON.stringify(sessionId ? { id, method, params, sessionId } : { id, method, params }));
165
+ });
166
+ };
167
+
168
+ const { targetId } = await send("Target.createTarget", { url: "about:blank" });
169
+ const { sessionId } = await send("Target.attachToTarget", { targetId, flatten: true });
170
+ const page = (method, params, timeoutMs) => send(method, params, sessionId, timeoutMs);
171
+
172
+ await page("Page.enable");
173
+ await page("Runtime.enable");
174
+ await page("Emulation.setDeviceMetricsOverride", {
175
+ width: 1600,
176
+ height: 1200,
177
+ deviceScaleFactor: 1,
178
+ mobile: false,
179
+ });
180
+
181
+ mkdirSync(outDir, { recursive: true });
182
+ const sheets = [];
183
+ for (let i = 0; i < lines.length; i += perSheet) {
184
+ sheets.push(lines.slice(i, i + perSheet));
185
+ }
186
+
187
+ const esc = (s) =>
188
+ String(s)
189
+ .replace(/&/g, "&amp;")
190
+ .replace(/</g, "&lt;")
191
+ .replace(/>/g, "&gt;")
192
+ .replace(/"/g, "&quot;");
193
+
194
+ for (let s = 0; s < sheets.length; s++) {
195
+ const cells = sheets[s]
196
+ .map(
197
+ (r) =>
198
+ `<figure><img src="${esc(r.url)}" loading="eager"><figcaption>${esc(r.label)}</figcaption></figure>`,
199
+ )
200
+ .join("\n");
201
+ const html = `<!doctype html><meta charset=utf-8>
202
+ <style>
203
+ body { margin: 16px; background: #1a1a1a; color: #eee; font: 11px/1.2 system-ui, sans-serif; }
204
+ .grid { display: grid; grid-template-columns: repeat(6, 1fr); gap: 10px; }
205
+ figure { margin: 0; background: #2a2a2a; border-radius: 4px; overflow: hidden; }
206
+ img { display: block; width: 100%; height: 140px; object-fit: cover; background: #111; }
207
+ figcaption { padding: 6px 8px; word-break: break-word; max-height: 2.4em; overflow: hidden; }
208
+ </style>
209
+ <div class="grid">${cells}</div>
210
+ <script>
211
+ Promise.all([...document.images].map((img) => img.decode().catch(() => {}))).then(() => {
212
+ document.title = "ready";
213
+ });
214
+ </script>`;
215
+ const htmlPath = join(dir, `sheet-${s + 1}.html`);
216
+ writeFileSync(htmlPath, html);
217
+ await page("Page.navigate", { url: `file://${htmlPath}` }, 30000);
218
+ await sleep(500);
219
+ for (let i = 0; i < 60; i++) {
220
+ const title = (
221
+ await page("Runtime.evaluate", { expression: "document.title", returnByValue: true })
222
+ ).result.value;
223
+ if (title === "ready") break;
224
+ await sleep(150);
225
+ }
226
+ await sleep(400);
227
+ const metrics = await page("Page.getLayoutMetrics");
228
+ const size = metrics.cssContentSize || metrics.contentSize;
229
+ const width = Math.max(1, Math.ceil(size.width || 1600));
230
+ const height = Math.max(1, Math.min(Math.ceil(size.height || 1200), 8000));
231
+ const { data } = await page(
232
+ "Page.captureScreenshot",
233
+ {
234
+ format: "jpeg",
235
+ quality: 80,
236
+ captureBeyondViewport: true,
237
+ clip: { x: 0, y: 0, width, height, scale: 1 },
238
+ },
239
+ 60000,
240
+ );
241
+ const outPath = join(outDir, `sheet-${String(s + 1).padStart(2, "0")}.jpg`);
242
+ writeFileSync(outPath, Buffer.from(data, "base64"));
243
+ console.log(outPath);
244
+ }
245
+
246
+ drop();
247
+ process.exit(0);
@@ -0,0 +1,27 @@
1
+ #!/usr/bin/env node
2
+ // WCAG 2.x contrast for colour pairs.
3
+ // node contrast.mjs "#2c2824 on #f6f1e7" "#b0563a on #f6f1e7:mark"
4
+ // Suffix :large or :mark checks against 3:1 instead of 4.5:1.
5
+ const lum = (hex) => {
6
+ const [r, g, b] = [1, 3, 5]
7
+ .map((i) => parseInt(hex.slice(i, i + 2), 16) / 255)
8
+ .map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
9
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
10
+ };
11
+ let failed = false;
12
+ for (const arg of process.argv.slice(2)) {
13
+ const m = arg.match(/^(#[0-9a-f]{6})\s+on\s+(#[0-9a-f]{6})(?::(large|mark))?$/i);
14
+ if (!m) {
15
+ console.error(`skip: ${arg}`);
16
+ continue;
17
+ }
18
+ const [a, b] = [lum(m[1]), lum(m[2])];
19
+ const ratio = (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
20
+ const need = m[3] ? 3 : 4.5;
21
+ const verdict = ratio >= 7 && !m[3] ? "AAA" : ratio >= need ? "AA" : "FAIL";
22
+ if (verdict === "FAIL") failed = true;
23
+ console.log(
24
+ `${m[1]} on ${m[2]} ${ratio.toFixed(2)}:1 ${verdict}${m[3] ? ` (${m[3]}, needs 3:1)` : ""}`,
25
+ );
26
+ }
27
+ process.exit(failed ? 1 : 0);