@tjakoen/grain 0.1.33 → 0.1.34

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 (40) hide show
  1. package/README.md +49 -0
  2. package/catalog/catalog.test.ts +56 -1
  3. package/catalog/catalog.ts +208 -32
  4. package/components/dashboards/bullet-graph/bullet-graph.css +15 -0
  5. package/components/dashboards/bullet-graph/bullet-graph.md +34 -0
  6. package/components/dashboards/dash-panel/dash-panel.css +14 -0
  7. package/components/dashboards/dash-panel/dash-panel.md +66 -0
  8. package/components/dashboards/dashboard/dashboard.css +19 -0
  9. package/components/dashboards/dashboard/dashboard.md +70 -0
  10. package/components/dashboards/dashboards.test.ts +44 -0
  11. package/components/dashboards/delta/delta.css +9 -0
  12. package/components/dashboards/delta/delta.md +42 -0
  13. package/components/dashboards/rank-list/rank-list.css +10 -0
  14. package/components/dashboards/rank-list/rank-list.md +27 -0
  15. package/components/organisms/app-shell/app-shell.md +9 -1
  16. package/components/organisms/note/note.css +1 -2
  17. package/components/organisms/note/note.md +2 -2
  18. package/package.json +3 -2
  19. package/scripts/fixtures/grain-lint/accent-word.fail.html +28 -0
  20. package/scripts/fixtures/grain-lint/card-run.fail.html +34 -0
  21. package/scripts/fixtures/grain-lint/clean.html +32 -0
  22. package/scripts/fixtures/grain-lint/closing-signup.fail.html +29 -0
  23. package/scripts/fixtures/grain-lint/contrast-aa.fail.html +29 -0
  24. package/scripts/fixtures/grain-lint/dead-form.fail.html +28 -0
  25. package/scripts/fixtures/grain-lint/focus-visible.fail.html +29 -0
  26. package/scripts/fixtures/grain-lint/heading-widow.fail.html +29 -0
  27. package/scripts/fixtures/grain-lint/hero-overflow.fail.html +29 -0
  28. package/scripts/fixtures/grain-lint/image-ratio.fail.html +28 -0
  29. package/scripts/fixtures/grain-lint/label-above-heading.fail.html +31 -0
  30. package/scripts/fixtures/grain-lint/off-scale-space.fail.html +29 -0
  31. package/scripts/fixtures/grain-lint/phone-overflow.fail.html +29 -0
  32. package/scripts/fixtures/grain-lint/raw-color.fail.html +29 -0
  33. package/scripts/fixtures/grain-lint/reduced-motion.fail.html +30 -0
  34. package/scripts/fixtures/grain-lint/text-above-h1.allowed.html +28 -0
  35. package/scripts/fixtures/grain-lint/text-above-h1.fail.html +28 -0
  36. package/scripts/fixtures/grain-lint/tracked-caps.fail.html +29 -0
  37. package/scripts/grain-lint-rules.ts +524 -0
  38. package/scripts/grain-lint.test.ts +77 -0
  39. package/scripts/grain-lint.ts +179 -0
  40. package/styles/global.css +4 -3
