okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221rc1 merge tui-update (3165c2e8a)a1cc285fa

main
16.7 KiB401 linesraw
1#!/usr/bin/env node
2/**
3 * Strata contrast probe.
4 *
5 *   node scripts/contrast.mjs
6 *
7 * Measures real rendered contrast in the running app rather than reading token
8 * values, because the things that actually fail are pairings: a label on a
9 * filled button, text on a translucent tint, muted copy on a quiet panel.
10 *
11 * Translucent backgrounds are composited over their ancestors before the ratio
12 * is computed, and every interactive state is measured separately — the kit's
13 * primary button passes at rest and fails on hover, which a single measurement
14 * would have missed.
15 *
16 * Requires the dev server. Exits non-zero if anything falls below WCAG AA.
17 */
18import { chromium } from 'playwright-core';
19import { existsSync } from 'node:fs';
20import { join } from 'node:path';
21import { homedir } from 'node:os';
22import { requireChromium } from './browser.mjs';
23
24const BASE = process.env.STRATA_URL ?? 'http://localhost:5199';
25
26const executablePath = requireChromium();
27
28if (!executablePath) {
29  console.error('No cached Chromium found. Run `npm run shot -- x.png <url>` once to confirm the harness.');
30  process.exit(2);
31}
32
33/** Runs in the page. Kept as a string so it can be injected verbatim. */
34const PROBE = () => {
35  // Chrome serialises color-mix() results as `color(srgb r g b)` with 0–1
36  // components. Reading those as 0–255 made a tinted fill look almost black,
37  // which silently defeated both the contrast and luminance measurements.
38  const parse = (c) => {
39    const s = String(c);
40    const srgb = s.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+))?\)/);
41    if (srgb) {
42      return { r: +srgb[1] * 255, g: +srgb[2] * 255, b: +srgb[3] * 255, a: srgb[4] === undefined ? 1 : +srgb[4] };
43    }
44    const n = s.match(/[\d.]+/g);
45    if (!n) return null;
46    return { r: +n[0], g: +n[1], b: +n[2], a: n[3] === undefined ? 1 : +n[3] };
47  };
48  const over = (f, bg) => ({
49    r: f.r * f.a + bg.r * (1 - f.a),
50    g: f.g * f.a + bg.g * (1 - f.a),
51    b: f.b * f.a + bg.b * (1 - f.a),
52    a: 1,
53  });
54  const lum = ({ r, g, b }) => {
55    const f = (v) => {
56      v /= 255;
57      return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
58    };
59    return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b);
60  };
61  const bgOf = (el) => {
62    const stack = [];
63    let n = el;
64    while (n) {
65      const c = parse(getComputedStyle(n).backgroundColor);
66      if (c.a > 0) stack.push(c);
67      if (c.a === 1) break;
68      n = n.parentElement;
69    }
70    if (!stack.length || stack[stack.length - 1].a < 1) stack.push({ r: 255, g: 255, b: 255, a: 1 });
71    let acc = stack[stack.length - 1];
72    for (let i = stack.length - 2; i >= 0; i -= 1) acc = over(stack[i], acc);
73    return acc;
74  };
75  const ratio = (a, b) => {
76    const [hi, lo] = [lum(a), lum(b)].sort((x, y) => y - x);
77    return Number(((hi + 0.05) / (lo + 0.05)).toFixed(2));
78  };
79  const probe = (label, sel, size) => {
80    const el = document.querySelector(sel);
81    if (!el) return null;
82    const px = size ?? parseFloat(getComputedStyle(el).fontSize);
83    const bg = bgOf(el);
84    const f0 = parse(getComputedStyle(el).color);
85    const fg = f0.a < 1 ? over(f0, bg) : f0;
86    const r = ratio(fg, bg);
87    const bold = Number(getComputedStyle(el).fontWeight) >= 700;
88    const large = px >= 24 || (px >= 18.66 && bold);
89    const need = large ? 3 : 4.5;
90    return { label, ratio: r, px: Math.round(px), need, pass: r >= need };
91  };
92  return [
93    probe('primary button', '.st-btn--primary'),
94    probe('secondary button', '.st-btn--secondary'),
95    probe('body copy', '.main__sub'),
96    probe('muted meta', '.st-msg__meta', 12),
97    probe('sidebar nav', '.navitem__text'),
98    probe('sidebar group label', '.navgroup__label', 11),
99    probe('user bubble', '.st-msg--user .st-bubble'),
100    probe('assistant bubble', '.st-msg--assistant .st-bubble'),
101    probe('accent badge', '.st-pill--accent, .st-badge--generating', 13),
102    probe('table header', '.st-table th', 11),
103    probe('mono code', '.mono', 13),
104    probe('file preview', '.filepreview__body', 13),
105    // The accent-filled surfaces. In dark mode these are a tinted material
106    // rather than a solid fill, so the label and the fill both need checking.
107    probe('accent fill label', '.st-btn--primary'),
108    probe('user bubble (tinted)', '.st-msg--user .st-bubble'),
109  ].filter(Boolean);
110};
111
112/**
113 * WCAG 1.4.11 — non-text contrast.
114 *
115 * Text pairings were covered; the *components* were not. A focus ring, an input
116 * boundary and a switch track all have to reach **3:1** against what sits
117 * beside them, and these are the things that vanish first when a theme is
118 * retuned, because nothing was measuring them.
119 *
120 * Measured against the actual adjacent surface, not against a token, for the
121 * same reason the text probe measures rendered pixels.
122 *
123 * **What is enforced and what is only reported.** 1.4.11 covers information
124 * *required to identify* a component, so the question for each thing measured
125 * is "is this the only thing telling you what it is or what state it is in?"
126 *
127 * - **Focus indicators — enforced.** Nothing else says "the keyboard is here".
128 * - **Card and input boundaries — reported.** A card is grouping, not a
129 *   control; a labelled input is identified by its label and position. The
130 *   light hairline is a deliberate house style shared with Apple's light-mode
131 *   controls, not a defect.
132 * - **Toggle track — reported.** The switch carries its state in the *knob
133 *   position*, which is not a contrast matter; the track colour reinforces it.
134 *
135 * The distinction matters because a probe that fails on things WCAG does not
136 * require is a probe people learn to ignore — and then it catches nothing.
137 */
138async function nonText(theme) {
139  const page = await browser.newPage({ viewport: { width: 1512, height: 1110 } });
140  const errors = [];
141  page.on('pageerror', (e) => errors.push(e.message));
142  const rows = [];
143  const boundaries = [];
144  for (const route of ['chat', 'models', 'tuning', 'settings', 'serving', 'skills']) {
145    await page.goto(`${BASE}/#/${route}`, { waitUntil: 'domcontentloaded' });
146    await page.waitForTimeout(1000);
147    if (theme === 'dark') {
148      const t = await page.$('button[title="Switch to dark mode"]');
149      if (t) {
150        await t.click();
151        await page.waitForTimeout(350);
152      }
153    }
154    // Drive the keyboard so a real focus ring renders rather than a simulated one.
155    await page.keyboard.press('Tab');
156    await page.keyboard.press('Tab');
157    await page.waitForTimeout(250);
158    const { results, info } = await page.evaluate(() => {
159      const lum = ({ r, g, b }) => {
160        const f = (v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; };
161        return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b);
162      };
163      const parse = (c) => {
164        const s = String(c);
165        const srgb = s.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+))?\)/);
166        if (srgb) return { r: +srgb[1] * 255, g: +srgb[2] * 255, b: +srgb[3] * 255, a: srgb[4] === undefined ? 1 : +srgb[4] };
167        const n = s.match(/[\d.]+/g);
168        if (!n || n.length < 3) return null;
169        return { r: +n[0], g: +n[1], b: +n[2], a: n[3] === undefined ? 1 : +n[3] };
170      };
171      const ratio = (a, b) => {
172        const [hi, lo] = [lum(a), lum(b)].sort((x, y) => y - x);
173        return (hi + 0.05) / (lo + 0.05);
174      };
175      const under = (el) => {
176        let n = el?.parentElement;
177        while (n) {
178          const c = parse(getComputedStyle(n).backgroundColor);
179          if (c && c.a > 0.85) return c;
180          n = n.parentElement;
181        }
182        return parse(getComputedStyle(document.body).backgroundColor) ?? { r: 255, g: 255, b: 255, a: 1 };
183      };
184      const results = [];
185      // the focus ring, whatever the browser is drawing it on
186      const focused = document.activeElement;
187      if (focused && focused !== document.body) {
188        const cs = getComputedStyle(focused);
189        const ring = parse(cs.outlineColor);
190        const w = parseFloat(cs.outlineWidth) || 0;
191        if (ring && w > 0 && cs.outlineStyle !== 'none') {
192          results.push({ label: `focus ring on ${focused.tagName.toLowerCase()}.${String(focused.className).split(' ')[0]}`, ratio: ratio(ring, under(focused)) });
193        }
194      }
195      const info = [];
196      for (const [label, sel] of [['input boundary', '.st-input'], ['card boundary', '.st-card']]) {
197        const el = document.querySelector(sel);
198        if (!el) continue;
199        const cs = getComputedStyle(el);
200        const border = parse(cs.borderTopColor);
201        const bw = parseFloat(cs.borderTopWidth) || 0;
202        if (border && bw > 0) info.push({ label, ratio: ratio(border, under(el)) });
203      }
204      // A switch's state is carried by knob position; the track reinforces it.
205      const sw = document.querySelector('.st-toggle');
206      if (sw) {
207        const track = parse(getComputedStyle(sw).backgroundColor);
208        if (track && track.a > 0.15) {
209          info.push({ label: `toggle track (state also shown by knob position)`, ratio: ratio(track, under(sw)) });
210        }
211      }
212      return { results, info };
213    });
214    rows.push(...results.map((r) => ({ ...r, route })));
215    boundaries.push(...info.map((r) => ({ ...r, route })));
216  }
217  await page.close();
218  return { rows, boundaries, errors };
219}
220
221const browser = await chromium.launch({ executablePath, args: ['--no-sandbox'] });
222let failures = 0;
223
224async function measure(theme, hoverSelector, view) {
225  const page = await browser.newPage({ viewport: { width: 1512, height: 1110 } });
226  const errors = [];
227  page.on('pageerror', (e) => errors.push(e.message));
228  await page.goto(`${BASE}/#/chat`, { waitUntil: 'domcontentloaded' });
229  await page.waitForTimeout(1200);
230  if (theme === 'dark') {
231    await page.click('button[title="Switch to dark mode"]');
232    await page.waitForTimeout(500);
233  }
234  if (view === 'conversation') {
235    await page.click('button.nav-new');
236    await page.waitForTimeout(300);
237    await page.fill('textarea', 'Show me everything');
238    await page.keyboard.press('Enter');
239    await page.waitForTimeout(6200);
240  }
241  if (view === 'workspace') {
242    /* The file preview renders on the kit's dark code surface. It inherited
243       that background but overrode the text colour with the light theme's ink,
244       giving #303030 on #1b1f23 — a ratio of 1.26, where body text needs 4.5.
245       Nothing measured it, because the probe only ever visited Chat. */
246    await page.goto(`${BASE}/#/workspace`, { waitUntil: 'domcontentloaded' });
247    await page.waitForTimeout(1600);
248    await page.evaluate(() => {
249      const file = [...document.querySelectorAll('.treerow')].find((r) => r.dataset.kind === 'file');
250      file?.click();
251    });
252    await page.waitForTimeout(1200);
253  }
254  if (hoverSelector) {
255    await page.hover(hoverSelector);
256    await page.waitForTimeout(350);
257  } else {
258    await page.mouse.move(760, 980); // park away from controls so nothing is hovered
259    await page.waitForTimeout(250);
260  }
261  const results = await page.evaluate(PROBE);
262  await page.close();
263  return { results, errors };
264}
265
266for (const theme of ['light', 'dark']) {
267  const nt = await nonText(theme);
268  console.log(`\n${theme} · non-text contrast (WCAG 1.4.11, enforced at 3:1)`);
269  const seen = new Set();
270  for (const r of nt.rows) {
271    if (seen.has(r.label)) continue;
272    seen.add(r.label);
273    const pass = r.ratio >= 3;
274    if (!pass) failures += 1;
275    console.log(`  ${r.ratio.toFixed(2).padStart(6)}  need 3.0  ${pass ? 'PASS' : 'FAIL'}  ${r.label} (${r.route})`);
276  }
277  const seenB = new Set();
278  const infoRows = nt.boundaries.filter((r) => !seenB.has(r.label) && seenB.add(r.label));
279  if (infoRows.length) {
280    console.log(`  — reported only, not required by 1.4.11 —`);
281    for (const r of infoRows) {
282      console.log(`  ${r.ratio.toFixed(2).padStart(6)}  (info)     ${r.label}`);
283    }
284  }
285  if (nt.errors.length) {
286    failures += nt.errors.length;
287    console.log(`  page errors: ${nt.errors.join('; ')}`);
288  }
289
290  for (const view of ['chrome', 'conversation', 'workspace']) {
291    const { results, errors } = await measure(theme, null, view);
292    console.log(`\n${theme} · ${view}`);
293    for (const r of results) {
294      if (!r.pass) failures += 1;
295      console.log(`  ${String(r.ratio).padStart(6)}  need ${r.need}  ${r.pass ? 'PASS' : 'FAIL'}  ${r.label} (${r.px}px)`);
296    }
297    if (errors.length) {
298      failures += errors.length;
299      console.log(`  page errors: ${errors.join('; ')}`);
300    }
301  }
302}
303
304// Hover is where the kit's primary button used to fail.
305/**
306 * How a tinted control stays visible, which differs by theme.
307 *
308 * On a near-black page the fill itself must separate from the background, so
309 * dark asserts fill-vs-page. On a near-white page a tinted fill cannot reach
310 * that ratio and does not need to: the control is delimited by its accent
311 * hairline and its shadow, the way Apple's light-mode tinted controls are. So
312 * light asserts the *border* is present and visibly differs from the page —
313 * which is exactly the thing that broke when the border was mistakenly bound to
314 * the white specular token.
315 */
316async function fillVsPage(theme) {
317  const page = await browser.newPage({ viewport: { width: 1512, height: 1110 } });
318  await page.goto(`${BASE}/#/chat`, { waitUntil: 'domcontentloaded' });
319  await page.waitForTimeout(1300);
320  if (theme === 'dark') {
321    await page.click('button[title="Switch to dark mode"]');
322    await page.waitForTimeout(500);
323  }
324  const out = await page.evaluate(() => {
325    const lum = ({ r, g, b }) => {
326      const f = (v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; };
327      return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b);
328    };
329    const parse = (c) => {
330      const s = String(c);
331      const srgb = s.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+))?\)/);
332      if (srgb) {
333        return { r: +srgb[1] * 255, g: +srgb[2] * 255, b: +srgb[3] * 255, a: srgb[4] === undefined ? 1 : +srgb[4] };
334      }
335      const n = s.match(/[\d.]+/g);
336      return n ? { r: +n[0], g: +n[1], b: +n[2], a: n[3] === undefined ? 1 : +n[3] } : null;
337    };
338    const btn = document.querySelector('.st-btn--primary');
339    if (!btn) return null;
340    const fill = parse(getComputedStyle(btn).backgroundColor);
341    if (!fill) return null;
342    let pageBg = parse(getComputedStyle(document.querySelector('.main__body') ?? document.body).backgroundColor);
343    if (!pageBg || (pageBg.r === 0 && pageBg.g === 0 && pageBg.b === 0)) {
344      pageBg = parse(getComputedStyle(document.body).backgroundColor);
345    }
346    const [hi, lo] = [lum(fill), lum(pageBg)].sort((a, b) => b - a);
347    const cs = getComputedStyle(btn);
348    const bw = parseFloat(cs.borderTopWidth) || 0;
349    const declared = parse(cs.borderTopColor);
350    // Composite the border over the page before comparing. A declared-but-faint
351    // border (say 2% alpha) differs wildly from the page as a raw value while
352    // being invisible on screen, which would make this check meaningless.
353    const border = declared
354      ? {
355          r: declared.r * (declared.a ?? 1) + pageBg.r * (1 - (declared.a ?? 1)),
356          g: declared.g * (declared.a ?? 1) + pageBg.g * (1 - (declared.a ?? 1)),
357          b: declared.b * (declared.a ?? 1) + pageBg.b * (1 - (declared.a ?? 1)),
358        }
359      : null;
360    const borderDelta = border
361      ? Math.max(Math.abs(border.r - pageBg.r), Math.abs(border.g - pageBg.g), Math.abs(border.b - pageBg.b))
362      : 0;
363    return {
364      ratio: Number(((hi + 0.05) / (lo + 0.05)).toFixed(2)),
365      luminance: Number(lum(fill).toFixed(3)),
366      borderWidth: bw,
367      borderDelta: Math.round(borderDelta),
368    };
369  });
370  await page.close();
371  return out;
372}
373
374for (const theme of ['light', 'dark']) {
375  const r = await fillVsPage(theme);
376  if (!r) continue;
377  if (theme === 'dark') {
378    const ok = r.ratio >= 1.5;
379    if (!ok) failures += 1;
380    console.log(
381      `\ndark · primary fill vs page\n  ${String(r.ratio).padStart(6)}  need 1.5  ${ok ? 'PASS' : 'FAIL'}  fill separates from the page (luminance ${r.luminance})`,
382    );
383  } else {
384    // Light: the hairline carries the definition, not the fill.
385    const ok = r.borderWidth >= 1 && r.borderDelta >= 10;
386    if (!ok) failures += 1;
387    console.log(
388      `\nlight · primary fill definition\n  ${String(r.borderDelta).padStart(6)}  need 10   ${ok ? 'PASS' : 'FAIL'}  accent hairline delimits the tinted fill (fill is only ${r.ratio}:1 by design)`,
389    );
390  }
391}
392
393const { results: hovered } = await measure('light', '.nav__rail-hide', 'chrome');
394const primary = hovered.find((r) => r.label === 'primary button');
395if (primary && !primary.pass) failures += 1;
396console.log(`\nlight · primary button hovered\n  ${String(primary?.ratio).padStart(6)}  need ${primary?.need}  ${primary?.pass ? 'PASS' : 'FAIL'}  primary button (hover)`);
397
398await browser.close();
399
400console.log(failures ? `\ncontrast probe: ${failures} failure(s)` : '\ncontrast probe: all pairings pass WCAG AA');
401process.exit(failures ? 1 : 0);