@uselazuli/cli 1.0.1 → 1.0.3

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.
Files changed (61) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +5 -5
  3. package/bin/lazuli.mjs +69 -19
  4. package/package.json +1 -1
  5. package/rules/content/HYPOTHESES.md +3 -2
  6. package/rules/content/review.yaml +33 -2
  7. package/rules/graphic/HYPOTHESES.md +1 -0
  8. package/rules/graphic/review.yaml +29 -0
  9. package/rules/motion/HYPOTHESES.md +3 -3
  10. package/rules/motion/review.yaml +4 -4
  11. package/rules/typography/HYPOTHESES.md +1 -1
  12. package/rules/typography/review.yaml +2 -2
  13. package/rules/ui/HYPOTHESES.md +3 -3
  14. package/rules/ui/compose.yaml +28 -1
  15. package/rules/ui/review.yaml +4 -3
  16. package/skills/lazuli/SKILL.md +9 -6
  17. package/skills/lazuli/procedures/review-design.md +1 -0
  18. package/skills/lazuli/procedures/show-options.md +2 -1
  19. package/skills/lazuli-content-interface-writing/SKILL.md +1 -1
  20. package/skills/lazuli-content-voice/SKILL.md +1 -0
  21. package/skills/lazuli-graphic-identity/SKILL.md +3 -1
  22. package/skills/lazuli-ui-composition/SKILL.md +4 -4
  23. package/skills/lazuli-ui-layout-review/SKILL.md +2 -2
  24. package/src/browser.mjs +2 -1
  25. package/src/commands/capture.mjs +1 -1
  26. package/src/commands/catalog.mjs +1 -1
  27. package/src/commands/check-design.mjs +62 -17
  28. package/src/commands/compare-designs.mjs +73 -6
  29. package/src/commands/draft-memo.mjs +7 -3
  30. package/src/commands/hooks.mjs +7 -5
  31. package/src/commands/record-log.mjs +87 -25
  32. package/src/commands/render-options.mjs +81 -15
  33. package/src/measure/a11y.mjs +8 -0
  34. package/src/measure/cases.mjs +24 -5
  35. package/src/measure/color.mjs +7 -0
  36. package/src/measure/in-page/a11y.js +84 -0
  37. package/src/measure/in-page/color.js +3 -1
  38. package/src/measure/in-page/composition.js +10 -3
  39. package/src/measure/in-page/extreme.js +42 -9
  40. package/src/measure/in-page/motion-probe.js +2 -0
  41. package/src/measure/in-page/type.js +3 -0
  42. package/src/measure/layout.mjs +21 -3
  43. package/src/measure/motion.mjs +2 -1
  44. package/src/measure/registry.mjs +3 -2
  45. package/src/measure/rhythm.mjs +8 -0
  46. package/src/measure/timeline.mjs +5 -5
  47. package/src/project/gate.mjs +12 -3
  48. package/src/project/lazuli-md.mjs +35 -5
  49. package/src/project/log.mjs +18 -12
  50. package/src/project/match.mjs +102 -5
  51. package/src/report/evaluators/a11y.mjs +24 -0
  52. package/src/report/evaluators/color.mjs +77 -1
  53. package/src/report/evaluators/extreme.mjs +45 -9
  54. package/src/report/evaluators/layout.mjs +10 -1
  55. package/src/report/evaluators/motion.mjs +10 -3
  56. package/src/report/evaluators/rhythm.mjs +1 -1
  57. package/src/report/evaluators/type.mjs +6 -3
  58. package/src/report/format.mjs +4 -4
  59. package/src/rules/load.mjs +18 -0
  60. package/src/rules/schema.mjs +8 -0
  61. package/templates/LAZULI.md +3 -1
@@ -1,9 +1,15 @@
1
1
  import fs from "node:fs/promises";
2
2
  import { existsSync, statSync } from "node:fs";
3
3
  import path from "node:path";
4
- import { openBrowser, openTarget } from "../browser.mjs";
4
+ import { VIEWPORT_HEIGHT, openBrowser, openTarget } from "../browser.mjs";
5
+ import { FULL_PAGE_CAP_PX } from "./capture.mjs";
6
+ import { checkHeight } from "./check-design.mjs";
7
+ import { baselineName, signatureAt } from "./compare-designs.mjs";
8
+ import { distance } from "../measure/signature.mjs";
5
9
  import { measureLayout } from "../measure/layout.mjs";
6
10
  import { MEASURERS } from "../measure/registry.mjs";
11
+ import { readLazuliMd } from "../project/lazuli-md.mjs";
12
+ import { applyBreaks, applyDeclarations, matchGoals, sameTarget } from "../project/match.mjs";
7
13
  import { evaluate } from "../report/evaluate.mjs";
8
14
  import { KIT_RULES_DIR, loadKit } from "../rules/load.mjs";
9
15
 
