@jonandev/longbeard 0.13.0 → 0.15.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 +5 -5
- package/CHANGELOG.md +35 -0
- package/README.md +3 -4
- package/beard.json +6 -17
- package/bin/long-beard.js +2 -2
- package/package.json +1 -1
- package/skills/design/SKILL.md +7 -11
- package/skills/design-brief/SKILL.md +5 -35
- package/skills/design-check/SKILL.md +5 -7
- package/skills/design-check/references/design-rules.md +26 -4
- package/skills/design-check/scripts/rules.mjs +143 -9
- package/skills/design-content/SKILL.md +3 -8
- package/skills/design-direction/SKILL.md +58 -53
- package/skills/design-direction/references/design-floor.md +118 -0
- package/skills/design-direction/references/graphic.md +5 -6
- package/skills/design-direction/references/library.md +7 -7
- package/skills/design-direction/references/screen-template.html +7 -164
- package/skills/design-direction/references/screen.js +163 -0
- package/skills/design-direction/references/subject.md +3 -3
- package/skills/design-direction/references/variants.js +43 -0
- package/skills/design-direction/scripts/canvas.mjs +12 -9
- package/skills/design-direction/scripts/colours.mjs +247 -0
- package/skills/design-direction/scripts/moodboard.mjs +1 -1
- package/skills/design-direction/scripts/rules.mjs +747 -0
- package/skills/design-direction/scripts/sheet.mjs +3 -1
- package/skills/design-figma/SKILL.md +4 -6
- package/skills/design-identity/SKILL.md +12 -14
- package/skills/design-identity/references/design-floor.md +118 -0
- package/skills/design-identity/scripts/colours.mjs +35 -1
- package/skills/design-identity/scripts/sheet.mjs +3 -1
- package/skills/design-moodboard/SKILL.md +11 -11
- package/skills/design-moodboard/references/graphic.md +1 -1
- package/skills/design-moodboard/references/sources.md +1 -1
- package/skills/design-moodboard/scripts/group.mjs +1 -1
- package/skills/design-moodboard/scripts/moodboard.mjs +1 -1
- package/skills/design-prototype/SKILL.md +51 -49
- package/skills/design-prototype/references/design-floor.md +118 -0
- package/skills/design-prototype/references/design-md-template.md +4 -2
- package/skills/design-prototype/references/graphic.md +6 -5
- package/skills/design-prototype/references/variants.js +43 -0
- package/skills/design-prototype/scripts/links.mjs +5 -4
- package/skills/design-prototype/scripts/rules.mjs +143 -9
- package/skills/design-prototype/scripts/sheet.mjs +3 -1
- package/skills/design-wordmark/SKILL.md +9 -8
- package/skills/design-wordmark/scripts/sheet.mjs +3 -1
- package/skills/framework-skills/SKILL.md +3 -5
- package/skills/idea/SKILL.md +7 -9
- package/skills/design-direction/references/design-rules.md +0 -204
- package/skills/design-direction/references/full-build.md +0 -20
- package/skills/design-direction/references/grid.md +0 -97
- package/skills/design-direction/scripts/layout-diff.mjs +0 -118
- package/skills/design-families/SKILL.md +0 -139
- package/skills/design-families/scripts/contact-sheet.mjs +0 -259
- package/skills/design-families/scripts/families.mjs +0 -607
- package/skills/design-families/scripts/measure.mjs +0 -1728
- package/skills/design-families/scripts/moodboard.mjs +0 -609
- package/skills/design-families/scripts/tag.mjs +0 -289
- package/skills/design-prototype/references/design-rules.md +0 -204
- package/skills/design-prototype/references/five-second.md +0 -46
|
@@ -0,0 +1,747 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The hard rules a browser can measure, measured. Opens a page headless at a
|
|
3
|
+
// desktop and a phone width and prints findings in design-check's table, each
|
|
4
|
+
// tied to a rule in design-rules.md. Node 22+, an installed Chrome, no
|
|
5
|
+
// dependencies.
|
|
6
|
+
//
|
|
7
|
+
// node rules.mjs "file://$PWD/.longbeard/design/prototype/home.html" --screen home
|
|
8
|
+
// node rules.mjs http://localhost:3000/orders --screen orders --cookie "session=abc" --app
|
|
9
|
+
//
|
|
10
|
+
// Checks (all hard):
|
|
11
|
+
// 13 Responsive nothing runs past the screen's edge at phone width (sideways scroll)
|
|
12
|
+
// 10 Accessibility targets at least 24x24 CSS px, or 24 px of clear space around them
|
|
13
|
+
// (--app: 44x44 at phone width, no spacing exception; links inside a
|
|
14
|
+
// sentence are exempt, as WCAG 2.2 exempts them)
|
|
15
|
+
// 10 Accessibility every input has a visible label (a placeholder or an aria-label alone is not one)
|
|
16
|
+
// 10 Accessibility a focused control shows a change (outline, ring, fill, border). Real Tab
|
|
17
|
+
// presses; the 3:1 contrast of the indicator is NOT measured
|
|
18
|
+
// 11 Copy no lorem ipsum, and no text that is only "Title", "Button", "User Name"...
|
|
19
|
+
// 5 Typography text cut by its container, including an ellipsis. Text cut on purpose
|
|
20
|
+
// carries data-crop on the element (or one above it) and is skipped
|
|
21
|
+
// 5 Typography text size: nothing under 12px; text a person acts on (links, buttons,
|
|
22
|
+
// labels, fields, navigation) at least 14px; body (running text of 60
|
|
23
|
+
// characters or more) at least 16px. Text marked data-board-size (on it or
|
|
24
|
+
// above it: the board shows it that small and the person kept it) is a
|
|
25
|
+
// warning with its measure, not a block
|
|
26
|
+
// Soft (reported, never blocking):
|
|
27
|
+
// 6 Colour proportion on the first screen, text and pictures left out: the ground
|
|
28
|
+
// (the largest colour) under 50%, or the accent over 20% (--accent "#hex"
|
|
29
|
+
// names it; else the most saturated colour). A board that does otherwise wins
|
|
30
|
+
// Not checked, on purpose: overlap, collision, alignment, empty space, section height. They are
|
|
31
|
+
// the look's own moves. Not checked either: contrast (screen-contrast.mjs), states, hierarchy.
|
|
32
|
+
//
|
|
33
|
+
// Rounds and waivers (state in .longbeard/design/, --dir to move it):
|
|
34
|
+
// rounds.json per screen: a run on a changed page is a round. Fix after every run, then
|
|
35
|
+
// run again: two runs with no fix between are one round, and so is a first run
|
|
36
|
+
// of another state of the same screen (another url, same --screen). After
|
|
37
|
+
// --rounds (2: a check and one re-check) it says "rounds used up": stop fixing,
|
|
38
|
+
// report what is open.
|
|
39
|
+
// waivers.json --waive <id> --reason "why this finding is false", one finding at a time. The id
|
|
40
|
+
// is in the Where cell. A reason of fewer than three words is refused. Waived
|
|
41
|
+
// findings are still listed, with the reason.
|
|
42
|
+
// --ship "their words" the person ends the loop: the words are recorded, the open findings
|
|
43
|
+
// are reported, and runs on that page exit 0.
|
|
44
|
+
//
|
|
45
|
+
// Exit 0 no hard findings (or closed by the person), 1 hard findings open, 2 usage, 3 could not
|
|
46
|
+
// run. A check that could not run is "not checked", never passed. The first failure on a screen
|
|
47
|
+
// says what to do; the second says to report it as not checked and go on.
|
|
48
|
+
// --widths 1440,390, --screen name, --app, --cookie "a=b; c=d", --wait 300 (ms), --timeout 120000
|
|
49
|
+
// (ms for the whole run; every browser call also has its own 15 s limit), --rounds 2, --dir,
|
|
50
|
+
// --accent "#hex" (the accent from DESIGN.md, for the proportion), --json
|
|
51
|
+
import { spawn } from "node:child_process";
|
|
52
|
+
import { createHash } from "node:crypto";
|
|
53
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
54
|
+
import { tmpdir } from "node:os";
|
|
55
|
+
import { join } from "node:path";
|
|
56
|
+
|
|
57
|
+
const args = process.argv.slice(2);
|
|
58
|
+
const flag = (name, def = "") => {
|
|
59
|
+
const i = args.indexOf(`--${name}`);
|
|
60
|
+
return i === -1 ? def : (args.splice(i, 2)[1] ?? "");
|
|
61
|
+
};
|
|
62
|
+
const has = (name) => {
|
|
63
|
+
const i = args.indexOf(`--${name}`);
|
|
64
|
+
return i === -1 ? false : (args.splice(i, 1), true);
|
|
65
|
+
};
|
|
66
|
+
const screenArg = flag("screen");
|
|
67
|
+
const widths = flag("widths", "1440,390").split(",").map((w) => Number(w.trim()));
|
|
68
|
+
const cookieArg = flag("cookie");
|
|
69
|
+
const wait = Number(flag("wait", "300"));
|
|
70
|
+
const totalMs = Number(flag("timeout", "120000"));
|
|
71
|
+
const limit = Number(flag("rounds", "2"));
|
|
72
|
+
const stateDir = flag("dir", ".longbeard/design");
|
|
73
|
+
const waiveId = flag("waive");
|
|
74
|
+
const reason = flag("reason");
|
|
75
|
+
const shipWords = flag("ship");
|
|
76
|
+
const app = has("app");
|
|
77
|
+
const json = has("json");
|
|
78
|
+
const accentArg = flag("accent");
|
|
79
|
+
const [url] = args;
|
|
80
|
+
const usage = 'usage: node rules.mjs "<file:// or http(s):// url>" [--screen name] [--widths 1440,390] [--app] [--cookie "a=b"] [--wait 300] [--timeout 120000] [--rounds 2] [--dir .longbeard/design] [--accent "#hex"] [--json]\n node rules.mjs --screen name --waive <id> --reason "why this finding is false"\n node rules.mjs --screen name --ship "the person\'s words"';
|
|
81
|
+
const recording = Boolean(waiveId || shipWords);
|
|
82
|
+
const usageOk = recording ? Boolean(screenArg || url) && args.length <= 1 : url && args.length === 1 && /^(https?|file):/.test(url);
|
|
83
|
+
if (!usageOk || widths.some((w) => !(w >= 200 && w <= 3840)) || !(wait >= 0 && wait <= 10000) || !(totalMs >= 5000) || !(limit >= 1) || (waiveId && shipWords) || (reason && !waiveId) || (accentArg && !/^#?[0-9a-f]{6}$/i.test(accentArg))) {
|
|
84
|
+
console.error(usage);
|
|
85
|
+
process.exit(2);
|
|
86
|
+
}
|
|
87
|
+
const screen = screenArg || url.split("#")[0];
|
|
88
|
+
|
|
89
|
+
// ---- state: rounds and waivers ----
|
|
90
|
+
const roundsFile = join(stateDir, "rounds.json");
|
|
91
|
+
const waiversFile = join(stateDir, "waivers.json");
|
|
92
|
+
const readJson = (file, empty) => {
|
|
93
|
+
if (!existsSync(file)) return empty;
|
|
94
|
+
try {
|
|
95
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
96
|
+
} catch {
|
|
97
|
+
console.error(`rules: ${file} could not be read; it was moved to ${file}.bad and started again`);
|
|
98
|
+
renameSync(file, `${file}.bad`);
|
|
99
|
+
return empty;
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
const writeJson = (file, value) => {
|
|
103
|
+
mkdirSync(stateDir, { recursive: true });
|
|
104
|
+
writeFileSync(file, `${JSON.stringify(value, null, 1)}\n`);
|
|
105
|
+
};
|
|
106
|
+
const rounds = readJson(roundsFile, {});
|
|
107
|
+
const waivers = readJson(waiversFile, []);
|
|
108
|
+
const record = rounds[screen] || {};
|
|
109
|
+
const today = () => new Date().toISOString().slice(0, 10);
|
|
110
|
+
|
|
111
|
+
if (waiveId) {
|
|
112
|
+
const found = (record.found || []).find((f) => f.id === waiveId);
|
|
113
|
+
if (!found) {
|
|
114
|
+
console.error(`rules: no open finding ${waiveId} on ${screen}. Run the check, and use the id in the Where cell.`);
|
|
115
|
+
process.exit(2);
|
|
116
|
+
}
|
|
117
|
+
if (reason.trim().split(/\s+/).filter(Boolean).length < 3) {
|
|
118
|
+
console.error('rules: a waiver needs a reason in words: why this finding is false (--reason "…"). A hard rule is never waived, only a finding that is wrong.');
|
|
119
|
+
process.exit(2);
|
|
120
|
+
}
|
|
121
|
+
if (waivers.some((w) => w.screen === screen && w.id === waiveId)) {
|
|
122
|
+
console.error(`rules: ${waiveId} is already waived on ${screen}.`);
|
|
123
|
+
process.exit(2);
|
|
124
|
+
}
|
|
125
|
+
waivers.push({ screen, id: waiveId, rule: found.rule, where: found.where, reason: reason.trim(), at: today() });
|
|
126
|
+
writeJson(waiversFile, waivers);
|
|
127
|
+
console.log(`waived ${waiveId} on ${screen}: ${reason.trim()}`);
|
|
128
|
+
process.exit(0);
|
|
129
|
+
}
|
|
130
|
+
if (shipWords) {
|
|
131
|
+
if (!shipWords.trim()) {
|
|
132
|
+
console.error(usage);
|
|
133
|
+
process.exit(2);
|
|
134
|
+
}
|
|
135
|
+
if (!record.found) {
|
|
136
|
+
console.error(`rules: ${screen} has not been checked yet. Run it once, so the open findings are on record.`);
|
|
137
|
+
process.exit(2);
|
|
138
|
+
}
|
|
139
|
+
record.closed = { words: shipWords.trim(), at: today(), open: record.found.filter((f) => (f.level || "hard") === "hard" && !waivers.some((w) => w.screen === screen && w.id === f.id)) };
|
|
140
|
+
rounds[screen] = record;
|
|
141
|
+
writeJson(roundsFile, rounds);
|
|
142
|
+
console.log(`${screen} closed by the person: "${record.closed.words}". Open findings, to report as open:`);
|
|
143
|
+
for (const f of record.closed.open) console.log(`- ${f.rule}: ${f.where} [${f.id}]`);
|
|
144
|
+
process.exit(0);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// ---- could not run: the first time blocks with what to do, the second lets go ----
|
|
148
|
+
let finished = false;
|
|
149
|
+
function couldNot(why) {
|
|
150
|
+
if (finished) return;
|
|
151
|
+
finished = true;
|
|
152
|
+
const failed = (record.failed || 0) + 1;
|
|
153
|
+
try {
|
|
154
|
+
rounds[screen] = { ...record, failed };
|
|
155
|
+
writeJson(roundsFile, rounds);
|
|
156
|
+
} catch {}
|
|
157
|
+
console.error(`rules: could not run: ${why}`);
|
|
158
|
+
console.log(`not checked: ${screen} (${why}).`);
|
|
159
|
+
console.log(failed === 1 ? "Fix what stops it (the address, the login with --cookie, Chrome via CHROME_PATH) and run it once more. Until it runs, this screen is not checked." : "It could not run twice. Report this screen as not checked, never as passed, and go on.");
|
|
160
|
+
process.exit(3);
|
|
161
|
+
}
|
|
162
|
+
const watchdog = setTimeout(() => couldNot(`the whole run took more than ${Math.round(totalMs / 1000)} s`), totalMs);
|
|
163
|
+
|
|
164
|
+
function findChrome() {
|
|
165
|
+
const env = process.env.CHROME_PATH;
|
|
166
|
+
// CHROME_PATH=none: run as if no browser were installed (a quick test run).
|
|
167
|
+
if (env === "none") return null;
|
|
168
|
+
if (env && existsSync(env)) return env;
|
|
169
|
+
const home = process.env.HOME || process.env.USERPROFILE || "";
|
|
170
|
+
const pf = process.env.PROGRAMFILES || "C:\\Program Files";
|
|
171
|
+
return [
|
|
172
|
+
join(pf, "Google/Chrome/Application/chrome.exe"),
|
|
173
|
+
join(process.env.LOCALAPPDATA || "", "Google/Chrome/Application/chrome.exe"),
|
|
174
|
+
join(pf, "Microsoft/Edge/Application/msedge.exe"),
|
|
175
|
+
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
176
|
+
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
|
177
|
+
join(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
|
|
178
|
+
"/usr/bin/google-chrome",
|
|
179
|
+
"/usr/bin/google-chrome-stable",
|
|
180
|
+
"/usr/bin/chromium",
|
|
181
|
+
"/usr/bin/chromium-browser",
|
|
182
|
+
].find((path) => path && existsSync(path));
|
|
183
|
+
}
|
|
184
|
+
const exe = findChrome();
|
|
185
|
+
if (!exe) couldNot("No Chrome/Edge/Chromium found. Install one or set CHROME_PATH.");
|
|
186
|
+
const dir = mkdtempSync(join(tmpdir(), "rules-"));
|
|
187
|
+
const 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"] });
|
|
188
|
+
process.once("exit", () => {
|
|
189
|
+
try {
|
|
190
|
+
proc.kill("SIGKILL");
|
|
191
|
+
} catch {}
|
|
192
|
+
try {
|
|
193
|
+
rmSync(dir, { recursive: true, force: true });
|
|
194
|
+
} catch {}
|
|
195
|
+
});
|
|
196
|
+
let buf = "";
|
|
197
|
+
const wsUrl = await new Promise((done, no) => {
|
|
198
|
+
const t = setTimeout(() => no(new Error("Chrome did not start within 20 s")), 20000);
|
|
199
|
+
proc.on("error", (e) => no(e));
|
|
200
|
+
proc.stderr.on("data", (d) => {
|
|
201
|
+
const m = (buf += d).match(/DevTools listening on (ws:\/\/\S+)/);
|
|
202
|
+
if (m) done(m[1], clearTimeout(t));
|
|
203
|
+
});
|
|
204
|
+
}).catch((e) => couldNot(e.message));
|
|
205
|
+
const ws = new WebSocket(wsUrl);
|
|
206
|
+
await new Promise((done, no) => {
|
|
207
|
+
const t = setTimeout(() => no(new Error("Chrome did not answer within 10 s")), 10000);
|
|
208
|
+
ws.onopen = () => done(clearTimeout(t));
|
|
209
|
+
ws.onerror = () => no(new Error("could not connect to Chrome"));
|
|
210
|
+
}).catch((e) => couldNot(e.message));
|
|
211
|
+
let nextId = 0;
|
|
212
|
+
const pending = new Map();
|
|
213
|
+
ws.onmessage = (ev) => {
|
|
214
|
+
const msg = JSON.parse(String(ev.data));
|
|
215
|
+
if (pending.has(msg.id)) pending.get(msg.id)(msg), pending.delete(msg.id);
|
|
216
|
+
};
|
|
217
|
+
ws.onclose = () => {
|
|
218
|
+
for (const [id, done] of pending) done({ id, error: { message: "Chrome closed" } });
|
|
219
|
+
pending.clear();
|
|
220
|
+
};
|
|
221
|
+
// Every browser call has a time limit.
|
|
222
|
+
const send = (method, params = {}, sessionId, ms = 15000) =>
|
|
223
|
+
new Promise((done, no) => {
|
|
224
|
+
const id = ++nextId;
|
|
225
|
+
const t = setTimeout(() => (pending.delete(id), no(new Error(`${method} took more than ${ms / 1000} s`))), ms);
|
|
226
|
+
pending.set(id, (m) => (clearTimeout(t), m.error ? no(new Error(`${method}: ${m.error.message}`)) : done(m)));
|
|
227
|
+
ws.send(JSON.stringify({ id, method, params, sessionId }));
|
|
228
|
+
});
|
|
229
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
230
|
+
|
|
231
|
+
// ---- what runs inside the page ----
|
|
232
|
+
// Each function is sent to the page as text, so it may use nothing outside itself.
|
|
233
|
+
|
|
234
|
+
// Fingerprint of the page as built: the rendered markup without scripts, and every stylesheet.
|
|
235
|
+
function pageFingerprint() {
|
|
236
|
+
const clone = document.documentElement.cloneNode(true);
|
|
237
|
+
clone.querySelectorAll("script").forEach((s) => s.remove());
|
|
238
|
+
let css = "";
|
|
239
|
+
for (const sheet of document.styleSheets) {
|
|
240
|
+
try {
|
|
241
|
+
css += [...sheet.cssRules].map((r) => r.cssText).join("");
|
|
242
|
+
} catch {}
|
|
243
|
+
}
|
|
244
|
+
return clone.outerHTML + css;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// The static checks. Returns { found: [{ rule, check, path, desc, detail }], notChecked: [{ check, why }] }.
|
|
248
|
+
function staticChecks(opt) {
|
|
249
|
+
const found = [];
|
|
250
|
+
const notChecked = [];
|
|
251
|
+
const vw = opt.width;
|
|
252
|
+
const phone = vw <= 480;
|
|
253
|
+
const visible = (el) => el.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true, opacityProperty: true, visibilityProperty: true });
|
|
254
|
+
const path = (el) => {
|
|
255
|
+
if (el.id && document.querySelectorAll(`[id="${el.id.replace(/"/g, '\\"')}"]`).length === 1) return `#${el.id}`;
|
|
256
|
+
const parts = [];
|
|
257
|
+
for (let n = el; n && n.nodeType === 1 && n !== document.documentElement; n = n.parentElement) {
|
|
258
|
+
const same = n.parentElement ? [...n.parentElement.children].filter((c) => c.tagName === n.tagName) : [n];
|
|
259
|
+
parts.unshift(`${n.tagName.toLowerCase()}${same.length > 1 ? `:nth-of-type(${same.indexOf(n) + 1})` : ""}`);
|
|
260
|
+
}
|
|
261
|
+
return parts.join(">");
|
|
262
|
+
};
|
|
263
|
+
const words = (el, n = 30) => {
|
|
264
|
+
const t = (el.innerText || el.value || el.getAttribute("aria-label") || el.getAttribute("placeholder") || "").trim().replace(/\s+/g, " ");
|
|
265
|
+
return t.length > n ? `${t.slice(0, n - 1)}…` : t;
|
|
266
|
+
};
|
|
267
|
+
const desc = (el) => {
|
|
268
|
+
const cls = typeof el.className === "string" ? el.className.trim().split(/\s+/).filter(Boolean).slice(0, 2).map((c) => `.${c}`).join("") : "";
|
|
269
|
+
const w = words(el);
|
|
270
|
+
return `${el.tagName.toLowerCase()}${el.id ? `#${el.id}` : ""}${cls}${w ? ` "${w}"` : ""}`;
|
|
271
|
+
};
|
|
272
|
+
const add = (rule, check, el, detail) => found.push({ rule, check, path: path(el), desc: desc(el), detail });
|
|
273
|
+
const marked = (el) => !!el.closest("[data-crop]");
|
|
274
|
+
const run = (check, fn) => {
|
|
275
|
+
try {
|
|
276
|
+
fn();
|
|
277
|
+
} catch (e) {
|
|
278
|
+
notChecked.push({ check, why: String(e && e.message ? e.message : e).slice(0, 80) });
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
const all = [...document.body.querySelectorAll("*")].filter((el) => !(el instanceof SVGElement && el.tagName !== "svg") && !/^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE|HEAD|META|LINK)$/.test(el.tagName));
|
|
282
|
+
const ownText = (el) => [...el.childNodes].some((n) => n.nodeType === 3 && n.textContent.trim());
|
|
283
|
+
|
|
284
|
+
// 13: nothing runs past the screen's edge at phone width.
|
|
285
|
+
if (phone)
|
|
286
|
+
run("13 sideways", () => {
|
|
287
|
+
const root = document.scrollingElement;
|
|
288
|
+
// A page whose root or body clips sideways does not scroll sideways: it cuts instead.
|
|
289
|
+
const hx = getComputedStyle(document.documentElement).overflowX, bx = getComputedStyle(document.body).overflowX;
|
|
290
|
+
const holds = hx === "hidden" || hx === "clip" || (hx === "visible" && (bx === "hidden" || bx === "clip"));
|
|
291
|
+
const scrolls = !holds && root.scrollWidth > root.clientWidth + 1;
|
|
292
|
+
const fixedAbove = (el) => {
|
|
293
|
+
for (let n = el; n && n !== document.documentElement; n = n.parentElement) if (getComputedStyle(n).position === "fixed") return true;
|
|
294
|
+
return false;
|
|
295
|
+
};
|
|
296
|
+
const contained = (el) => {
|
|
297
|
+
for (let n = el.parentElement; n && n !== document.body && n !== document.documentElement; n = n.parentElement) {
|
|
298
|
+
const s = getComputedStyle(n);
|
|
299
|
+
if (s.overflowX !== "visible") return true;
|
|
300
|
+
}
|
|
301
|
+
return false;
|
|
302
|
+
};
|
|
303
|
+
const over = [];
|
|
304
|
+
for (const el of all) {
|
|
305
|
+
if (!visible(el) || marked(el) || fixedAbove(el)) continue;
|
|
306
|
+
const r = el.getBoundingClientRect();
|
|
307
|
+
if (r.width < 1 || r.height < 1 || (r.right <= vw + 1 && r.left >= -1)) continue;
|
|
308
|
+
const wholly = r.left >= vw || r.right <= 0;
|
|
309
|
+
// A page that holds still cuts what runs past the edge. Only words and controls count then.
|
|
310
|
+
if (!scrolls && (wholly || !(ownText(el) || el.matches("a, button, input, select, textarea, img")))) continue;
|
|
311
|
+
if (contained(el)) continue;
|
|
312
|
+
over.push({ el, by: Math.round(Math.max(r.right - vw, -r.left)) });
|
|
313
|
+
}
|
|
314
|
+
const outer = over.filter((o) => !over.some((p) => p.el !== o.el && p.el.contains(o.el)));
|
|
315
|
+
for (const o of outer.slice(0, 6)) add("13 Responsive", "sideways", o.el, `runs ${o.by}px past the screen's edge${scrolls ? ", so the page scrolls sideways" : ", and is cut"}`);
|
|
316
|
+
if (scrolls && !outer.length) add("13 Responsive", "sideways", document.body, `the page is ${root.scrollWidth - root.clientWidth}px wider than the screen`);
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
// 10: targets.
|
|
320
|
+
const min = opt.app && phone ? 44 : 24;
|
|
321
|
+
run("10 targets", () => {
|
|
322
|
+
const sel = 'a[href], button, input:not([type=hidden]), select, textarea, summary, [role=button], [role=link], [role=checkbox], [role=radio], [role=tab], [role=menuitem], [role=switch], [onclick]';
|
|
323
|
+
const targets = [];
|
|
324
|
+
for (const el of document.body.querySelectorAll(sel)) {
|
|
325
|
+
if (el.disabled || el.getAttribute("aria-disabled") === "true") continue;
|
|
326
|
+
if (visible(el) && el.getBoundingClientRect().width >= 1) {
|
|
327
|
+
const r = el.getBoundingClientRect();
|
|
328
|
+
// A checkbox or radio drawn by its label: the label is what a finger meets.
|
|
329
|
+
if (el.matches("input[type=checkbox], input[type=radio]") && (r.width < 6 || r.height < 6 || Number(getComputedStyle(el).opacity) === 0) && el.labels?.[0] && visible(el.labels[0])) targets.push(el.labels[0]);
|
|
330
|
+
else targets.push(el);
|
|
331
|
+
} else if (el.matches("input[type=checkbox], input[type=radio]") && el.labels?.[0] && visible(el.labels[0])) targets.push(el.labels[0]);
|
|
332
|
+
}
|
|
333
|
+
const set = [...new Set(targets)].filter((el) => !targets.some((o) => o !== el && o.contains(el) && o.matches("a, button, label")));
|
|
334
|
+
const boxes = set.map((el) => ({ el, r: el.getBoundingClientRect() }));
|
|
335
|
+
const small = (b) => b.r.width < 24 || b.r.height < 24;
|
|
336
|
+
for (const b of boxes) {
|
|
337
|
+
const { el, r } = b;
|
|
338
|
+
if (r.width >= min && r.height >= min) continue;
|
|
339
|
+
const p = el.parentElement;
|
|
340
|
+
const inline = getComputedStyle(el).display === "inline" && p && p.textContent.replace(el.textContent, "").trim().length > 0;
|
|
341
|
+
if (inline) continue;
|
|
342
|
+
if (min === 24) {
|
|
343
|
+
// The spacing exception: a 24px circle on its centre touches no other target.
|
|
344
|
+
const cx = r.left + r.width / 2, cy = r.top + r.height / 2;
|
|
345
|
+
const clear = boxes.every((o) => {
|
|
346
|
+
if (o === b || o.el.contains(el) || el.contains(o.el)) return true;
|
|
347
|
+
if (small(o)) return Math.hypot(cx - (o.r.left + o.r.width / 2), cy - (o.r.top + o.r.height / 2)) >= 24;
|
|
348
|
+
const dx = Math.max(o.r.left - cx, 0, cx - o.r.right), dy = Math.max(o.r.top - cy, 0, cy - o.r.bottom);
|
|
349
|
+
return Math.hypot(dx, dy) >= 12;
|
|
350
|
+
});
|
|
351
|
+
if (clear && r.width >= 1 && r.height >= 1 && small(b)) continue;
|
|
352
|
+
}
|
|
353
|
+
add(min === 44 ? "10 Accessibility, apps list" : "10 Accessibility", "target", el, `${Math.round(r.width)}×${Math.round(r.height)}px, needs ${min}×${min}${min === 24 ? " or 24px of clear space around it" : " for touch"}`);
|
|
354
|
+
}
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
// 10: every input has a visible label.
|
|
358
|
+
run("10 labels", () => {
|
|
359
|
+
const shown = (l) => {
|
|
360
|
+
if (!l || !visible(l)) return false;
|
|
361
|
+
const r = l.getBoundingClientRect();
|
|
362
|
+
return r.width > 3 && r.height > 3 && (l.innerText || "").trim().length > 0;
|
|
363
|
+
};
|
|
364
|
+
const sel = "input:not([type=hidden]):not([type=submit]):not([type=button]):not([type=reset]):not([type=image]), select, textarea";
|
|
365
|
+
for (const el of document.body.querySelectorAll(sel)) {
|
|
366
|
+
const custom = el.matches("input[type=checkbox], input[type=radio]");
|
|
367
|
+
if (!visible(el) && !(custom && el.labels?.length)) continue;
|
|
368
|
+
const labelled = [...(el.labels || [])].some(shown) || (el.getAttribute("aria-labelledby") || "").split(/\s+/).some((id) => shown(document.getElementById(id)));
|
|
369
|
+
if (labelled) continue;
|
|
370
|
+
const how = el.getAttribute("placeholder") ? "only a placeholder" : el.getAttribute("aria-label") || el.title ? "only a hidden name (aria-label or title), none you can see" : "no label";
|
|
371
|
+
add("10 Accessibility", "label", el, `input with ${how}`);
|
|
372
|
+
}
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
// 11: placeholder copy.
|
|
376
|
+
run("11 copy", () => {
|
|
377
|
+
const stock = new Set(["title", "button", "user name", "heading", "subheading", "subtitle", "placeholder", "your text here", "body text", "sample text", "text here"]);
|
|
378
|
+
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
|
|
379
|
+
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
|
380
|
+
const el = n.parentElement;
|
|
381
|
+
const t = n.textContent.trim().replace(/\s+/g, " ");
|
|
382
|
+
if (!t || !el || /^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE)$/.test(el.tagName) || !visible(el)) continue;
|
|
383
|
+
const lorem = /lorem ipsum|dolor sit amet|consectetur adipiscing/i.test(t);
|
|
384
|
+
// A field's own name ("Title" on a label or a column) is a label, not placeholder copy.
|
|
385
|
+
const stockWord = stock.has(t.toLowerCase()) && !el.closest("label, legend, th, option, dt, summary");
|
|
386
|
+
if (lorem || stockWord) add("11 Copy", "placeholder", el, `"${t.length > 40 ? `${t.slice(0, 39)}…` : t}" is ${lorem ? "lorem ipsum" : "placeholder copy"}`);
|
|
387
|
+
}
|
|
388
|
+
for (const el of document.body.querySelectorAll("[placeholder], img[alt]")) {
|
|
389
|
+
const t = el.getAttribute("placeholder") || el.getAttribute("alt") || "";
|
|
390
|
+
if (/lorem ipsum|dolor sit amet/i.test(t) && visible(el)) add("11 Copy", "placeholder", el, "lorem ipsum in its placeholder or alt");
|
|
391
|
+
}
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
// 5: text cut by its container. Text cut on purpose carries data-crop.
|
|
395
|
+
run("5 clipped", () => {
|
|
396
|
+
const cuts = (v) => v === "hidden" || v === "clip";
|
|
397
|
+
const done = new Set();
|
|
398
|
+
for (const el of all) {
|
|
399
|
+
if (!ownText(el) || el instanceof SVGElement) continue;
|
|
400
|
+
if (!visible(el) || marked(el)) continue;
|
|
401
|
+
const box = el.getBoundingClientRect();
|
|
402
|
+
if (box.width <= 2 || box.height <= 2) continue; // visually hidden text, read by screen readers
|
|
403
|
+
const s = getComputedStyle(el);
|
|
404
|
+
let how = "";
|
|
405
|
+
// The element's own box is smaller than its text.
|
|
406
|
+
if (s.display !== "inline") {
|
|
407
|
+
if (cuts(s.overflowX) && el.clientWidth > 0 && el.scrollWidth > el.clientWidth + 1) how = `${el.scrollWidth - el.clientWidth}px of its text is cut at the side${s.textOverflow === "ellipsis" ? " (an ellipsis)" : ""}`;
|
|
408
|
+
else if (cuts(s.overflowY) && el.clientHeight > 0 && el.scrollHeight > el.clientHeight + 1) how = `${el.scrollHeight - el.clientHeight}px of its text is cut below${s.webkitLineClamp && s.webkitLineClamp !== "none" ? " (a line clamp)" : ""}`;
|
|
409
|
+
}
|
|
410
|
+
// Or a box above it is: some of the text shows, some does not.
|
|
411
|
+
if (!how) {
|
|
412
|
+
const rects = [];
|
|
413
|
+
for (const n of el.childNodes) {
|
|
414
|
+
if (n.nodeType !== 3 || !n.textContent.trim()) continue;
|
|
415
|
+
const range = document.createRange();
|
|
416
|
+
range.selectNodeContents(n);
|
|
417
|
+
rects.push(...[...range.getClientRects()].filter((r) => r.width >= 1 && r.height >= 1));
|
|
418
|
+
}
|
|
419
|
+
for (let a = el; a && a !== document.body && a !== document.documentElement && !how; a = a.parentElement) {
|
|
420
|
+
const as = getComputedStyle(a);
|
|
421
|
+
const ab = a.getBoundingClientRect();
|
|
422
|
+
const clip = { l: ab.left + a.clientLeft, t: ab.top + a.clientTop };
|
|
423
|
+
clip.r = clip.l + a.clientWidth;
|
|
424
|
+
clip.b = clip.t + a.clientHeight;
|
|
425
|
+
const axes = [cuts(as.overflowX) ? "x" : "", cuts(as.overflowY) ? "y" : ""].filter(Boolean);
|
|
426
|
+
if (!axes.length) continue;
|
|
427
|
+
const part = (r, x) => (x ? [Math.min(r.right, clip.r) - Math.max(r.left, clip.l), r.width] : [Math.min(r.bottom, clip.b) - Math.max(r.top, clip.t), r.height]);
|
|
428
|
+
let shows = false, cut = false;
|
|
429
|
+
for (const r of rects) {
|
|
430
|
+
for (const x of [true, false]) {
|
|
431
|
+
if (!axes.includes(x ? "x" : "y")) continue;
|
|
432
|
+
const [inside, whole] = part(r, x);
|
|
433
|
+
if (inside > 0.5) shows = true;
|
|
434
|
+
if (inside < whole - 1) cut = true;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
if (shows && cut) how = "some of its text is cut by the box around it";
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
if (how && !done.has(el)) (done.add(el), add("5 Typography", "clipped", el, how));
|
|
441
|
+
}
|
|
442
|
+
});
|
|
443
|
+
|
|
444
|
+
// 5: text size. Nothing under 12px; what a person acts on 14px; body 16px.
|
|
445
|
+
run("5 size", () => {
|
|
446
|
+
const act = 'a, button, label, input, select, textarea, summary, legend, nav, [role=button], [role=link], [role=tab], [role=menuitem], [role=option]';
|
|
447
|
+
const done = new Set();
|
|
448
|
+
const size = (el) => parseFloat(getComputedStyle(el).fontSize);
|
|
449
|
+
const judge = (el, text) => {
|
|
450
|
+
if (done.has(el)) return;
|
|
451
|
+
done.add(el);
|
|
452
|
+
const px = size(el);
|
|
453
|
+
const acts = !!el.closest(act);
|
|
454
|
+
const block = el.closest("p, li, dd, blockquote");
|
|
455
|
+
const body = !acts && block && !el.closest("figcaption, small, footer, aside, sup, sub") && (block.innerText || "").trim().length >= 60;
|
|
456
|
+
const [floor, role] = acts ? [14, "text a person acts on"] : body ? [16, "body text"] : [12, "text"];
|
|
457
|
+
if (px >= floor - 0.05) return;
|
|
458
|
+
const board = !!el.closest("[data-board-size]");
|
|
459
|
+
found.push({ rule: "5 Typography", check: "size", level: board ? "warn" : "hard", path: path(el), desc: desc(el), detail: `${Math.round(px * 10) / 10}px ${role}, floor ${floor}px${board ? " (data-board-size: the board's size, kept)" : ""}` });
|
|
460
|
+
};
|
|
461
|
+
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
|
|
462
|
+
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
|
463
|
+
const el = n.parentElement;
|
|
464
|
+
if (!el || !n.textContent.trim() || el instanceof SVGElement || /^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE|OPTION)$/.test(el.tagName) || !visible(el)) continue;
|
|
465
|
+
const box = el.getBoundingClientRect();
|
|
466
|
+
if (box.width <= 2 || box.height <= 2) continue; // visually hidden text, read by screen readers
|
|
467
|
+
judge(el);
|
|
468
|
+
}
|
|
469
|
+
for (const el of document.body.querySelectorAll("input:not([type=hidden]):not([type=checkbox]):not([type=radio]):not([type=range]):not([type=color]), select, textarea")) if (visible(el)) judge(el);
|
|
470
|
+
});
|
|
471
|
+
|
|
472
|
+
return { found, notChecked };
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// Colour proportion of the first screen, from a shot with the text hidden. Pictures are left out.
|
|
476
|
+
// Returns { shares: [{ hex, share, chroma }], ground, accent } in shares of the pixels counted.
|
|
477
|
+
async function colourProportion(opt) {
|
|
478
|
+
const out = [];
|
|
479
|
+
for (const el of document.body.querySelectorAll("*")) {
|
|
480
|
+
const s = getComputedStyle(el);
|
|
481
|
+
if (el.matches("img, video, canvas, picture, iframe, svg image, object, embed") || /url\(/.test(s.backgroundImage)) {
|
|
482
|
+
const r = el.getBoundingClientRect();
|
|
483
|
+
if (r.width >= 1 && r.height >= 1) out.push(r);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
const img = new Image();
|
|
487
|
+
img.src = `data:image/png;base64,${opt.png}`;
|
|
488
|
+
await img.decode();
|
|
489
|
+
const c = document.createElement("canvas");
|
|
490
|
+
c.width = img.naturalWidth;
|
|
491
|
+
c.height = img.naturalHeight;
|
|
492
|
+
const g = c.getContext("2d", { willReadFrequently: true });
|
|
493
|
+
g.drawImage(img, 0, 0);
|
|
494
|
+
const px = g.getImageData(0, 0, c.width, c.height).data;
|
|
495
|
+
const lin = (v) => ((v /= 255) <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4);
|
|
496
|
+
const lab = (r, gr, b) => {
|
|
497
|
+
const [R, G, B] = [lin(r), lin(gr), lin(b)];
|
|
498
|
+
const l = Math.cbrt(0.4122214708 * R + 0.5363325363 * G + 0.0514459929 * B), m = Math.cbrt(0.2119034982 * R + 0.6806995451 * G + 0.1073969566 * B), s2 = Math.cbrt(0.0883024619 * R + 0.2817188376 * G + 0.6299787005 * B);
|
|
499
|
+
return [0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s2, 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s2, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s2];
|
|
500
|
+
};
|
|
501
|
+
const buckets = new Map();
|
|
502
|
+
let total = 0;
|
|
503
|
+
const step = 2;
|
|
504
|
+
for (let y = 0; y < c.height; y += step)
|
|
505
|
+
for (let x = 0; x < c.width; x += step) {
|
|
506
|
+
if (out.some((r) => x >= r.left && x < r.right && y >= r.top && y < r.bottom)) continue;
|
|
507
|
+
const i = (y * c.width + x) * 4;
|
|
508
|
+
const key = ((px[i] >> 3) << 10) | ((px[i + 1] >> 3) << 5) | (px[i + 2] >> 3);
|
|
509
|
+
const b = buckets.get(key) || { n: 0, r: px[i], g: px[i + 1], b: px[i + 2] };
|
|
510
|
+
b.n++;
|
|
511
|
+
buckets.set(key, b);
|
|
512
|
+
total++;
|
|
513
|
+
}
|
|
514
|
+
if (!total) return { shares: [], ground: null, accent: null };
|
|
515
|
+
// Near colours are one colour: a bucket joins the biggest cluster within a small distance.
|
|
516
|
+
const clusters = [];
|
|
517
|
+
for (const b of [...buckets.values()].sort((a, z) => z.n - a.n)) {
|
|
518
|
+
const L = lab(b.r, b.g, b.b);
|
|
519
|
+
const near = clusters.find((k) => Math.hypot(k.lab[0] - L[0], k.lab[1] - L[1], k.lab[2] - L[2]) < 0.06);
|
|
520
|
+
if (near) near.n += b.n;
|
|
521
|
+
else clusters.push({ n: b.n, lab: L, rgb: [b.r, b.g, b.b] });
|
|
522
|
+
}
|
|
523
|
+
const hex = (rgb) => `#${rgb.map((v) => v.toString(16).padStart(2, "0")).join("")}`;
|
|
524
|
+
const shares = clusters.sort((a, z) => z.n - a.n).map((k) => ({ hex: hex(k.rgb), share: k.n / total, chroma: Math.hypot(k.lab[1], k.lab[2]), lab: k.lab }));
|
|
525
|
+
const ground = shares[0];
|
|
526
|
+
let accent = null;
|
|
527
|
+
if (opt.accent) {
|
|
528
|
+
const h = opt.accent.replace("#", "");
|
|
529
|
+
const A = lab(parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16));
|
|
530
|
+
const near = shares.filter((k) => Math.hypot(k.lab[0] - A[0], k.lab[1] - A[1], k.lab[2] - A[2]) < 0.06);
|
|
531
|
+
accent = { hex: `#${h.toLowerCase()}`, share: near.reduce((a, k) => a + k.share, 0), named: true };
|
|
532
|
+
} else {
|
|
533
|
+
// Unnamed, the accent is the most saturated colour other than the ground.
|
|
534
|
+
const pick = shares.slice(1).filter((k) => k.chroma >= 0.1 && k.share >= 0.005).sort((a, z) => z.chroma - a.chroma)[0];
|
|
535
|
+
if (pick) accent = { hex: pick.hex, share: pick.share, named: false };
|
|
536
|
+
}
|
|
537
|
+
return { shares: shares.slice(0, 4).map(({ hex: h, share }) => ({ hex: h, share })), ground: { hex: ground.hex, share: ground.share }, accent };
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
// The focus check. Called once to take the baseline, then after each Tab.
|
|
541
|
+
function focusBaseline() {
|
|
542
|
+
const sig = (el) => {
|
|
543
|
+
const s = getComputedStyle(el);
|
|
544
|
+
const pseudo = ["::before", "::after"].map((p) => {
|
|
545
|
+
const q = getComputedStyle(el, p);
|
|
546
|
+
return [q.content, q.backgroundColor, q.borderTopColor, q.borderTopWidth, q.boxShadow, q.outlineStyle, q.outlineWidth, q.opacity, q.transform].join("/");
|
|
547
|
+
});
|
|
548
|
+
return [s.outlineStyle === "none" ? "none" : [s.outlineStyle, s.outlineWidth, s.outlineColor, s.outlineOffset].join(" "), s.boxShadow, s.borderTopColor, s.borderTopWidth, s.borderBottomColor, s.borderBottomWidth, s.borderLeftColor, s.borderRightColor, s.backgroundColor, s.backgroundImage, s.color, s.textDecorationLine, s.textDecorationColor, s.filter, s.transform, s.opacity, ...pseudo].join("|");
|
|
549
|
+
};
|
|
550
|
+
const style = document.createElement("style");
|
|
551
|
+
style.textContent = "*, *::before, *::after { transition: none !important; animation: none !important; }";
|
|
552
|
+
document.head.appendChild(style);
|
|
553
|
+
const visible = (el) => el.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true, opacityProperty: true, visibilityProperty: true });
|
|
554
|
+
const sel = 'a[href], button, input:not([type=hidden]), select, textarea, summary, [tabindex]:not([tabindex^="-"]), [contenteditable=true]';
|
|
555
|
+
const tabbable = [...document.body.querySelectorAll(sel)].filter((el) => !el.disabled && visible(el) && el.getBoundingClientRect().width >= 1 && !(el.tabIndex < 0));
|
|
556
|
+
const base = new Map();
|
|
557
|
+
// What may show the focus: the control, three boxes above it, its neighbours, its labels.
|
|
558
|
+
const near = (el) => {
|
|
559
|
+
const set = [el, el.previousElementSibling, el.nextElementSibling, ...(el.labels || [])];
|
|
560
|
+
for (let n = el.parentElement, i = 0; n && i < 3; n = n.parentElement, i++) set.push(n);
|
|
561
|
+
return set.filter(Boolean);
|
|
562
|
+
};
|
|
563
|
+
for (const el of tabbable) for (const x of near(el)) if (!base.has(x)) base.set(x, sig(x));
|
|
564
|
+
window.__rules = { sig, base, near, tabbable: new Set(tabbable), seen: new Set(), bare: [] };
|
|
565
|
+
if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur();
|
|
566
|
+
window.scrollTo(0, 0);
|
|
567
|
+
return tabbable.length;
|
|
568
|
+
}
|
|
569
|
+
function focusStep() {
|
|
570
|
+
const R = window.__rules;
|
|
571
|
+
const el = document.activeElement;
|
|
572
|
+
if (!el || el === document.body || el === document.documentElement || R.seen.has(el)) return { done: true };
|
|
573
|
+
R.seen.add(el);
|
|
574
|
+
if (!R.tabbable.has(el)) return { done: false };
|
|
575
|
+
const shows = R.near(el).some((x) => R.base.has(x) && R.base.get(x) !== R.sig(x));
|
|
576
|
+
if (!shows) {
|
|
577
|
+
const path = (e) => {
|
|
578
|
+
if (e.id && document.querySelectorAll(`[id="${e.id.replace(/"/g, '\\"')}"]`).length === 1) return `#${e.id}`;
|
|
579
|
+
const parts = [];
|
|
580
|
+
for (let n = e; n && n.nodeType === 1 && n !== document.documentElement; n = n.parentElement) {
|
|
581
|
+
const same = n.parentElement ? [...n.parentElement.children].filter((c) => c.tagName === n.tagName) : [n];
|
|
582
|
+
parts.unshift(`${n.tagName.toLowerCase()}${same.length > 1 ? `:nth-of-type(${same.indexOf(n) + 1})` : ""}`);
|
|
583
|
+
}
|
|
584
|
+
return parts.join(">");
|
|
585
|
+
};
|
|
586
|
+
const t = (el.innerText || el.value || el.getAttribute("aria-label") || el.getAttribute("placeholder") || "").trim().replace(/\s+/g, " ");
|
|
587
|
+
const cls = typeof el.className === "string" ? el.className.trim().split(/\s+/).filter(Boolean).slice(0, 2).map((c) => `.${c}`).join("") : "";
|
|
588
|
+
return { done: false, bare: { path: path(el), desc: `${el.tagName.toLowerCase()}${el.id ? `#${el.id}` : ""}${cls}${t ? ` "${t.length > 30 ? `${t.slice(0, 29)}…` : t}"` : ""}` } };
|
|
589
|
+
}
|
|
590
|
+
return { done: false };
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
// ---- the run ----
|
|
594
|
+
const FIX = {
|
|
595
|
+
sideways: "Let it wrap or shrink to the screen's width, or put a wide table or strip in its own scrolling box. If it bleeds off the edge on purpose, mark it data-crop.",
|
|
596
|
+
target: "Make it at least 24×24 px (44×44 on touch in an app), or leave 24px of clear space around it.",
|
|
597
|
+
label: "Put a visible label beside the field. A placeholder, aria-label or title is not one.",
|
|
598
|
+
focus: "Give it a visible :focus-visible style with 3:1 contrast against what is around it (an outline or ring). Never outline: none alone.",
|
|
599
|
+
placeholder: "Write the real copy, in the product's voice.",
|
|
600
|
+
clipped: "Let the box grow or the text wrap, so no word is cut. If the cut is the look, mark that element data-crop.",
|
|
601
|
+
size: "Scale the step up, keeping the reference's proportions between sizes. If the board shows it this small and the person kept it, mark it data-board-size.",
|
|
602
|
+
proportion: "Let the ground dominate, the primary support and the accent stay small (about 60/30/10). If the board clearly does otherwise, keep it and say so in a note.",
|
|
603
|
+
};
|
|
604
|
+
const RULE_OF = { focus: "10 Accessibility" };
|
|
605
|
+
const found = new Map();
|
|
606
|
+
const notChecked = [];
|
|
607
|
+
const proportions = [];
|
|
608
|
+
const checkedAt = new Map();
|
|
609
|
+
const evaluate = async (expression, call) => {
|
|
610
|
+
const r = await call("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });
|
|
611
|
+
if (r.result?.exceptionDetails) throw new Error(r.result.exceptionDetails.exception?.description?.split("\n")[0] || "the page threw");
|
|
612
|
+
return r.result?.result?.value;
|
|
613
|
+
};
|
|
614
|
+
let fingerprint = "";
|
|
615
|
+
try {
|
|
616
|
+
const { result: target } = await send("Target.createTarget", { url: "about:blank" });
|
|
617
|
+
const { result: att } = await send("Target.attachToTarget", { targetId: target.targetId, flatten: true });
|
|
618
|
+
const call = (method, params, ms) => send(method, params, att.sessionId, ms);
|
|
619
|
+
await call("Page.enable");
|
|
620
|
+
await call("Emulation.setFocusEmulationEnabled", { enabled: true }).catch(() => {});
|
|
621
|
+
if (cookieArg && /^https?:/.test(url)) {
|
|
622
|
+
const cookies = cookieArg.split(";").map((p) => p.trim()).filter(Boolean).map((p) => ({ name: p.slice(0, p.indexOf("=")), value: p.slice(p.indexOf("=") + 1), url: new URL(url).origin }));
|
|
623
|
+
if (cookies.some((c) => !c.name)) {
|
|
624
|
+
console.error('cookie must be "name=value; name=value"');
|
|
625
|
+
process.exit(2);
|
|
626
|
+
}
|
|
627
|
+
await call("Network.setCookies", { cookies });
|
|
628
|
+
}
|
|
629
|
+
const record1 = (item, w, check) => {
|
|
630
|
+
const key = `${item.rule || RULE_OF[check] || ""}|${check}|${item.path}`;
|
|
631
|
+
if (!found.has(key)) found.set(key, { rule: item.rule || RULE_OF[check], check, level: item.level || "hard", path: item.path, desc: item.desc, detail: item.detail || "", widths: [] });
|
|
632
|
+
const f = found.get(key);
|
|
633
|
+
if (!f.widths.includes(w)) f.widths.push(w);
|
|
634
|
+
};
|
|
635
|
+
for (const w of widths) {
|
|
636
|
+
await call("Emulation.setDeviceMetricsOverride", { width: w, height: w < 768 ? 844 : 900, deviceScaleFactor: 1, mobile: false });
|
|
637
|
+
const nav = await call("Page.navigate", { url });
|
|
638
|
+
if (nav.result?.errorText) throw new Error(`could not open ${url}: ${nav.result.errorText}`);
|
|
639
|
+
for (let i = 0; i < 100 && (await evaluate("document.readyState", call).catch(() => "")) !== "complete"; i++) await sleep(200);
|
|
640
|
+
await evaluate("document.fonts ? document.fonts.ready.then(() => true) : true", call).catch(() => true);
|
|
641
|
+
await sleep(wait);
|
|
642
|
+
const landed = await evaluate("location.href", call);
|
|
643
|
+
const where = (href) => {
|
|
644
|
+
const u = new URL(href);
|
|
645
|
+
return `${u.origin}${u.pathname.replace(/\/$/, "")}`;
|
|
646
|
+
};
|
|
647
|
+
if (where(landed) !== where(url)) throw new Error(`the page landed on ${landed}, not ${url}.${/^https?:/.test(landed) ? " Behind a login? Pass --cookie." : ""}`);
|
|
648
|
+
if (!fingerprint) fingerprint = createHash("sha1").update(await evaluate(`(${pageFingerprint})()`, call)).digest("hex");
|
|
649
|
+
const out = await evaluate(`(${staticChecks})(${JSON.stringify({ app, width: w })})`, call);
|
|
650
|
+
for (const f of out.found) record1(f, w, f.check);
|
|
651
|
+
for (const n of out.notChecked) notChecked.push({ check: n.check, width: w, why: n.why });
|
|
652
|
+
// Focus, with real Tab presses so that :focus-visible applies.
|
|
653
|
+
try {
|
|
654
|
+
const n = await evaluate(`(${focusBaseline})()`, call);
|
|
655
|
+
for (let i = 0; i < Math.min(n + 2, 70); i++) {
|
|
656
|
+
for (const type of ["rawKeyDown", "keyUp"]) await call("Input.dispatchKeyEvent", { type, key: "Tab", code: "Tab", windowsVirtualKeyCode: 9, nativeVirtualKeyCode: 9 });
|
|
657
|
+
const step = await evaluate(`(${focusStep})()`, call);
|
|
658
|
+
if (step.bare) record1({ path: step.bare.path, desc: step.bare.desc, detail: "takes focus and shows no change" }, w, "focus");
|
|
659
|
+
if (step.done) break;
|
|
660
|
+
}
|
|
661
|
+
} catch (e) {
|
|
662
|
+
notChecked.push({ check: "10 focus", width: w, why: String(e.message).slice(0, 80) });
|
|
663
|
+
}
|
|
664
|
+
// Colour proportion, last: it hides the text. The first screen only, as a person meets it.
|
|
665
|
+
try {
|
|
666
|
+
await evaluate(`(() => {
|
|
667
|
+
window.scrollTo(0, 0);
|
|
668
|
+
if (document.activeElement) document.activeElement.blur();
|
|
669
|
+
const s = document.createElement("style");
|
|
670
|
+
s.textContent = "* { color: transparent !important; text-shadow: none !important; -webkit-text-fill-color: transparent !important; text-decoration-color: transparent !important; caret-color: transparent !important; outline: none !important; }";
|
|
671
|
+
document.head.appendChild(s);
|
|
672
|
+
return new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(() => done(true))));
|
|
673
|
+
})()`, call);
|
|
674
|
+
const shot = await call("Page.captureScreenshot", { format: "png" });
|
|
675
|
+
const p = await evaluate(`(${colourProportion})(${JSON.stringify({ png: shot.result.data, accent: accentArg })})`, call);
|
|
676
|
+
proportions.push({ width: w, ...p });
|
|
677
|
+
const pct = (x) => `${Math.round(x * 100)}%`;
|
|
678
|
+
if (p.ground && p.ground.share < 0.5) record1({ rule: "6 Colour", level: "soft", path: "ground", desc: "first screen", detail: `the ground (${p.ground.hex}) covers ${pct(p.ground.share)}; it should dominate (about 60%)` }, w, "proportion");
|
|
679
|
+
if (p.accent && p.accent.share > 0.2) record1({ rule: "6 Colour", level: "soft", path: "accent", desc: "first screen", detail: `the accent (${p.accent.hex}${p.accent.named ? "" : ", read as the most saturated colour"}) covers ${pct(p.accent.share)}; it should stay small (about 10%)` }, w, "proportion");
|
|
680
|
+
} catch (e) {
|
|
681
|
+
notChecked.push({ check: "6 proportion", width: w, why: String(e.message).slice(0, 80) });
|
|
682
|
+
}
|
|
683
|
+
checkedAt.set(w, true);
|
|
684
|
+
}
|
|
685
|
+
ws.close();
|
|
686
|
+
} catch (e) {
|
|
687
|
+
couldNot(e.message);
|
|
688
|
+
}
|
|
689
|
+
clearTimeout(watchdog);
|
|
690
|
+
finished = true;
|
|
691
|
+
|
|
692
|
+
// ---- the verdict ----
|
|
693
|
+
const id = (f) => createHash("sha1").update(`${f.rule}|${f.check}|${f.path}`).digest("hex").slice(0, 6);
|
|
694
|
+
const rows = [...found.values()].map((f) => ({ ...f, id: id(f), where: `${f.desc}: ${f.detail} (at ${f.widths.sort((a, b) => b - a).join(", ")})` }));
|
|
695
|
+
const waived = rows.filter((f) => waivers.some((w) => w.screen === screen && w.id === f.id));
|
|
696
|
+
// Hard findings block. Warnings (the board's own small text) and soft ones are reported only.
|
|
697
|
+
const open = rows.filter((f) => !waived.includes(f) && f.level === "hard");
|
|
698
|
+
const reported = rows.filter((f) => !waived.includes(f) && f.level !== "hard");
|
|
699
|
+
|
|
700
|
+
// A run on a changed page is a round; the same page again is the same round. Each url of a screen
|
|
701
|
+
// (a state: ?menu=open) keeps its own fingerprint, so the first look at another state is part of
|
|
702
|
+
// the round it is in, not a new one: only a change since that url's last run counts.
|
|
703
|
+
const key = url ? url.split("#")[0] : "";
|
|
704
|
+
const fps = record.fps || (record.fp ? { [key]: record.fp } : {});
|
|
705
|
+
const used = record.round || 0;
|
|
706
|
+
const seen = Object.hasOwn(fps, key);
|
|
707
|
+
const changed = seen && fps[key] !== fingerprint;
|
|
708
|
+
const round = !used ? 1 : changed && used < limit ? used + 1 : used;
|
|
709
|
+
const beyond = changed && used >= limit;
|
|
710
|
+
const closed = changed ? null : record.closed || null;
|
|
711
|
+
rounds[screen] = { round, fps: { ...fps, [key]: fingerprint }, at: today(), failed: 0, found: rows.map((f) => ({ id: f.id, rule: f.rule, level: f.level, where: f.where })), ...(closed ? { closed } : {}) };
|
|
712
|
+
writeJson(roundsFile, rounds);
|
|
713
|
+
|
|
714
|
+
const widthNote = widths.join(" and ");
|
|
715
|
+
const checks = [["13 sideways", "13 sideways scroll (phone width)"], ["10 targets", `10 targets (${app ? "44 on phone, 24 otherwise" : "24"})`], ["10 labels", "10 visible labels"], ["10 focus", "10 focus shown (not its contrast)"], ["11 copy", "11 placeholder copy"], ["5 clipped", "5 clipped text (data-crop skipped)"], ["5 size", "5 text size (12 / 14 / 16)"], ["6 proportion", "6 colour proportion (soft)"]];
|
|
716
|
+
if (!widths.some((w) => w <= 480)) notChecked.push({ check: "13 sideways", width: widths.join(","), why: "no phone width (480 or less) in --widths" });
|
|
717
|
+
const done = checks.filter(([key]) => !notChecked.some((n) => n.check === key)).map(([, label]) => label);
|
|
718
|
+
if (json) {
|
|
719
|
+
console.log(JSON.stringify({ screen, round, limit, roundsUsedUp: round >= limit && open.length > 0, closed, open, reported, waived, proportions, notChecked, checked: done }, null, 1));
|
|
720
|
+
} else {
|
|
721
|
+
console.log(`rules: ${screen} at ${widthNote}, round ${round} of ${limit}${beyond ? " (this page changed after the last round: not counted)" : changed || !used ? "" : seen ? " (the page has not changed since the last run)" : " (another state of this screen: same round)"}`);
|
|
722
|
+
if (closed) console.log(`closed by the person on ${closed.at}: "${closed.words}". Do not fix more. Report what is open.`);
|
|
723
|
+
if (open.length) {
|
|
724
|
+
console.log("| Rule | Hard/soft | Where | Fix |\n|---|---|---|---|");
|
|
725
|
+
// A long page can fail one check dozens of times. Ten rows of each are shown, the rest counted: --json has all.
|
|
726
|
+
const shown = {};
|
|
727
|
+
for (const f of open) {
|
|
728
|
+
shown[f.check] = (shown[f.check] || 0) + 1;
|
|
729
|
+
if (shown[f.check] <= 10) console.log(`| ${f.rule} | hard | ${f.where.replace(/\|/g, "/")} [${f.id}] | ${FIX[f.check]} |`);
|
|
730
|
+
}
|
|
731
|
+
for (const [check, n] of Object.entries(shown)) if (n > 10) console.log(`(${n - 10} more ${check} findings with the same fix, not listed: fix these, run again, or use --json for all)`);
|
|
732
|
+
} else console.log(`passes: ${done.join("; ")}`);
|
|
733
|
+
if (reported.length) {
|
|
734
|
+
console.log("reported, not blocking:\n| Rule | Hard/soft | Where | Fix |\n|---|---|---|---|");
|
|
735
|
+
for (const f of reported.slice(0, 20)) console.log(`| ${f.rule} | ${f.level} | ${f.where.replace(/\|/g, "/")} [${f.id}] | ${FIX[f.check]} |`);
|
|
736
|
+
if (reported.length > 20) console.log(`(${reported.length - 20} more, not listed: --json has all)`);
|
|
737
|
+
}
|
|
738
|
+
for (const p of proportions) if (p.ground) console.log(`colour proportion at ${p.width}: ground ${p.ground.hex} ${Math.round(p.ground.share * 100)}%${p.shares.slice(1).map((k) => `, ${k.hex} ${Math.round(k.share * 100)}%`).join("")}${p.accent ? `; accent ${p.accent.hex} ${Math.round(p.accent.share * 100)}%` : ""}`);
|
|
739
|
+
if (waived.length) {
|
|
740
|
+
console.log(`waived (${waived.length}), listed so the person sees them:`);
|
|
741
|
+
for (const f of waived) console.log(`- ${f.rule}: ${f.where} [${f.id}]: ${waivers.find((w) => w.screen === screen && w.id === f.id).reason}`);
|
|
742
|
+
}
|
|
743
|
+
for (const n of notChecked) console.log(`not checked: ${n.check} at ${n.width} (${n.why})`);
|
|
744
|
+
if (open.length && !closed && round >= limit) console.log("rounds used up: stop fixing. Report the findings above as open.");
|
|
745
|
+
else if (open.length && !closed) console.log(`${open.length} hard finding${open.length > 1 ? "s" : ""} open. Fix them (or waive one that is false: --waive <id> --reason "…"), then run again.`);
|
|
746
|
+
}
|
|
747
|
+
process.exit(open.length && !closed ? 1 : notChecked.length ? 3 : 0);
|