@uselazuli/cli 1.0.1 → 1.0.2

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 (56) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +3 -3
  3. package/bin/lazuli.mjs +67 -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 +1 -1
  14. package/rules/ui/compose.yaml +27 -0
  15. package/rules/ui/review.yaml +2 -1
  16. package/skills/lazuli/SKILL.md +8 -5
  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-voice/SKILL.md +1 -0
  20. package/skills/lazuli-graphic-identity/SKILL.md +3 -1
  21. package/skills/lazuli-ui-composition/SKILL.md +4 -4
  22. package/skills/lazuli-ui-layout-review/SKILL.md +2 -2
  23. package/src/browser.mjs +2 -1
  24. package/src/commands/catalog.mjs +1 -1
  25. package/src/commands/check-design.mjs +51 -16
  26. package/src/commands/compare-designs.mjs +65 -2
  27. package/src/commands/draft-memo.mjs +4 -3
  28. package/src/commands/hooks.mjs +7 -5
  29. package/src/commands/record-log.mjs +54 -25
  30. package/src/commands/render-options.mjs +78 -15
  31. package/src/measure/a11y.mjs +8 -0
  32. package/src/measure/cases.mjs +22 -5
  33. package/src/measure/color.mjs +7 -0
  34. package/src/measure/in-page/a11y.js +33 -0
  35. package/src/measure/in-page/color.js +3 -1
  36. package/src/measure/in-page/extreme.js +28 -6
  37. package/src/measure/in-page/motion-probe.js +2 -0
  38. package/src/measure/in-page/type.js +3 -0
  39. package/src/measure/layout.mjs +9 -0
  40. package/src/measure/motion.mjs +2 -1
  41. package/src/measure/registry.mjs +3 -2
  42. package/src/measure/timeline.mjs +5 -5
  43. package/src/project/gate.mjs +12 -3
  44. package/src/project/lazuli-md.mjs +27 -3
  45. package/src/project/log.mjs +16 -10
  46. package/src/project/match.mjs +93 -5
  47. package/src/report/evaluators/a11y.mjs +21 -0
  48. package/src/report/evaluators/color.mjs +48 -1
  49. package/src/report/evaluators/extreme.mjs +43 -9
  50. package/src/report/evaluators/layout.mjs +10 -1
  51. package/src/report/evaluators/motion.mjs +10 -3
  52. package/src/report/evaluators/type.mjs +6 -3
  53. package/src/report/format.mjs +4 -4
  54. package/src/rules/load.mjs +18 -0
  55. package/src/rules/schema.mjs +8 -0
  56. package/templates/LAZULI.md +2 -0
@@ -4,7 +4,7 @@ import fs from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { toUrl } from "../browser.mjs";
7
- import { isAssetGoal, readLazuliMd } from "../project/lazuli-md.mjs";
7
+ import { isAssetGoal, isOptionsGoal, readLazuliMd } from "../project/lazuli-md.mjs";
8
8
  import { gateStatus as realGateStatus } from "../project/gate.mjs";
9
9
  import { identity } from "../project/match.mjs";
10
10
  import { readEdits, recordEdit } from "../project/edits.mjs";