@@ -26,22 +32,37 @@ const show = (v, unit = "") => (v === null || v === undefined ? "n/a" : `${v}${u
26
32
 
27
33
  // One line under a thumbnail: the measures the agent reads to name scale, empty space, focal point and tension.
28
34
  // The sheet gives no ranking and no combined score.
29
- // A failed rule is never hidden: fails and breaks are named next to the hints. A crop note, when given, is a third line.
30
- export function optionLabel(layout, findings, note) {
35
+ // A failed rule is never hidden: fails, breaks and declared moves are named next to the hints. A UR3 finding that read
36
+ // the UC9 pair names the pair it compared on the next line. A crop note, when given, follows.
37
+ export function optionLabel(layout, findings, note, screensLine, distanceLine) {
31
38
  const f = layout.focal;
32
39
  const focal = f ? `focal ${f.selector} ${show(f.dominance, "x")} at (${show(f.x)}, ${show(f.y)})` : "focal none";
33
40
  const empty = layout.emptyShare === null ? "n/a" : `${Math.round(layout.emptyShare * 100)}%`;
34
41
  const ids = (level) => [...new Set(findings.filter((x) => x.level === level).map((x) => x.ruleId))];
35
- const named = [["fails", ids("fail")], ["breaks", ids("break")], ["hints", ids("hint")]]
42
+ const named = [["fails", ids("fail")], ["breaks", ids("break")], ["declared", ids("declared")], ["hints", ids("hint")]]
36
43
  .filter(([, list]) => list.length)
37
44
  .map(([word, list]) => `${word} ${list.join(", ")}`);
45
+ const pair = findings.find((x) => x.ruleId === "UR3" && x.moves?.UC9)?.moves.UC9.detail;
38
46
  return [
39
47
  `scale ${show(layout.textRatio, "x")} text, ${show(layout.areaRatio, "x")} area; empty ${empty}, spread ${show(layout.emptySpread)}; ${focal}`,
40
48
  named.length ? named.join("; ") : "no hints",
49
+ ...(pair ? [`UR3 pair: ${pair}`] : []),
41
50
  ...(note ? [note] : []),
51
+ ...(screensLine ? [screensLine] : []),
52
+ ...(distanceLine ? [distanceLine] : []),
42
53
  ];
43
54
  }
44
55
 
56
+ // The label line of a thumbnail that shows more than the first view; null for one screen.
57
+ export const screensNote = (screens, height) =>
58
+ screens > 1 ? `thumbnail shows ${screens} screens of ${height} px; measures read the first view` : null;
59
+
60
+ // Why the earlier measures at a width were dropped: the option files changed, or only the height did.
61
+ export const droppedLine = (r, w) =>
62
+ r.droppedReason === "height"
63
+ ? `The earlier measures at ${w} px were read at ${r.droppedHeight} px, not ${r.height} px; they were dropped.`
64
+ : `Option files changed since the last run; the earlier measures at ${w} px were dropped.`;
65
+
45
66
  // The option canvas has its own width; rendered narrower, the view is a crop of it.
46
67
  export const cropNote = (width) => `The option is wider than ${width} px; this view is a crop and its bleeds are not meaningful.`;
47
68
  // The canvas is the body or html box, not the scroll width: a block that bleeds on purpose does not widen it.
@@ -65,10 +86,15 @@ figcaption { margin-top: 8px; display: flex; flex-direction: column; gap: 2px; }
65
86
  </style></head><body><h1>Options at ${width} px, in file order (no ranking)</h1><main>${items}</main></body></html>`;
66
87
  }
67
88
 