@@ -0,0 +1,524 @@
1
+ // grain-lint-rules.ts: the tells of machine-made design, written as data.
2
+ //
3
+ // Each rule has one tier, and the tier decides what a finding does:
4
+ // floor blocks, with no override.
5
+ // reflex blocks unless the element (or an ancestor) carries
6
+ // data-grain-lint-allow="rule-id: reason", so the excuse sits in the diff.
7
+ // finish reports and never blocks.
8
+ //
9
+ // A rule checks the source text (static, no browser, runs on every edit), the rendered page
10
+ // (a function executed inside the page at each width), or both. Rendered checks run in the
11
+ // browser, so they must be self-contained: no closures over this module. They reach shared
12
+ // helpers through window.__gl, which grain-lint.ts installs before any rule runs.
13
+ //
14
+ // Every rule carries a fix line that names the GRAIN token, component or pattern to use instead,
15
+ // so the agent's correction lands inside the system rather than in fresh CSS.
16
+
17
+ export type Tier = "floor" | "reflex" | "finish";
18
+
19
+ /** One raw hit from a check, before tier and allow handling. */
20
+ export interface Hit {
21
+ selector: string;
22
+ detail: string;
23
+ /** The allow attribute that covers the hit, when the check could see one. */
24
+ allow?: string;
25
+ line?: number;
26
+ }
27
+
28
+ export interface StaticSource {
29
+ path: string;
30
+ text: string;
31
+ kind: "html" | "css";
32
+ }
33
+
34
+ export interface Rule {
35
+ id: string;
36
+ tier: Tier;
37
+ description: string;
38
+ fix: string;
39
+ static?: (src: StaticSource) => Hit[];
40
+ /** Runs in the page. Receives the viewport width; returns hits. */
41
+ rendered?: (width: number) => Hit[];
42
+ }
43
+
44
+ // ---- static helpers ---------------------------------------------------------------------------
45
+
46
+ const lineOf = (text: string, index: number): number => text.slice(0, index).split("\n").length;
47
+
48
+ /** Token files define colours on purpose; everything else must read them. */
49
+ const isTokenFile = (path: string): boolean =>
50
+ /(variables|tokens|themes?)[^/]*\.css$/.test(path) || /\/themes\//.test(path);
51
+
52
+ const COLOR_LITERAL = /#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|oklch|oklab|lab|lch)\(/g;
53
+
54
+ /** Strip comments and data: URLs so neither trips a colour or spacing check. */
55
+ const cleanCss = (css: string): string =>
56
+ css.replace(/\/\*[\s\S]*?\*\//g, m => m.replace(/[^\n]/g, " "))
57
+ .replace(/url\((["']?)data:[^)]*\)/g, m => m.replace(/[^\n]/g, " "));
58
+
59
+ /** Declarations outside custom-property definitions, with their offset in the text. */
60
+ function declarations(css: string): { prop: string; value: string; index: number }[] {
61
+ const out: { prop: string; value: string; index: number }[] = [];
62
+ const re = /([a-z-]+)\s*:\s*([^;{}]+)/g;
63
+ let m: RegExpExecArray | null;
64
+ while ((m = re.exec(css))) {
65
+ // Skip selector pseudo-classes such as a:hover { by requiring a terminator after the value.
66
+ const after = css[m.index + m[0].length];
67
+ if (after !== ";" && after !== "}") continue;
68
+ out.push({ prop: m[1]!, value: m[2]!.trim(), index: m.index });
69
+ }
70
+ return out;
71
+ }
72
+
73
+ /** CSS blocks in a source: the whole file for CSS, every <style> body and style="" for HTML. */
74
+ function cssChunks(src: StaticSource): { css: string; offset: number; inline: boolean }[] {
75
+ if (src.kind === "css") return [{ css: cleanCss(src.text), offset: 0, inline: false }];
76
+ const chunks: { css: string; offset: number; inline: boolean }[] = [];
77
+ for (const m of src.text.matchAll(/<style[^>]*>([\s\S]*?)<\/style>/g))
78
+ chunks.push({ css: cleanCss(m[1]!), offset: m.index! + m[0].indexOf(m[1]!), inline: false });
79
+ for (const m of src.text.matchAll(/\sstyle="([^"]*)"/g))
80
+ chunks.push({ css: m[1]! + ";", offset: m.index! + 8, inline: true });
81
+ return chunks;
82
+ }
83
+
84
+ const allowIn = (tag: string): string | undefined =>
85
+ /data-grain-lint-allow="([^"]*)"/.exec(tag)?.[1];
86
+
87
+ /** Visible text of a small HTML fragment. */
88
+ const textOf = (html: string): string => html.replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim();
89
+
90
+ // ---- the rules --------------------------------------------------------------------------------
91
+
92
+ export const RULES: Rule[] = [
93
+ // ======== floor ========
94
+ {
95
+ id: "contrast-aa",
96
+ tier: "floor",
97
+ description: "Text contrast below WCAG AA (4.5:1, or 3:1 for large text).",
98
+ fix: "Use --color-fg for body text and --color-muted only where the theme keeps it at AA.",
99
+ rendered: () => (window as any).__gl.contrast(),
100
+ },
101
+ {
102
+ id: "focus-visible",
103
+ tier: "floor",
104
+ description: "A focusable element that shows no ring when it takes keyboard focus.",
105
+ fix: "Keep grain's :focus-visible ring (the accent outline in global.css); never set outline: none without a replacement.",
106
+ rendered: () => (window as any).__gl.focus(),
107
+ },
108
+ {
109
+ id: "reduced-motion",
110
+ tier: "floor",
111
+ description: "Animation still running when the reader asked for reduced motion.",
112
+ fix: "Drive motion from the --motion-* tokens and wrap it in @media (prefers-reduced-motion: no-preference).",
113
+ rendered: () => {
114
+ const gl = (window as any).__gl;
115
+ const hits: Hit[] = [];
116
+ for (const a of document.getAnimations()) {
117
+ if (a.playState !== "running") continue;
118
+ const t = a.effect?.getComputedTiming();
119
+ const dur = Number(t?.duration ?? 0);
120
+ if (dur <= 100 && t?.iterations !== Infinity) continue;
121
+ const el = (a.effect as KeyframeEffect | null)?.target as Element | null;
122
+ if (!el) continue;
123
+ hits.push({ selector: gl.sel(el), detail: `${(a as any).animationName ?? "animation"} runs ${dur}ms under reduced motion`, allow: gl.allow(el) });
124
+ }
125
+ return hits;
126
+ },
127
+ },
128
+ {
129
+ id: "raw-color",
130
+ tier: "floor",
131
+ description: "A hardcoded colour where a semantic token belongs.",
132
+ fix: "Read a semantic token: --color-fg, --color-muted, --color-bg, --color-surface, --color-accent, --color-danger.",
133
+ static: src => {
134
+ if (src.kind === "css" && isTokenFile(src.path)) return [];
135
+ const hits: Hit[] = [];
136
+ for (const chunk of cssChunks(src))
137
+ for (const d of declarations(chunk.css)) {
138
+ if (d.prop.startsWith("--")) continue;
139
+ const v = d.value.replace(/var\([^)]*\)/g, "");
140
+ if (!v.match(COLOR_LITERAL)) continue;
141
+ hits.push({ selector: d.prop, detail: `${d.prop}: ${d.value}`, line: lineOf(src.text, chunk.offset + d.index) });
142
+ }
143
+ return hits;
144
+ },
145
+ },
146
+ {
147
+ id: "phone-overflow",
148
+ tier: "floor",
149
+ description: "Horizontal scroll or text clipped past the edge at phone width.",
150
+ fix: "Let the column wrap: .container or .board with --page-pad, and min-width: 0 on flex children.",
151
+ rendered: width => {
152
+ if (width > 400) return [];
153
+ const gl = (window as any).__gl;
154
+ const hits: Hit[] = [];
155
+ const root = document.scrollingElement!;
156
+ if (root.scrollWidth > innerWidth + 1) {
157
+ // Name the widest element that sticks out, which is what the agent has to fix.
158
+ let worst: Element | null = null, right = innerWidth + 1;
159
+ for (const el of document.body.querySelectorAll("*")) {
160
+ const r = el.getBoundingClientRect();
161
+ if (r.width && r.right > right && gl.visible(el)) { right = r.right; worst = el; }
162
+ }
163
+ hits.push({ selector: worst ? gl.sel(worst) : "html", detail: `page scrolls sideways: ${root.scrollWidth}px wide at ${innerWidth}px`, allow: worst ? gl.allow(worst) : undefined });
164
+ }
165
+ return hits;
166
+ },
167
+ },
168
+ {
169
+ id: "dead-form",
170
+ tier: "floor",
171
+ description: "A form whose submit goes nowhere: no action and no door to the contract.",
172
+ fix: "Give the form an action, or route it through the contract door with data-surface so a submit raises an intent.",
173
+ rendered: () => {
174
+ const gl = (window as any).__gl;
175
+ const hits: Hit[] = [];
176
+ for (const f of document.querySelectorAll("form")) {
177
+ const action = f.getAttribute("action");
178
+ const real = action && action !== "#" && !action.startsWith("javascript:");
179
+ if (real || f.closest("[data-surface]") || f.onsubmit || f.method === "dialog") continue;
180
+ hits.push({ selector: gl.sel(f), detail: "form has no action and no data-surface", allow: gl.allow(f) });
181
+ }
182
+ return hits;
183
+ },
184
+ },
185
+
186
+ // ======== reflex ========
187
+ {
188
+ id: "text-above-h1",
189
+ tier: "reflex",
190
+ description: "Text above the page's h1 other than breadcrumb navigation in the header.",
191
+ fix: "Put context below the headline: .masthead, then .byline (name and date), then .rule.",
192
+ static: src => {
193
+ if (src.kind !== "html") return [];
194
+ const hits: Hit[] = [];
195
+ for (const m of src.text.matchAll(/<(p|span|div|small)\b([^>]*)>([^<]{1,120}(?:<[^/][^>]*>[^<]*<\/[^>]+>[^<]*)*)<\/\1>\s*<h1\b/g)) {
196
+ hits.push({ selector: `${m[1]}${/class="([^"]*)"/.exec(m[2]!)?.[1]?.split(" ").map(c => "." + c).join("") ?? ""}`, detail: `"${textOf(m[3]!)}" sits above the h1`, allow: allowIn(m[2]!), line: lineOf(src.text, m.index!) });
197
+ }
198
+ return hits;
199
+ },
200
+ rendered: () => {
201
+ const gl = (window as any).__gl;
202
+ const h1 = document.querySelector("h1");
203
+ if (!h1 || !gl.visible(h1)) return [];
204
+ const hits: Hit[] = [];
205
+ const STOP = "main, article, section, [role=main], .board, .container, body";
206
+ let el: Element = h1;
207
+ while (el.parentElement && !el.matches(STOP)) {
208
+ for (let p = el.previousElementSibling; p; p = p.previousElementSibling) {
209
+ if (p.matches("nav, [role=navigation], [aria-label*=readcrumb], script, style, template, .sr-only")) continue;
210
+ const text = (p as HTMLElement).innerText?.trim();
211
+ if (!text || !gl.visible(p)) continue;
212
+ hits.push({ selector: gl.sel(p), detail: `"${text.slice(0, 60)}" sits above the h1`, allow: gl.allow(p) });
213
+ }
214
+ el = el.parentElement;
215
+ }
216
+ return hits;
217
+ },
218
+ },
219
+ {
220
+ id: "label-above-heading",
221
+ tier: "reflex",
222
+ description: "A short label sitting directly above a section heading.",
223
+ fix: "Let the heading carry the section: .section-head, with any context in the first sentence below it.",
224
+ static: src => {
225
+ if (src.kind !== "html") return [];
226
+ const hits: Hit[] = [];
227
+ for (const m of src.text.matchAll(/<(p|span|div|small)\b([^>]*)>([^<]{1,40})<\/\1>\s*<h[23]\b/g))
228
+ hits.push({ selector: m[1]!, detail: `"${m[3]!.trim()}" labels the heading below it`, allow: allowIn(m[2]!), line: lineOf(src.text, m.index!) });
229
+ return hits;
230
+ },
231
+ rendered: () => {
232
+ const gl = (window as any).__gl;
233
+ const hits: Hit[] = [];
234
+ for (const h of document.querySelectorAll("h2, h3")) {
235
+ const p = h.previousElementSibling as HTMLElement | null;
236
+ if (!p || p.matches("h1, h2, h3, h4, hr, nav, figure, img, ul, ol, table, pre") || !gl.visible(p) || !gl.visible(h)) continue;
237
+ const text = p.innerText?.trim() ?? "";
238
+ if (!text || text.length > 40 || p.children.length > 2) continue;
239
+ const small = parseFloat(getComputedStyle(p).fontSize) < parseFloat(getComputedStyle(h).fontSize);
240
+ if (small) hits.push({ selector: gl.sel(p), detail: `"${text}" labels ${h.tagName.toLowerCase()} "${(h as HTMLElement).innerText.trim().slice(0, 40)}"`, allow: gl.allow(p) });
241
+ }
242
+ return hits;
243
+ },
244
+ },
245
+ {
246
+ id: "tracked-caps",
247
+ tier: "reflex",
248
+ description: "Uppercase, letter-spaced text used as decoration.",
249
+ fix: "Use sentence case at --text-sm; let weight or position carry the hierarchy, not tracking.",
250
+ static: src => {
251
+ const hits: Hit[] = [];
252
+ for (const chunk of cssChunks(src)) {
253
+ if (chunk.inline) {
254
+ if (/text-transform\s*:\s*uppercase/.test(chunk.css) && /letter-spacing\s*:\s*(?!0|normal)/.test(chunk.css))
255
+ hits.push({ selector: "style attribute", detail: "uppercase with letter-spacing", line: lineOf(src.text, chunk.offset) });
256
+ continue;
257
+ }
258
+ for (const m of chunk.css.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
259
+ const body = m[2]!;
260
+ if (/text-transform\s*:\s*uppercase/.test(body) && /letter-spacing\s*:\s*(?!0[;\s}]|normal|-)/.test(body))
261
+ hits.push({ selector: m[1]!.trim().replace(/\s+/g, " "), detail: "uppercase with letter-spacing", line: lineOf(src.text, chunk.offset + m.index!) });
262
+ }
263
+ }
264
+ return hits;
265
+ },
266
+ rendered: () => {
267
+ const gl = (window as any).__gl;
268
+ const hits: Hit[] = [];
269
+ for (const el of gl.textElements() as HTMLElement[]) {
270
+ const cs = getComputedStyle(el);
271
+ if (cs.textTransform !== "uppercase") continue;
272
+ const ls = parseFloat(cs.letterSpacing);
273
+ if (!(ls > parseFloat(cs.fontSize) * 0.03)) continue;
274
+ hits.push({ selector: gl.sel(el), detail: `"${el.innerText.trim().slice(0, 40)}" is tracked caps`, allow: gl.allow(el) });
275
+ }
276
+ return hits;
277
+ },
278
+ },
279
+ {
280
+ id: "accent-word",
281
+ tier: "reflex",
282
+ description: "One or two words in a headline picked out in another colour.",
283
+ fix: "Keep the headline one ink (--color-fg); the one accent belongs to links and focus.",
284
+ rendered: () => {
285
+ const gl = (window as any).__gl;
286
+ const hits: Hit[] = [];
287
+ for (const h of document.querySelectorAll("h1, h2")) {
288
+ const base = getComputedStyle(h).color;
289
+ const whole = (h as HTMLElement).innerText.trim().length;
290
+ for (const c of h.querySelectorAll("span, em, strong, mark, b, i")) {
291
+ if (c.closest("a")) continue;
292
+ const t = (c as HTMLElement).innerText.trim();
293
+ if (!t || t.length > whole * 0.5) continue;
294
+ if (getComputedStyle(c).color !== base)
295
+ hits.push({ selector: gl.sel(c), detail: `"${t}" is coloured apart from its headline`, allow: gl.allow(c) });
296
+ }
297
+ }
298
+ return hits;
299
+ },
300
+ },
301
+ {
302
+ id: "card-run",
303
+ tier: "reflex",
304
+ description: "Three or more identical boxed cards in a row, each with its own heading.",
305
+ fix: "Ask whether a list (b-list) or a table carries this better; cards are for things a reader picks between.",
306
+ rendered: () => {
307
+ const gl = (window as any).__gl;
308
+ const hits: Hit[] = [];
309
+ for (const parent of document.querySelectorAll("body *")) {
310
+ const kids = [...parent.children].filter(k => gl.visible(k));
311
+ if (kids.length < 3) continue;
312
+ const sig = (k: Element) => k.tagName + "." + [...k.classList].sort().join(".");
313
+ if (new Set(kids.map(sig)).size !== 1) continue;
314
+ const boxed = kids.every(k => {
315
+ const cs = getComputedStyle(k);
316
+ return (parseFloat(cs.borderTopWidth) > 0 || cs.boxShadow !== "none" || cs.backgroundColor !== getComputedStyle(parent).backgroundColor)
317
+ && k.querySelector("h2, h3, h4");
318
+ });
319
+ if (boxed) hits.push({ selector: gl.sel(parent), detail: `${kids.length} identical cards (${sig(kids[0]!).toLowerCase()})`, allow: gl.allow(parent) });
320
+ }
321
+ return hits;
322
+ },
323
+ },
324
+ {
325
+ id: "closing-signup",
326
+ tier: "reflex",
327
+ description: "A sign-up block that closes the page.",
328
+ fix: "End on the content and the .rule; a subscribe offer is one underlined link in a sentence where it is earned.",
329
+ rendered: () => {
330
+ const gl = (window as any).__gl;
331
+ const forms = [...document.querySelectorAll("form")].filter(f => f.querySelector("input[type=email]") && gl.visible(f));
332
+ const last = forms.at(-1);
333
+ if (!last) return [];
334
+ // It closes the page when no visible text follows it in reading order.
335
+ const after = (gl.textElements() as Element[]).some(el =>
336
+ !last.contains(el) && (last.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING) && !el.closest("footer, nav"));
337
+ if (after) return [];
338
+ return [{ selector: gl.sel(last), detail: "an email sign-up closes the page", allow: gl.allow(last) }];
339
+ },
340
+ },
341
+ {
342
+ id: "hero-overflow",
343
+ tier: "reflex",
344
+ description: "The headline does not land inside the first screen.",
345
+ fix: "Use the masthead pattern at --display; drop the decorative block that pushes it down.",
346
+ rendered: width => {
347
+ if (width < 700) return [];
348
+ const gl = (window as any).__gl;
349
+ const h1 = document.querySelector("h1");
350
+ if (!h1 || !gl.visible(h1)) return [];
351
+ const r = h1.getBoundingClientRect();
352
+ if (r.bottom + scrollY <= innerHeight) return [];
353
+ return [{ selector: gl.sel(h1), detail: `h1 ends at ${Math.round(r.bottom + scrollY)}px, below the ${innerHeight}px first screen`, allow: gl.allow(h1) }];
354
+ },
355
+ },
356
+
357
+ // ======== finish ========
358
+ {
359
+ id: "heading-widow",
360
+ tier: "finish",
361
+ description: "A heading whose last line is a single word.",
362
+ fix: "h1 to h3 already set text-wrap: balance in global.css; do not override it.",
363
+ rendered: () => {
364
+ const gl = (window as any).__gl;
365
+ const hits: Hit[] = [];
366
+ for (const h of document.querySelectorAll("h1, h2, h3")) {
367
+ if (!gl.visible(h)) continue;
368
+ const words = gl.wordRects(h) as DOMRect[];
369
+ if (words.length < 3) continue;
370
+ const last = words.at(-1)!, prev = words.at(-2)!;
371
+ if (last.top - prev.top > last.height / 2)
372
+ hits.push({ selector: gl.sel(h), detail: `last line of "${(h as HTMLElement).innerText.trim().slice(0, 40)}" is one word`, allow: gl.allow(h) });
373
+ }
374
+ return hits;
375
+ },
376
+ },
377
+ {
378
+ id: "off-scale-space",
379
+ tier: "finish",
380
+ description: "A margin, padding or gap that is not on the spacing scale.",
381
+ fix: "Use a --space-* step (or --page-pad for page gutters).",
382
+ static: src => {
383
+ if (src.kind === "css" && isTokenFile(src.path)) return [];
384
+ const hits: Hit[] = [];
385
+ for (const chunk of cssChunks(src))
386
+ for (const d of declarations(chunk.css)) {
387
+ if (!/^(margin|padding|gap|row-gap|column-gap)(-|$)/.test(d.prop)) continue;
388
+ const v = d.value.replace(/var\([^)]*\)/g, "").replace(/calc\([^)]*\)/g, "").replace(/!important/, "");
389
+ const raw = v.match(/(?<![\w.-])\d*\.?\d+(px|rem|em)\b/g)?.filter(x => parseFloat(x) !== 0 && !/^1px$/.test(x));
390
+ if (raw?.length) hits.push({ selector: d.prop, detail: `${d.prop}: ${d.value}`, line: lineOf(src.text, chunk.offset + d.index) });
391
+ }
392
+ return hits;
393
+ },
394
+ },
395
+ {
396
+ id: "image-ratio",
397
+ tier: "finish",
398
+ description: "An image with no stated aspect ratio, so the page jumps as it loads.",
399
+ fix: "Give the img width and height attributes, or set aspect-ratio on its frame.",
400
+ rendered: () => {
401
+ const gl = (window as any).__gl;
402
+ const hits: Hit[] = [];
403
+ for (const img of document.querySelectorAll("img")) {
404
+ if (img.hasAttribute("width") && img.hasAttribute("height")) continue;
405
+ if (getComputedStyle(img).aspectRatio !== "auto") continue;
406
+ hits.push({ selector: gl.sel(img), detail: `img ${img.getAttribute("src")?.slice(0, 50) ?? ""} has no aspect ratio`, allow: gl.allow(img) });
407
+ }
408
+ return hits;
409
+ },
410
+ },
411
+ ];
412
+
413
+ export const RULE_IDS = RULES.map(r => r.id);
414
+
415
+ /** Parse an allow attribute ("rule-a: reason; rule-b: reason") and say whether it excuses a rule. */
416
+ export function allowReason(attr: string | undefined, ruleId: string): string | undefined {
417
+ if (!attr) return undefined;
418
+ for (const part of attr.split(";")) {
419
+ const [id, ...rest] = part.split(":");
420
+ const reason = rest.join(":").trim();
421
+ if (id?.trim() === ruleId && reason) return reason;
422
+ }
423
+ return undefined;
424
+ }
425
+
426
+ /**
427
+ * The in-page helpers every rendered rule reaches through window.__gl. Shipped as a string so it
428
+ * runs in the browser as written; grain-lint.ts evaluates it once per page load.
429
+ */
430
+ export const PAGE_HELPERS = String.raw`
431
+ window.__gl = (() => {
432
+ const esc = s => (window.CSS && CSS.escape) ? CSS.escape(s) : s;
433
+ const sel = el => {
434
+ const parts = [];
435
+ for (let e = el; e && e.nodeType === 1 && parts.length < 4; e = e.parentElement) {
436
+ if (e.id) { parts.unshift("#" + esc(e.id)); break; }
437
+ let p = e.tagName.toLowerCase();
438
+ const cls = [...e.classList].filter(c => !/^(is-|has-)/.test(c)).slice(0, 2);
439
+ if (cls.length) p += "." + cls.map(esc).join(".");
440
+ else if (e.parentElement) {
441
+ const same = [...e.parentElement.children].filter(s => s.tagName === e.tagName);
442
+ if (same.length > 1) p += ":nth-of-type(" + (same.indexOf(e) + 1) + ")";
443
+ }
444
+ parts.unshift(p);
445
+ if (e.tagName === "BODY") break;
446
+ }
447
+ return parts.join(" > ");
448
+ };
449
+ const allow = el => el.closest && el.closest("[data-grain-lint-allow]") ? el.closest("[data-grain-lint-allow]").getAttribute("data-grain-lint-allow") : undefined;
450
+ const visible = el => {
451
+ if (!el.getClientRects().length) return false;
452
+ const cs = getComputedStyle(el);
453
+ if (cs.visibility === "hidden" || cs.opacity === "0") return false;
454
+ const r = el.getBoundingClientRect();
455
+ return r.width > 1 && r.height > 1 && !el.closest("[hidden], [aria-hidden=true], .sr-only");
456
+ };
457
+ const ownText = el => [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim());
458
+ const textElements = () => [...document.body.querySelectorAll("*")].filter(el =>
459
+ !el.matches("script, style, noscript, svg, svg *, template") && ownText(el) && visible(el));
460
+
461
+ // Colours: normalise anything the browser can paint to RGBA through a 1x1 canvas.
462
+ const cv = document.createElement("canvas"); cv.width = cv.height = 1;
463
+ const cx = cv.getContext("2d", { willReadFrequently: true });
464
+ const rgba = c => { cx.clearRect(0, 0, 1, 1); cx.fillStyle = "#000"; cx.fillStyle = c; cx.fillRect(0, 0, 1, 1); const d = cx.getImageData(0, 0, 1, 1).data; return [d[0], d[1], d[2], d[3] / 255]; };
465
+ const over = (top, under) => { const a = top[3]; return [top[0] * a + under[0] * (1 - a), top[1] * a + under[1] * (1 - a), top[2] * a + under[2] * (1 - a), 1]; };
466
+ const lum = c => { const f = v => { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); }; return 0.2126 * f(c[0]) + 0.7152 * f(c[1]) + 0.0722 * f(c[2]); };
467
+ const ratio = (a, b) => { const x = lum(a), y = lum(b); return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05); };
468
+ const bgOf = el => {
469
+ const stack = [];
470
+ for (let e = el; e; e = e.parentElement) {
471
+ const cs = getComputedStyle(e);
472
+ if (cs.backgroundImage !== "none" && !/grain|noise|svg/.test(cs.backgroundImage)) return null; // an image under text: unknowable here
473
+ const c = rgba(cs.backgroundColor);
474
+ if (c[3] > 0) { stack.push(c); if (c[3] >= 1) break; }
475
+ }
476
+ let bg = [255, 255, 255, 1];
477
+ for (let i = stack.length - 1; i >= 0; i--) bg = over(stack[i], bg);
478
+ return bg;
479
+ };
480
+ const contrast = () => {
481
+ const hits = [];
482
+ for (const el of textElements()) {
483
+ const cs = getComputedStyle(el);
484
+ const bg = bgOf(el); if (!bg) continue;
485
+ const fg = over(rgba(cs.color), bg);
486
+ const size = parseFloat(cs.fontSize), bold = parseInt(cs.fontWeight) >= 700;
487
+ const need = (size >= 24 || (bold && size >= 18.66)) ? 3 : 4.5;
488
+ const r = ratio(fg, bg);
489
+ if (r < need) hits.push({ selector: sel(el), detail: '"' + el.innerText.trim().slice(0, 40) + '" is ' + r.toFixed(2) + ":1, needs " + need + ":1", allow: allow(el) });
490
+ }
491
+ return hits;
492
+ };
493
+ const focus = () => {
494
+ const hits = [];
495
+ const els = [...document.querySelectorAll("a[href], button, input:not([type=hidden]), select, textarea, [tabindex]:not([tabindex='-1'])")].filter(visible).slice(0, 60);
496
+ for (const el of els) {
497
+ const before = getComputedStyle(el);
498
+ const was = [before.outlineStyle, before.outlineWidth, before.boxShadow, before.borderColor, before.backgroundColor].join("|");
499
+ el.focus({ preventScroll: true, focusVisible: true });
500
+ if (document.activeElement !== el) continue;
501
+ const cs = getComputedStyle(el);
502
+ const ring = (cs.outlineStyle !== "none" && parseFloat(cs.outlineWidth) > 0) || cs.boxShadow !== "none";
503
+ const now = [cs.outlineStyle, cs.outlineWidth, cs.boxShadow, cs.borderColor, cs.backgroundColor].join("|");
504
+ const wrap = el.closest(".field");
505
+ const wrapRing = wrap && (getComputedStyle(wrap).outlineStyle !== "none" || getComputedStyle(wrap).boxShadow !== "none");
506
+ if (!ring && now === was && !wrapRing) hits.push({ selector: sel(el), detail: "no visible change on keyboard focus", allow: allow(el) });
507
+ el.blur();
508
+ }
509
+ return hits;
510
+ };
511
+ const wordRects = el => {
512
+ const rects = [];
513
+ const walk = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
514
+ for (let n = walk.nextNode(); n; n = walk.nextNode()) {
515
+ for (const m of n.textContent.matchAll(/\S+/g)) {
516
+ const r = document.createRange(); r.setStart(n, m.index); r.setEnd(n, m.index + m[0].length);
517
+ const b = r.getBoundingClientRect(); if (b.width) rects.push(b);
518
+ }
519
+ }
520
+ return rects;
521
+ };
522
+ return { sel, allow, visible, textElements, contrast, focus, wordRects };
523
+ })();
524
+ `;
@@ -0,0 +1,77 @@
1
+ // grain-lint.test.ts: every rule against its pair, a page that fails it and one clean page that
2
+ // passes every rule. Rendered checks drive a real Chromium, like the mermaid diagram test.
3
+ import { test, expect, beforeAll, afterAll } from "bun:test";
4
+ import { readFileSync, readdirSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+ import { chromium, type Browser, type Page } from "playwright";
8
+ import { RULES, allowReason } from "./grain-lint-rules.ts";
9
+ import { lintPage, lintSource, blocks, DEFAULT_WIDTHS, type LintPage } from "./grain-lint.ts";
10
+
11
+ const DIR = join(import.meta.dir, "fixtures", "grain-lint");
12
+ const url = (name: string) => pathToFileURL(join(DIR, name)).href;
13
+ const source = (name: string) => ({ path: name, text: readFileSync(join(DIR, name), "utf8"), kind: "html" as const });
14
+
15
+ let browser: Browser;
16
+ let page: Page;
17
+ beforeAll(async () => {
18
+ browser = await chromium.launch();
19
+ page = await (await browser.newContext({ reducedMotion: "reduce" })).newPage();
20
+ });
21
+ afterAll(async () => { await browser?.close(); });
22
+
23
+ test("every rule has a failing fixture, and no fixture names an unknown rule", () => {
24
+ const fails = readdirSync(DIR).filter(f => f.endsWith(".fail.html")).map(f => f.replace(".fail.html", ""));
25
+ expect(fails.sort()).toEqual(RULES.map(r => r.id).sort());
26
+ });
27
+
28
+ test("every rule carries a tier, a description and a fix line", () => {
29
+ for (const r of RULES) {
30
+ expect(["floor", "reflex", "finish"]).toContain(r.tier);
31
+ expect(r.description.length).toBeGreaterThan(10);
32
+ expect(r.fix).toMatch(/--[a-z]|\.[a-z]|grain|b-|aspect-ratio|width|action|text-wrap/);
33
+ expect(Boolean(r.static || r.rendered)).toBe(true);
34
+ }
35
+ });
36
+
37
+ test("the clean page passes every rule, static and rendered, at every width", async () => {
38
+ expect(lintSource(source("clean.html"))).toEqual([]);
39
+ expect(await lintPage(page as unknown as LintPage, url("clean.html"), { widths: DEFAULT_WIDTHS })).toEqual([]);
40
+ }, 60_000);
41
+
42
+ for (const rule of RULES) {
43
+ const file = `${rule.id}.fail.html`;
44
+ if (rule.static) test(`${rule.id} (static) fails its fixture`, () => {
45
+ const found = lintSource(source(file), { rules: [rule.id] });
46
+ expect(found.length).toBeGreaterThan(0);
47
+ expect(found.every(f => f.rule === rule.id && f.fix === rule.fix)).toBe(true);
48
+ });
49
+ if (rule.rendered) test(`${rule.id} (rendered) fails its fixture`, async () => {
50
+ const widths = rule.id === "phone-overflow" ? [360] : [1280];
51
+ const found = await lintPage(page as unknown as LintPage, url(file), { rules: [rule.id], widths });
52
+ expect(found.length).toBeGreaterThan(0);
53
+ expect(found[0]!.selector.length).toBeGreaterThan(0);
54
+ expect(blocks(found[0]!)).toBe(rule.tier !== "finish");
55
+ }, 30_000);
56
+ }
57
+
58
+ test("a reflex finding with a stated reason is allowed and does not block", async () => {
59
+ const found = await lintPage(page as unknown as LintPage, url("text-above-h1.allowed.html"), { rules: ["text-above-h1"], widths: [1280] });
60
+ expect(found).toHaveLength(1);
61
+ expect(found[0]!.allowed).toBe("a series name the reader navigates by");
62
+ expect(blocks(found[0]!)).toBe(false);
63
+ expect(lintSource(source("text-above-h1.allowed.html"), { rules: ["text-above-h1"] }).every(f => !blocks(f))).toBe(true);
64
+ }, 30_000);
65
+
66
+ test("an allow needs a reason, and names the rule it excuses", () => {
67
+ expect(allowReason("text-above-h1: series name", "text-above-h1")).toBe("series name");
68
+ expect(allowReason("text-above-h1:", "text-above-h1")).toBeUndefined();
69
+ expect(allowReason("card-run: picker; tracked-caps: kbd hints", "tracked-caps")).toBe("kbd hints");
70
+ expect(allowReason("card-run: picker", "tracked-caps")).toBeUndefined();
71
+ });
72
+
73
+ test("static mode stays under a second on the whole fixture set", () => {
74
+ const t = performance.now();
75
+ for (const f of readdirSync(DIR).filter(f => f.endsWith(".html"))) lintSource(source(f));
76
+ expect(performance.now() - t).toBeLessThan(1000);
77
+ });