@a.incantalupo/web-tools 0.1.0 → 0.3.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.
@@ -3,7 +3,10 @@
3
3
  // mid-range phone, and a page can score well while a retina laptop downloads four times
4
4
  // the photos.
5
5
  //
6
- // Usage: stack-tools images <url...> [--budget 600]
6
+ // Usage: stack-tools images <url...> [--budget 600] [--brief | --full | --json]
7
+ //
8
+ // --brief (or STACK_TOOLS_OUTPUT=brief): one line per page, the failures in full, the
9
+ // warnings as a count; --json: the same as JSON; --full: every finding (the default).
7
10
  //
8
11
  // Fails (exit 1) on what is always wrong: an image that didn't load, or a lazy-loaded
9
12
  // largest image (LCP). Warns on what is usually wrong: a file much larger than its slot,
@@ -12,12 +15,13 @@ import { chromium } from "playwright-core";
12
15
  import { homedir } from "node:os";
13
16
  import { join } from "node:path";
14
17
  import { parseArgs } from "node:util";
18
+ import { outputMode, outputOptions, outputUsage, Report } from "../report.js";
15
19
  const { values, positionals: urls } = parseArgs({
16
20
  allowPositionals: true,
17
- options: { budget: { type: "string", default: "600" } },
21
+ options: { budget: { type: "string", default: "600" }, ...outputOptions },
18
22
  });
19
23
  if (!urls.length) {
20
- console.error("Usage: stack-tools images <url...> [--budget 600]");
24
+ console.error(`Usage: stack-tools images <url...> [--budget 600] ${outputUsage}`);
21
25
  process.exit(1);
22
26
  }
23
27
  const budget = Number(values.budget);
@@ -41,11 +45,12 @@ const browser = await chromium.launch({
41
45
  executablePath: process.env.CHROME_PATH ??
42
46
  join(homedir(), ".cache/ms-playwright/chromium-1194/chrome-linux/chrome"),
43
47
  });
44
- let failures = 0;
45
- let warnings = 0;
48
+ const out = new Report("images", urls, outputMode(values));
46
49
  const kb = (bytes) => `${Math.round(bytes / 1024)} KB`;