@@ -150,7 +150,9 @@ export function summarizeForAgent(result, file) {
150
150
  const findings = result?.findings ?? [];
151
151
  const fails = findings.filter((f) => f.level === "fail");
152
152
  const hints = findings.filter((f) => f.level === "hint");
153
- const parts = [`Lazuli check-design after editing ${file}: ${result?.target} at ${HOOK_WIDTHS.join(", ")} px, ${fails.length} fail, ${hints.length} hint.`];
153
+ // A declared move is never a fail; it is counted so the agent sees the hint was explained.
154
+ const declared = findings.filter((f) => f.level === "declared");
155
+ const parts = [`Lazuli check-design after editing ${file}: ${result?.target} at ${HOOK_WIDTHS.join(", ")} px, ${fails.length} fail, ${hints.length} hint${declared.length > 0 ? `, ${declared.length} declared` : ""}.`];
154
156
  if (fails.length > 0) {
155
157
  parts.push(`Fails: ${fails.map((f) => `${f.ruleId} ${f.name}: ${String(f.message ?? "").replace(/\.+$/, "")}`).join("; ")}.`);
156
158
  }
@@ -176,8 +178,8 @@ function pickTargets(file, ext, md, cwd) {
176
178
  const found = [];
177
179
  const bad = [];
178
180
  for (const g of md.goals ?? []) {
179
- // A derived piece or a symbol is not a page: it is checked with --asset, so it never takes a page's place.
180
- if (!g.target || isAssetGoal(g)) {
181
+ // A derived piece or a symbol is not a page: it is checked with --asset, so it never takes a page's place. Nor is a folder of options.
182
+ if (!g.target || isAssetGoal(g) || isOptionsGoal(g)) {
181
183
  continue;
182
184
  }
183
185
  try {
@@ -235,7 +237,7 @@ export async function handlePostEdit(input, deps = {}) {
235
237
  return SILENT;
236
238
  }
237
239
  const ext = path.extname(file).toLowerCase();
238
- const watched = HTML.has(ext) || STYLE.has(ext) || (SOURCE.has(ext) && (md.goals ?? []).some((g) => g.target && isUrlTarget(g.target, cwd)));
240
+ const watched = HTML.has(ext) || STYLE.has(ext) || (SOURCE.has(ext) && (md.goals ?? []).some((g) => g.target && !isOptionsGoal(g) && isUrlTarget(g.target, cwd)));
239
241
  if (!watched) {
240
242
  return SILENT;
241
243
  }
@@ -2,7 +2,8 @@ import { readFile, writeFile, access, rename, rm, mkdir } from "node:fs/promises
2
2
  import { isDeepStrictEqual } from "node:util";
3
3
  import path from "node:path";
4
4
  import { KIT_RULES_DIR, loadKit } from "../rules/load.mjs";
5
- import { parseLazuliMd } from "../project/lazuli-md.mjs";
5
+ import { isOptionsGoal, parseLazuliMd } from "../project/lazuli-md.mjs";
6
+ import { entryTargetForm, matchGoals, sameEntryTarget } from "../project/match.mjs";
6
7
  import { writeBreak, writeDecision, LogInputError } from "../project/log.mjs";
7
8
  import { RecordError, findCapture, readRecords, withLock, writeFileAtomic } from "../project/records.mjs";
8
9
 
@@ -44,14 +45,31 @@ async function readText(file) {
44
45
  }
45
46
  }
46
47
 
47
- async function prepare({ cwd, piece, rule }) {
48
+ // --target names one file: a glob is refused (it would match only its own text and never apply).
49
+ function oneFile(target, cwd) {
50
+ if (target === undefined) {
51
+ return undefined;
52
+ }
53
+ if (String(target).includes("*")) {
54
+ throw new RecordInputError([`--target takes one file, not a glob: ${String(target).trim()}.`]);
55
+ }
56
+ return entryTargetForm(target, cwd);
57
+ }
58
+
59
+ // asWritten: --target as the person wrote it, for the messages.
60
+ async function prepare({ cwd, piece, rule, target, asWritten = target }) {
48
61
  const file = await findFile(cwd);
49
62
  const text = await readText(file);
50
- const goals = parseLazuliMd(text).goals;
63
+ const md = parseLazuliMd(text);
64
+ const goals = md.goals;
51
65
  const goal = goals.find((g) => norm(g.piece) === norm(piece));
52
66
  if (!goal) {
53
67
  throw new RecordInputError([`Piece "${piece}" is not a goal in LAZULI.md. Goals: ${goals.length > 0 ? goals.map((g) => g.piece).join(", ") : "none"}.`]);
54
68
  }
69
+ // A Target names one file of the piece: an exact Target of the goal or a file its glob covers.
70
+ if (target !== undefined && !matchGoals(md, target, path.resolve(cwd)).some((g) => norm(g.piece) === norm(goal.piece))) {
71
+ throw new RecordInputError([`--target ${String(asWritten).trim()} is not covered by the goal "${goal.piece}".`]);
72
+ }
55
73
  const kit = await loadKit({
56
74
  dirs: [process.env.LAZULI_RULES_DIR ?? KIT_RULES_DIR],
57
75
  projectDir: path.join(cwd, ".lazuli", "rules"),
@@ -132,7 +150,7 @@ function guard(fn) {
132
150
  // .lazuli/breaks.json: when each break was last set by record-break with a status other than kept.
133
151
  // { "breaks": { "<rule>|<piece>": "<ISO time>" } }, keys lower case. A file that cannot be read holds no times.
134
152
  const stampsFile = (cwd) => path.join(path.resolve(cwd), ".lazuli", "breaks.json");
135
- const stampKey = (rule, piece) => `${norm(rule)}|${norm(piece)}`;
153
+ const stampKey = (rule, piece, target) => `${norm(rule)}|${norm(piece)}${target ? `|${norm(target)}` : ""}`;
136
154
 
137
155
  async function readStamps(cwd) {
138
156
  try {
@@ -143,18 +161,18 @@ async function readStamps(cwd) {
143
161
  }
144
162
  }
145
163
 
146
- async function stampBreak(cwd, rule, piece) {
164
+ async function stampBreak(cwd, rule, piece, target) {
147
165
  const file = stampsFile(cwd);
148
166
  await mkdir(path.dirname(file), { recursive: true });
149
167
  await withLock(file, async () => {
150
- const breaks = { ...(await readStamps(cwd)), [stampKey(rule, piece)]: new Date().toISOString() };
168
+ const breaks = { ...(await readStamps(cwd)), [stampKey(rule, piece, target)]: new Date().toISOString() };
151
169
  await writeFileAtomic(file, JSON.stringify({ breaks }, null, 2));
152
170
  });
153
171
  }
154
172
 
155
173
  // A break becomes kept only after the separate reviewer has seen its declared effect: the latest review of a page
156
174
  // of the piece judged the piece, on a capture taken after the break was last set. The builder never confirms it alone.
157
- async function assertReviewed({ cwd, goals, rule, piece, was, given }) {
175
+ async function assertReviewed({ cwd, goals, rule, piece, target, was, given }) {
158
176
  const refuse = (why) => {
159
177
  throw new RecordError([`Break ${rule} on ${piece} cannot be kept yet: ${why}`]);
160
178
  };
@@ -171,12 +189,17 @@ async function assertReviewed({ cwd, goals, rule, piece, was, given }) {
171
189
  if (was.status === "reverted") {
172
190
  refuse("it is reverted. Set it to trying again with record-break --status trying, then review the page with review-design.");
173
191
  }
174
- const at = Date.parse((await readStamps(cwd))[stampKey(rule, piece)]);
192
+ const at = Date.parse((await readStamps(cwd))[stampKey(rule, piece, target)]);
175
193
  if (Number.isNaN(at)) {
176
194
  refuse("Lazuli has no record of when this break was last set. Run record-break again with --status trying, then review the page with review-design.");
177
195
  }
178
- const pages = goals.filter((g) => norm(g.piece) === norm(piece) && g.target);
196
+ // A break on one file is reviewed on that file; an options goal is never a page that a review counts for.
197
+ const pages = target ? [{ target }] : goals.filter((g) => norm(g.piece) === norm(piece) && g.target && !isOptionsGoal(g));
179
198
  if (pages.length === 0) {
199
+ const options = goals.filter((g) => norm(g.piece) === norm(piece) && isOptionsGoal(g)).map((g) => g.target);
200
+ if (options.length > 0) {
201
+ refuse(`"${piece}" covers option files (${options.join(", ")}); a break on it is kept per file: give --target <option file>.`);
202
+ }
180
203
  refuse(`"${piece}" has no Target, so no review can check the declared effect. Add a Target with set-goals, or revert the break.`);
181
204
  }
182
205
  for (const g of pages) {
@@ -202,25 +225,25 @@ async function assertReviewed({ cwd, goals, rule, piece, was, given }) {
202
225
  }
203
226
 
204
227
  // What a break on one id must hold before anything is written: a known rule that is not a norm, and for kept a review.
205
- async function checkBreak({ cwd, rule, piece, status, effect, check }) {
206
- const base = await prepare({ cwd, piece, rule });
228
+ async function checkBreak({ cwd, rule, piece, target, targetArg, status, effect, check }) {
229
+ const base = await prepare({ cwd, piece, rule, target, asWritten: targetArg });
207
230
  const { text, goal, known } = base;
208
231
  if (known.origin === "norm") {
209
232
  throw new RecordInputError([`${known.id} is a norm and cannot be broken. Fix it instead.`]);
210
233
  }
211
- const given = { rule: known.id, piece: goal.piece, status, ...(effect !== undefined ? { effect } : {}), ...(check !== undefined ? { check } : {}) };
212
- const next = guard(() => writeBreak(text, given));
213
- const isTarget = (b) => norm(b.rule) === norm(known.id) && norm(b.piece) === norm(goal.piece);
234
+ const given = { rule: known.id, piece: goal.piece, ...(target !== undefined ? { target } : {}), status, ...(effect !== undefined ? { effect } : {}), ...(check !== undefined ? { check } : {}) };
235
+ const next = guard(() => writeBreak(text, given, { sameTarget: (a, b) => sameEntryTarget(a, b, cwd) }));
236
+ const isTarget = (b) => norm(b.rule) === norm(known.id) && norm(b.piece) === norm(goal.piece) && sameEntryTarget(b.target, target, cwd);
214
237
  const keeping = String(status ?? "").trim() === "kept";
215
238
  if (keeping) {
216
239
  const md = parseLazuliMd(text);
217
- await assertReviewed({ cwd, goals: md.goals, rule: known.id, piece: goal.piece, was: md.breaks.find(isTarget), given });
240
+ await assertReviewed({ cwd, goals: md.goals, rule: known.id, piece: goal.piece, target, was: md.breaks.find(isTarget), given });
218
241
  }
219
242
  return { ...base, given, next, isTarget, keeping };
220
243
  }
221
244
 
222
245
  async function breakOne(args) {
223
- const { cwd, status } = args;
246
+ const { cwd, status, target } = args;
224
247
  const { file, text, goal, known, given, next, isTarget, keeping } = await checkBreak(args);
225
248
  const copies = await commit({
226
249
  file,
@@ -232,7 +255,7 @@ async function breakOne(args) {
232
255
  ["effect", "check", "status"].every((k) => (k in given ? norm(now[k]) === norm(given[k]) : was !== undefined && now[k] === was[k])) &&
233
256
  (was === undefined || now.piece === was.piece),
234
257
  // Stamped before LAZULI.md is written: a write that fails after it only asks for a newer review.
235
- beforeWrite: keeping ? undefined : () => stampBreak(cwd, known.id, goal.piece),
258
+ beforeWrite: keeping ? undefined : () => stampBreak(cwd, known.id, goal.piece, target),
236
259
  });
237
260
  const notes = copies > 1 ? [`Another entry for ${known.id} on ${goal.piece} was left as it was.`] : [];
238
261
  return { path: file, rule: known.id, piece: goal.piece, status, notes };
@@ -240,12 +263,17 @@ async function breakOne(args) {
240
263
 
241
264
  // One entry per id of a comma list. Every id is checked before the first is written, so a bad id writes nothing.
242
265
  // A rule that shares its measure with kit rules outside the list reports the same finding under them: they are named.
243
- export async function recordBreak({ cwd = process.cwd(), rule, piece, effect, check, status }) {
244
- const ids = [...new Set(String(rule ?? "").split(",").map((s) => s.trim()).filter((s) => s !== ""))];
266
+ export async function recordBreak({ cwd = process.cwd(), rule, piece, target: targetArg, effect, check, status }) {
267
+ const target = oneFile(targetArg, cwd);
268
+ // One entry per id, however it is written: pa11,PA11 is one id.
269
+ const ids = String(rule ?? "")
270
+ .split(",")
271
+ .map((s) => s.trim())
272
+ .filter((s, i, all) => s !== "" && all.findIndex((x) => norm(x) === norm(s)) === i);
245
273
  if (ids.length === 0) {
246
274
  throw new RecordInputError(["--rule needs a rule id."]);
247
275
  }
248
- const args = (id) => ({ cwd, rule: id, piece, effect, check, status });
276
+ const args = (id) => ({ cwd, rule: id, piece, target, targetArg, effect, check, status });
249
277
  const checked = [];
250
278
  for (const id of ids) {
251
279
  checked.push(await checkBreak(args(id)));
@@ -268,27 +296,28 @@ export async function recordBreak({ cwd = process.cwd(), rule, piece, effect, ch
268
296
  }
269
297
 
270
298
  // --rule of a decision: "<id> followed|broken|accepted", or "none" for a decision tied to no rule.
271
- export async function recordDecision({ cwd = process.cwd(), decision, piece, goal: served, rule, measure }) {
299
+ export async function recordDecision({ cwd = process.cwd(), decision, piece, target: targetArg, goal: served, rule, measure }) {
300
+ const target = oneFile(targetArg, cwd);
272
301
  const written = String(rule ?? "").trim();
273
302
  const none = /^none$/i.test(written);
274
303
  const match = /^(\S+)\s+(followed|broken|accepted)$/i.exec(written);
275
304
  if (!match && !none) {
276
305
  throw new RecordInputError(['--rule needs a rule id and followed, broken or accepted, for example "PA4 followed", or none.']);
277
306
  }
278
- const { file, text, goal, known } = await prepare({ cwd, piece, rule: none ? null : match[1] });
307
+ const { file, text, goal, known } = await prepare({ cwd, piece, target, asWritten: targetArg, rule: none ? null : match[1] });
279
308
  const action = none ? "none" : match[2].toLowerCase();
280
309
  if (action === "accepted" && known.origin === "norm") {
281
310
  throw new RecordInputError([`${known.id} is a norm and cannot be accepted. Fix it instead.`]);
282
311
  }
283
312
  const ruleId = none ? "none" : known.id;
284
- const given = { decision, piece: goal.piece, goal: served, rule: none ? "none" : `${known.id} ${action}`, measure };
285
- const next = guard(() => writeDecision(text, given));
313
+ const given = { decision, piece: goal.piece, ...(target !== undefined ? { target } : {}), goal: served, rule: none ? "none" : `${known.id} ${action}`, measure };
314
+ const next = guard(() => writeDecision(text, given, { sameTarget: (a, b) => sameEntryTarget(a, b, cwd) }));
286
315
  const copies = await commit({
287
316
  file,
288
317
  text,
289
318
  next,
290
319
  kind: "decisions",
291
- isTarget: (d) => norm(d.decision) === norm(decision) && norm(d.piece) === norm(goal.piece),
320
+ isTarget: (d) => norm(d.decision) === norm(decision) && norm(d.piece) === norm(goal.piece) && sameEntryTarget(d.target, target, cwd),
292
321
  expected: (now) => norm(now.goal) === norm(served) && now.rule === ruleId && now.action === action && norm(now.measure) === norm(measure),
293
322
  });
294
323
  const notes = copies > 1 ? [`Another entry for decision "${decision}" on ${goal.piece} was left as it was.`] : [];
@@ -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,34 @@ 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 crop note, when given, is a third line.
36
+ export function optionLabel(layout, findings, note, screensLine, distanceLine) {
31
37
  const f = layout.focal;
32
38
  const focal = f ? `focal ${f.selector} ${show(f.dominance, "x")} at (${show(f.x)}, ${show(f.y)})` : "focal none";
33
39
  const empty = layout.emptyShare === null ? "n/a" : `${Math.round(layout.emptyShare * 100)}%`;
34
40
  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")]]
41
+ const named = [["fails", ids("fail")], ["breaks", ids("break")], ["declared", ids("declared")], ["hints", ids("hint")]]
36
42
  .filter(([, list]) => list.length)
37
43
  .map(([word, list]) => `${word} ${list.join(", ")}`);
38
44
  return [
39
45
  `scale ${show(layout.textRatio, "x")} text, ${show(layout.areaRatio, "x")} area; empty ${empty}, spread ${show(layout.emptySpread)}; ${focal}`,
40
46
  named.length ? named.join("; ") : "no hints",
41
47
  ...(note ? [note] : []),
48
+ ...(screensLine ? [screensLine] : []),
49
+ ...(distanceLine ? [distanceLine] : []),
42
50
  ];
43
51
  }
44
52
 
53
+ // The label line of a thumbnail that shows more than the first view; null for one screen.
54
+ export const screensNote = (screens, height) =>
55
+ screens > 1 ? `thumbnail shows ${screens} screens of ${height} px; measures read the first view` : null;
56
+
57
+ // Why the earlier measures at a width were dropped: the option files changed, or only the height did.
58
+ export const droppedLine = (r, w) =>
59
+ r.droppedReason === "height"
60
+ ? `The earlier measures at ${w} px were read at ${r.droppedHeight} px, not ${r.height} px; they were dropped.`
61
+ : `Option files changed since the last run; the earlier measures at ${w} px were dropped.`;
62
+
45
63
  // The option canvas has its own width; rendered narrower, the view is a crop of it.
46
64
  export const cropNote = (width) => `The option is wider than ${width} px; this view is a crop and its bleeds are not meaningful.`;
47
65
  // The canvas is the body or html box, not the scroll width: a block that bleeds on purpose does not widen it.
@@ -65,10 +83,15 @@ figcaption { margin-top: 8px; display: flex; flex-direction: column; gap: 2px; }
65
83
  </style></head><body><h1>Options at ${width} px, in file order (no ranking)</h1><main>${items}</main></body></html>`;
66
84
  }
67
85
 
68
- async function optionFiles(folder) {
86
+ // The option files of the folder; a baseline kept in the folder is not an option (as compare-designs --options).
87
+ async function optionFiles(folder, baseline, cwd) {
69
88
  if (!existsSync(folder) || !statSync(folder).isDirectory()) throw new OptionsInputError(`Options folder not found: ${folder}`);
70
89
  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();
90
+ const files = entries
91
+ .filter((e) => e.isFile() && /\.html$/i.test(e.name))
92
+ .map((e) => e.name)
93
+ .sort()
94
+ .filter((name) => !baseline || !sameTarget(path.join(folder, name), baseline, cwd));
72
95
  if (files.length < MIN_OPTIONS || files.length > MAX_OPTIONS) {
73
96
  throw new OptionsInputError(`Found ${files.length} option files in ${folder}; show-options needs ${MIN_OPTIONS} to ${MAX_OPTIONS}.`);
74
97
  }
@@ -85,22 +108,47 @@ async function readEarlier(jsonPath) {
85
108
  }
86
109
  }
87
110
 
111
+ // The first `screens` viewport heights of the page, cut at the page end.
112
+ async function screensClip(page, width, height, screens) {
113
+ const pageHeight = await page.evaluate(() => Math.max(document.documentElement.scrollHeight, innerHeight));
114
+ return { x: 0, y: 0, width, height: Math.min(pageHeight, screens * height) };
115
+ }
116
+
88
117
  // Renders and measures the option files of a folder and writes one contact sheet per width.
89
118
  // Measures of widths rendered in an earlier run are kept when the option files are the same ones, and dropped otherwise.
90
119
  // 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 }) {
120
+ export async function renderOptions({ folder: given, widths = [1440], height = VIEWPORT_HEIGHT, screens = 1, cwd = process.cwd(), browser: givenBrowser, rules: givenRules, baseline }) {
121
+ checkHeight(height);
122
+ if (!Number.isInteger(screens) || screens < 1) throw new OptionsInputError("--screens needs a whole number of 1 or more.");
123
+ if (screens * height > FULL_PAGE_CAP_PX) throw new OptionsInputError(`--screens ${screens} at ${height} px is taller than ${FULL_PAGE_CAP_PX} px.`);
92
124
  const folder = path.resolve(cwd, given);
93
- const files = await optionFiles(folder);
125
+ const files = await optionFiles(folder, baseline, cwd);
94
126
  const all = givenRules ?? (await loadKit({ dirs: [process.env.LAZULI_RULES_DIR ?? KIT_RULES_DIR], projectDir: path.join(cwd, ".lazuli", "rules") })).rules;
95
127
  const rules = all.filter((r) => typeof r.measure === "string" && r.measure.startsWith("layout."));
128
+ // The breaks and declared moves of LAZULI.md apply to each option file through the goals that cover it (an options goal's glob).
129
+ const md = await readLazuliMd(cwd);
130
+ const knownIds = new Set(all.map((r) => r.id));
131
+ const declared = (findings, file) => {
132
+ if (!md) return findings;
133
+ const goals = matchGoals(md, file, cwd);
134
+ return applyDeclarations(applyBreaks(findings, md.breaks, goals, all, knownIds, file, cwd).findings, md, goals, all, file, cwd).findings;
135
+ };
96
136
 
97
137
  const jsonPath = path.join(folder, "options.json");
98
138
  const prev = await readEarlier(jsonPath);
99
139
  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]);
140
+ // An options.json written before heights were recorded was rendered at the default height.
141
+ const filesMatch = prev !== null && prev.options.length === files.length && prev.options.every((o, i) => o.file === files[i]);
142
+ const prevHeight = prev?.height ?? VIEWPORT_HEIGHT;
143
+ const sameFiles = filesMatch && prevHeight === height;
101
144
  const earlier = prevWidths.filter((w) => !widths.includes(w));
102
145
  const kept = sameFiles ? earlier : [];
103
146
  const dropped = prev && !sameFiles ? earlier : [];
147
+ const droppedWhy = dropped.length === 0 ? {} : filesMatch ? { droppedReason: "height", droppedHeight: prevHeight } : { droppedReason: "files" };
148
+ // The screens each width was rendered with: a kept width keeps its own (a 1.0.1 file holds one value for all).
149
+ const screensAt = {};
150
+ for (const w of kept) screensAt[String(w)] = prev.screensAt?.[String(w)] ?? prev.screens ?? 1;
151
+ for (const w of widths) screensAt[String(w)] = screens;
104
152
 
105
153
  const thumbs = path.join(folder, "thumbs");
106
154
  await fs.mkdir(thumbs, { recursive: true });
@@ -114,23 +162,38 @@ export async function renderOptions({ folder: given, widths = [1440], cwd = proc
114
162
  }
115
163
  return option;
116
164
  });
165
+ const baselineSigs = new Map();
117
166
  const pngs = new Map();
118
167
  const sheets = {};
119
- for (const w of kept) if (prev.sheets?.[String(w)]) sheets[String(w)] = prev.sheets[String(w)];
168
+ // A kept sheet whose file is gone is dropped from sheets and named, so the width can be run again.
169
+ const missingSheets = [];
170
+ for (const w of kept) {
171
+ const file = prev.sheets?.[String(w)];
172
+ if (!file) continue;
173
+ if (existsSync(file)) sheets[String(w)] = file;
174
+ else missingSheets.push(w);
175
+ }
120
176
  const browser = givenBrowser ?? (await openBrowser());
121
177
  try {
122
178
  for (const option of options) {
123
179
  const name = path.basename(option.file, path.extname(option.file));
124
180
  for (const width of widths) {
125
- const page = await openTarget(browser, path.join(folder, option.file), width, { cwd });
181
+ const file = path.join(folder, option.file);
182
+ const page = await openTarget(browser, file, width, { cwd, height });
126
183
  try {
127
184
  const layout = await measureLayout(page, { options: true });
128
185
  if ((await canvasWidth(page)) > width) option.notes[String(width)] = cropNote(width);
129
- const png = await page.screenshot();
186
+ const png = screens === 1 ? await page.screenshot() : await page.screenshot({ fullPage: true, clip: await screensClip(page, width, height, screens) });
130
187
  await fs.writeFile(path.join(thumbs, `${name}-${width}.png`), png);
131
188
  pngs.set(`${option.file}|${width}`, png);
132
189
  option.measures[String(width)] = layout;
133
- option.findings.push(...evaluate(rules, [{ width, layout }], MEASURERS));
190
+ if (baseline) {
191
+ // The baseline is read once per width, not once per option.
192
+ if (!baselineSigs.has(width)) baselineSigs.set(width, await signatureAt(browser, baseline, width, cwd, height));
193
+ const d = distance(await signatureAt(browser, file, width, cwd, height), baselineSigs.get(width));
194
+ (option.distances ??= {})[String(width)] = `distance ${d.value} from ${baselineName(baseline)} (H1)`;
195
+ }
196
+ option.findings.push(...declared(evaluate(rules, [{ width, layout }], MEASURERS), file));
134
197
  } finally {
135
198
  await page.context().close();
136
199
  }
@@ -140,7 +203,7 @@ export async function renderOptions({ folder: given, widths = [1440], cwd = proc
140
203
  const cells = options.map((o) => ({
141
204
  file: o.file,
142
205
  png: pngs.get(`${o.file}|${width}`),
143
- lines: optionLabel(o.measures[String(width)], o.findings.filter((f) => f.width === width), o.notes[String(width)]),
206
+ 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
207
  }));
145
208
  const context = await browser.newContext({ viewport: { width: SHEET_PX, height: 900 } });
146
209
  try {
@@ -158,7 +221,7 @@ export async function renderOptions({ folder: given, widths = [1440], cwd = proc
158
221
  }
159
222
 
160
223
  const allWidths = [...new Set([...(sameFiles ? prevWidths : []), ...widths])];
161
- const result = { folder, widths: allWidths, kept, dropped, options, sheets, jsonPath };
224
+ const result = { folder, widths: allWidths, height, screens, screensAt, ...(baseline ? { baselineHeight: height } : {}), kept, dropped, ...droppedWhy, missingSheets, options, sheets, jsonPath };
162
225
  await fs.writeFile(jsonPath, JSON.stringify(result, null, 2));
163
226
  return result;
164
227
  }
@@ -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,12 @@ 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 (null when the base reading has no bleed fields).
472
480
  export function compareBreaks(base, kase, injected = { removed: [] }) {
473
481
  const baseText = new Map(base.texts.map((t) => [t.id, t]));
474
482
  const baseKept = new Set(base.kept);
@@ -490,7 +498,7 @@ export function compareBreaks(base, kase, injected = { removed: [] }) {
490
498
  const describe = (o, copies, fallback, extra = {}) => {
491
499
  const b = baseText.get(o) ?? fallback;
492
500
  const suffix = copies > 0 ? ` (${copies} ${plural(copies, "copy", "copies")})` : "";
493
- return { id: o, selector: b?.selector ?? "", text: `${b?.text ?? ""}${suffix}`, ...extra };
501
+ return { id: o, selector: b?.selector ?? "", text: `${b?.text ?? ""}${suffix}`, bleedsAtRest: baseText.get(o)?.bleeds === true, ...extra };
494
502
  };
495
503
 
496
504
  const spills = group(kase.texts.filter((t) => t.spills && !baseText.get(originOf(t.id))?.spills).map((t) => t.id));
@@ -528,8 +536,17 @@ export function compareBreaks(base, kase, injected = { removed: [] }) {
528
536
  describe(g.ob, g.cb.size, caseText.get(g.ob)),
529
537
  ]);
530
538
 
531
- const dx = kase.overflowX - base.overflowX;
532
- return { overflowX: dx > SLACK_PX ? dx : null, spills, cut, lost, overlaps };
539
+ const grew = (k, b) => (Number.isFinite(k) && Number.isFinite(b) && k - b > SLACK_PX ? k - b : null);
540
+ const overflowX = grew(kase.overflowX, base.overflowX);
541
+ const clippedX = grew(kase.clippedX, base.clippedX);
542
+ // Past the right edge in the case and not at rest, or further past it than at rest.
543
+ const newlyPast = (t) => {
544
+ const b = baseText.get(originOf(t.id));
545
+ return !b?.pastRight || grew(t.right, b.right) !== null;
546
+ };
547
+ const wide = overflowX === null && clippedX === null ? [] : group(kase.texts.filter((t) => t.pastRight && newlyPast(t)).map((t) => t.id));
548
+ const restBleeds = base.texts.some((t) => "bleeds" in t) ? base.texts.filter((t) => t.bleeds).length : null;
549
+ return { overflowX, clippedX, spills, cut, lost, overlaps, wide, restBleeds };
533
550
  }
534
551
 
535
552
  // 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,38 @@
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
+ const treatmentOf = (el) => {
477
+ const rule = opts.treatment;
478
+ if (!rule || !Array.isArray(rule.filters)) return null;
479
+ const names = [];
480
+ let blend = null;
481
+ for (let node = el; node && node.nodeType === 1; node = node.parentElement) {
482
+ const cs = getComputedStyle(node);
483
+ for (const m of String(cs.filter).matchAll(/([a-z-]+)\(((?:[^()]|\([^()]*\))*)\)/g)) {
484
+ if (identity(m[1], m[2])) continue;
485
+ if (rule.filters.includes(m[1]) && !names.includes(m[1])) names.push(m[1]);
486
+ }
487
+ if (rule.blends === true && !blend && cs.mixBlendMode && cs.mixBlendMode !== "normal") blend = cs.mixBlendMode;
488
+ if (/^(section|article|body)$/i.test(node.tagName) && node !== el) break;
489
+ }
490
+ const parts = [...names, ...(blend ? ["mix-blend-mode " + blend] : [])];
491
+ return parts.length > 0 ? parts.join(", ") : null;
492
+ };
461
493
  const largeImages = [];
462
494
  let totalLarge = 0;
463
495
  if (Number.isFinite(opts.minSidePx) && opts.minSidePx > 0) {
@@ -473,6 +505,7 @@
473
505
  decorative: info.decorative || Boolean(el.closest("[aria-hidden=true]")),
474
506
  widthPx: round(r.width),
475
507
  heightPx: round(r.height),
508
+ treatment: treatmentOf(el),
476
509
  });
477
510
  }
478
511
  }
@@ -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
  });