68
- async function optionFiles(folder) {
89
+ // The option files of the folder; a baseline kept in the folder is not an option (as compare-designs --options).
90
+ async function optionFiles(folder, baseline, cwd) {
69
91
  if (!existsSync(folder) || !statSync(folder).isDirectory()) throw new OptionsInputError(`Options folder not found: ${folder}`);
70
92
  const entries = await fs.readdir(folder, { withFileTypes: true });
71
- const files = entries.filter((e) => e.isFile() && /\.html$/i.test(e.name)).map((e) => e.name).sort();
93
+ const files = entries
94
+ .filter((e) => e.isFile() && /\.html$/i.test(e.name))
95
+ .map((e) => e.name)
96
+ .sort()
97
+ .filter((name) => !baseline || !sameTarget(path.join(folder, name), baseline, cwd));
72
98
  if (files.length < MIN_OPTIONS || files.length > MAX_OPTIONS) {
73
99
  throw new OptionsInputError(`Found ${files.length} option files in ${folder}; show-options needs ${MIN_OPTIONS} to ${MAX_OPTIONS}.`);
74
100
  }
@@ -85,22 +111,47 @@ async function readEarlier(jsonPath) {
85
111
  }
86
112
  }
87
113
 
114
+ // The first `screens` viewport heights of the page, cut at the page end.
115
+ async function screensClip(page, width, height, screens) {
116
+ const pageHeight = await page.evaluate(() => Math.max(document.documentElement.scrollHeight, innerHeight));
117
+ return { x: 0, y: 0, width, height: Math.min(pageHeight, screens * height) };
118
+ }
119
+
88
120
  // Renders and measures the option files of a folder and writes one contact sheet per width.
89
121
  // Measures of widths rendered in an earlier run are kept when the option files are the same ones, and dropped otherwise.
90
122
  // The CLI renders and measures; choosing is the agent's or the person's job.
91
- export async function renderOptions({ folder: given, widths = [1440], cwd = process.cwd(), browser: givenBrowser, rules: givenRules }) {
123
+ export async function renderOptions({ folder: given, widths = [1440], height = VIEWPORT_HEIGHT, screens = 1, cwd = process.cwd(), browser: givenBrowser, rules: givenRules, baseline }) {
124
+ checkHeight(height);
125
+ if (!Number.isInteger(screens) || screens < 1) throw new OptionsInputError("--screens needs a whole number of 1 or more.");
126
+ if (screens * height > FULL_PAGE_CAP_PX) throw new OptionsInputError(`--screens ${screens} at ${height} px is taller than ${FULL_PAGE_CAP_PX} px.`);
92
127
  const folder = path.resolve(cwd, given);
93
- const files = await optionFiles(folder);
128
+ const files = await optionFiles(folder, baseline, cwd);
94
129
  const all = givenRules ?? (await loadKit({ dirs: [process.env.LAZULI_RULES_DIR ?? KIT_RULES_DIR], projectDir: path.join(cwd, ".lazuli", "rules") })).rules;
95
130
  const rules = all.filter((r) => typeof r.measure === "string" && r.measure.startsWith("layout."));
131
+ // The breaks and declared moves of LAZULI.md apply to each option file through the goals that cover it (an options goal's glob).
132
+ const md = await readLazuliMd(cwd);
133
+ const knownIds = new Set(all.map((r) => r.id));
134
+ const declared = (findings, file) => {
135
+ if (!md) return findings;
136
+ const goals = matchGoals(md, file, cwd);
137
+ return applyDeclarations(applyBreaks(findings, md.breaks, goals, all, knownIds, file, cwd).findings, md, goals, all, file, cwd).findings;
138
+ };
96
139
 
97
140
  const jsonPath = path.join(folder, "options.json");
98
141
  const prev = await readEarlier(jsonPath);
99
142
  const prevWidths = prev ? [...new Set(Object.values(prev.options).flatMap((o) => Object.keys(o.measures ?? {})).map(Number))] : [];
100
- const sameFiles = prev !== null && prev.options.length === files.length && prev.options.every((o, i) => o.file === files[i]);
143
+ // An options.json written before heights were recorded was rendered at the default height.
144
+ const filesMatch = prev !== null && prev.options.length === files.length && prev.options.every((o, i) => o.file === files[i]);
145
+ const prevHeight = prev?.height ?? VIEWPORT_HEIGHT;
146
+ const sameFiles = filesMatch && prevHeight === height;
101
147
  const earlier = prevWidths.filter((w) => !widths.includes(w));
102
148
  const kept = sameFiles ? earlier : [];
103
149
  const dropped = prev && !sameFiles ? earlier : [];
150
+ const droppedWhy = dropped.length === 0 ? {} : filesMatch ? { droppedReason: "height", droppedHeight: prevHeight } : { droppedReason: "files" };
151
+ // The screens each width was rendered with: a kept width keeps its own (a 1.0.1 file holds one value for all).
152
+ const screensAt = {};
153
+ for (const w of kept) screensAt[String(w)] = prev.screensAt?.[String(w)] ?? prev.screens ?? 1;
154
+ for (const w of widths) screensAt[String(w)] = screens;
104
155
 
105
156
  const thumbs = path.join(folder, "thumbs");
106
157
  await fs.mkdir(thumbs, { recursive: true });
@@ -114,23 +165,38 @@ export async function renderOptions({ folder: given, widths = [1440], cwd = proc
114
165
  }
115
166
  return option;
116
167
  });
168
+ const baselineSigs = new Map();
117
169
  const pngs = new Map();
118
170
  const sheets = {};
119
- for (const w of kept) if (prev.sheets?.[String(w)]) sheets[String(w)] = prev.sheets[String(w)];
171
+ // A kept sheet whose file is gone is dropped from sheets and named, so the width can be run again.
172
+ const missingSheets = [];
173
+ for (const w of kept) {
174
+ const file = prev.sheets?.[String(w)];
175
+ if (!file) continue;
176
+ if (existsSync(file)) sheets[String(w)] = file;
177
+ else missingSheets.push(w);
178
+ }
120
179
  const browser = givenBrowser ?? (await openBrowser());
121
180
  try {
122
181
  for (const option of options) {
123
182
  const name = path.basename(option.file, path.extname(option.file));
124
183
  for (const width of widths) {
125
- const page = await openTarget(browser, path.join(folder, option.file), width, { cwd });
184
+ const file = path.join(folder, option.file);
185
+ const page = await openTarget(browser, file, width, { cwd, height });
126
186
  try {
127
187
  const layout = await measureLayout(page, { options: true });
128
188
  if ((await canvasWidth(page)) > width) option.notes[String(width)] = cropNote(width);
129
- const png = await page.screenshot();
189
+ const png = screens === 1 ? await page.screenshot() : await page.screenshot({ fullPage: true, clip: await screensClip(page, width, height, screens) });
130
190
  await fs.writeFile(path.join(thumbs, `${name}-${width}.png`), png);
131
191
  pngs.set(`${option.file}|${width}`, png);
132
192
  option.measures[String(width)] = layout;
133
- option.findings.push(...evaluate(rules, [{ width, layout }], MEASURERS));
193
+ if (baseline) {
194
+ // The baseline is read once per width, not once per option.
195
+ if (!baselineSigs.has(width)) baselineSigs.set(width, await signatureAt(browser, baseline, width, cwd, height));
196
+ const d = distance(await signatureAt(browser, file, width, cwd, height), baselineSigs.get(width));
197
+ (option.distances ??= {})[String(width)] = `structure distance ${d.value} from ${baselineName(baseline)} (H1)`;
198
+ }
199
+ option.findings.push(...declared(evaluate(rules, [{ width, layout }], MEASURERS), file));
134
200
  } finally {
135
201
  await page.context().close();
136
202
  }
@@ -140,7 +206,7 @@ export async function renderOptions({ folder: given, widths = [1440], cwd = proc
140
206
  const cells = options.map((o) => ({
141
207
  file: o.file,
142
208
  png: pngs.get(`${o.file}|${width}`),
143
- lines: optionLabel(o.measures[String(width)], o.findings.filter((f) => f.width === width), o.notes[String(width)]),
209
+ lines: optionLabel(o.measures[String(width)], o.findings.filter((f) => f.width === width), o.notes[String(width)], screensNote(screens, height), o.distances?.[String(width)]),
144
210
  }));
145
211
  const context = await browser.newContext({ viewport: { width: SHEET_PX, height: 900 } });
146
212
  try {
@@ -158,7 +224,7 @@ export async function renderOptions({ folder: given, widths = [1440], cwd = proc
158
224
  }
159
225
 
160
226
  const allWidths = [...new Set([...(sameFiles ? prevWidths : []), ...widths])];
161
- const result = { folder, widths: allWidths, kept, dropped, options, sheets, jsonPath };
227
+ const result = { folder, widths: allWidths, height, screens, screensAt, ...(baseline ? { baselineHeight: height } : {}), kept, dropped, ...droppedWhy, missingSheets, options, sheets, jsonPath };
162
228
  await fs.writeFile(jsonPath, JSON.stringify(result, null, 2));
163
229
  return result;
164
230
  }
@@ -323,7 +323,14 @@ export async function measureA11y(page, ctx) {
323
323
 
324
324
  const minSidePx = thresholdOf(ctx, "a11y.decorative-images")?.minSidePx;
325
325
 
326
+ const treatRule = thresholdOf(ctx, "a11y.image-treatment");
327
+ const treatment = treatRule && Array.isArray(treatRule.filters) ? { filters: treatRule.filters, blends: treatRule.blends === true } : null;
328
+ if (treatment && !Number.isFinite(minSidePx)) {
329
+ notes.push("Treated images were not read: the large image size comes from rule AP6, which was not part of this run.");
330
+ }
331
+
326
332
  const opts = {
333
+ treatment,
327
334
  globalKey: GLOBAL_KEY,
328
335
  minPx: Number.isFinite(minPx) ? minPx : null,
329
336
  maxTargets: MAX_TARGETS,
@@ -372,6 +379,7 @@ export async function measureA11y(page, ctx) {
372
379
  genericLinks: ax.genericLinks,
373
380
  targets: parts.targets,
374
381
  largeImages: parts.largeImages,
382
+ totalLarge: parts.totalLarge,
375
383
  focus,
376
384
  reflow,
377
385
  textSpacing,
@@ -15,6 +15,9 @@ import { flowStopUrl } from "../project/tasks.mjs";
15
15
  // Definitions, not cutoffs (fixed before any page was measured, never edited after a reading).
16
16
  // A spill, cut or overlap must exceed this many px (subpixel rounding).
17
17
  export const SLACK_PX = 1;
18
+ // A box bleeds when it crosses the left or right edge of the viewport by more than this many px: the
19
+ // composition tolerance (the same value as ALIGN_PX in in-page/composition.js, which its bleeds use).
20
+ export const ALIGN_PX = 2;
18
21
  // "centenas de itens": the many case fills each list to this many items.
19
22
  export const MANY_ITEMS = 300;
20
23
  // Lists by markup; an element with REPEATED_MIN or more visible element children sharing tag and class list
@@ -51,7 +54,7 @@ export const MAX_LISTED = 10;
51
54
  export const MAX_MEMORY_BYTES = 100_000_000;
52
55
 
53
56
  export const EXTREME_DEFS = {
54
- SLACK_PX, MANY_ITEMS, LIST_SELECTOR, REPEATED_MIN, NOT_LIST, LABEL_SCOPE, HEADING_SCOPE, DECORATIVE, INLINE_ITEMS,
57
+ SLACK_PX, ALIGN_PX, MANY_ITEMS, LIST_SELECTOR, REPEATED_MIN, NOT_LIST, LABEL_SCOPE, HEADING_SCOPE, DECORATIVE, INLINE_ITEMS,
55
58
  LONG_LABEL, LONG_HEADING, LONG_TEXT, GROWTH_FILL, MAX_LISTS, MAX_CLONE_ELEMENTS, MAX_RECTS,
56
59
  };
57
60
 
@@ -468,7 +471,13 @@ export function loadsDiffer(base, kase) {
468
471
  // still in the case DOM (not removed), not kept in the case and cut away entirely by a hidden or clip box;
469
472
  // an overlap counts only when the base had none between the same originals and both members had every
470
473
  // line box read in the base and in the case. Copies of one original are reported once, with
471
- // "(<n> copies)" after the text; texts carry the base text of the original.
474
+ // "(<n> copies)" after the text; texts carry the base text of the original and bleedsAtRest, true when the
475
+ // original's box crossed the viewport's left or right edge in the base. overflowX: the sideways scroll the case
476
+ // adds (null on a page that hides its sideways overflow); clippedX: on such a page, how much further the content
477
+ // runs past the clipped right edge. wide: the texts whose right edge passes the viewport in the case and did not
478
+ // at rest, or passes it further than at rest, listed only when the case adds one of the two. restBleeds: how many texts of the
479
+ // base bleed at rest, the kept texts that bleed plus restDecorative (null when the base reading has no bleed fields);
480
+ // restSideways: the base scrolls sideways at rest (overflowX past ALIGN_PX on a page that does not hide it), where no text bleeds.
472
481
  export function compareBreaks(base, kase, injected = { removed: [] }) {
473
482
  const baseText = new Map(base.texts.map((t) => [t.id, t]));
474
483
  const baseKept = new Set(base.kept);
@@ -490,7 +499,7 @@ export function compareBreaks(base, kase, injected = { removed: [] }) {
490
499
  const describe = (o, copies, fallback, extra = {}) => {
491
500
  const b = baseText.get(o) ?? fallback;
492
501
  const suffix = copies > 0 ? ` (${copies} ${plural(copies, "copy", "copies")})` : "";
493
- return { id: o, selector: b?.selector ?? "", text: `${b?.text ?? ""}${suffix}`, ...extra };
502
+ return { id: o, selector: b?.selector ?? "", text: `${b?.text ?? ""}${suffix}`, bleedsAtRest: baseText.get(o)?.bleeds === true, ...extra };
494
503
  };
495
504
 
496
505
  const spills = group(kase.texts.filter((t) => t.spills && !baseText.get(originOf(t.id))?.spills).map((t) => t.id));
@@ -528,8 +537,18 @@ export function compareBreaks(base, kase, injected = { removed: [] }) {
528
537
  describe(g.ob, g.cb.size, caseText.get(g.ob)),
529
538
  ]);
530
539
 
531
- const dx = kase.overflowX - base.overflowX;
532
- return { overflowX: dx > SLACK_PX ? dx : null, spills, cut, lost, overlaps };
540
+ const grew = (k, b) => (Number.isFinite(k) && Number.isFinite(b) && k - b > SLACK_PX ? k - b : null);
541
+ const overflowX = grew(kase.overflowX, base.overflowX);
542
+ const clippedX = grew(kase.clippedX, base.clippedX);
543
+ // Past the right edge in the case and not at rest, or further past it than at rest.
544
+ const newlyPast = (t) => {
545
+ const b = baseText.get(originOf(t.id));
546
+ return !b?.pastRight || grew(t.right, b.right) !== null;
547
+ };
548
+ const wide = overflowX === null && clippedX === null ? [] : group(kase.texts.filter((t) => t.pastRight && newlyPast(t)).map((t) => t.id));
549
+ const restBleeds = Array.isArray(base.restDecorative) || base.texts.some((t) => "bleeds" in t) ? base.texts.filter((t) => t.bleeds).length + (base.restDecorative?.length ?? 0) : null;
550
+ const restSideways = Number.isFinite(base.overflowX) && base.overflowX > ALIGN_PX;
551
+ return { overflowX, clippedX, spills, cut, lost, overlaps, wide, restBleeds, restSideways };
533
552
  }
534
553
 
535
554
  // The verdict of one case: breaks are reported only when every stylesheet was
@@ -75,5 +75,12 @@ export async function measureColor(page, ctx = {}) {
75
75
  }
76
76
  const report = mergeColorReports(parts);
77
77
  report.notes.push(...extra);
78
+ // GR10: the Brand colors travel with the report so the evaluator can compare them with the area entries.
79
+ if ((ctx.rules ?? []).some((r) => r.measure === "color.brand")) {
80
+ report.brand = ctx.brand?.colors ?? [];
81
+ if (report.brand.length === 0) {
82
+ report.notes.push("LAZULI.md has no Brand Color lines, so the brand in the first view was not checked.");
83
+ }
84
+ }
78
85
  return report;
79
86
  }
@@ -458,6 +458,87 @@
458
458
 
459
459
  // Visible img elements with both rendered sides at least minSidePx (from the rule data), and whether each is
460
460
  // marked decorative: alt="", role presentation or none, or inside an aria-hidden subtree. Off without the cutoff.
461
+ // treatment (opts.treatment: { filters, blends } from the CR14 rule data, or null): the color-changing filter
462
+ // functions of the image or an ancestor up to its nearest section, article or body, and its mix-blend-mode
463
+ // when not normal, as one text; null when none.
464
+ // The identity value of each color filter function (CSS Filter Effects: the function leaves the image as it
465
+ // is); an omitted argument is the function's default, never the identity except for hue-rotate. url() always
466
+ // counts.
467
+ const FILTER_IDENTITY = { grayscale: 0, sepia: 0, invert: 0, saturate: 1, contrast: 1, brightness: 1, "hue-rotate": 0 };
468
+ const identity = (name, arg) => {
469
+ if (!(name in FILTER_IDENTITY)) return false;
470
+ const a = arg.trim();
471
+ if (a === "") return name === "hue-rotate";
472
+ const n = parseFloat(a);
473
+ if (!Number.isFinite(n)) return false;
474
+ return (a.endsWith("%") ? n / 100 : n) === FILTER_IDENTITY[name];
475
+ };
476
+ // The top-level name(argument) calls of a filter value, in order. Parentheses are counted to any depth and
477
+ // a quoted string (a url) is skipped whole, so an argument that holds its own calls or parentheses never hides
478
+ // the function after it.
479
+ const filterCalls = (text) => {
480
+ const calls = [];
481
+ const s = String(text);
482
+ let i = 0;
483
+ while (i < s.length) {
484
+ const m = /[a-z-]+\(/y;
485
+ m.lastIndex = i;
486
+ const hit = m.exec(s);
487
+ if (!hit) { i += 1; continue; }
488
+ const name = hit[0].slice(0, -1);
489
+ let depth = 1;
490
+ let j = i + hit[0].length;
491
+ const from = j;
492
+ let quote = null;
493
+ for (; j < s.length && depth > 0; j += 1) {
494
+ const c = s[j];
495
+ if (quote) {
496
+ if (c === "\\") j += 1;
497
+ else if (c === quote) quote = null;
498
+ } else if (c === '"' || c === "'") quote = c;
499
+ else if (c === "(") depth += 1;
500
+ else if (c === ")") depth -= 1;
501
+ }
502
+ if (depth > 0) break;
503
+ calls.push([name, s.slice(from, j - 1)]);
504
+ i = j;
505
+ }
506
+ return calls;
507
+ };
508
+ const treatmentOf = (el) => {
509
+ const rule = opts.treatment;
510
+ if (!rule || !Array.isArray(rule.filters)) return null;
511
+ const names = [];
512
+ let blend = null;
513
+ for (let node = el; node && node.nodeType === 1; node = node.parentElement) {
514
+ const cs = getComputedStyle(node);
515
+ for (const [name, arg] of filterCalls(cs.filter)) {
516
+ if (identity(name, arg)) continue;
517
+ if (rule.filters.includes(name) && !names.includes(name)) names.push(name);
518
+ }
519
+ if (rule.blends === true && !blend && cs.mixBlendMode && cs.mixBlendMode !== "normal") blend = cs.mixBlendMode;
520
+ if (/^(section|article|body)$/i.test(node.tagName) && node !== el) break;
521
+ }
522
+ const parts = [...names, ...(blend ? ["mix-blend-mode " + blend] : [])];
523
+ return parts.length > 0 ? parts.join(", ") : null;
524
+ };
525
+ // The last path segment of an image's full address, for naming an image that has no alt: query, fragment and
526
+ // host dropped, decoded when percent-encoded, whitespace collapsed, clipped to 40. A data: or blob: source, or
527
+ // an address with no path segment, has no name ("").
528
+ const fileNameOf = (el) => {
529
+ // No source at all would resolve to the page itself and name the image after it.
530
+ if (!(el.currentSrc || el.getAttribute("src"))) return "";
531
+ try {
532
+ const u = new URL(el.currentSrc || el.getAttribute("src") || "", document.baseURI);
533
+ if (!/^(https?|file):$/.test(u.protocol)) return "";
534
+ const seg = u.pathname.split("/").filter(Boolean).pop() || "";
535
+ let name = seg;
536
+ try { name = decodeURIComponent(seg); } catch { /* keep the raw segment */ }
537
+ return clip(norm(name), 40);
538
+ } catch {
539
+ return "";
540
+ }
541
+ };
461
542
  const largeImages = [];
462
543
  let totalLarge = 0;
463
544
  if (Number.isFinite(opts.minSidePx) && opts.minSidePx > 0) {
@@ -470,9 +551,12 @@
470
551
  largeImages.push({
471
552
  selector: info.selector,
472
553
  src: info.src.slice(0, 200),
554
+ alt: clip(norm(el.getAttribute("alt")), 40),
555
+ fileName: fileNameOf(el),
473
556
  decorative: info.decorative || Boolean(el.closest("[aria-hidden=true]")),
474
557
  widthPx: round(r.width),
475
558
  heightPx: round(r.height),
559
+ treatment: treatmentOf(el),
476
560
  });
477
561
  }
478
562
  }
@@ -121,7 +121,8 @@ async (shotDataUrl, shotCssWidth, contrast, tile, warn) => {
121
121
  const area = [...buckets.values()]
122
122
  .map((b) => {
123
123
  const c = meanOf(b);
124
- return { hex: hex(c), pct: +((100 * b.n) / total).toFixed(1), ...hsl(c) };
124
+ // pct is rounded for the report; share is the unrounded fraction of the view.
125
+ return { hex: hex(c), pct: +((100 * b.n) / total).toFixed(1), share: b.n / total, ...hsl(c) };
125
126
  })
126
127
  .sort((a, b) => b.pct - a.pct);
127
128
  noteOnce("Area comes from the first viewport; text backgrounds over images use the full-page screenshot.");
@@ -323,6 +324,7 @@ async (shotDataUrl, shotCssWidth, contrast, tile, warn) => {
323
324
  bg: hex(bg),
324
325
  ratio: +r.toFixed(2),
325
326
  size: large ? "large" : "normal",
327
+ hidden: !!el.closest('[aria-hidden="true"]'),
326
328
  pass: r >= (large ? 3 : 4.5),
327
329
  warning: isWarning(el, text),
328
330
  });
@@ -1,7 +1,7 @@
1
1
  // Evaluated inside the page as a function expression: (opts, lookOf) => plain data. Plain script, no imports.
2
2
  // The shared composition library (blocks, sections, coverage, body size) lives inside; opts.read picks
3
3
  // the reader that turns it into plain data ("layout", "rhythm", "components", "forms", "actions", "piece",
4
- // "motion" or "chart").
4
+ // "motion", "chart" or "viewport").
5
5
  // opts.options true is the render-options reading: elements marked data-block are the option blocks. Without it
6
6
  // the marks are ignored (a finished page measures as a page) and counted in the reader's marks.
7
7
  // lookOf is the look.js function, injected as source by the caller:
@@ -1488,9 +1488,16 @@
1488
1488
  return { charts, notes };
1489
1489
  };
1490
1490
 
1491
- const readers = { layout, rhythm, components, forms, actions, piece, motion, content, seen: contentKept, chart };
1491
+ // The viewport reader: whether the page hides its overflow on each axis (the one place this lock is read).
1492
+ const viewport = () => ({ lockedX: locked(viewportOverflow("x")), lockedY: locked(viewportOverflow("y")) });
1493
+
1494
+ const readers = { layout, rhythm, components, forms, actions, piece, motion, content, seen: contentKept, chart, viewport };
1492
1495
  // Every reader says how many data-block marks the page carries; Node notes them when they were not read.
1493
1496
  const out = readers[opts.read](opts);
1494
- if (out && typeof out === "object" && !Array.isArray(out)) out.marks = document.querySelectorAll("[data-block]").length;
1497
+ if (out && typeof out === "object" && !Array.isArray(out)) {
1498
+ out.marks = document.querySelectorAll("[data-block]").length;
1499
+ // With options asked, whether the blocks were the marks (a mark in the walk) or the finished-page blocks.
1500
+ if (opts.options === true) out.byMarks = isOptions();
1501
+ }
1495
1502
  return out;
1496
1503
  }
@@ -5,21 +5,28 @@
5
5
  // the case page only: it never clicks, focuses, types, selects or submits, and sends nothing.
6
6
  //
7
7
  // Kept elements are those the composition walk keeps (read "seen", keepPinned) outside DECORATIVE (aria-hidden)
8
- // subtrees: hidden, clipped, off-page and decorative content is never read, changed or reported.
8
+ // subtrees: hidden, clipped, off-page and decorative content is never changed or reported; decorative text the
9
+ // walk keeps is read only for restDecorative.
9
10
  // tag(): data-lazuli-x on body and every element in it, a sequential index in document order; returns the count.
10
11
  // inject(kind, params) -> { lists, added, shortLists, cut, removed } for kind "base", "growth", "long-text",
11
12
  // "empty", "one", "many". shortLists: the lists many filled with fewer than MANY_ITEMS items. removed lists the data-lazuli-x of every element removed, descendants included. The k-th copy of an
12
13
  // item (many) has its data-lazuli-x and those of its descendants rewritten to <original>~c<k> and its id
13
14
  // attributes removed, so every copy stays apart and is compared through its original. The caller runs
14
15
  // the at-rest walk again (restStill) before read().
15
- // read() -> { overflowX, texts: { id, selector, text, spills, cut, whole }[], kept, overlaps, rectsCut, away,
16
- // fonts, sheets, brokenImages }. whole: every line box of the text was read for overlap. away: the
16
+ // read() -> { overflowX, clippedX, texts: { id, selector, text, spills, cut, whole, bleeds, pastRight, right }[], restDecorative, kept, overlaps,
17
+ // rectsCut, away, fonts, sheets, brokenImages }. restDecorative: { selector, text }[], the decorative text elements
18
+ // the walk keeps whose box crosses the left or right edge, with the gate of bleeds; read only, no case changes them. overflowX: how far the page scrolls sideways, null when the
19
+ // viewport hides its sideways overflow (html, or body when html is visible, has overflow-x hidden or clip, as
20
+ // composition reads it); clippedX: on such a page, how far the content runs past the clipped right edge, else
21
+ // null. whole: every line box of the text was read for overlap. bleeds:
22
+ // the text's box (its element's box joined with its line boxes) is partly in the viewport and crosses its left
23
+ // or right edge by more than ALIGN_PX, on a page that does not scroll sideways (the gate of composition's bleeds); pastRight: that box's right edge passes the viewport by more than ALIGN_PX; right: that edge in px. away: the
17
24
  // tagged text elements the walk did not keep whose every line box lies outside the padding box of a hidden or
18
25
  // clip ancestor, walked by containing block. fonts: the font faces loaded, loading or failed; sheets: the
19
26
  // linked stylesheets and how many rules each holds; brokenImages: the ids of images that failed.
20
27
  (composition, defs) => {
21
28
  const {
22
- SLACK_PX, MANY_ITEMS, LIST_SELECTOR, NOT_LIST, REPEATED_MIN, LABEL_SCOPE, HEADING_SCOPE, DECORATIVE, INLINE_ITEMS,
29
+ SLACK_PX, ALIGN_PX, MANY_ITEMS, LIST_SELECTOR, NOT_LIST, REPEATED_MIN, LABEL_SCOPE, HEADING_SCOPE, DECORATIVE, INLINE_ITEMS,
23
30
  LONG_LABEL, LONG_HEADING, LONG_TEXT, GROWTH_FILL, MAX_LISTS, MAX_CLONE_ELEMENTS, MAX_RECTS,
24
31
  } = defs;
25
32
  const ATTR = "data-lazuli-x";
@@ -29,7 +36,8 @@
29
36
  const SCROLLS = new Set(["auto", "scroll", "overlay"]);
30
37
 
31
38
  const INLINE = new Set(INLINE_ITEMS);
32
- const keptEls = () => composition({ read: "seen", keepPinned: true }).filter((el) => !el.closest(DECORATIVE));
39
+ const seenEls = () => composition({ read: "seen", keepPinned: true });
40
+ const keptEls = () => seenEls().filter((el) => !el.closest(DECORATIVE));
33
41
  const idOf = (el) => el.getAttribute(ATTR);
34
42
  const ownTexts = (el) => [...el.childNodes].filter((n) => n.nodeType === 3 && /\S/.test(n.nodeValue));
35
43
  const isInputButton = (el) => el.tagName === "INPUT" && INPUT_BUTTONS.has((el.getAttribute("type") || "").toLowerCase());
@@ -257,9 +265,30 @@
257
265
  );
258
266
  };
259
267
 
268
+ // The text's box across: its element's box joined with its line boxes (a word can run out of its box).
269
+ const across = (el, rects) => {
270
+ const b = el.getBoundingClientRect();
271
+ return { left: Math.min(b.left, ...rects.map((r) => r.left)), right: Math.max(b.right, ...rects.map((r) => r.right)) };
272
+ };
273
+
260
274
  const read = () => {
261
- const kept = keptEls();
275
+ const seen = seenEls();
276
+ const kept = seen.filter((el) => !el.closest(DECORATIVE));
262
277
  const keptSet = new Set(kept);
278
+ const root = document.documentElement;
279
+ const vw = root.clientWidth;
280
+ // As composition's bleeds: a page that scrolls sideways (html, or body when html is visible, does not
281
+ // hide that overflow) has no bleed.
282
+ const { lockedX } = composition({ read: "viewport" });
283
+ const sideways = root.scrollWidth > vw + ALIGN_PX && !lockedX;
284
+ const crosses = (box) => !sideways && box.right > 0 && box.left < vw && (box.left < -ALIGN_PX || box.right > vw + ALIGN_PX);
285
+ const restDecorative = [];
286
+ for (const el of seen) {
287
+ if (!el.closest(DECORATIVE)) continue;
288
+ const nodes = ownTexts(el);
289
+ if (nodes.length === 0 || !crosses(across(el, rectsOf(nodes)))) continue;
290
+ restDecorative.push({ selector: selectorOf(el), text: collapse(nodes.map((n) => n.nodeValue).join(" ")).slice(0, 40) });
291
+ }
263
292
  const entries = [];
264
293
  for (const el of kept) {
265
294
  const id = idOf(el);
@@ -268,9 +297,12 @@
268
297
  if (nodes.length === 0) continue;
269
298
  const rects = rectsOf(nodes);
270
299
  const container = containerOf(el);
300
+ const box = across(el, rects);
301
+ const pastRight = box.right > vw + ALIGN_PX;
302
+ const bleeds = crosses(box);
271
303
  entries.push({
272
304
  el, rects, container,
273
- text: { id, selector: selectorOf(el), text: collapse(nodes.map((n) => n.nodeValue).join(" ")).slice(0, 40), spills: spillsOf(container, rects), cut: cutOf(container, rects), whole: true },
305
+ text: { id, selector: selectorOf(el), text: collapse(nodes.map((n) => n.nodeValue).join(" ")).slice(0, 40), spills: spillsOf(container, rects), cut: cutOf(container, rects), whole: true, bleeds, pastRight, right: box.right },
274
306
  });
275
307
  }
276
308
  // Overlaps over the first MAX_RECTS line boxes, in document order.
@@ -337,10 +369,11 @@
337
369
  })
338
370
  .sort((a, b) => (a.href < b.href ? -1 : a.href > b.href ? 1 : 0));
339
371
  const brokenImages = [...new Set([...document.images].filter((img) => img.complete && img.naturalWidth === 0 && idOf(img) !== null).map(idOf))].sort(byId);
340
- const root = document.documentElement;
341
372
  return {
342
- overflowX: root.scrollWidth - root.clientWidth,
373
+ overflowX: lockedX ? null : root.scrollWidth - root.clientWidth,
374
+ clippedX: lockedX ? root.scrollWidth - root.clientWidth : null,
343
375
  texts: entries.map((e) => e.text),
376
+ restDecorative,
344
377
  kept: kept.map(idOf).filter((id) => id !== null),
345
378
  overlaps,
346
379
  rectsCut,
@@ -98,6 +98,8 @@
98
98
  from: valuesAt(frames[0]),
99
99
  to: valuesAt(frames[frames.length - 1]),
100
100
  related,
101
+ // A scroll or view timeline: the scroll position is the curve, not the timing function.
102
+ scrollLinked: !!a.timeline && a.timeline !== document.timeline,
101
103
  });
102
104
  };
103
105
  const scan = () => {
@@ -208,12 +208,15 @@
208
208
  const pad = ["paddingTop", "paddingBottom", "borderTopWidth", "borderBottomWidth"].reduce((s, k) => s + (parseFloat(cs[k]) || 0), 0);
209
209
  ratio = (box - pad) / size;
210
210
  }
211
+ const weight = parseInt(cs.fontWeight, 10) || 400;
211
212
  return {
212
213
  selector: selectorOf(el),
213
214
  chars,
214
215
  lines,
215
216
  charsPerLine: round(chars / lines),
216
217
  sizePx: round(size, 2),
218
+ // WCAG 2.2 large scale (24 px, or 18.66 px at weight 700 or more), the same rule the color reading uses.
219
+ large: size >= 24 || (size >= 18.66 && weight >= 700),
217
220
  lineHeightRatio: round(ratio, 3),
218
221
  charAdvancePx: round(textWidth / chars, 2),
219
222
  };
@@ -1,4 +1,5 @@
1
1
  import fs from "node:fs/promises";
2
+ import { isOptionsGoal } from "../project/lazuli-md.mjs";
2
3
 
3
4
  // Resolution, not a composition rule: the first view is read as SPACE_CELLS by SPACE_CELLS cells for
4
5
  // where its empty space sits.
@@ -19,8 +20,9 @@ const unique = (list) => [...new Set(list)];
19
20
  // First view scale contrast, empty space and focal point; sections and their grid edges; bleeds and crossings.
20
21
  // Report shape as in LayoutReport, except sections[].left and sections[].right are
21
22
  // number | null: null (and centered false) for a section with no blocks, which uniformGrid leaves out.
22
- // ctx.options true is the render-options reading: elements marked data-block are the option blocks. Any other
23
- // caller measures a finished page, and the marks it carries are ignored and noted.
23
+ // ctx.options true is the options reading: elements marked data-block are the option blocks (render-options, and
24
+ // check-design on a file an options goal covers, whose pieces come from ctx.goals). Any other caller measures a
25
+ // finished page, and the marks it carries are ignored and noted.
24
26
  export async function measureLayout(page, ctx = {}) {
25
27
  script ??= await fs.readFile(new URL("./in-page/composition.js", import.meta.url), "utf8");
26
28
  const raw = await page.evaluate(`(${script})(${JSON.stringify({ read: "layout", spaceCells: SPACE_CELLS, options: ctx?.options === true })})`);
@@ -39,9 +41,18 @@ export async function measureLayout(page, ctx = {}) {
39
41
  const order = areas.map((a, i) => i).sort((a, b) => areas[b] - areas[a] || a - b);
40
42
  const top = order[0];
41
43
  const c = raw.clipped[top];
44
+ // The pair of the two largest blocks: the second over the third, and the gap between their boxes
45
+ // (the larger of the gaps across and down; negative when the boxes overlap, the overlap depth).
46
+ const pair = order.length >= 2 ? raw.clipped[order[1]] : null;
47
+ const gap = pair
48
+ ? Math.max(Math.max(c.x, pair.x) - Math.min(c.x + c.w, pair.x + pair.w), Math.max(c.y, pair.y) - Math.min(c.y + c.h, pair.y + pair.h))
49
+ : null;
42
50
  focal = {
43
51
  selector: raw.blocks[top].selector,
52
+ second: pair ? raw.blocks[order[1]].selector : null,
44
53
  dominance: areas.length >= 2 && areas[order[1]] > 0 ? round(areas[top] / areas[order[1]]) : null,
54
+ pairLead: areas.length >= 3 && areas[order[2]] > 0 ? round(areas[order[1]] / areas[order[2]]) : null,
55
+ pairGapPx: round(gap),
45
56
  x: round((c.x + c.w / 2) / w),
46
57
  y: round((c.y + c.h / 2) / h),
47
58
  };
@@ -49,7 +60,14 @@ export async function measureLayout(page, ctx = {}) {
49
60
 
50
61
  const emptyCells = raw.emptyCells.map(round);
51
62
  if (raw.ground.length) notes.push(`Covers the whole first view, read as ground and not as a block: ${unique(raw.ground).join(", ")}.`);
52
- if (raw.marks > 0 && ctx?.options !== true) notes.push("This page has data-block marks; check-design measures it as a finished page and ignores them (only render-options reads them).");
63
+ if (raw.marks > 0 && ctx?.options !== true) notes.push("This page has data-block marks; check-design measures it as a finished page and ignores them (only a file covered by an options goal is read by its marks).");
64
+ const pieces = (ctx?.goals ?? []).filter(isOptionsGoal).map((g) => g.piece);
65
+ if (ctx?.options === true && pieces.length && raw.byMarks) {
66
+ const named = pieces.length === 1 ? `the options goal "${pieces[0]}"` : `the options goals ${pieces.map((p) => `"${p}"`).join(", ")}`;
67
+ notes.push(`Read as an option (covered by ${named}): its data-block marks are the blocks, as render-options reads them.`);
68
+ } else if (ctx?.options === true && pieces.length && raw.marks > 0) {
69
+ notes.push("This file is covered by an options goal, but none of its data-block marks is in the first view, so it was read as a finished page.");
70
+ }
53
71
  if (raw.spaces.length) notes.push(`Space blocks are not counted as figure: ${unique(raw.spaces).join(", ")}.`);
54
72
  if (!raw.scrolls) notes.push("The page does not scroll; it was read as one section.");
55
73
  if (raw.noSections && raw.pinnedContent) notes.push("Content sits in a fixed container and was not measured.");
@@ -144,11 +144,12 @@ function inventory(pass) {
144
144
  delayMs: Math.round(a.delayMs),
145
145
  durationMs: Math.round(a.durationMs),
146
146
  easing: a.easing,
147
+ scrollLinked: a.scrollLinked === true,
147
148
  properties,
148
149
  from,
149
150
  to,
150
151
  moves,
151
- entrance: (trigger === "load" || trigger === "scroll") && endMs !== null && (opacityRises || returns),
152
+ entrance: (trigger === "load" || trigger === "scroll") && endMs !== null && a.scrollLinked !== true && (opacityRises || returns),
152
153
  layoutProps: properties.filter((p) => LAYOUT_PROPS.includes(p)),
153
154
  },
154
155
  });