@jonandev/longbeard 0.11.2 → 0.12.1
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 +4 -5
- package/CHANGELOG.md +72 -0
- package/README.md +64 -43
- package/beard.json +124 -28
- package/bin/long-beard.js +171 -36
- package/package.json +1 -1
- package/skills/design/SKILL.md +51 -126
- 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 +115 -200
- 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 +21 -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/framework-skills/SKILL.md +71 -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
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
// Full-page capture. Unsticks fixed/sticky chrome first so Chrome does not
|
|
3
3
|
// repeat the same fold. Node 22+. Uses an installed Chrome/Edge/Chromium.
|
|
4
4
|
//
|
|
5
|
-
// node capture.mjs <url> --out design
|
|
6
|
-
// node capture.mjs <url> --out design
|
|
7
|
-
// node capture.mjs <url> --out design
|
|
8
|
-
// node capture.mjs <url> --out design
|
|
5
|
+
// node capture.mjs <url> --out .longbeard/design/moodboard/refs/name.jpg
|
|
6
|
+
// node capture.mjs <url> --out .longbeard/design/moodboard/refs/name.jpg --review /tmp/name-review.jpg
|
|
7
|
+
// node capture.mjs <url> --out .longbeard/design/moodboard/refs/name.jpg --clip x,y,w,h
|
|
8
|
+
// node capture.mjs <url> --out .longbeard/design/moodboard/refs/name.jpg --clip-selector "main"
|
|
9
9
|
// node capture.mjs <url> --out /tmp/mobile.png --width 390
|
|
10
10
|
// node capture.mjs http://localhost:3000/app --out /tmp/app.png --cookie "session=abc; theme=dark" --strict
|
|
11
11
|
//
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
// www) is named on stderr. With --strict that is exit 1, so a 0 means the
|
|
14
14
|
// shot is of the page asked for.
|
|
15
15
|
// node capture.mjs file:///abs/path/moodboard.html --out /tmp/moodboard.jpg
|
|
16
|
-
// node capture.mjs file:///abs/path/shot.jpg --out design
|
|
16
|
+
// node capture.mjs file:///abs/path/shot.jpg --out .longbeard/design/moodboard/refs/name.jpg --clip x,y,w,h
|
|
17
17
|
//
|
|
18
18
|
// Before the shot it waits out loaders: until no loader covers the screen and
|
|
19
19
|
// the screen is not one flat colour and the network is quiet, for at most --wait ms (15 s on the web,
|
|
@@ -27,19 +27,20 @@
|
|
|
27
27
|
// start as the page opens, so the loader and the intro are in them. With
|
|
28
28
|
// --scroll they start once it has loaded, and each frame scrolls half a
|
|
29
29
|
// screen by the wheel, so scroll-driven motion plays.
|
|
30
|
-
// node capture.mjs <url> --out design
|
|
31
|
-
// node capture.mjs <url> --out design
|
|
30
|
+
// node capture.mjs <url> --out .longbeard/design/moodboard/refs/name-intro --frames 12
|
|
31
|
+
// node capture.mjs <url> --out .longbeard/design/moodboard/refs/name-scroll --frames 12 --every 400 --scroll
|
|
32
32
|
//
|
|
33
33
|
// --click "css" clicks that element once the page has loaded, as a person
|
|
34
34
|
// would. Alone it keeps the screen after the click (an open menu). With
|
|
35
35
|
// --frames the first frame is before the click and the rest record what the
|
|
36
36
|
// click does (a menu opening, a page transition).
|
|
37
|
-
// node capture.mjs <url> --out design
|
|
38
|
-
// node capture.mjs <url> --out design
|
|
39
|
-
import { spawn
|
|
37
|
+
// node capture.mjs <url> --out .longbeard/design/moodboard/refs/name-menu.jpg --click "button[aria-label*=menu i]"
|
|
38
|
+
// node capture.mjs <url> --out .longbeard/design/moodboard/refs/name-menu-open --frames 10 --every 150 --click "header button"
|
|
39
|
+
import { spawn } from "node:child_process";
|
|
40
40
|
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
41
41
|
import { tmpdir } from "node:os";
|
|
42
|
-
import { dirname,
|
|
42
|
+
import { dirname, join, resolve } from "node:path";
|
|
43
|
+
import { fileURLToPath } from "node:url";
|
|
43
44
|
import { inflateSync } from "node:zlib";
|
|
44
45
|
|
|
45
46
|
const args = process.argv.slice(2);
|
|
@@ -47,6 +48,11 @@ const flag = (name, def) => {
|
|
|
47
48
|
const i = args.indexOf(`--${name}`);
|
|
48
49
|
if (i === -1) return def;
|
|
49
50
|
const v = args[i + 1];
|
|
51
|
+
// A flag that needs a value and has none is a usage error, not a plain shot.
|
|
52
|
+
if (v === undefined || /^--[a-z]/.test(v)) {
|
|
53
|
+
console.error(`--${name} needs a value`);
|
|
54
|
+
process.exit(2);
|
|
55
|
+
}
|
|
50
56
|
args.splice(i, 2);
|
|
51
57
|
return v;
|
|
52
58
|
};
|
|
@@ -73,7 +79,7 @@ const waitArg = flag("wait", "") || "";
|
|
|
73
79
|
const width = Math.round(Number(flag("width", "1440")));
|
|
74
80
|
if (!url || !/^(https?|file):\/\//.test(url) || !outArg) {
|
|
75
81
|
console.error(
|
|
76
|
-
'usage: node capture.mjs <https://url | file:///path> --out design
|
|
82
|
+
'usage: node capture.mjs <https://url | file:///path> --out .longbeard/design/moodboard/refs/name.jpg [--review /tmp/name-review.jpg] [--clip x,y,w,h | --clip-selector "css"] [--width 390] [--cookie "name=value; …"] [--strict] [--wait ms] [--click "css"] [--frames N [--every ms] [--scroll]]',
|
|
77
83
|
);
|
|
78
84
|
process.exit(2);
|
|
79
85
|
}
|
|
@@ -104,7 +110,8 @@ if ((frames || clickArg) && (reviewArg || clipArg || clipSelector)) {
|
|
|
104
110
|
process.exit(2);
|
|
105
111
|
}
|
|
106
112
|
// A local page has no loader worth waiting for, so a sparse screen costs little.
|
|
107
|
-
// A full page stops at 14000 px; our own files (a picker, a moodboard)
|
|
113
|
+
// A full page stops at 14000 px; our own files (a picker, a moodboard) run to 30000 px a part,
|
|
114
|
+
// and a longer one is kept in parts (see below).
|
|
108
115
|
const tallest = /^file:/.test(url) ? 30000 : 14000;
|
|
109
116
|
const local = /^file:/.test(url) || /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/.test(url);
|
|
110
117
|
const maxWait = waitArg ? Number(waitArg) : local ? 2000 : 15000;
|
|
@@ -119,23 +126,26 @@ if (clipArg && clipSelector) {
|
|
|
119
126
|
process.exit(2);
|
|
120
127
|
}
|
|
121
128
|
|
|
122
|
-
|
|
123
|
-
try {
|
|
124
|
-
return execSync("git rev-parse --show-toplevel", { encoding: "utf8" }).trim();
|
|
125
|
-
} catch {
|
|
126
|
-
return process.cwd();
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
|
|
129
|
+
// A relative path is relative to the folder the command runs in.
|
|
130
130
|
function resolveOut(path) {
|
|
131
|
-
|
|
132
|
-
if (isAbsolute(path)) return path;
|
|
133
|
-
return resolve(projectRoot(), path);
|
|
131
|
+
return path ? resolve(path) : "";
|
|
134
132
|
}
|
|
135
133
|
|
|
136
134
|
const out = resolveOut(outArg);
|
|
137
135
|
const reviewOut = resolveOut(reviewArg);
|
|
138
136
|
|
|
137
|
+
// A page that is not there would otherwise be a black shot that looks like a result.
|
|
138
|
+
if (/^file:/.test(url)) {
|
|
139
|
+
let file = "";
|
|
140
|
+
try {
|
|
141
|
+
file = fileURLToPath(url.replace(/[?#].*$/, ""));
|
|
142
|
+
} catch {}
|
|
143
|
+
if (!file || !existsSync(file)) {
|
|
144
|
+
console.error(`no such file: ${file || url}`);
|
|
145
|
+
process.exit(1);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
139
149
|
function parseClip(s) {
|
|
140
150
|
if (!s) return null;
|
|
141
151
|
const parts = s.split(",").map((n) => Number(n.trim()));
|
|
@@ -155,6 +165,8 @@ const clip = parseClip(clipArg);
|
|
|
155
165
|
|
|
156
166
|
function findChrome() {
|
|
157
167
|
const env = process.env.CHROME_PATH;
|
|
168
|
+
// CHROME_PATH=none: run as if no browser were installed (a quick test run).
|
|
169
|
+
if (env === "none") return null;
|
|
158
170
|
if (env && existsSync(env)) return env;
|
|
159
171
|
const home = process.env.HOME || process.env.USERPROFILE || "";
|
|
160
172
|
const local = process.env.LOCALAPPDATA || "";
|
|
@@ -200,6 +212,13 @@ const drop = () => {
|
|
|
200
212
|
} catch {}
|
|
201
213
|
};
|
|
202
214
|
process.once("exit", drop);
|
|
215
|
+
// An interrupt or a harness timeout must not leave Chrome or its profile behind.
|
|
216
|
+
for (const [sig, code] of [["SIGINT", 130], ["SIGTERM", 143]]) {
|
|
217
|
+
process.once(sig, () => {
|
|
218
|
+
drop();
|
|
219
|
+
process.exit(code);
|
|
220
|
+
});
|
|
221
|
+
}
|
|
203
222
|
|
|
204
223
|
proc = spawn(
|
|
205
224
|
exe,
|
|
@@ -218,6 +237,10 @@ proc = spawn(
|
|
|
218
237
|
],
|
|
219
238
|
{ stdio: ["ignore", "ignore", "pipe"] },
|
|
220
239
|
);
|
|
240
|
+
proc.on("error", (e) => {
|
|
241
|
+
console.error(`could not start ${exe}: ${e.message}`);
|
|
242
|
+
process.exit(1);
|
|
243
|
+
});
|
|
221
244
|
|
|
222
245
|
let buf = "";
|
|
223
246
|
const wsUrl = await new Promise((resolveWs, reject) => {
|
|
@@ -238,8 +261,15 @@ const wsUrl = await new Promise((resolveWs, reject) => {
|
|
|
238
261
|
|
|
239
262
|
const ws = new WebSocket(wsUrl);
|
|
240
263
|
await new Promise((res, rej) => {
|
|
241
|
-
|
|
242
|
-
ws.
|
|
264
|
+
const t = setTimeout(() => rej(new Error("CDP socket did not open")), 10000);
|
|
265
|
+
ws.onopen = () => {
|
|
266
|
+
clearTimeout(t);
|
|
267
|
+
res();
|
|
268
|
+
};
|
|
269
|
+
ws.onerror = () => {
|
|
270
|
+
clearTimeout(t);
|
|
271
|
+
rej(new Error("CDP socket failed"));
|
|
272
|
+
};
|
|
243
273
|
});
|
|
244
274
|
let nextId = 1;
|
|
245
275
|
const pending = new Map();
|
|
@@ -257,6 +287,10 @@ ws.onmessage = (ev) => {
|
|
|
257
287
|
inflight.delete(msg.params.requestId);
|
|
258
288
|
lastNetwork = Date.now();
|
|
259
289
|
}
|
|
290
|
+
// An alert, confirm or beforeunload prompt holds the page until it is answered.
|
|
291
|
+
if (msg.method === "Page.javascriptDialogOpening") {
|
|
292
|
+
send("Page.handleJavaScriptDialog", { accept: false }, msg.sessionId).catch(() => {});
|
|
293
|
+
}
|
|
260
294
|
if (msg.id && pending.has(msg.id)) {
|
|
261
295
|
const { resolve: ok, reject: bad } = pending.get(msg.id);
|
|
262
296
|
pending.delete(msg.id);
|
|
@@ -264,6 +298,10 @@ ws.onmessage = (ev) => {
|
|
|
264
298
|
else ok(msg.result);
|
|
265
299
|
}
|
|
266
300
|
};
|
|
301
|
+
// If Chrome goes away, every call waiting on it fails now, not at its time limit.
|
|
302
|
+
ws.onclose = () => {
|
|
303
|
+
for (const { reject: bad } of [...pending.values()]) bad(new Error("Chrome closed the connection"));
|
|
304
|
+
};
|
|
267
305
|
const send = (method, params = {}, sessionId, timeoutMs = 30000) => {
|
|
268
306
|
const id = nextId++;
|
|
269
307
|
return new Promise((resolveSend, reject) => {
|
|
@@ -455,18 +493,41 @@ async function settle() {
|
|
|
455
493
|
// Clicks a consent button, which can be any element, or else strips a short
|
|
456
494
|
// privacy notice. Rejecting comes first: a script has no use for tracking,
|
|
457
495
|
// and accepting can start scripts that redraw the page.
|
|
458
|
-
// A local page is a state someone set up on purpose, so it is left as it is
|
|
496
|
+
// A local page is a state someone set up on purpose, so it is left as it is, and
|
|
497
|
+
// so is a record of motion (--frames): nothing there is cleaned up.
|
|
459
498
|
const dismissConsent = () =>
|
|
460
499
|
local ? Promise.resolve(false) : evalValue(`(() => {
|
|
461
|
-
|
|
462
|
-
const
|
|
500
|
+
// The common consent tools first, by their own ids: reject, then accept.
|
|
501
|
+
const known = [
|
|
502
|
+
"#onetrust-reject-all-handler", "#CybotCookiebotDialogBodyButtonDecline", "#didomi-notice-disagree-button",
|
|
503
|
+
".cky-btn-reject", "#cmplz-deny, .cmplz-deny", "[data-cookiefirst-action=reject]", ".iubenda-cs-reject-btn",
|
|
504
|
+
"#onetrust-accept-btn-handler", "#CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll", "#didomi-notice-agree-button",
|
|
505
|
+
".cky-btn-accept", ".cmplz-accept", "[data-cookiefirst-action=accept]", ".iubenda-cs-accept-btn",
|
|
506
|
+
];
|
|
507
|
+
for (const sel of known) {
|
|
508
|
+
const el = document.querySelector(sel);
|
|
509
|
+
if (el && el.getClientRects().length) {
|
|
510
|
+
el.click();
|
|
511
|
+
return true;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
const accept = /^(accept( all)?( cookies)?|accept (and|&) (close|continue)|agree|i agree|ok|okay|got it|allow( all)?( cookies)?|i understand|acepto|aceptar( todas?| todo| cookies)?|aceptar y (cerrar|continuar)|onartu( guztiak)?|accepter( tout)?|tout accepter|j'accepte|alle akzeptieren|akzeptieren|accetta( tutti)?|accetto|aceitar( todos)?)$/i;
|
|
515
|
+
const reject = /^(reject( all)?( cookies)?|decline( all)?|deny|only (essential|necessary)( cookies)?|rechazar( todas?| todo| cookies)?|denegar|ukatu( guztiak)?|refuser( tout)?|tout refuser|continuer sans accepter|alle ablehnen|ablehnen|rifiuta( tutti)?|rejeitar( todos)?)$/i;
|
|
463
516
|
const clickable = [...document.querySelectorAll("button, [role=button], a, input[type=button], input[type=submit], [onclick], div, span")]
|
|
464
517
|
.filter((el) => el.childElementCount <= 2 && el.getClientRects().length);
|
|
465
|
-
// Only inside a notice about cookies or privacy
|
|
518
|
+
// Only inside something that looks like a notice about cookies or privacy: a
|
|
519
|
+
// dialog, a layer fixed or sticky over the page, or one named like a banner.
|
|
520
|
+
// Never the page itself, so a short page that mentions privacy is not a notice.
|
|
521
|
+
const about = /cookie|consent|privacy|gdpr|datenschutz|privacidad|consentimiento|confidentialit|privacit/i;
|
|
522
|
+
const named = /cookie|consent|gdpr|privacy|banner|notice|popup|modal|dialog/i;
|
|
466
523
|
const notice = (el) => {
|
|
467
|
-
for (let up = el, i = 0; up && i < 8; up = up.parentElement, i++) {
|
|
524
|
+
for (let up = el, i = 0; up && up !== document.body && up !== document.documentElement && i < 8; up = up.parentElement, i++) {
|
|
468
525
|
const t = up.innerText || "";
|
|
469
|
-
if (t.length
|
|
526
|
+
if (t.length >= 1500 || !about.test(t)) continue;
|
|
527
|
+
const pos = getComputedStyle(up).position;
|
|
528
|
+
const label = (typeof up.className === "string" ? up.className : "") + " " + up.id;
|
|
529
|
+
if (up.tagName === "DIALOG" || /^(dialog|alertdialog)$/.test(up.getAttribute("role") || "") ||
|
|
530
|
+
up.getAttribute("aria-modal") === "true" || pos === "fixed" || pos === "sticky" || named.test(label)) return true;
|
|
470
531
|
}
|
|
471
532
|
return false;
|
|
472
533
|
};
|
|
@@ -513,7 +574,14 @@ async function clickOn(selector) {
|
|
|
513
574
|
}
|
|
514
575
|
|
|
515
576
|
const navigateStarted = Date.now();
|
|
516
|
-
|
|
577
|
+
// A page that cannot be reached comes back as Chrome's own error page, which would be saved as if
|
|
578
|
+
// it were the site: say so and stop.
|
|
579
|
+
const nav = await page("Page.navigate", { url: target }, 40000);
|
|
580
|
+
if (nav?.errorText && nav.errorText !== "net::ERR_ABORTED") {
|
|
581
|
+
console.error(`could not reach ${target}: ${nav.errorText}`);
|
|
582
|
+
drop();
|
|
583
|
+
process.exit(1);
|
|
584
|
+
}
|
|
517
585
|
|
|
518
586
|
if (frames) {
|
|
519
587
|
// The frames are the record of motion, so nothing is paused, unstuck or cleaned up.
|
|
@@ -523,10 +591,6 @@ if (frames) {
|
|
|
523
591
|
if (scrollFrames || clickArg) {
|
|
524
592
|
const why = await settle();
|
|
525
593
|
if (why) console.error(`waited ${maxWait} ms: ${why}`);
|
|
526
|
-
if (await dismissConsent()) {
|
|
527
|
-
await sleep(800);
|
|
528
|
-
await settle();
|
|
529
|
-
}
|
|
530
594
|
await sleep(600);
|
|
531
595
|
t0 = Date.now();
|
|
532
596
|
}
|
|
@@ -745,6 +809,26 @@ mkdirSync(dirname(out), { recursive: true });
|
|
|
745
809
|
writeFileSync(out, Buffer.from(data, "base64"));
|
|
746
810
|
console.log(out);
|
|
747
811
|
|
|
812
|
+
// A local page longer than one shot (a families board of hundreds) is kept whole, in parts:
|
|
813
|
+
// <out>-2, <out>-3 … each up to the same height, so nothing below the first part is lost.
|
|
814
|
+
const realHeight = Math.ceil(size.height || height);
|
|
815
|
+
if (clipBox && (shotClip.height < clipBox.height || shotClip.width < clipBox.width)) {
|
|
816
|
+
console.error(`the clip reaches past the page (${fullWidth}x${realHeight} px): kept ${shotClip.width}x${shotClip.height} px of ${clipBox.width}x${clipBox.height}`);
|
|
817
|
+
} else if (!clipBox && !/^file:/.test(url) && realHeight > fullHeight) {
|
|
818
|
+
console.error(`the page is ${realHeight} px, over the ${tallest} px limit: kept the first ${fullHeight} px`);
|
|
819
|
+
}
|
|
820
|
+
if (!clipBox && /^file:/.test(url) && realHeight > fullHeight) {
|
|
821
|
+
const parts = Math.min(10, Math.ceil(realHeight / tallest));
|
|
822
|
+
for (let i = 1; i < parts; i++) {
|
|
823
|
+
const y = i * tallest;
|
|
824
|
+
const { data: part } = await page("Page.captureScreenshot", { format, ...(format === "png" ? {} : { quality: 70 }), captureBeyondViewport: true, clip: { x: 0, y, width: fullWidth, height: Math.min(tallest, realHeight - y), scale: 1 } }, 60000);
|
|
825
|
+
const partOut = out.replace(/(\.[a-z]+)?$/i, (ext) => `-${i + 1}${ext || ".jpg"}`);
|
|
826
|
+
writeFileSync(partOut, Buffer.from(part, "base64"));
|
|
827
|
+
console.log(partOut);
|
|
828
|
+
}
|
|
829
|
+
if (realHeight > parts * tallest) console.error(`the page is ${realHeight} px: kept the first ${parts * tallest} px in ${parts} parts`);
|
|
830
|
+
}
|
|
831
|
+
|
|
748
832
|
if (reviewOut) {
|
|
749
833
|
// Side-by-side columns ~2800 px tall so a tall capture stays readable.
|
|
750
834
|
// Real capture stays the single tall file; review is scratch only.
|
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// Build labelled contact sheets from a TSV of label\timageURL.
|
|
3
|
-
//
|
|
2
|
+
// Build labelled contact sheets from a TSV of label\timageURL. The image can
|
|
3
|
+
// be a local file too, so a family's references are sorted by eye from a few
|
|
4
|
+
// sheets of thumbnails, not opened one at a time.
|
|
5
|
+
// Writes JPEG grids (~36 per sheet) into an output directory (scratch, not .longbeard/design/).
|
|
4
6
|
// Viewing listing thumbnails is allowed; this is not a capture.
|
|
5
7
|
//
|
|
6
8
|
// node contact-sheet.mjs candidates.tsv --out /tmp/hunt-sheets
|
|
9
|
+
// node contact-sheet.mjs family-f3.tsv --out <scratch>/f3 --contain # TSV: label<TAB>refs/name.jpg
|
|
7
10
|
import { spawn } from "node:child_process";
|
|
8
11
|
import {
|
|
9
12
|
existsSync,
|
|
@@ -15,6 +18,7 @@ import {
|
|
|
15
18
|
} from "node:fs";
|
|
16
19
|
import { tmpdir } from "node:os";
|
|
17
20
|
import { join, resolve } from "node:path";
|
|
21
|
+
import { pathToFileURL } from "node:url";
|
|
18
22
|
|
|
19
23
|
const args = process.argv.slice(2);
|
|
20
24
|
const flag = (name, def) => {
|
|
@@ -27,8 +31,12 @@ const flag = (name, def) => {
|
|
|
27
31
|
const tsvPath = args[0];
|
|
28
32
|
const outDir = resolve(flag("out", "") || "");
|
|
29
33
|
const perSheet = Math.max(1, Number(flag("per", "36")) || 36);
|
|
34
|
+
const cols = Math.min(8, Math.max(1, Number(flag("cols", "6")) || 6));
|
|
35
|
+
const containAt = args.indexOf("--contain");
|
|
36
|
+
const contain = containAt !== -1;
|
|
37
|
+
if (contain) args.splice(containAt, 1);
|
|
30
38
|
if (!tsvPath || !outDir) {
|
|
31
|
-
console.error("usage: node contact-sheet.mjs candidates.tsv --out
|
|
39
|
+
console.error("usage: node contact-sheet.mjs candidates.tsv --out <scratch>/sheets [--per 36] [--cols 6] [--contain]");
|
|
32
40
|
process.exit(2);
|
|
33
41
|
}
|
|
34
42
|
|
|
@@ -42,7 +50,8 @@ const lines = readFileSync(tsvPath, "utf8")
|
|
|
42
50
|
if (cols.length === 1) return { label: l, url: l };
|
|
43
51
|
return { label: cols[0], url: cols[1] };
|
|
44
52
|
})
|
|
45
|
-
.
|
|
53
|
+
.map((r) => (/^https?:\/\//i.test(r.url) || !existsSync(r.url) ? r : { ...r, url: pathToFileURL(resolve(r.url)).href }))
|
|
54
|
+
.filter((r) => /^(https?|file):\/\//i.test(r.url));
|
|
46
55
|
|
|
47
56
|
if (!lines.length) {
|
|
48
57
|
console.error("no label\timageURL rows found");
|
|
@@ -51,6 +60,8 @@ if (!lines.length) {
|
|
|
51
60
|
|
|
52
61
|
function findChrome() {
|
|
53
62
|
const env = process.env.CHROME_PATH;
|
|
63
|
+
// CHROME_PATH=none: run as if no browser were installed (a quick test run).
|
|
64
|
+
if (env === "none") return null;
|
|
54
65
|
if (env && existsSync(env)) return env;
|
|
55
66
|
const home = process.env.HOME || process.env.USERPROFILE || "";
|
|
56
67
|
const local = process.env.LOCALAPPDATA || "";
|
|
@@ -202,9 +213,9 @@ for (let s = 0; s < sheets.length; s++) {
|
|
|
202
213
|
const html = `<!doctype html><meta charset=utf-8>
|
|
203
214
|
<style>
|
|
204
215
|
body { margin: 16px; background: #1a1a1a; color: #eee; font: 11px/1.2 system-ui, sans-serif; }
|
|
205
|
-
.grid { display: grid; grid-template-columns: repeat(
|
|
216
|
+
.grid { display: grid; grid-template-columns: repeat(${cols}, 1fr); gap: 10px; }
|
|
206
217
|
figure { margin: 0; background: #2a2a2a; border-radius: 4px; overflow: hidden; }
|
|
207
|
-
img { display: block; width: 100%; height:
|
|
218
|
+
img { display: block; width: 100%; height: ${contain ? Math.round(1200 / cols) : 140}px; object-fit: ${contain ? "contain" : "cover"}; background: #111; }
|
|
208
219
|
figcaption { padding: 6px 8px; word-break: break-word; max-height: 2.4em; overflow: hidden; }
|
|
209
220
|
</style>
|
|
210
221
|
<div class="grid">${cells}</div>
|
|
@@ -215,7 +226,7 @@ Promise.all([...document.images].map((img) => img.decode().catch(() => {}))).the
|
|
|
215
226
|
</script>`;
|
|
216
227
|
const htmlPath = join(dir, `sheet-${s + 1}.html`);
|
|
217
228
|
writeFileSync(htmlPath, html);
|
|
218
|
-
await page("Page.navigate", { url:
|
|
229
|
+
await page("Page.navigate", { url: pathToFileURL(htmlPath).href }, 30000);
|
|
219
230
|
await sleep(500);
|
|
220
231
|
for (let i = 0; i < 60; i++) {
|
|
221
232
|
const title = (
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The face options of design-identity, from Google Fonts' own list, not the agent's memory: faces of
|
|
3
|
+
// the same kind as the one the chosen screen has, nearest in shape first. The kind is the list's
|
|
4
|
+
// (serif or sans, display or text, the weight in use, Latin); the shape is measured in one Chrome,
|
|
5
|
+
// each face set at the weight in use: how wide it runs, its x-height, how dark it sets, and its
|
|
6
|
+
// stroke contrast (thick over thin, from an "o"). A face from elsewhere is still measured, given
|
|
7
|
+
// its kind with --kind, and --kind also overrides the list's kind for a face Google files wrongly. Node 22+, an installed Chrome, no dependencies.
|
|
8
|
+
//
|
|
9
|
+
// node fonts.mjs "Newsreader" --weight 300
|
|
10
|
+
// node fonts.mjs "Inter" --body the body row: text faces with 400 and 700
|
|
11
|
+
// node fonts.mjs "Their Face" --kind serif --css https://…/their-face.css
|
|
12
|
+
// a face not in Google's list, from its stylesheet
|
|
13
|
+
// node fonts.mjs "Italiana" --kind serif the list calls it a sans: say what it is
|
|
14
|
+
// node fonts.mjs --shape width=0.53,xheight=0.54,contrast=1.3 --kind sans --weight 700
|
|
15
|
+
// a reference that is only a picture: no face to
|
|
16
|
+
// name, so the shape measure.mjs read from its
|
|
17
|
+
// pixels (type.display) stands in for it
|
|
18
|
+
//
|
|
19
|
+
// Prints one row a face, nearest first: face, kind, width, x-height, dark, contrast (each the
|
|
20
|
+
// face's own, the chosen one's first), weights, axes, how widely it is used (its rank in Google's
|
|
21
|
+
// list, 1 the most used). The order is nearness, never taste: which to show, and why each is
|
|
22
|
+
// of the same kind, is still the agent's to say, and which to keep is theirs.
|
|
23
|
+
// --css <url> (the chosen face's own stylesheet), --count 8 (rows), --json, --metadata <file> (Google's list, saved), --local (installed faces
|
|
24
|
+
// only, no stylesheets: for tests)
|
|
25
|
+
import { spawn } from "node:child_process";
|
|
26
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
27
|
+
import { tmpdir } from "node:os";
|
|
28
|
+
import { join } from "node:path";
|
|
29
|
+
if (typeof WebSocket === "undefined") { console.error("Node 22+ is required."); process.exit(1); }
|
|
30
|
+
|
|
31
|
+
const args = process.argv.slice(2);
|
|
32
|
+
const flag = (name, def = "") => {
|
|
33
|
+
const i = args.indexOf(`--${name}`);
|
|
34
|
+
return i === -1 ? def : (args.splice(i, 2)[1] ?? "");
|
|
35
|
+
};
|
|
36
|
+
const has = (name) => {
|
|
37
|
+
const i = args.indexOf(`--${name}`);
|
|
38
|
+
return i === -1 ? false : (args.splice(i, 1), true);
|
|
39
|
+
};
|
|
40
|
+
const weight = Number(flag("weight", "400"));
|
|
41
|
+
const count = Number(flag("count", "8"));
|
|
42
|
+
const kindArg = flag("kind").toLowerCase();
|
|
43
|
+
const metadataArg = flag("metadata");
|
|
44
|
+
const cssArg = flag("css");
|
|
45
|
+
const json = has("json");
|
|
46
|
+
const body = has("body");
|
|
47
|
+
const italic = has("italic");
|
|
48
|
+
const local = has("local");
|
|
49
|
+
const shapeArg = flag("shape");
|
|
50
|
+
// --shape: the shape read from a picture (measure.mjs, type.display), as width, xheight, dark and
|
|
51
|
+
// contrast; any left out are not compared. Its kind must be said: there is no face to look up.
|
|
52
|
+
const given = Object.fromEntries(shapeArg.split(",").filter(Boolean).map((kv) => kv.split("=")).map(([k, v]) => [k.trim(), Number(v)]));
|
|
53
|
+
const shapeBad = shapeArg && (!kindArg || !Object.keys(given).length || Object.entries(given).some(([k, v]) => !["width", "xheight", "dark", "contrast"].includes(k) || !(v > 0)));
|
|
54
|
+
const face = shapeArg ? "the picture's type" : args.join(" ").trim();
|
|
55
|
+
const KINDS = { serif: ["Serif", "Serif"], slab: ["Serif", "Slab Serif"], sans: ["Sans Serif", "Sans Serif"], display: ["Display", null], handwriting: ["Handwriting", null], mono: ["Monospace", null] };
|
|
56
|
+
if (!face || shapeBad || (shapeArg && args.length) || !(weight >= 100 && weight <= 1000) || !(count >= 1 && count <= 40) || (kindArg && !KINDS[kindArg])) {
|
|
57
|
+
console.error(`usage: node fonts.mjs "Face" [--weight 400] [--italic] [--body] [--kind ${Object.keys(KINDS).join("|")}] [--count 8] [--json]\n node fonts.mjs --shape width=0.53,xheight=0.54,dark=0.2,contrast=1.3 --kind ${Object.keys(KINDS).join("|")} [--weight 400] [--count 8] [--json]`);
|
|
58
|
+
process.exit(2);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function findChrome() {
|
|
62
|
+
const env = process.env.CHROME_PATH;
|
|
63
|
+
// CHROME_PATH=none: run as if no browser were installed (a quick test run).
|
|
64
|
+
if (env === "none") return null;
|
|
65
|
+
if (env && existsSync(env)) return env;
|
|
66
|
+
const home = process.env.HOME || process.env.USERPROFILE || "";
|
|
67
|
+
const pf = process.env.PROGRAMFILES || "C:\\Program Files";
|
|
68
|
+
return [
|
|
69
|
+
join(pf, "Google/Chrome/Application/chrome.exe"),
|
|
70
|
+
join(process.env.LOCALAPPDATA || "", "Google/Chrome/Application/chrome.exe"),
|
|
71
|
+
join(pf, "Microsoft/Edge/Application/msedge.exe"),
|
|
72
|
+
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
73
|
+
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
|
74
|
+
join(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
|
|
75
|
+
"/usr/bin/google-chrome",
|
|
76
|
+
"/usr/bin/google-chrome-stable",
|
|
77
|
+
"/usr/bin/chromium",
|
|
78
|
+
"/usr/bin/chromium-browser",
|
|
79
|
+
].find((path) => path && existsSync(path));
|
|
80
|
+
}
|
|
81
|
+
const exe = findChrome();
|
|
82
|
+
if (!exe) {
|
|
83
|
+
console.error("No Chrome/Edge/Chromium found. Install one or set CHROME_PATH.");
|
|
84
|
+
process.exit(1);
|
|
85
|
+
}
|
|
86
|
+
const dir = mkdtempSync(join(tmpdir(), "fonts-chrome-"));
|
|
87
|
+
const proc = spawn(exe, ["--headless=new", "--remote-debugging-port=0", `--user-data-dir=${dir}`, "--no-first-run", "--force-color-profile=srgb", "about:blank"], { stdio: ["ignore", "ignore", "pipe"] });
|
|
88
|
+
process.once("exit", () => {
|
|
89
|
+
try {
|
|
90
|
+
proc.kill("SIGKILL");
|
|
91
|
+
} catch {}
|
|
92
|
+
try {
|
|
93
|
+
rmSync(dir, { recursive: true, force: true });
|
|
94
|
+
} catch {}
|
|
95
|
+
});
|
|
96
|
+
const fail = (text) => {
|
|
97
|
+
console.error(`fonts: ${text}`);
|
|
98
|
+
process.exit(1);
|
|
99
|
+
};
|
|
100
|
+
let buf = "";
|
|
101
|
+
const wsUrl = await new Promise((done, no) => {
|
|
102
|
+
const t = setTimeout(() => no(new Error("Chrome did not start")), 20000);
|
|
103
|
+
proc.stderr.on("data", (d) => {
|
|
104
|
+
const m = (buf += d).match(/DevTools listening on (ws:\/\/\S+)/);
|
|
105
|
+
if (m) done(m[1], clearTimeout(t));
|
|
106
|
+
});
|
|
107
|
+
}).catch((e) => fail(e.message));
|
|
108
|
+
const ws = new WebSocket(wsUrl);
|
|
109
|
+
await new Promise((done) => (ws.onopen = done));
|
|
110
|
+
let nextId = 0;
|
|
111
|
+
const pending = new Map();
|
|
112
|
+
ws.onmessage = (ev) => {
|
|
113
|
+
const msg = JSON.parse(String(ev.data));
|
|
114
|
+
if (pending.has(msg.id)) pending.get(msg.id)(msg), pending.delete(msg.id);
|
|
115
|
+
};
|
|
116
|
+
const send = (method, params = {}, sessionId) => new Promise((done) => (pending.set(++nextId, done), ws.send(JSON.stringify({ id: nextId, method, params, sessionId }))));
|
|
117
|
+
const { result: target } = await send("Target.createTarget", { url: "about:blank" });
|
|
118
|
+
const { result: att } = await send("Target.attachToTarget", { targetId: target.targetId, flatten: true });
|
|
119
|
+
const call = (method, params) => send(method, params, att.sessionId);
|
|
120
|
+
const evaluate = async (expression) => {
|
|
121
|
+
const r = await call("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });
|
|
122
|
+
if (r.result?.exceptionDetails) throw new Error(r.result.exceptionDetails.exception?.description || "the page threw");
|
|
123
|
+
return r.result.result.value;
|
|
124
|
+
};
|
|
125
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
126
|
+
const go = async (url) => {
|
|
127
|
+
await call("Page.navigate", { url });
|
|
128
|
+
for (let i = 0; i < 150 && (await evaluate("document.readyState").catch(() => "")) !== "complete"; i++) await sleep(200);
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
// Google's list, saved for a week. Read through the browser, which uses the network the way a page does.
|
|
132
|
+
const saved = metadataArg || join(tmpdir(), "longbeard-google-fonts.json");
|
|
133
|
+
let list;
|
|
134
|
+
if (existsSync(saved) && (metadataArg || Date.now() - statSync(saved).mtimeMs < 7 * 864e5)) list = readFileSync(saved, "utf8");
|
|
135
|
+
else {
|
|
136
|
+
await go("https://fonts.google.com/metadata/fonts");
|
|
137
|
+
list = await evaluate("document.body.innerText");
|
|
138
|
+
if (!/familyMetadataList/.test(list || "")) fail("could not read Google Fonts' list (fonts.google.com/metadata/fonts): check the network");
|
|
139
|
+
writeFileSync(saved, list);
|
|
140
|
+
}
|
|
141
|
+
const families = JSON.parse(list.replace(/^\)\]\}'\s*/, "")).familyMetadataList || [];
|
|
142
|
+
|
|
143
|
+
// The kind: the list's category and stroke, display or not, in Latin, with the weight in use.
|
|
144
|
+
const offers = (f, w, it) => (it ? `${w}i` : `${w}`) in f.fonts || (f.axes || []).some((a) => a.tag === "wght" && a.min <= w && a.max >= w && (!it || Object.keys(f.fonts).some((k) => k.endsWith("i"))));
|
|
145
|
+
const isDisplay = (f) => (f.classifications || []).includes("Display");
|
|
146
|
+
const chosen = shapeArg ? null : families.find((f) => f.family.toLowerCase() === face.toLowerCase());
|
|
147
|
+
if (!chosen && !kindArg) fail(`${face} is not in Google Fonts' list: say its kind with --kind ${Object.keys(KINDS).join("|")}`);
|
|
148
|
+
// --kind wins over the list: Google files some faces under the wrong kind (Italiana is listed as a
|
|
149
|
+
// sans), and a row of the wrong kind is no row at all.
|
|
150
|
+
const [category, stroke] = kindArg ? KINDS[kindArg] : [chosen.category, chosen.stroke];
|
|
151
|
+
const display = kindArg ? kindArg === "display" : isDisplay(chosen);
|
|
152
|
+
const pool = families
|
|
153
|
+
// A shape read from a picture has no list to say display or text: both are in reach, and the shape decides.
|
|
154
|
+
.filter((f) => f !== chosen && f.category === category && (!stroke || !f.stroke || f.stroke === stroke) && (shapeArg ? true : isDisplay(f) === display))
|
|
155
|
+
// A small-caps twin is the same face; a slab in a serif's row is another kind. A slab is one Google
|
|
156
|
+
// lists as a slab, or, where it lists no stroke, one named so.
|
|
157
|
+
.filter((f) => !/ SC$/.test(f.family) && (f.stroke === "Slab Serif" || /slab/i.test(f.family)) === (stroke === "Slab Serif"))
|
|
158
|
+
.filter((f) => (f.subsets || []).includes("latin") && !f.isNoto && !(f.classifications || []).includes("Symbols"))
|
|
159
|
+
// A weight read from a picture is an estimate: a face within 100 of it is in reach, set at its nearest.
|
|
160
|
+
.filter((f) => (body ? offers(f, 400, false) && offers(f, 700, false) : shapeArg ? [weight, weight - 100, weight + 100].some((w) => offers(f, w, italic)) : offers(f, weight, italic)))
|
|
161
|
+
.sort((a, b) => a.popularity - b.popularity);
|
|
162
|
+
if (!pool.length) fail(`no faces of ${face}'s kind (${category}${stroke ? `, ${stroke}` : ""}${display ? ", display" : ""}) offer weight ${body ? "400 and 700" : weight}`);
|
|
163
|
+
// Every face of the kind is measured (a stylesheet of the sample letters only is small), so the
|
|
164
|
+
// less known are in reach as much as the most used. Past 800 faces, the most used 800.
|
|
165
|
+
const candidates = pool.slice(0, 800);
|
|
166
|
+
const weightOf = Object.fromEntries(candidates.map((f) => [f.family, shapeArg ? [weight, weight - 100, weight + 100].find((w) => offers(f, w, italic)) : weight]));
|
|
167
|
+
const rank = new Map([...families].sort((a, b) => a.popularity - b.popularity).map((f, i) => [f.family, i + 1]));
|
|
168
|
+
|
|
169
|
+
// The shape of each face, set at the weight in use. A face is only measured once it is really
|
|
170
|
+
// there: set with two different fallbacks, it must measure the same in both.
|
|
171
|
+
await go("about:blank");
|
|
172
|
+
const shapes = await evaluate(`(async () => {
|
|
173
|
+
const W = ${weight}, IT = ${italic}, LOCAL = ${local}, CSS = ${JSON.stringify(cssArg)}, SAMPLE = "Hamburgefonstivxo";
|
|
174
|
+
const faces = ${JSON.stringify([...(shapeArg ? [] : [face]), ...candidates.map((f) => f.family)])};
|
|
175
|
+
const WEIGHTS = ${JSON.stringify(weightOf)};
|
|
176
|
+
const c = Object.assign(document.createElement("canvas"), { width: 2400, height: 420 }).getContext("2d", { willReadFrequently: true });
|
|
177
|
+
const font = (name, fb, size = 120) => (IT ? "italic " : "") + (WEIGHTS[name] || W) + " " + size + "px \\"" + name + "\\", " + fb;
|
|
178
|
+
const load = (name) => new Promise((done) => {
|
|
179
|
+
if (LOCAL && !(name === faces[0] && CSS)) return done();
|
|
180
|
+
const fam = encodeURIComponent(name).replace(/%20/g, "+");
|
|
181
|
+
const link = Object.assign(document.createElement("link"), { rel: "stylesheet", href: name === faces[0] && CSS ? CSS : "https://fonts.googleapis.com/css2?family=" + fam + ":" + (IT ? "ital,wght@1," : "wght@") + (WEIGHTS[name] || W) + "&text=" + SAMPLE + "&display=block" });
|
|
182
|
+
const t = setTimeout(done, 8000);
|
|
183
|
+
link.onload = link.onerror = () => (clearTimeout(t), done());
|
|
184
|
+
document.head.appendChild(link);
|
|
185
|
+
});
|
|
186
|
+
// In batches, and once more for any face not in yet: two hundred stylesheets at once time out by the half.
|
|
187
|
+
const arrived = (n) => document.fonts.check(font(n, "serif"), SAMPLE);
|
|
188
|
+
for (let pass = 0; pass < 2; pass++) {
|
|
189
|
+
const todo = faces.filter((n) => !pass || !arrived(n));
|
|
190
|
+
if (pass) for (const l of [...document.querySelectorAll("link[rel=stylesheet]")]) if (todo.some((n) => l.href.includes(encodeURIComponent(n).replace(/%20/g, "+")))) l.remove();
|
|
191
|
+
for (let i = 0; i < todo.length; i += 25) {
|
|
192
|
+
const batch = todo.slice(i, i + 25);
|
|
193
|
+
await Promise.all(batch.map(load));
|
|
194
|
+
await Promise.all(batch.map((n) => document.fonts.load(font(n, "serif"), SAMPLE).catch(() => [])));
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
const ink = (n) => {
|
|
198
|
+
c.clearRect(0, 0, 2400, 420);
|
|
199
|
+
c.font = font(n, "serif");
|
|
200
|
+
c.fillText(SAMPLE, 10, 200);
|
|
201
|
+
const d = c.getImageData(0, 0, 2400, 420).data;
|
|
202
|
+
let dark = 0;
|
|
203
|
+
for (let i = 3; i < d.length; i += 4) dark += d[i] / 255;
|
|
204
|
+
return dark;
|
|
205
|
+
};
|
|
206
|
+
// Contrast: an "o" at 300 px, its side stroke (across the middle row) over its top (down the middle).
|
|
207
|
+
const contrast = (n) => {
|
|
208
|
+
c.clearRect(0, 0, 2400, 420);
|
|
209
|
+
c.font = font(n, "serif", 300);
|
|
210
|
+
const m = c.measureText("o");
|
|
211
|
+
c.fillText("o", 10, 380);
|
|
212
|
+
const d = c.getImageData(0, 0, 2400, 420).data, a = (x, y) => d[(y * 2400 + x) * 4 + 3] > 127;
|
|
213
|
+
const midY = Math.round(380 - m.actualBoundingBoxAscent / 2), midX = Math.round(10 + (m.actualBoundingBoxRight - m.actualBoundingBoxLeft) / 2 - m.actualBoundingBoxLeft);
|
|
214
|
+
const run = (get, from, to) => { let s = -1; for (let i = from; i < to; i++) { if (get(i) && s < 0) s = i; if (!get(i) && s >= 0) return i - s; } return 0; };
|
|
215
|
+
const side = run((x) => a(x, midY), 0, 2400), top = run((y) => a(midX, y), 0, 420);
|
|
216
|
+
return side && top ? side / top : null;
|
|
217
|
+
};
|
|
218
|
+
const out = {};
|
|
219
|
+
for (const n of faces) {
|
|
220
|
+
c.font = font(n, "monospace");
|
|
221
|
+
const mono = c.measureText(SAMPLE).width;
|
|
222
|
+
c.font = font(n, "serif");
|
|
223
|
+
const m = c.measureText(SAMPLE);
|
|
224
|
+
if (Math.abs(mono - m.width) > 0.5) continue;
|
|
225
|
+
const x = (c.font = font(n, "serif"), c.measureText("x").actualBoundingBoxAscent);
|
|
226
|
+
out[n] = { width: m.width / 120 / SAMPLE.length, xheight: x / 120, dark: ink(n) / (m.width * 120), contrast: contrast(n) };
|
|
227
|
+
}
|
|
228
|
+
return out;
|
|
229
|
+
})()`);
|
|
230
|
+
ws.close();
|
|
231
|
+
|
|
232
|
+
// A picture's stroke contrast reads higher than a face's "o" does once hairlines are a pixel or two
|
|
233
|
+
// thick; past 5 it is clamped, so a didone read at 10 still finds the didones.
|
|
234
|
+
if (shapeArg && given.contrast > 5) given.contrast = 5;
|
|
235
|
+
const mine = shapeArg ? given : shapes[face];
|
|
236
|
+
if (!mine) fail(`${face} did not load${local ? " (--local: it must be installed)" : chosen ? "" : " (a face not in Google's list needs --css, its stylesheet)"}: check the name and the weight (${weight})`);
|
|
237
|
+
const ln = (a, b) => Math.abs(Math.log(a / b));
|
|
238
|
+
// Only what is known counts: a shape read from a picture may lack a measure, and then it is left out.
|
|
239
|
+
const far = (s) => (mine.width ? ln(s.width, mine.width) / 0.12 : 0) + (mine.xheight ? Math.abs(s.xheight - mine.xheight) / 0.05 : 0) + (mine.dark ? ln(s.dark, mine.dark) / 0.2 : 0) + (mine.contrast ? (s.contrast ? ln(s.contrast, mine.contrast) / 0.3 : 1) : 0);
|
|
240
|
+
const meta = new Map(families.map((f) => [f.family, f]));
|
|
241
|
+
const r2 = (v) => (v == null ? null : Math.round(v * 100) / 100);
|
|
242
|
+
const row = (name, s) => {
|
|
243
|
+
const f = meta.get(name);
|
|
244
|
+
const ws = f ? Object.keys(f.fonts).filter((k) => !k.endsWith("i")).map(Number).sort((a, b) => a - b) : [];
|
|
245
|
+
return {
|
|
246
|
+
face: name,
|
|
247
|
+
kind: [category, stroke !== category && stroke, display && "display"].filter(Boolean).join(", "),
|
|
248
|
+
width: r2(s.width),
|
|
249
|
+
xheight: r2(s.xheight),
|
|
250
|
+
dark: r2(s.dark),
|
|
251
|
+
contrast: r2(s.contrast),
|
|
252
|
+
weights: ws.length ? (ws.length > 2 ? `${ws[0]}–${ws.at(-1)}` : ws.join(",")) : "",
|
|
253
|
+
italic: f ? Object.keys(f.fonts).some((k) => k.endsWith("i")) : null,
|
|
254
|
+
axes: f ? (f.axes || []).map((a) => a.tag).join(" ") : "",
|
|
255
|
+
used: rank.get(name) || null,
|
|
256
|
+
far: r2(far(s)),
|
|
257
|
+
};
|
|
258
|
+
};
|
|
259
|
+
const rows = Object.entries(shapes)
|
|
260
|
+
.filter(([n]) => n !== face)
|
|
261
|
+
.map(([n, s]) => row(n, s))
|
|
262
|
+
.sort((a, b) => a.far - b.far)
|
|
263
|
+
.slice(0, count);
|
|
264
|
+
const missed = candidates.length - Object.keys(shapes).filter((n) => n !== face).length;
|
|
265
|
+
// Nothing close: say so, so the face is shown as a stand-in and others are looked at, never taken quietly.
|
|
266
|
+
const close = rows.length && rows[0].far <= 2;
|
|
267
|
+
if (shapeArg && !close) console.error(`fonts: nothing close to the picture's type (nearest is ${rows[0]?.far ?? "none"} far): render the top three with the reference's words beside it and take the one of its kind, or try --kind display, and call it a stand-in`);
|
|
268
|
+
const top = shapeArg ? { face, kind: row(face, { width: 1, xheight: 0, dark: 1 }).kind, ...given, far: 0 } : row(face, mine);
|
|
269
|
+
if (json) console.log(JSON.stringify({ chosen: top, close, rows, measured: candidates.length - missed, missed }, null, 1));
|
|
270
|
+
else {
|
|
271
|
+
const cols = ["face", "kind", "width", "xheight", "dark", "contrast", "weights", "italic", "axes", "used", "far"];
|
|
272
|
+
console.log(cols.join("\t"));
|
|
273
|
+
for (const r of [top, ...rows]) console.log(cols.map((k) => r[k] ?? "").join("\t"));
|
|
274
|
+
console.error(`fonts: ${candidates.length - missed} of ${pool.length} faces of this kind measured${missed ? `, ${missed} did not load` : ""}; nearest first, the chosen face on top`);
|
|
275
|
+
}
|
|
276
|
+
process.exit(0);
|