47
50
  for (const url of urls) {
48
- console.log(`\n${url}`);
51
+ const pg = out.page(url);
52
+ const firsts = [];
53
+ out.say(`\n${url}`);
49
54
  for (const [name, options] of Object.entries(screens)) {
50
55
  const context = await browser.newContext(options);
51
56
  const page = await context.newPage();
@@ -116,48 +121,45 @@ for (const url of urls) {
116
121
  const dpr = options.deviceScaleFactor;
117
122
  const notes = [];
118
123
  const broken = slots.filter((s) => s.broken || failed.has(s.url));
119
- if (broken.length) {
120
- failures++;
121
- notes.push(`FAIL ${broken.length} image(s) didn't load, e.g. ${broken[0].url.split("/").slice(-2).join("/")}`);
122
- }
123
- if (lcp?.lazy) {
124
- failures++;
125
- notes.push(`FAIL the largest image is lazy-loaded (${lcp.what})`);
126
- }
124
+ if (broken.length)
125
+ notes.push(pg.fail("broken", out.mode === "full"
126
+ ? `${broken.length} image(s) didn't load, e.g. ${broken[0].url.split("/").slice(-2).join("/")}`
127
+ : `${broken.length} image(s) didn't load: ${broken
128
+ .slice(0, 12)
129
+ .map((s) => s.url.split("/").slice(-2).join("/"))
130
+ .join(", ")}`, name));
131
+ if (lcp?.lazy)
132
+ notes.push(pg.fail("lazy-lcp", `the largest image is lazy-loaded (${lcp.what})`, name));
127
133
  // Much more file than the slot can show, and heavy enough to matter.
128
134
  const big = slots.filter((s) => s.css > 0 &&
129
135
  s.file / (s.css * dpr) > 2 &&
130
136
  (bytes.get(s.url) ?? 0) > 40_000);
131
- if (big.length) {
132
- warnings++;
133
- notes.push(`warn ${big.length} file(s) over twice their slot, e.g. ${big[0].file} px for ${big[0].css} px shown (${kb(bytes.get(big[0].url) ?? 0)})`);
134
- }
137
+ if (big.length)
138
+ notes.push(pg.warn("oversized", `${big.length} file(s) over twice their slot, e.g. ${big[0].file} px for ${big[0].css} px shown (${kb(bytes.get(big[0].url) ?? 0)})`, name));
135
139
  // Stretched: under 1.5 file pixels per CSS pixel on a dense screen (the eye stops
136
140
  // gaining around 2x, so a 3x phone isn't held to 3x), under 0.9 on a 1x one.
137
141
  const soft = slots.filter((s) => s.css >= 200 &&
138
142
  s.file > 0 &&
139
143
  s.file / s.css < (dpr >= 2 ? 1.5 : 0.9));
140
- if (soft.length) {
141
- warnings++;
142
- notes.push(`warn ${soft.length} photo(s) stretched, e.g. ${soft[0].file} px for ${soft[0].css} px at ${dpr}x`);
143
- }
144
- if (first / 1024 > budget) {
145
- warnings++;
146
- notes.push(`warn images before any scroll over ${budget} KB`);
147
- }
144
+ if (soft.length)
145
+ notes.push(pg.warn("stretched", `${soft.length} photo(s) stretched, e.g. ${soft[0].file} px for ${soft[0].css} px at ${dpr}x`, name));
146
+ if (first / 1024 > budget)
147
+ notes.push(pg.warn("over-budget", `images before any scroll over ${budget} KB`, name));
148
+ firsts.push(Math.round(first / 1024));
148
149
  const picks = new Map();
149
150
  for (const s of slots.filter((s) => s.css >= 60 && bytes.has(s.url))) {
150
151
  const key = `${s.css}→${s.file}`;
151
152
  picks.set(key, (picks.get(key) ?? 0) + 1);
152
153
  }
153
- console.log(` ${name.padEnd(17)} first screen ${kb(first).padStart(7)}, whole page ${kb(total).padStart(7)}, largest: ${lcp?.what ?? "?"}`);
154
- console.log(` ${"".padEnd(17)} shown→file px: ${[...picks].map(([k, n]) => `${n}× ${k}`).join(", ") || "none"}`);
154
+ out.say(` ${name.padEnd(17)} first screen ${kb(first).padStart(7)}, whole page ${kb(total).padStart(7)}, largest: ${lcp?.what ?? "?"}`);
155
+ out.say(` ${"".padEnd(17)} shown→file px: ${[...picks].map(([k, n]) => `${n}× ${k}`).join(", ") || "none"}`);
155
156
  for (const note of notes)
156
- console.log(` ${"".padEnd(17)} ${note}`);
157
+ out.say(` ${"".padEnd(17)} ${note}`);
157
158
  await context.close();
158
159
  }
160
+ // Phone, laptop, monitor: what downloads before any scroll.
161
+ pg.key(`first screen ${firsts.join("/")} KB`);
162
+ pg.end();
159
163
  }
160
164
  await browser.close();
161
- console.log(`\n${failures} failure(s), ${warnings} warning(s) on ${urls.length} page(s).`);
162
- if (failures)
163
- process.exitCode = 1;
165
+ out.done();
package/dist/refs/text.js CHANGED
@@ -1,21 +1,29 @@
1
1
  // Can everyone read this page? The words (reading ease, long sentences), how big and how
2
2
  // dark the text is, whether the fields and the things you tap are large and visible
3
- // enough. Rules and reasons: web-stack-kb, stack-writing-readable-accessible-ui.
3
+ // enough (WCAG 2.2 AA, plus a stricter bar for small text).
4
4
  //
5
- // Usage: stack-tools text <url...> [--verbose] [--login <email>]
5
+ // Usage: stack-tools text <url...> [--verbose] [--login <email>] [--brief | --full | --json]
6
+ //
7
+ // --brief (or STACK_TOOLS_OUTPUT=brief): one line per page, the failures in full, the
8
+ // warnings as a count; --json: the same as JSON; --full: every finding (the default).
6
9
  //
7
10
  // --login signs in at /admin/login of the first URL's site first (password from
8
11
  // CHECK_PASSWORD), so admin pages can be measured. Use a login on the dev database.
9
12
  //
10
- // Each page is opened on a phone (390 px) and a desktop (1440 px), plus once at 320 px
11
- // for sideways scroll.
13
+ // Each page is opened on a phone (390 px) and a desktop (1440 px), once at 320 px for
14
+ // sideways scroll, and once on the phone with the reader's text size raised to 130, 150
15
+ // and 200% (the browser's default font size, as a phone's text setting does to a page
16
+ // with <meta name="text-scale" content="scale">, and as Chrome's own text size does).
12
17
  //
13
18
  // Fails (exit 1) on the floors: text under 4.5:1 on a plain background (3:1 from 24 px,
14
19
  // or 18.66 px bold), a target under 24 px, a field under 16 px (an iPhone zooms the page
15
- // on focus), sideways scroll at 320 px.
20
+ // on focus), sideways scroll at 320 px; with text at 200% (WCAG 1.4.4): text cut off by
21
+ // a box that doesn't grow, sideways scroll on the phone.
16
22
  // Warns on the rules we set ourselves: reading ease under 60 (Gulpease), a sentence over
17
23
  // 25 words, text under 16 px, small text under 7:1, text on a bright part of a photo,
18
- // a field edge under 3:1, a target under 44 px on the phone, lines over 80 characters.
24
+ // a field edge under 3:1, a target under 44 px on the phone, lines over 80 characters;
25
+ // with text at 200%: texts that start to overlap, text shortened with "…" or a line
26
+ // clamp, text that keeps its size (px), no text-scale meta.
19
27
  //
20
28
  // Text inside an element marked `data-quoted` (a customer's review, the client's own
21
29
  // description) is someone else's writing: its words are not measured.
@@ -23,15 +31,17 @@ import { chromium } from "playwright-core";
23
31
  import { homedir } from "node:os";
24
32
  import { join } from "node:path";
25
33
  import { parseArgs } from "node:util";
34
+ import { outputMode, outputOptions, outputUsage, Report } from "../report.js";
26
35
  const { values, positionals: urls } = parseArgs({
27
36
  allowPositionals: true,
28
37
  options: {
29
38
  verbose: { type: "boolean", default: false },
30
39
  login: { type: "string" },
40
+ ...outputOptions,
31
41
  },
32
42
  });
33
43
  if (!urls.length) {
34
- console.error("Usage: stack-tools text <url...> [--verbose] [--login <email>]");
44
+ console.error(`Usage: stack-tools text <url...> [--verbose] [--login <email>] ${outputUsage}`);
35
45
  process.exit(1);
36
46
  }
37
47
  const screens = {
@@ -82,7 +92,10 @@ function measure() {
82
92
  const r = el.getBoundingClientRect();
83
93
  if (r.width < 1 || r.height < 1)
84
94
  return false;
85
- if (r.right < 0 || r.left > innerWidth + 5)
95
+ if (r.right < 0 || r.left > document.documentElement.clientWidth + 5)
96
+ return false;
97
+ // Skipped by the browser (a closed <details>' answer, content-visibility: hidden).
98
+ if (!el.checkVisibility())
86
99
  return false;
87
100
  for (let e = el; e; e = e.parentElement) {
88
101
  const s = getComputedStyle(e);
@@ -281,9 +294,190 @@ function measure() {
281
294
  lines,
282
295
  blocks: [...new Set(blocks)],
283
296
  quoted,
284
- overflow: document.documentElement.scrollWidth - innerWidth,
297
+ overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
298
+ };
299
+ }
300
+ /** Runs in the page. The first call picks the text elements; later calls measure the
301
+ * same ones, after the text size has changed. */
302
+ function probe(first) {
303
+ const w = window;
304
+ const visible = (el) => {
305
+ const r = el.getBoundingClientRect();
306
+ if (r.width < 1 || r.height < 1)
307
+ return false;
308
+ if (r.right < 0 || r.left > document.documentElement.clientWidth + 5)
309
+ return false;
310
+ // Skipped by the browser (a closed <details>' answer, content-visibility: hidden).
311
+ if (!el.checkVisibility())
312
+ return false;
313
+ for (let e = el; e; e = e.parentElement) {
314
+ const s = getComputedStyle(e);
315
+ if (s.visibility === "hidden" || s.display === "none")
316
+ return false;
317
+ if (Number(s.opacity) < 0.05)
318
+ return false;
319
+ if (e.getAttribute("aria-hidden") === "true")
320
+ return false;
321
+ }
322
+ return true;
323
+ };
324
+ if (first || !w.__bigText) {
325
+ const els = new Set();
326
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
327
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
328
+ const el = node.parentElement;
329
+ if (!node.textContent?.trim() || !el)
330
+ continue;
331
+ if (el.closest("svg, script, style, noscript, option"))
332
+ continue;
333
+ if (!els.has(el) && visible(el))
334
+ els.add(el);
335
+ }
336
+ w.__bigText = [...els];
337
+ }
338
+ const clips = (v) => v === "hidden" || v === "clip";
339
+ // innerText is empty for some rendered text (inside a closed <details>...): fall back.
340
+ const textOf = (el) => (el.innerText?.trim() || el.textContent || "")
341
+ .replace(/\s+/g, " ")
342
+ .trim();
343
+ const rows = w.__bigText.map((el) => {
344
+ const lines = [];
345
+ const range = document.createRange();
346
+ for (const node of el.childNodes) {
347
+ if (node.nodeType !== Node.TEXT_NODE || !node.textContent?.trim())
348
+ continue;
349
+ range.selectNodeContents(node);
350
+ for (const r of range.getClientRects())
351
+ if (r.width >= 1 && r.height >= 1)
352
+ lines.push([r.x, r.y + scrollY, r.width, r.height]);
353
+ }
354
+ let clip = 0;
355
+ if (lines.length) {
356
+ const top = Math.min(...lines.map((l) => l[1] - scrollY));
357
+ const bottom = Math.max(...lines.map((l) => l[1] - scrollY + l[3]));
358
+ const left = Math.min(...lines.map((l) => l[0]));
359
+ const right = Math.max(...lines.map((l) => l[0] + l[2]));
360
+ for (let a = el; a && a !== document.body; a = a.parentElement) {
361
+ const s = getComputedStyle(a);
362
+ const y = clips(s.overflowY);
363
+ const x = clips(s.overflowX);
364
+ if (!x && !y)
365
+ continue;
366
+ const r = a.getBoundingClientRect();
367
+ const inTop = r.top + a.clientTop;
368
+ const inLeft = r.left + a.clientLeft;
369
+ const cut = (y && (bottom > inTop + a.clientHeight + 2 || top < inTop - 2)) ||
370
+ (x && (right > inLeft + a.clientWidth + 2 || left < inLeft - 2));
371
+ if (!cut)
372
+ continue;
373
+ const lineClamp = s.webkitLineClamp ??
374
+ "none";
375
+ clip = lineClamp !== "none" || s.textOverflow === "ellipsis" ? 2 : 1;
376
+ break;
377
+ }
378
+ }
379
+ return {
380
+ text: textOf(el),
381
+ size: parseFloat(getComputedStyle(el).fontSize),
382
+ clip,
383
+ lines,
384
+ };
385
+ });
386
+ // The layout viewport: on a phone innerWidth grows to a page that's too wide.
387
+ const vw = document.documentElement.clientWidth;
388
+ const overflow = document.documentElement.scrollWidth - vw;
389
+ const culprits = [];
390
+ if (overflow > 1) {
391
+ // How far right an element reaches: its box, or its own text when a long word
392
+ // runs out of the box (the box stays put, the page still scrolls).
393
+ const reach = (el) => {
394
+ let right = el.getBoundingClientRect().right;
395
+ // A box that clips its own text (a visually hidden label) holds it.
396
+ if (getComputedStyle(el).overflowX !== "visible")
397
+ return right;
398
+ const range = document.createRange();
399
+ for (const node of el.childNodes)
400
+ if (node.nodeType === Node.TEXT_NODE && node.textContent?.trim()) {
401
+ range.selectNodeContents(node);
402
+ right = Math.max(right, range.getBoundingClientRect().right);
403
+ }
404
+ return right;
405
+ };
406
+ const out = new Map();
407
+ for (const el of document.body.querySelectorAll("*")) {
408
+ const right = reach(el);
409
+ if (right <= vw + 1)
410
+ continue;
411
+ // Inside a box that scrolls or clips on its own (a strip of cards): not the page's.
412
+ let held = false;
413
+ for (let a = el.parentElement; a && a !== document.body; a = a.parentElement)
414
+ if (getComputedStyle(a).overflowX !== "visible" &&
415
+ a.getBoundingClientRect().right <= vw + 1) {
416
+ held = true;
417
+ break;
418
+ }
419
+ if (!held)
420
+ out.set(el, right);
421
+ }
422
+ for (const [el, right] of out) {
423
+ if ([...el.children].some((c) => out.has(c)))
424
+ continue;
425
+ const cls = (el.getAttribute("class") ?? "").split(/\s+/).filter(Boolean);
426
+ const text = textOf(el);
427
+ culprits.push(`${el.tagName.toLowerCase()}${cls.length ? `.${cls.slice(0, 2).join(".")}` : ""}` +
428
+ `${text ? ` "${text.slice(0, 24)}"` : ""} to ${Math.round(right)} px`);
429
+ }
430
+ }
431
+ return {
432
+ rows,
433
+ root: parseFloat(getComputedStyle(document.documentElement).fontSize),
434
+ meta: !!document.querySelector('meta[name="text-scale" i][content="scale" i]'),
435
+ overflow,
436
+ culprits: [...new Set(culprits)],
285
437
  };
286
438
  }
439
+ /** Pairs of texts whose lines cross by more than a sliver. A clipped text is left out:
440
+ * its hidden lines still have boxes (a clamped title's third line under the facts). */
441
+ function overlaps(p) {
442
+ const pairs = new Set();
443
+ const all = p.rows.flatMap((row, i) => row.clip ? [] : row.lines.map((l) => ({ i, l })));
444
+ all.sort((a, b) => a.l[1] - b.l[1]);
445
+ for (let a = 0; a < all.length; a++)
446
+ for (let b = a + 1; b < all.length; b++) {
447
+ const [x1, y1, w1, h1] = all[a].l;
448
+ const [x2, y2, w2, h2] = all[b].l;
449
+ if (y2 >= y1 + h1)
450
+ break;
451
+ if (all[a].i === all[b].i)
452
+ continue;
453
+ const dx = Math.min(x1 + w1, x2 + w2) - Math.max(x1, x2);
454
+ const dy = Math.min(y1 + h1, y2 + h2) - Math.max(y1, y2);
455
+ // Line boxes of stacked lines touch: a third of the shorter line is a real overlap.
456
+ if (dx > 2 && dy > Math.min(h1, h2) / 3)
457
+ pairs.add([all[a].i, all[b].i].sort((m, n) => m - n).join(","));
458
+ }
459
+ return pairs;
460
+ }
461
+ const scales = [1.3, 1.5, 2];
462
+ async function bigText(page) {
463
+ const cdp = await page.context().newCDPSession(page);
464
+ const base = await page.evaluate(probe, true);
465
+ const baseOverlaps = overlaps(base);
466
+ const runs = [];
467
+ for (const scale of scales) {
468
+ await cdp.send("Page.setFontSizes", {
469
+ fontSizes: { standard: Math.round(16 * scale), fixed: Math.round(13 * scale) },
470
+ });
471
+ await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => setTimeout(r, 150))));
472
+ const p = await page.evaluate(probe, false);
473
+ runs.push({
474
+ scale,
475
+ p,
476
+ overlaps: [...overlaps(p)].filter((k) => !baseOverlaps.has(k)),
477
+ });
478
+ }
479
+ return { base, runs };
480
+ }
287
481
  // --- The words (Italian) ---
