@tjakoen/grain 0.1.33 → 0.1.35

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.
@@ -0,0 +1,179 @@
1
+ #!/usr/bin/env bun
2
+ // grain-lint.ts: check a GRAIN page for the tells of machine-made design.
3
+ //
4
+ // bun grain-lint.ts <url|file.html> [more...] rendered: Playwright at 360, 768 and 1280
5
+ // bun grain-lint.ts --static <file|dir> [more...] static: source text only, no browser, < 1s
6
+ // flags: --json --rule <id> (repeatable) --widths 360,768,1280
7
+ //
8
+ // Exit 1 on any floor finding, or a reflex finding without a data-grain-lint-allow reason.
9
+ // Finish findings report and never block. The rules live in grain-lint-rules.ts.
10
+ import { readFileSync, readdirSync, statSync, existsSync } from "node:fs";
11
+ import { resolve, extname, join } from "node:path";
12
+ import { pathToFileURL } from "node:url";
13
+ import { RULES, PAGE_HELPERS, allowReason, type Rule, type Tier, type StaticSource, type Hit } from "./grain-lint-rules.ts";
14
+
15
+ export interface Finding {
16
+ rule: string;
17
+ tier: Tier;
18
+ target: string;
19
+ selector: string;
20
+ detail: string;
21
+ fix: string;
22
+ widths?: number[];
23
+ line?: number;
24
+ /** The reason from data-grain-lint-allow, when one excuses a reflex finding. */
25
+ allowed?: string;
26
+ }
27
+
28
+ export interface LintOptions { rules?: string[]; widths?: number[] }
29
+
30
+ export const DEFAULT_WIDTHS = [360, 768, 1280];
31
+
32
+ const pick = (ids?: string[]): Rule[] => ids?.length ? RULES.filter(r => ids.includes(r.id)) : RULES;
33
+
34
+ function toFinding(rule: Rule, target: string, hit: Hit, width?: number): Finding {
35
+ const allowed = rule.tier === "reflex" ? allowReason(hit.allow, rule.id) : undefined;
36
+ return {
37
+ rule: rule.id, tier: rule.tier, target, selector: hit.selector, detail: hit.detail, fix: rule.fix,
38
+ ...(width ? { widths: [width] } : {}), ...(hit.line ? { line: hit.line } : {}), ...(allowed ? { allowed } : {}),
39
+ };
40
+ }
41
+
42
+ /** A finding blocks when it is floor, or reflex with no recorded reason. */
43
+ export const blocks = (f: Finding): boolean => f.tier === "floor" || (f.tier === "reflex" && !f.allowed);
44
+
45
+ // ---- static mode ------------------------------------------------------------------------------
46
+
47
+ export function lintSource(src: StaticSource, opts: LintOptions = {}): Finding[] {
48
+ const out: Finding[] = [];
49
+ for (const rule of pick(opts.rules)) {
50
+ if (!rule.static) continue;
51
+ for (const hit of rule.static(src)) out.push(toFinding(rule, src.path, hit));
52
+ }
53
+ return out;
54
+ }
55
+
56
+ function collect(path: string, into: string[] = []): string[] {
57
+ if (statSync(path).isDirectory()) {
58
+ for (const name of readdirSync(path)) {
59
+ if (name === "node_modules" || name.startsWith(".")) continue;
60
+ collect(join(path, name), into);
61
+ }
62
+ } else if ([".html", ".css"].includes(extname(path))) into.push(path);
63
+ return into;
64
+ }
65
+
66
+ export function lintStatic(paths: string[], opts: LintOptions = {}): Finding[] {
67
+ const files = paths.flatMap(p => collect(resolve(p)));
68
+ return files.flatMap(path =>
69
+ lintSource({ path, text: readFileSync(path, "utf8"), kind: extname(path) === ".css" ? "css" : "html" }, opts));
70
+ }
71
+
72
+ // ---- rendered mode ----------------------------------------------------------------------------
73
+
74
+ /** axe-core's source, when the consumer carries it (the portfolio does), for contrast and focus. */
75
+ function axeSource(): string | undefined {
76
+ try { return readFileSync(Bun.resolveSync("axe-core/axe.min.js", process.cwd()), "utf8"); } catch { return undefined; }
77
+ }
78
+
79
+ /** The page surface the rendered mode needs; Playwright's Page satisfies it. */
80
+ export interface LintPage {
81
+ setViewportSize(size: { width: number; height: number }): Promise<void>;
82
+ goto(url: string, opts?: { waitUntil?: "load" | "networkidle" }): Promise<unknown>;
83
+ evaluate<R, A>(fn: (arg: A) => R, arg: A): Promise<R>;
84
+ evaluate<R>(script: string): Promise<R>;
85
+ }
86
+
87
+ export async function lintPage(page: LintPage, url: string, opts: LintOptions = {}): Promise<Finding[]> {
88
+ const rules = pick(opts.rules).filter(r => r.rendered);
89
+ const axe = rules.some(r => r.id === "contrast-aa") ? axeSource() : undefined;
90
+ const byKey = new Map<string, Finding>();
91
+ for (const width of opts.widths ?? DEFAULT_WIDTHS) {
92
+ await page.setViewportSize({ width, height: width < 700 ? 780 : 800 });
93
+ await page.goto(url, { waitUntil: "load" });
94
+ await page.evaluate("document.fonts ? document.fonts.ready.then(() => true) : true");
95
+ await page.evaluate(PAGE_HELPERS);
96
+ for (const rule of rules) {
97
+ let hits: Hit[];
98
+ if (rule.id === "contrast-aa" && axe) hits = await axeContrast(page, axe);
99
+ else hits = await page.evaluate(new Function("w", `return (${rule.rendered!.toString()})(w)`) as (w: number) => Hit[], width);
100
+ for (const hit of hits) {
101
+ const key = `${rule.id}|${hit.selector}`;
102
+ const seen = byKey.get(key);
103
+ if (seen) { if (!seen.widths!.includes(width)) seen.widths!.push(width); continue; }
104
+ byKey.set(key, toFinding(rule, url, hit, width));
105
+ }
106
+ }
107
+ }
108
+ return [...byKey.values()];
109
+ }
110
+
111
+ /** Reuse axe's color-contrast run rather than writing the rule twice, when axe is installed. */
112
+ async function axeContrast(page: LintPage, axe: string): Promise<Hit[]> {
113
+ await page.evaluate(axe);
114
+ return page.evaluate(`axe.run(document, { runOnly: ["color-contrast"], resultTypes: ["violations"] }).then(r =>
115
+ r.violations.flatMap(v => v.nodes.map(n => {
116
+ const el = document.querySelector(n.target[0]);
117
+ return { selector: String(n.target[0]), detail: n.failureSummary.split("\\n").pop().trim(), allow: el ? window.__gl.allow(el) : undefined };
118
+ })))`);
119
+ }
120
+
121
+ export async function lintUrls(targets: string[], opts: LintOptions = {}): Promise<Finding[]> {
122
+ const { chromium } = await import("playwright");
123
+ const browser = await chromium.launch();
124
+ try {
125
+ const context = await browser.newContext({ reducedMotion: "reduce" });
126
+ const page = await context.newPage();
127
+ const out: Finding[] = [];
128
+ for (const t of targets) {
129
+ const url = /^https?:|^file:/.test(t) ? t : pathToFileURL(resolve(t)).href;
130
+ out.push(...await lintPage(page as unknown as LintPage, url, opts));
131
+ }
132
+ return out;
133
+ } finally { await browser.close(); }
134
+ }
135
+
136
+ // ---- report -----------------------------------------------------------------------------------
137
+
138
+ const TIER_ORDER: Tier[] = ["floor", "reflex", "finish"];
139
+
140
+ export function format(findings: Finding[]): string {
141
+ const lines: string[] = [];
142
+ for (const tier of TIER_ORDER) {
143
+ const group = findings.filter(f => f.tier === tier);
144
+ if (!group.length) continue;
145
+ const verb = tier === "finish" ? "reports" : "blocks";
146
+ lines.push(`${tier.toUpperCase()} (${group.length}, ${verb})`);
147
+ for (const f of group) {
148
+ const where = f.line ? `${f.target}:${f.line}` : f.target;
149
+ const at = f.widths ? ` @${f.widths.join(",")}` : "";
150
+ const mark = f.allowed ? " allowed" : "";
151
+ lines.push(` ${f.rule} ${f.selector}${at}${mark}`);
152
+ lines.push(` ${f.detail} (${where})`);
153
+ lines.push(f.allowed ? ` reason: ${f.allowed}` : ` fix: ${f.fix}`);
154
+ }
155
+ }
156
+ const blocking = findings.filter(blocks).length;
157
+ lines.push(blocking ? `grain-lint: ${blocking} blocking finding(s)` : `grain-lint: clean (${findings.length} non-blocking)`);
158
+ return lines.join("\n");
159
+ }
160
+
161
+ // ---- CLI --------------------------------------------------------------------------------------
162
+
163
+ if (import.meta.main) {
164
+ const args = process.argv.slice(2);
165
+ const flag = (name: string) => { const i = args.indexOf(name); if (i < 0) return false; args.splice(i, 1); return true; };
166
+ const values = (name: string) => { const out: string[] = []; let i; while ((i = args.indexOf(name)) >= 0) { out.push(args[i + 1]!); args.splice(i, 2); } return out; };
167
+ const json = flag("--json"), isStatic = flag("--static");
168
+ const rules = values("--rule");
169
+ const widths = values("--widths").flatMap(w => w.split(",").map(Number));
170
+ if (!args.length) { console.error("usage: grain-lint [--static] [--json] [--rule id] <url|file|dir>..."); process.exit(2); }
171
+ const unknown = rules.filter(r => !RULES.some(x => x.id === r));
172
+ if (unknown.length) { console.error(`unknown rule: ${unknown.join(", ")}`); process.exit(2); }
173
+ const opts = { rules, ...(widths.length ? { widths } : {}) };
174
+ const missing = args.filter(a => !/^https?:|^file:/.test(a) && !existsSync(a));
175
+ if (missing.length) { console.error(`not found: ${missing.join(", ")}`); process.exit(2); }
176
+ const findings = isStatic ? lintStatic(args, opts) : await lintUrls(args, opts);
177
+ console.log(json ? JSON.stringify(findings, null, 2) : format(findings));
178
+ process.exit(findings.some(blocks) ? 1 : 0);
179
+ }
package/styles/global.css CHANGED
@@ -45,10 +45,11 @@ body::before {
45
45
  h1, h2, h3 { font-weight: var(--font-weight-regular); letter-spacing: -0.01em; text-wrap: balance; }
46
46
  p { margin: 0 0 var(--space-4); text-wrap: pretty; } /* no orphans/ragged breaks — no JS */
47
47
 
48
- /* ---- Masthead (DESIGN-SYSTEM §5): eyebrow → display headline → hairline rule -- */
49
- .eyebrow { font-size: var(--text-sm); color: var(--color-fg); margin: 0 0 var(--space-2); }
50
- .eyebrow .name { text-decoration: underline; }
48
+ /* ---- Masthead (DESIGN-SYSTEM §5): display headline → byline → hairline rule ------
49
+ Context sits BELOW the headline, never above it: no eyebrow. The byline carries name + date. */
51
50
  .masthead { font-size: var(--display); line-height: var(--leading-tight); letter-spacing: -0.01em; margin: 0 0 var(--space-3); }
51
+ .byline { font-size: var(--text-sm); color: var(--color-fg); margin: 0 0 var(--space-3); }
52
+ .byline .name { text-decoration: underline; }
52
53
  .rule { border: 0; border-bottom: var(--rule); margin: 0 0 var(--space-6); }
53
54
 
54
55
  /* ---- Section header: label left, underlined action right -------------------- */