okami.mom/strata

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

Niko1221rc1 merge tui-update (3165c2e8a)a1cc285fa

main
7.5 KiB200 linesraw
1#!/usr/bin/env node
2/**
3 * Dark-mode brightness budget, and material layering.
4 *
5 *   node scripts/luminance.mjs
6 *
7 * The complaint this exists to prevent: "the green buttons are too rough on the
8 * eye if you keep working longer". It was correct — the primary button used to
9 * be a solid #34d399 at relative luminance 0.496 against a page at 0.005, making
10 * the brightest and most saturated object in the interface the one thing you are
11 * invited to click, usually several times a screen.
12 *
13 * So: in dark mode, no *large* surface may exceed a luminance ceiling. Small
14 * elements are exempt — a status dot or a 2px progress bar is meant to be vivid,
15 * and it is the area of a bright fill that fatigues, not its existence.
16 *
17 * It also asserts the Liquid Glass layering rule: **no material may be a
18 * descendant of another material.** Glass cannot sample glass — nesting blurs an
19 * already-blurred backdrop, doubling the compositor cost for a muddier result.
20 * The slash menu was doing exactly this inside the composer.
21 *
22 * Requires the dev server.
23 */
24import { chromium } from 'playwright-core';
25import { existsSync } from 'node:fs';
26import { join } from 'node:path';
27import { homedir } from 'node:os';
28import { requireChromium } from './browser.mjs';
29
30const BASE = process.env.STRATA_URL ?? 'http://localhost:5199';
31/** Anything at or above this projected area is "large". Roughly a 64×64 block. */
32const LARGE_AREA = 4000;
33
34/**
35 * And it has to be large in *both* directions.
36 *
37 * Area alone called a 501×8px progress fill a "large bright surface" — the same
38 * verdict as a 64×64 block, for a hairline. Worse, a progress fill's width is
39 * its value, so the check passed or failed on the same build depending on how
40 * full the bar happened to be. A minimum thickness keeps blocks and drops
41 * hairlines, meters and slivers.
42 */
43const MIN_THICKNESS = 32;
44/** Ceiling for the relative luminance of a large surface, in dark mode. */
45const CEILING = 0.15;
46
47const executablePath = requireChromium();
48
49if (!executablePath) {
50  console.error('No cached Chromium found.');
51  process.exit(2);
52}
53
54const browser = await chromium.launch({ executablePath, args: ['--no-sandbox'] });
55const page = await browser.newPage({ viewport: { width: 1512, height: 1110 } });
56const errors = [];
57page.on('pageerror', (e) => errors.push(e.message));
58
59/**
60 * Walk every element, composite its background over its ancestors, and report
61 * the large bright ones. Runs in the page.
62 */
63const SURVEY = ({ largeArea, minThickness, ceiling }) => {
64  // Chrome serialises color-mix() results as `color(srgb r g b)` with 0–1
65  // components. Reading those as 0–255 made a tinted fill look almost black,
66  // which silently defeated both the contrast and luminance measurements.
67  const parse = (c) => {
68    const s = String(c);
69    const srgb = s.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+))?\)/);
70    if (srgb) {
71      return { r: +srgb[1] * 255, g: +srgb[2] * 255, b: +srgb[3] * 255, a: srgb[4] === undefined ? 1 : +srgb[4] };
72    }
73    const n = s.match(/[\d.]+/g);
74    if (!n) return null;
75    return { r: +n[0], g: +n[1], b: +n[2], a: n[3] === undefined ? 1 : +n[3] };
76  };
77  const lum = ({ r, g, b }) => {
78    const f = (v) => {
79      v /= 255;
80      return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
81    };
82    return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b);
83  };
84  const bgOf = (el) => {
85    const stack = [];
86    let n = el;
87    while (n) {
88      const c = parse(getComputedStyle(n).backgroundColor);
89      if (c && c.a > 0) stack.push(c);
90      if (c && c.a === 1) break;
91      n = n.parentElement;
92    }
93    if (!stack.length || stack.at(-1).a < 1) stack.push({ r: 14, g: 17, b: 19, a: 1 });
94    let acc = stack.at(-1);
95    for (let i = stack.length - 2; i >= 0; i -= 1) {
96      const f = stack[i];
97      acc = {
98        r: f.r * f.a + acc.r * (1 - f.a),
99        g: f.g * f.a + acc.g * (1 - f.a),
100        b: f.b * f.a + acc.b * (1 - f.a),
101        a: 1,
102      };
103    }
104    return acc;
105  };
106
107  const offenders = [];
108  for (const el of document.querySelectorAll('*')) {
109    const cs = getComputedStyle(el);
110    if (cs.visibility === 'hidden' || cs.display === 'none' || +cs.opacity === 0) continue;
111    const rect = el.getBoundingClientRect();
112    const area = rect.width * rect.height;
113    if (area < largeArea) continue;
114    if (Math.min(rect.width, rect.height) < minThickness) continue;
115    // Only judge elements that are actually painted: a transparent wrapper
116    // inherits its parent's colour and would double-count.
117    const own = parse(cs.backgroundColor);
118    if (!own || own.a === 0) continue;
119    const L = lum(bgOf(el));
120    if (L > ceiling) {
121      offenders.push({
122        selector: el.className && typeof el.className === 'string'
123          ? '.' + el.className.trim().split(/\s+/).slice(0, 2).join('.')
124          : el.tagName.toLowerCase(),
125        luminance: Number(L.toFixed(3)),
126        area: Math.round(area),
127        colour: cs.backgroundColor,
128      });
129    }
130  }
131  // Brightest first, and collapse duplicates of the same selector.
132  const seen = new Map();
133  for (const o of offenders.sort((a, b) => b.luminance - a.luminance)) {
134    if (!seen.has(o.selector)) seen.set(o.selector, o);
135  }
136
137  // Material layering: a glass surface must not sit inside another one.
138  const nested = [];
139  for (const el of document.querySelectorAll('*')) {
140    const bdf = getComputedStyle(el).backdropFilter;
141    if (!bdf || bdf === 'none') continue;
142    let n = el.parentElement;
143    while (n && n !== document.body) {
144      const outer = getComputedStyle(n).backdropFilter;
145      if (outer && outer !== 'none') {
146        nested.push({
147          inner: '.' + (String(el.className).trim().split(/\s+/)[0] || el.tagName),
148          outer: '.' + (String(n.className).trim().split(/\s+/)[0] || n.tagName),
149        });
150        break;
151      }
152      n = n.parentElement;
153    }
154  }
155
156  return { bright: [...seen.values()], nested: [...new Map(nested.map((n) => [n.inner + n.outer, n])).values()] };
157};
158
159const routes = ['launch', 'chat', 'models', 'serving', 'monitor', 'tuning', 'workspace', 'skills', 'settings'];
160let failures = 0;
161
162console.log(`dark-mode surface budget — large fills (≥ ${LARGE_AREA}px²) under ${CEILING}, and no glass inside glass\n`);
163
164for (const route of routes) {
165  await page.goto(`${BASE}/#/${route}`, { waitUntil: 'domcontentloaded' });
166  await page.waitForTimeout(1100);
167  const theme = await page.evaluate(() => document.documentElement.dataset.theme);
168  if (theme !== 'dark') {
169    await page.click('button[title="Switch to dark mode"]');
170    await page.waitForTimeout(450);
171  }
172  const { bright, nested } = await page.evaluate(SURVEY, {
173    largeArea: LARGE_AREA,
174    minThickness: MIN_THICKNESS,
175    ceiling: CEILING,
176  });
177  const problems = [];
178  for (const o of bright) problems.push(`bright   ${String(o.luminance).padStart(6)}  ${String(o.area).padStart(7)}px²  ${o.selector}`);
179  for (const n of nested) problems.push(`layering ${n.inner} is inside glass ${n.outer}`);
180  if (problems.length) {
181    failures += problems.length;
182    console.log(`  ${route}`);
183    for (const p of problems) console.log(`    ${p}`);
184  } else {
185    console.log(`  ${route.padEnd(10)} ok`);
186  }
187}
188
189await browser.close();
190
191if (errors.length) {
192  failures += errors.length;
193  console.log(`\n  page errors: ${errors.join('; ')}`);
194}
195console.log(
196  failures
197    ? `\nluminance: ${failures} problem(s) — a bright fill this large fatigues over hours, and glass cannot sample glass`
198    : '\nluminance: every large dark surface is within budget, and no material is nested in another',
199);
200process.exit(failures ? 1 : 0);