288
482
  const words = (s) => s.match(/[\p{L}\p{N}][\p{L}\p{N}'’.-]*[\p{L}\p{N}]|[\p{L}\p{N}]/gu) ?? [];
289
483
  const letters = (s) => (s.match(/\p{L}/gu) ?? []).length;
@@ -357,8 +551,9 @@ const browser = await chromium.launch({
357
551
  executablePath: process.env.CHROME_PATH ??
358
552
  join(homedir(), ".cache/ms-playwright/chromium-1194/chrome-linux/chrome"),
359
553
  });
360
- let failures = 0;
361
- let warnings = 0;
554
+ const out = new Report("text", urls, outputMode(values));
555
+ // The short forms name every example of a failure: the reader fixes from that line alone.
556
+ const every = out.mode === "full" ? undefined : 12;
362
557
  const pad = "".padEnd(15);
363
558
  const short = (s, n = 44) => (s.length > n ? `${s.slice(0, n)}…` : s);
364
559
  const list = (rows, show, n = 3) => rows
@@ -413,7 +608,8 @@ async function open(url, options) {
413
608
  return { context, page };
414
609
  }
415
610
  for (const url of urls) {
416
- console.log(`\n${url}`);
611
+ const pg = out.page(url);
612
+ out.say(`\n${url}`);
417
613
  let first = true;
418
614
  for (const [name, options] of Object.entries(screens)) {
419
615
  const phone = name.startsWith("phone");
@@ -421,18 +617,19 @@ for (const url of urls) {
421
617
  const m = await page.evaluate(measure);
422
618
  const photos = await onPhotos(page, await context.newPage(), m.texts);
423
619
  await context.close();
424
- const fail = (note) => (failures++, `FAIL ${note}`);
425
- const warn = (note) => (warnings++, `warn ${note}`);
620
+ const fail = (kind, note) => pg.fail(kind, note, name);
621
+ const warn = (kind, note) => pg.warn(kind, note, name);
426
622
  const notes = [];
427
623
  if (first) {
428
624
  first = false;
429
625
  const p = prose(m.blocks);
430
626
  const score = p.score == null ? "no prose" : `reading ease ${Math.round(p.score)}`;
431
- console.log(` ${"words".padEnd(15)}${score} on ${p.sentences} sentence(s)${m.quoted ? `, ${m.quoted} quoted block(s) left out` : ""}`);
627
+ pg.key(score);
628
+ out.say(` ${"words".padEnd(15)}${score} on ${p.sentences} sentence(s)${m.quoted ? `, ${m.quoted} quoted block(s) left out` : ""}`);
432
629
  if (p.score != null && p.score < 60)
433
- console.log(` ${pad}${warn("reading ease under 60 (hard with the licenza media)")}`);
630
+ out.say(` ${pad}${pg.warn("reading-ease", "reading ease under 60 (hard with the licenza media)", "words")}`);
434
631
  if (p.long.length)
435
- console.log(` ${pad}${warn(`${p.long.length} sentence(s) over 25 words: ${list(p.long, (x) => `${x.n} "${short(x.s)}"`, 2)}`)}`);
632
+ out.say(` ${pad}${pg.warn("long-sentence", `${p.long.length} sentence(s) over 25 words: ${list(p.long, (x) => `${x.n} "${short(x.s)}"`, 2)}`, "words")}`);
436
633
  }
437
634
  const total = m.texts.reduce((a, t) => a + t.chars, 0) || 1;
438
635
  const share = (rows) => Math.round((100 * rows.reduce((a, t) => a + t.chars, 0)) / total);
@@ -442,46 +639,96 @@ for (const url of urls) {
442
639
  const pale = plain.filter((t) => t.size < 16 && t.ratio >= 4.5 && t.ratio < 7);
443
640
  const lowPhoto = photos.filter((p) => p.ratio < (p.text.large ? 3 : 4.5));
444
641
  if (low.length)
445
- notes.push(fail(`${low.length} text(s) under 4.5:1: ${list(low, (t) => `${t.ratio.toFixed(1)} "${short(t.text, 24)}"`)}`));
642
+ notes.push(fail("contrast", `${low.length} text(s) under 4.5:1: ${list(low, (t) => `${t.ratio.toFixed(1)} "${short(t.text, 24)}"`, every)}`));
446
643
  if (small.length)
447
- notes.push(warn(`${share(small)}% of the text under 16 px (${share(m.texts.filter((t) => t.size < 14))}% under 14 px)`));
644
+ notes.push(warn("small-text", `${share(small)}% of the text under 16 px (${share(m.texts.filter((t) => t.size < 14))}% under 14 px)`));
448
645
  if (pale.length)
449
- notes.push(warn(`${pale.length} small text(s) under 7:1: ${list(pale, (t) => `${t.ratio.toFixed(1)} "${short(t.text, 24)}"`, 2)}`));
646
+ notes.push(warn("pale-small-text", `${pale.length} small text(s) under 7:1: ${list(pale, (t) => `${t.ratio.toFixed(1)} "${short(t.text, 24)}"`, 2)}`));
450
647
  if (lowPhoto.length)
451
- notes.push(warn(`text on a bright part of a photo: ${list(lowPhoto, (p) => `${p.ratio.toFixed(1)} "${short(p.text.text, 24)}"`)}`));
648
+ notes.push(warn("text-on-photo", `text on a bright part of a photo: ${list(lowPhoto, (p) => `${p.ratio.toFixed(1)} "${short(p.text.text, 24)}"`)}`));
452
649
  const smallFields = m.fields.filter((f) => f.size < 16);
453
650
  const faint = m.fields.filter((f) => f.edge < 3);
454
651
  if (smallFields.length)
455
- notes.push(fail(`${smallFields.length} field(s) under 16 px: ${list(smallFields, (f) => `"${f.what}" ${f.size} px`)}`));
652
+ notes.push(fail("field-size", `${smallFields.length} field(s) under 16 px: ${list(smallFields, (f) => `"${f.what}" ${f.size} px`, every)}`));
456
653
  if (faint.length)
457
- notes.push(warn(`${faint.length} field(s) with an edge under 3:1: ${list(faint, (f) => `${f.edge.toFixed(2)} "${f.what}"`, 2)}`));
654
+ notes.push(warn("field-edge", `${faint.length} field(s) with an edge under 3:1: ${list(faint, (f) => `${f.edge.toFixed(2)} "${f.what}"`, 2)}`));
458
655
  const tiny = m.targets.filter((t) => t.w < 24 || t.h < 24);
459
656
  const under = m.targets.filter((t) => (t.w < 44 || t.h < 44) && !tiny.includes(t));
460
657
  const size = (t) => `"${t.what}" ${t.w}×${t.h}`;
461
658
  if (tiny.length)
462
- notes.push(fail(`${tiny.length} target(s) under 24 px: ${list(tiny, size)}`));
659
+ notes.push(fail("target-24", `${tiny.length} target(s) under 24 px: ${list(tiny, size, every)}`));
463
660
  if (phone && under.length)
464
- notes.push(warn(`${under.length} target(s) under 44 px: ${list(under, size)}`));
661
+ notes.push(warn("target-44", `${under.length} target(s) under 44 px: ${list(under, size)}`));
465
662
  const wide = m.lines.filter((l) => l.chars > 80);
466
663
  if (wide.length)
467
- notes.push(warn(`${wide.length} paragraph(s) over 80 characters a line: ${list(wide, (l) => `${l.chars} "${l.text}"`, 2)}`));
468
- console.log(` ${name.padEnd(15)}${m.texts.length} texts, ${m.fields.length} field(s), ${m.targets.length} target(s)${notes.length ? "" : ": nothing to report"}`);
664
+ notes.push(warn("line-length", `${wide.length} paragraph(s) over 80 characters a line: ${list(wide, (l) => `${l.chars} "${l.text}"`, 2)}`));
665
+ out.say(` ${name.padEnd(15)}${m.texts.length} texts, ${m.fields.length} field(s), ${m.targets.length} target(s)${notes.length ? "" : ": nothing to report"}`);
469
666
  for (const note of notes)
470
- console.log(` ${pad}${note}`);
667
+ out.say(` ${pad}${note}`);
471
668
  }
472
669
  const { context, page } = await open(url, {
473
670
  viewport: { width: 320, height: 640 },
474
671
  isMobile: true,
475
672
  hasTouch: true,
476
673
  });
477
- const overflow = await page.evaluate(() => document.documentElement.scrollWidth - innerWidth);
674
+ // The layout viewport (clientWidth), not innerWidth: on a phone a page wider than the
675
+ // screen widens innerWidth to the page, and the difference reads 0.
676
+ const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
478
677
  await context.close();
479
- if (overflow > 1) {
480
- failures++;
481
- console.log(` ${"narrow 320".padEnd(15)}FAIL scrolls sideways by ${overflow} px`);
678
+ if (overflow > 1)
679
+ out.say(` ${"narrow 320".padEnd(15)}${pg.fail("sideways-scroll-320", `scrolls sideways by ${overflow} px`, "narrow 320")}`);
680
+ // The reader's text size, raised: does the phone layout hold?
681
+ {
682
+ const { context, page } = await open(url, screens["phone 390"]);
683
+ const { base, runs } = await bigText(page);
684
+ await context.close();
685
+ const zoom = "text 130-200%";
686
+ const fail = (kind, note) => pg.fail(kind, note, zoom);
687
+ const warn = (kind, note) => pg.warn(kind, note, zoom);
688
+ const notes = [];
689
+ const top = runs[runs.length - 1];
690
+ const pct = (s) => `${Math.round(s * 100)}%`;
691
+ // From which size a problem starts, and the run to show it with (the biggest).
692
+ const first = (has) => {
693
+ const hit = runs.filter(has);
694
+ return hit.length
695
+ ? { from: pct(hit[0].scale), run: hit[hit.length - 1] }
696
+ : null;
697
+ };
698
+ const since = (from) => (from === pct(top.scale) ? "" : ` (from ${from})`);
699
+ const label = (i) => `"${short(base.rows[i].text, 24)}"`;
700
+ // Only what the bigger text breaks: a clamp or an overlap there at 100% is a choice.
701
+ const newly = (r, kind) => r.p.rows.flatMap((row, i) => row.clip === kind && base.rows[i].clip === 0 ? [i] : []);
702
+ if (!base.meta)
703
+ notes.push(warn("text-scale-meta", 'no <meta name="text-scale" content="scale">: phones keep this page at their default text size'));
704
+ if (top.p.root < base.root * 1.25)
705
+ notes.push(warn("fixed-root-size", `the page fixes its root font size (${base.root} px at 100%, ${top.p.root} px at ${pct(top.scale)}): nothing in rem follows the reader`));
706
+ const wide = first((r) => r.p.overflow > 1);
707
+ if (wide)
708
+ notes.push(fail("sideways-scroll-zoom", `scrolls sideways by ${wide.run.p.overflow} px at ${pct(wide.run.scale)}${since(wide.from)}: ${list(wide.run.p.culprits, (c) => c, every)}`));
709
+ const cut = first((r) => newly(r, 1).length > 0);
710
+ if (cut) {
711
+ const rows = newly(cut.run, 1);
712
+ notes.push(fail("cut-off-zoom", `${rows.length} text(s) cut off by a box that doesn't grow${since(cut.from)}: ${list(rows, label, every)}`));
713
+ }
714
+ const clamped = first((r) => newly(r, 2).length > 0);
715
+ if (clamped) {
716
+ const rows = newly(clamped.run, 2);
717
+ notes.push(warn("clamped-zoom", `${rows.length} text(s) shortened with "…" or a line clamp${since(clamped.from)}: ${list(rows, label, 2)}`));
718
+ }
719
+ const crossed = first((r) => r.overlaps.length > 0);
720
+ if (crossed)
721
+ notes.push(warn("overlap-zoom", `${crossed.run.overlaps.length} pair(s) of texts overlap${since(crossed.from)}: ${list(crossed.run.overlaps, (k) => k.split(",").map((i) => label(Number(i))).join(" on "), 2)}`));
722
+ const chars = base.rows.reduce((a, r) => a + r.text.length, 0) || 1;
723
+ const fixed = base.rows.flatMap((row, i) => top.p.rows[i] && top.p.rows[i].size < row.size * 1.25 ? [i] : []);
724
+ const fixedShare = Math.round((100 * fixed.reduce((a, i) => a + base.rows[i].text.length, 0)) / chars);
725
+ if (fixed.length && fixedShare >= 1)
726
+ notes.push(warn("fixed-size-text", `${fixedShare}% of the text keeps its size (set in px?): ${list(fixed, label, 2)}`));
727
+ out.say(` ${zoom.padEnd(15)}${base.rows.length} texts on the phone${notes.length ? "" : ": holds at 200%"}`);
728
+ for (const note of notes)
729
+ out.say(` ${pad}${note}`);
482
730
  }
731
+ pg.end();
483
732
  }
484
733
  await browser.close();
485
- console.log(`\n${failures} failure(s), ${warnings} warning(s) on ${urls.length} page(s).`);
486
- if (failures)
487
- process.exitCode = 1;
734
+ out.done();
@@ -0,0 +1,70 @@
1
+ export type Mode = "full" | "brief" | "json";
2
+ /** The three flags, for a check's `parseArgs` options. */
3
+ export declare const outputOptions: {
4
+ readonly brief: {
5
+ readonly type: "boolean";
6
+ readonly default: false;
7
+ };
8
+ readonly full: {
9
+ readonly type: "boolean";
10
+ readonly default: false;
11
+ };
12
+ readonly json: {
13
+ readonly type: "boolean";
14
+ readonly default: false;
15
+ };
16
+ };
17
+ export declare const outputUsage = "[--brief | --full | --json]";
18
+ export declare function outputMode(flags: {
19
+ brief?: boolean;
20
+ full?: boolean;
21
+ json?: boolean;
22
+ }): Mode;
23
+ export type Finding = {
24
+ /** A short, stable name for the rule (`contrast`, `lazy-lcp`): what brief counts by. */
25
+ kind: string;
26
+ note: string;
27
+ /** The screen or step it was found on (`phone 390`). */
28
+ where?: string;
29
+ };
30
+ export type PageResult = {
31
+ url: string;
32
+ status: "ok" | "warn" | "FAIL";
33
+ /** The page's key numbers, shown on its line in the brief form. */
34
+ keys: string[];
35
+ failures: Finding[];
36
+ warnings: Finding[];
37
+ };
38
+ export declare class PageReport {
39
+ readonly result: PageResult;
40
+ private ended;
41
+ private readonly report;
42
+ constructor(report: Report, url: string);
43
+ /** A key number for this page's line in the brief form (`reading ease 68`). */
44
+ key(text: string): void;
45
+ /** Records a failure; returns its line for the full form (`FAIL <note>`). */
46
+ fail(kind: string, note: string, where?: string): string;
47
+ /** Records a warning; returns its line for the full form (`warn <note>`). */
48
+ warn(kind: string, note: string, where?: string): string;
49
+ /** The page is measured: the brief form prints its line now. */
50
+ end(): void;
51
+ }
52
+ export declare class Report {
53
+ readonly pages: PageReport[];
54
+ readonly check: string;
55
+ readonly mode: Mode;
56
+ private readonly oneSite;
57
+ constructor(check: string, urls: string[], mode: Mode);
58
+ /** A line of the full form: printed only there. */
59
+ say(line?: string): void;
60
+ /** How a page is named on its brief line: its path when every page is on one site. */
61
+ label(url: string): string;
62
+ page(url: string): PageReport;
63
+ get failures(): number;
64
+ get warnings(): number;
65
+ /**
66
+ * The totals, in the chosen form, and the exit code: 1 when anything failed.
67
+ * `fullLine` replaces the full form's usual last line ("" for none).
68
+ */
69
+ done(fullLine?: string): void;
70
+ }