@jonandev/longbeard 0.11.1 → 0.12.0
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.
- package/AGENTS.md +3 -4
- package/CHANGELOG.md +72 -0
- package/README.md +63 -43
- package/beard.json +113 -26
- package/bin/long-beard.js +172 -36
- package/package.json +1 -1
- package/skills/design/SKILL.md +51 -122
- package/skills/design-brief/SKILL.md +146 -0
- package/skills/design-brief/references/graphic.md +59 -0
- package/skills/design-check/SKILL.md +27 -11
- package/skills/design-check/references/design-rules.md +21 -7
- package/skills/design-check/scripts/capture.mjs +121 -37
- package/skills/design-check/scripts/contrast.mjs +23 -9
- package/skills/design-check/scripts/rules.mjs +613 -0
- package/skills/design-check/scripts/screen-contrast.mjs +428 -0
- package/skills/design-check/scripts/tokens.mjs +346 -0
- package/skills/design-content/SKILL.md +118 -0
- package/skills/design-content/scripts/contact-sheet.mjs +259 -0
- package/skills/design-content/scripts/pictures.mjs +197 -0
- package/skills/design-direction/SKILL.md +117 -145
- package/skills/design-direction/references/controls.md +58 -0
- package/skills/{design → design-direction}/references/design-rules.md +21 -7
- package/skills/design-direction/references/five-second.md +47 -0
- package/skills/design-direction/references/full-build.md +19 -0
- package/skills/design-direction/references/graphic.md +35 -0
- package/skills/design-direction/references/grid.md +114 -0
- package/skills/design-direction/references/library.md +75 -0
- package/skills/design-direction/references/screen-template.html +233 -0
- package/skills/design-direction/references/subject.md +33 -0
- package/skills/design-direction/scripts/capture.mjs +121 -37
- package/skills/design-direction/scripts/contact-sheet.mjs +18 -7
- package/skills/design-direction/scripts/fonts.mjs +276 -0
- package/skills/design-direction/scripts/layout-diff.mjs +118 -0
- package/skills/design-direction/scripts/measure.mjs +1728 -0
- package/skills/design-direction/scripts/moodboard.mjs +123 -32
- package/skills/design-direction/scripts/picture-cast.mjs +270 -0
- package/skills/design-direction/scripts/pictures.mjs +197 -0
- package/skills/design-direction/scripts/screen-contrast.mjs +428 -0
- package/skills/design-direction/scripts/sheet.mjs +67 -0
- package/skills/design-direction/scripts/subject-colours.mjs +410 -0
- package/skills/design-families/SKILL.md +138 -0
- package/skills/design-families/scripts/contact-sheet.mjs +259 -0
- package/skills/design-families/scripts/families.mjs +606 -0
- package/skills/design-families/scripts/measure.mjs +1728 -0
- package/skills/design-families/scripts/moodboard.mjs +467 -0
- package/skills/design-families/scripts/tag.mjs +289 -0
- package/skills/design-figma/SKILL.md +69 -0
- package/skills/design-figma/references/graphic.md +26 -0
- package/skills/design-identity/SKILL.md +134 -0
- package/skills/design-identity/references/graphic.md +8 -0
- package/skills/design-identity/references/identity-board.html +140 -0
- package/skills/{design → design-identity}/scripts/capture.mjs +121 -37
- package/skills/design-identity/scripts/colours.mjs +213 -0
- package/skills/design-identity/scripts/contrast.mjs +41 -0
- package/skills/design-identity/scripts/fonts.mjs +276 -0
- package/skills/design-identity/scripts/measure.mjs +1728 -0
- package/skills/design-identity/scripts/sheet.mjs +67 -0
- package/skills/design-identity/scripts/subject-colours.mjs +410 -0
- package/skills/design-moodboard/SKILL.md +184 -0
- package/skills/design-moodboard/references/graphic.md +25 -0
- package/skills/{design-direction → design-moodboard}/references/sources.md +17 -11
- package/skills/design-moodboard/scripts/capture.mjs +893 -0
- package/skills/design-moodboard/scripts/contact-sheet.mjs +259 -0
- package/skills/design-moodboard/scripts/crops.mjs +256 -0
- package/skills/design-moodboard/scripts/dribbble-cards.mjs +418 -0
- package/skills/design-moodboard/scripts/families.mjs +606 -0
- package/skills/design-moodboard/scripts/group.mjs +221 -0
- package/skills/design-moodboard/scripts/measure.mjs +1728 -0
- package/skills/design-moodboard/scripts/moodboard.mjs +467 -0
- package/skills/{design-direction → design-moodboard}/scripts/picker.mjs +121 -20
- package/skills/design-moodboard/scripts/pictures.mjs +197 -0
- package/skills/design-moodboard/scripts/tag.mjs +289 -0
- package/skills/design-prototype/SKILL.md +149 -0
- package/skills/design-prototype/references/design-md-template.md +82 -0
- package/skills/design-prototype/references/design-rules.md +203 -0
- package/skills/design-prototype/references/five-second.md +47 -0
- package/skills/design-prototype/references/graphic.md +27 -0
- package/skills/design-prototype/scripts/capture.mjs +893 -0
- package/skills/design-prototype/scripts/contrast.mjs +41 -0
- package/skills/design-prototype/scripts/links.mjs +308 -0
- package/skills/design-prototype/scripts/pictures.mjs +197 -0
- package/skills/design-prototype/scripts/rules.mjs +613 -0
- package/skills/design-prototype/scripts/screen-contrast.mjs +428 -0
- package/skills/design-prototype/scripts/sheet.mjs +67 -0
- package/skills/design-prototype/scripts/tokens.mjs +346 -0
- package/skills/design-wordmark/SKILL.md +65 -0
- package/skills/design-wordmark/scripts/capture.mjs +893 -0
- package/skills/design-wordmark/scripts/sheet.mjs +67 -0
- package/skills/idea/SKILL.md +13 -7
- package/skills/idea/references/graphic.md +64 -0
- package/skills/design/references/design-md-template.md +0 -58
- package/skills/design/scripts/contrast.mjs +0 -27
- package/skills/design-direction/scripts/dribbble-cards.mjs +0 -356
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Contrast on the rendered screen, not on swatches. A colour pair can pass on
|
|
3
|
+
// its swatch and fail on the screen: a pale name that reads on the ground and
|
|
4
|
+
// runs off onto a photograph. This reads every piece of text where it sits.
|
|
5
|
+
// Node 22+, an installed Chrome, no dependencies.
|
|
6
|
+
//
|
|
7
|
+
// node screen-contrast.mjs "file://$PWD/.longbeard/design/direction/prototype/grid.html?n=3" --wait-title ready
|
|
8
|
+
//
|
|
9
|
+
// How: the page is opened at --size (1440x900), scrolled once from top to
|
|
10
|
+
// bottom so what appears on scroll is there, and measured at its full height
|
|
11
|
+
// (up to --max-height, 10000). Every visible text is found with its boxes, its
|
|
12
|
+
// colour and its size. Then all text is made transparent and the page is shot,
|
|
13
|
+
// so what is under each box is the real background: a ground, a gradient, a
|
|
14
|
+
// photograph. Every pixel under each box is compared with the text's colour.
|
|
15
|
+
// A text fails when its 5th-percentile contrast is under the threshold (4.5:1,
|
|
16
|
+
// or 3:1 for large text: 24px, or 18.66px bold; 7:1 and 4.5:1 at --level AAA),
|
|
17
|
+
// so one stray pixel is not the verdict. The worst pixel is reported too.
|
|
18
|
+
//
|
|
19
|
+
// A text colour can be written in any notation (rgb, hsl, oklch, lab,
|
|
20
|
+
// color(display-p3 ...)): the page resolves it to the sRGB it is drawn as. A
|
|
21
|
+
// text whose colour cannot be read, or whose fill is a picture or gradient
|
|
22
|
+
// clipped to the letters, is not measured. It is listed as "not read", and is
|
|
23
|
+
// neither a pass nor a fail.
|
|
24
|
+
//
|
|
25
|
+
// Prints one line per failing text: the text, its box, its colour, the
|
|
26
|
+
// background where it is worst, the contrast (5th percentile and worst), and
|
|
27
|
+
// the threshold. Then one "not read" line per text it could not measure. The
|
|
28
|
+
// last line, on stderr, counts the texts and says how far down the page it looked.
|
|
29
|
+
// --size 1440x900, --wait-title ready (wait for the page to set its title),
|
|
30
|
+
// --level AA|AAA, --min 4.5, --large 3 (these two win over --level),
|
|
31
|
+
// --max-height 10000 (the most of the page, in px, to look at),
|
|
32
|
+
// --timeout 60 (seconds each browser call may take), --json
|
|
33
|
+
//
|
|
34
|
+
// Exit 0 when no text fails, 1 when a text fails, 2 for a bad command line,
|
|
35
|
+
// 3 when it could not run (no Chrome, the page would not open, a browser call
|
|
36
|
+
// timed out). Chrome is closed and its profile removed on every exit, and on
|
|
37
|
+
// SIGINT and SIGTERM.
|
|
38
|
+
import { spawn } from "node:child_process";
|
|
39
|
+
import { existsSync, mkdtempSync, rmSync } from "node:fs";
|
|
40
|
+
import { tmpdir } from "node:os";
|
|
41
|
+
import { join } from "node:path";
|
|
42
|
+
if (typeof WebSocket === "undefined") { console.error("Node 22+ is required."); process.exit(1); }
|
|
43
|
+
|
|
44
|
+
const FAILED = 1, USAGE = 2, COULD_NOT_RUN = 3;
|
|
45
|
+
const args = process.argv.slice(2);
|
|
46
|
+
const flag = (name, def = "") => {
|
|
47
|
+
const i = args.indexOf(`--${name}`);
|
|
48
|
+
return i === -1 ? def : (args.splice(i, 2)[1] ?? "");
|
|
49
|
+
};
|
|
50
|
+
const has = (name) => {
|
|
51
|
+
const i = args.indexOf(`--${name}`);
|
|
52
|
+
return i === -1 ? false : (args.splice(i, 1), true);
|
|
53
|
+
};
|
|
54
|
+
const sizeArg = flag("size", "1440x900");
|
|
55
|
+
const waitTitle = flag("wait-title");
|
|
56
|
+
const level = flag("level", "AA").toUpperCase();
|
|
57
|
+
const min = Number(flag("min", level === "AAA" ? "7" : "4.5"));
|
|
58
|
+
const large = Number(flag("large", level === "AAA" ? "4.5" : "3"));
|
|
59
|
+
const maxHeight = Number(flag("max-height", "10000"));
|
|
60
|
+
const limit = Number(flag("timeout", "60"));
|
|
61
|
+
const json = has("json");
|
|
62
|
+
const [url] = args;
|
|
63
|
+
const [W, H] = sizeArg.split("x").map(Number);
|
|
64
|
+
if (!url || args.length !== 1 || !/^(https?|file):/.test(url) || !(W > 0 && H > 0) || !(min > 1) || !(large > 1) || !(level === "AA" || level === "AAA") || !(maxHeight >= H) || !(limit > 0)) {
|
|
65
|
+
console.error('usage: node screen-contrast.mjs "<file:// or https:// url>" [--size 1440x900] [--wait-title ready] [--level AA|AAA] [--min 4.5] [--large 3] [--max-height 10000] [--timeout 60] [--json]');
|
|
66
|
+
process.exit(USAGE);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const fail = (text, code = COULD_NOT_RUN) => {
|
|
70
|
+
console.error(`screen-contrast: ${text}`);
|
|
71
|
+
process.exit(code);
|
|
72
|
+
};
|
|
73
|
+
function findChrome() {
|
|
74
|
+
const env = process.env.CHROME_PATH;
|
|
75
|
+
// CHROME_PATH=none: run as if no browser were installed (a quick test run).
|
|
76
|
+
if (env === "none") return null;
|
|
77
|
+
if (env && existsSync(env)) return env;
|
|
78
|
+
const home = process.env.HOME || process.env.USERPROFILE || "";
|
|
79
|
+
const pf = process.env.PROGRAMFILES || "C:\\Program Files";
|
|
80
|
+
return [
|
|
81
|
+
join(pf, "Google/Chrome/Application/chrome.exe"),
|
|
82
|
+
join(process.env.LOCALAPPDATA || "", "Google/Chrome/Application/chrome.exe"),
|
|
83
|
+
join(pf, "Microsoft/Edge/Application/msedge.exe"),
|
|
84
|
+
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
85
|
+
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
|
86
|
+
join(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
|
|
87
|
+
"/usr/bin/google-chrome",
|
|
88
|
+
"/usr/bin/google-chrome-stable",
|
|
89
|
+
"/usr/bin/chromium",
|
|
90
|
+
"/usr/bin/chromium-browser",
|
|
91
|
+
].find((path) => path && existsSync(path));
|
|
92
|
+
}
|
|
93
|
+
const exe = findChrome();
|
|
94
|
+
if (!exe) fail("No Chrome/Edge/Chromium found. Install one or set CHROME_PATH.");
|
|
95
|
+
|
|
96
|
+
// Whatever ends the run, Chrome goes with it and so does its profile folder.
|
|
97
|
+
const dir = mkdtempSync(join(tmpdir(), "screen-contrast-"));
|
|
98
|
+
let proc = null;
|
|
99
|
+
let finished = false;
|
|
100
|
+
process.once("exit", () => {
|
|
101
|
+
try {
|
|
102
|
+
proc?.kill("SIGKILL");
|
|
103
|
+
} catch {}
|
|
104
|
+
// Chrome's helpers can still be writing as it goes: remove again until the folder is gone.
|
|
105
|
+
// Each try walks the folder afresh (rmSync's own retries only retry the last rmdir, and wait 21 s for nothing).
|
|
106
|
+
for (let end = Date.now() + 5000; ; Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50)) {
|
|
107
|
+
try {
|
|
108
|
+
rmSync(dir, { recursive: true, force: true });
|
|
109
|
+
break;
|
|
110
|
+
} catch {
|
|
111
|
+
if (Date.now() > end) break;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => fail(`stopped by ${signal}`));
|
|
116
|
+
process.on("unhandledRejection", (e) => fail(e?.message || String(e)));
|
|
117
|
+
|
|
118
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
119
|
+
// Run a step until it says yes or the time is up; the page may be slow, never stuck.
|
|
120
|
+
const until = async (ms, step) => {
|
|
121
|
+
for (const end = Date.now() + ms; Date.now() < end; await sleep(200)) if (await step().catch(() => false)) return true;
|
|
122
|
+
return false;
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
async function main() {
|
|
126
|
+
proc = spawn(exe, ["--headless=new", "--remote-debugging-port=0", `--user-data-dir=${dir}`, "--no-first-run", "--force-color-profile=srgb", "--hide-scrollbars", "--allow-file-access-from-files", "about:blank"], { stdio: ["ignore", "ignore", "pipe"] });
|
|
127
|
+
proc.on("exit", () => finished || fail("Chrome exited before the check was done"));
|
|
128
|
+
let buf = "";
|
|
129
|
+
const wsUrl = await new Promise((done, no) => {
|
|
130
|
+
const t = setTimeout(() => no(new Error("Chrome did not start")), 20000);
|
|
131
|
+
proc.stderr.on("data", (d) => {
|
|
132
|
+
const m = (buf += d).match(/DevTools listening on (ws:\/\/\S+)/);
|
|
133
|
+
if (m) done(m[1], clearTimeout(t));
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
const ws = new WebSocket(wsUrl);
|
|
137
|
+
await new Promise((done, no) => {
|
|
138
|
+
const t = setTimeout(() => no(new Error("Chrome did not accept the connection")), 20000);
|
|
139
|
+
ws.onopen = () => done(clearTimeout(t));
|
|
140
|
+
ws.onerror = () => no(new Error("Chrome did not accept the connection"));
|
|
141
|
+
});
|
|
142
|
+
ws.onclose = () => finished || fail("Chrome closed the connection");
|
|
143
|
+
let nextId = 0;
|
|
144
|
+
const pending = new Map();
|
|
145
|
+
ws.onmessage = (ev) => {
|
|
146
|
+
const msg = JSON.parse(String(ev.data));
|
|
147
|
+
if (pending.has(msg.id)) pending.get(msg.id)(msg), pending.delete(msg.id);
|
|
148
|
+
};
|
|
149
|
+
// Every call has a time limit: a page that hangs ends the run, it does not hang it.
|
|
150
|
+
const send = (method, params = {}, sessionId) =>
|
|
151
|
+
new Promise((done, no) => {
|
|
152
|
+
const id = ++nextId;
|
|
153
|
+
const timer = setTimeout(() => (pending.delete(id), no(new Error(`${method} did not answer within ${limit} s`))), limit * 1000);
|
|
154
|
+
pending.set(id, (msg) => done((clearTimeout(timer), msg)));
|
|
155
|
+
ws.send(JSON.stringify({ id, method, params, sessionId }));
|
|
156
|
+
});
|
|
157
|
+
const { result: target } = await send("Target.createTarget", { url: "about:blank" });
|
|
158
|
+
const { result: att } = await send("Target.attachToTarget", { targetId: target.targetId, flatten: true });
|
|
159
|
+
const call = (method, params) => send(method, params, att.sessionId);
|
|
160
|
+
const evaluate = async (expression) => {
|
|
161
|
+
const r = await call("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });
|
|
162
|
+
if (r.result?.exceptionDetails) throw new Error(r.result.exceptionDetails.exception?.description || "the page threw");
|
|
163
|
+
return r.result?.result?.value;
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
await call("Emulation.setDeviceMetricsOverride", { width: W, height: H, deviceScaleFactor: 1, mobile: W < 768 });
|
|
167
|
+
const nav = await call("Page.navigate", { url });
|
|
168
|
+
if (nav.result?.errorText) fail(`could not open ${url}: ${nav.result.errorText}`);
|
|
169
|
+
if (waitTitle) {
|
|
170
|
+
if (!(await until(20000, async () => (await evaluate("document.title")) === waitTitle))) fail(`the page did not set its title to "${waitTitle}" within 20 s`);
|
|
171
|
+
} else {
|
|
172
|
+
await until(20000, async () => (await evaluate("document.readyState")) === "complete");
|
|
173
|
+
await sleep(500);
|
|
174
|
+
}
|
|
175
|
+
await evaluate("document.fonts ? document.fonts.ready.then(() => true) : true").catch(() => true);
|
|
176
|
+
|
|
177
|
+
// Scroll down the page once, so what shows itself on scroll is showing, then back to the top.
|
|
178
|
+
const total = await evaluate("Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0)");
|
|
179
|
+
const looked = Math.min(total, maxHeight);
|
|
180
|
+
for (let y = H; y < looked; y += H) {
|
|
181
|
+
await evaluate(`window.scrollTo(0, ${y})`);
|
|
182
|
+
await sleep(120);
|
|
183
|
+
}
|
|
184
|
+
await evaluate("window.scrollTo(0, 0)");
|
|
185
|
+
await sleep(300);
|
|
186
|
+
|
|
187
|
+
// Every visible text: its element, its boxes down the page, its colour and size.
|
|
188
|
+
const texts = await evaluate(`(() => {
|
|
189
|
+
const W = ${W}, H = ${looked};
|
|
190
|
+
// Any notation Chrome knows, as the sRGB it is drawn as: [r, g, b, alpha], or null when it cannot be read.
|
|
191
|
+
// A colour the canvas will not take leaves its fill as it was, so two different starts tell the two apart.
|
|
192
|
+
const cv = Object.assign(document.createElement("canvas"), { width: 1, height: 1 });
|
|
193
|
+
const cx = cv.getContext("2d", { willReadFrequently: true });
|
|
194
|
+
const over = (css, ground) => {
|
|
195
|
+
cx.clearRect(0, 0, 1, 1);
|
|
196
|
+
cx.fillStyle = ground;
|
|
197
|
+
cx.fillRect(0, 0, 1, 1);
|
|
198
|
+
cx.fillStyle = css;
|
|
199
|
+
cx.fillRect(0, 0, 1, 1);
|
|
200
|
+
return cx.getImageData(0, 0, 1, 1).data;
|
|
201
|
+
};
|
|
202
|
+
const parse = (css) => {
|
|
203
|
+
if (!css) return null;
|
|
204
|
+
cx.fillStyle = "#010203";
|
|
205
|
+
cx.fillStyle = css;
|
|
206
|
+
const a = cx.fillStyle;
|
|
207
|
+
cx.fillStyle = "#fdfcfb";
|
|
208
|
+
cx.fillStyle = css;
|
|
209
|
+
if (a !== cx.fillStyle) return null;
|
|
210
|
+
const dark = over(css, "#000000"), light = over(css, "#ffffff");
|
|
211
|
+
const alpha = 1 - (light[0] - dark[0] + light[1] - dark[1] + light[2] - dark[2]) / 765;
|
|
212
|
+
if (alpha < 0.004) return [0, 0, 0, 0];
|
|
213
|
+
return [0, 1, 2].map((i) => Math.min(255, Math.round(dark[i] / alpha))).concat(Math.min(1, Math.round(alpha * 255) / 255));
|
|
214
|
+
};
|
|
215
|
+
const seen = (el) => {
|
|
216
|
+
for (let up = el; up && up.nodeType === 1; up = up.parentElement) {
|
|
217
|
+
const s = getComputedStyle(up);
|
|
218
|
+
if (s.display === "none" || s.visibility === "hidden" || Number(s.opacity) === 0) return false;
|
|
219
|
+
}
|
|
220
|
+
return true;
|
|
221
|
+
};
|
|
222
|
+
// A picture or gradient clipped to the letters is the text's fill; its pixels are not read here.
|
|
223
|
+
const clipped = (el) => {
|
|
224
|
+
for (let up = el; up && up.nodeType === 1; up = up.parentElement) {
|
|
225
|
+
const s = getComputedStyle(up);
|
|
226
|
+
if ((s.webkitBackgroundClip === "text" || s.backgroundClip === "text") && s.backgroundImage !== "none") return true;
|
|
227
|
+
}
|
|
228
|
+
return false;
|
|
229
|
+
};
|
|
230
|
+
// Is the text cut by a clip-path, a clip or an overflow on it or above it? Then only part of it shows.
|
|
231
|
+
const cut = (el, boxes) => {
|
|
232
|
+
for (let up = el; up && up.nodeType === 1; up = up.parentElement) {
|
|
233
|
+
const s = getComputedStyle(up);
|
|
234
|
+
if (s.clipPath && s.clipPath !== "none") return true;
|
|
235
|
+
if (s.clip && s.clip !== "auto" && /absolute|fixed/.test(s.position)) return true;
|
|
236
|
+
if (s.overflowX !== "visible" || s.overflowY !== "visible") {
|
|
237
|
+
const r = up.getBoundingClientRect();
|
|
238
|
+
const x = r.left + scrollX, y = r.top + scrollY;
|
|
239
|
+
if (boxes.some((b) => b.x < x - 0.5 || b.y < y - 0.5 || b.r > x + r.width + 0.5 || b.b > y + r.height + 0.5)) return true;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
return false;
|
|
243
|
+
};
|
|
244
|
+
const byEl = new Map();
|
|
245
|
+
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
|
|
246
|
+
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
|
247
|
+
if (!n.textContent.trim()) continue;
|
|
248
|
+
const el = n.parentElement;
|
|
249
|
+
if (!el || /^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE)$/.test(el.tagName) || !seen(el)) continue;
|
|
250
|
+
const range = document.createRange();
|
|
251
|
+
range.selectNodeContents(n);
|
|
252
|
+
const boxes = [...range.getClientRects()]
|
|
253
|
+
.map((r) => ({ x: Math.max(0, Math.floor(r.left + scrollX)), y: Math.max(0, Math.floor(r.top + scrollY)), r: Math.min(W, Math.ceil(r.right + scrollX)), b: Math.min(H, Math.ceil(r.bottom + scrollY)) }))
|
|
254
|
+
.filter((b) => b.r - b.x >= 1 && b.b - b.y >= 1);
|
|
255
|
+
if (!boxes.length) continue;
|
|
256
|
+
if (!byEl.has(el)) {
|
|
257
|
+
const s = getComputedStyle(el);
|
|
258
|
+
const size = parseFloat(s.fontSize), weight = parseInt(s.fontWeight, 10) || 400;
|
|
259
|
+
const own = parse(s.color), fill = parse(s.webkitTextFillColor || s.color), edge = parse(s.webkitTextStrokeColor);
|
|
260
|
+
const stroke = parseFloat(s.webkitTextStrokeWidth) || 0;
|
|
261
|
+
let colour = own, outline = false, unread = null;
|
|
262
|
+
if (!own || !fill) unread = "its colour is written in a way Chrome did not resolve: " + (!own ? s.color : s.webkitTextFillColor);
|
|
263
|
+
else {
|
|
264
|
+
// Text drawn only as an outline (a stroke, the fill clear): its stroke is what is read.
|
|
265
|
+
outline = stroke > 0 && fill[3] < 0.1;
|
|
266
|
+
if (outline) {
|
|
267
|
+
colour = edge;
|
|
268
|
+
if (!edge) unread = "its outline colour is written in a way Chrome did not resolve: " + s.webkitTextStrokeColor;
|
|
269
|
+
} else if (fill[3] < own[3]) colour = fill;
|
|
270
|
+
if (!unread && !outline && colour[3] < 0.1 && clipped(el)) unread = "its fill is a picture or gradient clipped to the letters";
|
|
271
|
+
}
|
|
272
|
+
// A faded container fades its text too: every opacity from the element up multiplies in.
|
|
273
|
+
if (colour) for (let up = el; up && up.nodeType === 1; up = up.parentElement) colour[3] *= Number(getComputedStyle(up).opacity);
|
|
274
|
+
byEl.set(el, { el: byEl.size, text: "", boxes: [], colour, unread, size, weight, outline, large: size >= 24 || (size >= 18.66 && weight >= 700) });
|
|
275
|
+
}
|
|
276
|
+
const t = byEl.get(el);
|
|
277
|
+
t.text += (t.text ? " " : "") + n.textContent.trim().replace(/\\s+/g, " ");
|
|
278
|
+
t.boxes.push(...boxes);
|
|
279
|
+
}
|
|
280
|
+
for (const [el, t] of byEl) t.cut = cut(el, t.boxes);
|
|
281
|
+
// Kept for the mask shots below, which show one element at a time.
|
|
282
|
+
window.__screenContrastEls = [...byEl.keys()];
|
|
283
|
+
return [...byEl.values()];
|
|
284
|
+
})()`);
|
|
285
|
+
|
|
286
|
+
// Hide every text, so the shot is what lies under it.
|
|
287
|
+
await evaluate(`(() => {
|
|
288
|
+
const s = document.createElement("style");
|
|
289
|
+
s.textContent = "* { color: transparent !important; text-shadow: none !important; -webkit-text-stroke: 0 !important; -webkit-text-fill-color: transparent !important; caret-color: transparent !important; text-decoration-color: transparent !important; }";
|
|
290
|
+
document.head.appendChild(s);
|
|
291
|
+
return new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(() => done(true))));
|
|
292
|
+
})()`);
|
|
293
|
+
const shot = await call("Page.captureScreenshot", { format: "png", captureBeyondViewport: looked > H, clip: { x: 0, y: 0, width: W, height: looked, scale: 1 } });
|
|
294
|
+
if (!shot.result?.data) fail(`could not take the screenshot${shot.error ? `: ${shot.error.message}` : ""}`);
|
|
295
|
+
|
|
296
|
+
const boxOf = (t) => {
|
|
297
|
+
const x = Math.min(...t.boxes.map((b) => b.x)), y = Math.min(...t.boxes.map((b) => b.y));
|
|
298
|
+
return [x, y, Math.max(...t.boxes.map((b) => b.r)) - x, Math.max(...t.boxes.map((b) => b.b)) - y];
|
|
299
|
+
};
|
|
300
|
+
// Where each text actually shows. A text cut by a clip-path, a clip or an overflow shows only
|
|
301
|
+
// inside its cut; and a copy of the same text in the same box drawn after it (a knockout label:
|
|
302
|
+
// the copy in another colour, clipped to a disc behind) hides it wherever that copy shows. For
|
|
303
|
+
// these texts one more shot is taken per element: everything hidden but that element, painted
|
|
304
|
+
// white on black, with its own and its ancestors' clips still applied. That shot is its mask.
|
|
305
|
+
const measured = texts.filter((t) => !t.unread);
|
|
306
|
+
const keyOf = (t) => t.text + "|" + boxOf(t).join(",");
|
|
307
|
+
for (const [i, t] of measured.entries()) {
|
|
308
|
+
const over = measured.slice(i + 1).filter((u) => keyOf(u) === keyOf(t));
|
|
309
|
+
t.covers = over.map((u) => u.el);
|
|
310
|
+
for (const u of over) u.cut = t.cut = true;
|
|
311
|
+
}
|
|
312
|
+
const masks = {};
|
|
313
|
+
const toMask = measured.filter((t) => t.cut);
|
|
314
|
+
if (toMask.length) {
|
|
315
|
+
await call("Emulation.setDefaultBackgroundColorOverride", { color: { r: 0, g: 0, b: 0, a: 1 } });
|
|
316
|
+
await evaluate(`(() => {
|
|
317
|
+
const s = document.createElement("style");
|
|
318
|
+
s.textContent = "html, body { background: none !important; } * { visibility: hidden !important; } [data-screen-contrast-mask] { visibility: visible !important; background: #fff !important; border-color: transparent !important; box-shadow: none !important; outline: none !important; filter: none !important; mix-blend-mode: normal !important; } [data-screen-contrast-mask] * { visibility: hidden !important; }";
|
|
319
|
+
document.head.appendChild(s);
|
|
320
|
+
return true;
|
|
321
|
+
})()`);
|
|
322
|
+
for (const t of toMask) {
|
|
323
|
+
const [x, y, w, h] = boxOf(t);
|
|
324
|
+
await evaluate(`(() => {
|
|
325
|
+
for (const e of document.querySelectorAll("[data-screen-contrast-mask]")) e.removeAttribute("data-screen-contrast-mask");
|
|
326
|
+
window.__screenContrastEls[${t.el}].setAttribute("data-screen-contrast-mask", "");
|
|
327
|
+
return new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(() => done(true))));
|
|
328
|
+
})()`);
|
|
329
|
+
const m = await call("Page.captureScreenshot", { format: "png", captureBeyondViewport: looked > H, clip: { x, y, width: w, height: h, scale: 1 } });
|
|
330
|
+
if (!m.result?.data) fail(`could not take a mask shot${m.error ? `: ${m.error.message}` : ""}`);
|
|
331
|
+
masks[t.el] = { x, y, w, h, data: m.result.data };
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// Read the shot's pixels in a blank page, and measure each text against what is under it.
|
|
336
|
+
await call("Page.navigate", { url: "about:blank" });
|
|
337
|
+
await sleep(200);
|
|
338
|
+
const results = await evaluate(`(async () => {
|
|
339
|
+
const texts = ${JSON.stringify(measured)};
|
|
340
|
+
const img = new Image();
|
|
341
|
+
img.src = "data:image/png;base64,${shot.result.data}";
|
|
342
|
+
await img.decode();
|
|
343
|
+
const c = Object.assign(document.createElement("canvas"), { width: img.width, height: img.height });
|
|
344
|
+
const g = c.getContext("2d", { willReadFrequently: true });
|
|
345
|
+
g.drawImage(img, 0, 0);
|
|
346
|
+
const d = g.getImageData(0, 0, img.width, img.height).data;
|
|
347
|
+
const lin = (v) => ((v /= 255) <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4);
|
|
348
|
+
const lum = (r, gg, b) => 0.2126 * lin(r) + 0.7152 * lin(gg) + 0.0722 * lin(b);
|
|
349
|
+
// Each mask as a test: does its element show at (x, y)? Shown means at least half its brightest
|
|
350
|
+
// pixel, so a faded ancestor still shows and a clip's soft edge counts on one side only.
|
|
351
|
+
const masks = ${JSON.stringify(masks)};
|
|
352
|
+
const shows = {};
|
|
353
|
+
for (const [el, m] of Object.entries(masks)) {
|
|
354
|
+
const mi = new Image();
|
|
355
|
+
mi.src = "data:image/png;base64," + m.data;
|
|
356
|
+
await mi.decode();
|
|
357
|
+
const mc = Object.assign(document.createElement("canvas"), { width: mi.width, height: mi.height });
|
|
358
|
+
const mg = mc.getContext("2d", { willReadFrequently: true });
|
|
359
|
+
mg.drawImage(mi, 0, 0);
|
|
360
|
+
const md = mg.getImageData(0, 0, mi.width, mi.height).data;
|
|
361
|
+
let peak = 0;
|
|
362
|
+
for (let i = 0; i < md.length; i += 4) peak = Math.max(peak, md[i], md[i + 1], md[i + 2]);
|
|
363
|
+
shows[el] = (x, y) => {
|
|
364
|
+
const mx = x - m.x, my = y - m.y;
|
|
365
|
+
if (peak < 8 || mx < 0 || my < 0 || mx >= mi.width || my >= mi.height) return false;
|
|
366
|
+
const i = (my * mi.width + mx) * 4;
|
|
367
|
+
return Math.max(md[i], md[i + 1], md[i + 2]) * 2 >= peak;
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
return texts.map((t) => {
|
|
371
|
+
const [tr, tg, tb, ta] = t.colour;
|
|
372
|
+
const area = t.boxes.reduce((s, b) => s + (b.r - b.x) * (b.b - b.y), 0);
|
|
373
|
+
const stride = Math.max(1, Math.floor(Math.sqrt(area / 20000)));
|
|
374
|
+
const ks = [];
|
|
375
|
+
let worst = Infinity, worstBg = null;
|
|
376
|
+
const own = shows[t.el], covers = (t.covers || []).map((c) => shows[c]);
|
|
377
|
+
for (const b of t.boxes) for (let y = b.y; y < b.b; y += stride) for (let x = b.x; x < b.r; x += stride) {
|
|
378
|
+
// Only where the text shows: inside its own cut, and not under a copy of it drawn on top.
|
|
379
|
+
if (own && !own(x, y)) continue;
|
|
380
|
+
if (covers.some((c) => c(x, y))) continue;
|
|
381
|
+
const i = (y * img.width + x) * 4;
|
|
382
|
+
const br = d[i], bg = d[i + 1], bb = d[i + 2];
|
|
383
|
+
// The text's alpha over the pixel under it.
|
|
384
|
+
const fr = tr * ta + br * (1 - ta), fg = tg * ta + bg * (1 - ta), fb = tb * ta + bb * (1 - ta);
|
|
385
|
+
const l1 = lum(fr, fg, fb), l2 = lum(br, bg, bb);
|
|
386
|
+
const k = (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
|
|
387
|
+
ks.push(k);
|
|
388
|
+
if (k < worst) (worst = k), (worstBg = [br, bg, bb]);
|
|
389
|
+
}
|
|
390
|
+
ks.sort((a, b) => a - b);
|
|
391
|
+
const p5 = ks.length ? ks[Math.floor(ks.length * 0.05)] : null;
|
|
392
|
+
return { ...t, p5, worst: ks.length ? worst : null, worstBg };
|
|
393
|
+
});
|
|
394
|
+
})()`);
|
|
395
|
+
finished = true;
|
|
396
|
+
ws.close();
|
|
397
|
+
|
|
398
|
+
const hex = (rgb) => `#${rgb.slice(0, 3).map((v) => Math.round(v).toString(16).padStart(2, "0")).join("")}`;
|
|
399
|
+
// Rounded down, so a ratio just under its threshold never prints as the threshold.
|
|
400
|
+
const r2 = (v) => (v == null ? null : Math.floor(v * 100) / 100);
|
|
401
|
+
const said = (t) => (t.text.length > 40 ? `${t.text.slice(0, 39)}…` : t.text);
|
|
402
|
+
const rows = results.map((t) => {
|
|
403
|
+
const need = t.large ? large : min;
|
|
404
|
+
return {
|
|
405
|
+
text: said(t),
|
|
406
|
+
box: boxOf(t),
|
|
407
|
+
colour: hex(t.colour) + (t.colour[3] < 1 ? ` at ${Math.round(t.colour[3] * 100)}%` : "") + (t.outline ? " (outline)" : ""),
|
|
408
|
+
size: t.size,
|
|
409
|
+
large: t.large,
|
|
410
|
+
background: t.worstBg ? hex(t.worstBg) : null,
|
|
411
|
+
p5: r2(t.p5),
|
|
412
|
+
worst: r2(t.worst),
|
|
413
|
+
need,
|
|
414
|
+
pass: t.p5 == null || t.p5 >= need,
|
|
415
|
+
};
|
|
416
|
+
});
|
|
417
|
+
const unread = texts.filter((t) => t.unread).map((t) => ({ text: said(t), box: boxOf(t), reason: t.unread }));
|
|
418
|
+
const failing = rows.filter((r) => !r.pass);
|
|
419
|
+
const reach = looked >= total ? `all ${total} px of the page` : `the top ${looked} of ${total} px; the rest is not checked (--max-height)`;
|
|
420
|
+
if (json) console.log(JSON.stringify({ texts: rows, failing: failing.length, unread, page: { height: total, looked, whole: looked >= total } }, null, 1));
|
|
421
|
+
else {
|
|
422
|
+
for (const r of failing) console.log([`"${r.text}"`, `box ${r.box.join(",")}`, `text ${r.colour}`, `worst on ${r.background}`, `${r.p5}:1 (worst ${r.worst}:1)`, `needs ${r.need}:1${r.large ? " (large)" : ""}`].join("\t"));
|
|
423
|
+
for (const u of unread) console.log([`not read: "${u.text}"`, `box ${u.box.join(",")}`, u.reason].join("\t"));
|
|
424
|
+
}
|
|
425
|
+
console.error(`screen-contrast: ${rows.length} texts, ${failing.length} under, ${unread.length} not read; looked at ${reach}`);
|
|
426
|
+
process.exit(failing.length ? FAILED : 0);
|
|
427
|
+
}
|
|
428
|
+
main().catch((e) => fail(e.message));
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Lay screenshots out as one numbered sheet, so a round of first screens can
|
|
3
|
+
// be seen and picked from together. It writes an HTML page; capture.mjs turns
|
|
4
|
+
// that into the picture to show. No dependencies.
|
|
5
|
+
//
|
|
6
|
+
// node sheet.mjs .longbeard/design/direction/grid/sheet.html .longbeard/design/direction/grid/1.png .longbeard/design/direction/grid/2.png …
|
|
7
|
+
// node sheet.mjs .longbeard/design/direction/grid/vary.html --cols 5 .longbeard/design/direction/grid/v*.png
|
|
8
|
+
// node capture.mjs "file://$PWD/.longbeard/design/direction/grid/sheet.html" --out .longbeard/design/direction/grid/sheet.png
|
|
9
|
+
// node sheet.mjs <out.html> --rough 1,2,4 --note "built without fresh agents: weaker" <shots…>
|
|
10
|
+
//
|
|
11
|
+
// --rough 1,2,4 (or none) labels those tiles "rough" and the rest "full", so a quick screen is never
|
|
12
|
+
// read as a finished one. --note prints a line under the sheet.
|
|
13
|
+
|
|
14
|
+
// Tiles are numbered in the order given, left to right, top to bottom, which
|
|
15
|
+
// is the recipe's number when the shots are passed in order.
|
|
16
|
+
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
17
|
+
import { dirname, relative, resolve } from "node:path";
|
|
18
|
+
|
|
19
|
+
const args = process.argv.slice(2);
|
|
20
|
+
const at = args.indexOf("--cols");
|
|
21
|
+
const cols = at === -1 ? 2 : Number(args.splice(at, 2)[1]);
|
|
22
|
+
const take = (name) => {
|
|
23
|
+
const i = args.indexOf(name);
|
|
24
|
+
return i === -1 ? null : (args.splice(i, 2)[1] ?? "");
|
|
25
|
+
};
|
|
26
|
+
const roughArg = take("--rough");
|
|
27
|
+
const note = take("--note");
|
|
28
|
+
const rough = new Set((roughArg ?? "").split(",").filter((n) => n && n !== "none").map(Number));
|
|
29
|
+
const [outArg, ...shots] = args;
|
|
30
|
+
if (!outArg || [...rough].some((n) => !Number.isInteger(n) || n < 1) || roughArg === "" || note === "" || !/\.html$/.test(outArg) || !shots.length || !Number.isInteger(cols) || cols < 1 || cols > 8) {
|
|
31
|
+
console.error('usage: node sheet.mjs <out.html> [--cols 2] [--rough 1,2|none] [--note "text"] <shot.png> …');
|
|
32
|
+
process.exit(2);
|
|
33
|
+
}
|
|
34
|
+
const out = resolve(outArg);
|
|
35
|
+
for (const shot of shots) {
|
|
36
|
+
if (!existsSync(resolve(shot))) {
|
|
37
|
+
console.error(`sheet: no file at ${shot}`);
|
|
38
|
+
process.exit(1);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const escape = (text) => text.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
|
42
|
+
// A local path in a src: each part encoded, so # ? % and spaces stay in the name.
|
|
43
|
+
const urlPath = (path) => path.split("/").map(encodeURIComponent).join("/");
|
|
44
|
+
const tiles = shots
|
|
45
|
+
.map((shot, i) => `<figure><img src="${escape(urlPath(relative(dirname(out), resolve(shot)).split("\\").join("/")))}" alt="Screen ${i + 1}"><figcaption>${i + 1}${roughArg === null ? "" : rough.has(i + 1) ? " · rough" : " · full"}</figcaption></figure>`)
|
|
46
|
+
.join("\n");
|
|
47
|
+
mkdirSync(dirname(out), { recursive: true });
|
|
48
|
+
writeFileSync(
|
|
49
|
+
out,
|
|
50
|
+
`<!doctype html>
|
|
51
|
+
<meta charset="utf-8">
|
|
52
|
+
<title>Sheet</title>
|
|
53
|
+
<style>
|
|
54
|
+
body { margin: 0; padding: 24px; background: #6f6f6f; font: 600 22px/1 system-ui, sans-serif; }
|
|
55
|
+
main { display: grid; grid-template-columns: repeat(${cols}, 720px); gap: 24px; width: max-content; }
|
|
56
|
+
figure { margin: 0; display: flex; flex-direction: column-reverse; gap: 8px; }
|
|
57
|
+
img { display: block; width: 720px; height: auto; }
|
|
58
|
+
/* The number sits above the screen, never on it: a corner of a screen is where its name or menu is. */
|
|
59
|
+
p { margin: 24px 0 0; max-width: 1200px; font-weight: 400; font-size: 20px; line-height: 1.4; color: #fff; }
|
|
60
|
+
figcaption { align-self: flex-start; min-width: 44px; padding: 8px 10px; text-align: center; background: #111; color: #fff; }
|
|
61
|
+
</style>
|
|
62
|
+
<main>
|
|
63
|
+
${tiles}
|
|
64
|
+
</main>
|
|
65
|
+
${note ? `<p>${escape(note)}</p>\n` : ""}`,
|
|
66
|
+
);
|
|
67
|
+
console.log(`${shots.length} screens, ${cols} across: ${outArg}`);
|