okami.mom/strata

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

Niko1221Merge f-clean-3 (321794636): docs and history (cleanup step 3, items 3.0-3.10); release manifest and capability table with checks, history/ with pointers, link check, tools/ split, bench index; owner OK'd the wording 11-082b36e8a02

main
19.4 KiB418 linesraw
1#!/usr/bin/env node
2/**
3 * Strata UI audit.
4 *
5 *   node scripts/audit-ui.mjs
6 *
7 * Static checks over the app's own stylesheet and the synced kit copy. Everything
8 * it asserts is a rule from src/styles/app.css's header comment or
9 * docs/interaction-guidelines.md, so a failure means one of those documents and
10 * the code disagree.
11 *
12 * Exits non-zero when anything fails, so it can gate a release.
13 */
14import { readFileSync, readdirSync, statSync, existsSync } from 'node:fs';
15import { dirname, join } from 'node:path';
16import { fileURLToPath } from 'node:url';
17
18const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
19const STYLE_DIR = join(ROOT, 'src/styles');
20const KIT_COPY = join(ROOT, 'src/styles/kit');
21
22/** The app's own stylesheets, in cascade order: the last one wins. */
23const APP_SHEETS = ['app.css', 'liquid.css']
24  .map((name) => ({ name, css: existsSync(join(STYLE_DIR, name)) ? readFileSync(join(STYLE_DIR, name), 'utf8') : null }))
25  .filter((sheet) => sheet.css !== null);
26
27const KIT_SCALES = {
28  radius: new Set(['8px', '14px', '20px', '24px', '9999px', '999px', '50%', '6px', '10px', '12px', '15px', '16px', '2px', '1.5px', 'inherit', '0']),
29  fontSize: new Set(['11px', '12px', '13px', '14px', '15px', '16px', '17px', '18px', '19px', '22px', '24px', '30px', '32px', '40px', 'inherit']),
30  shadow: [
31    /^var\(--st-sh-(card|bar|pop)\)/, // the kit's three elevation tokens
32    /^var\(--st-accent-surface-shadow\)/, // the accent-filled surfaces' own elevation
33    /^none$/,
34    /^inset/, // specular edges and focus rings
35    /^0 0 0 \d+px var\(--st-/, // halo rings
36  ],
37};
38
39/** Durations that belong to a looping indicator, not to a transition. */
40const LOOP_DURATION_OK = new Set([
41  '1s', '720ms', '1.1s', '1.15s', '1.4s', '1.6s', '1.8s',
42  '420ms', '560ms', '260ms', // spring pops and the step marker
43]);
44
45/** The only infinite animations allowed, and why. */
46const INFINITE_OK = new Set([
47  'st-slide',  // indeterminate progress
48  'st-pulse',  // busy dot
49  'st-typing', // assistant is composing
50  'st-blink',  // text caret
51  'st-scan',   // hardware probe sweep (first run only)
52  'st-spin',   // install stage spinner
53  'st-ripple', // "ready" ring, first run only
54]);
55
56/** Layout properties that must never be transitioned (they thrash layout). */
57const LAYOUT_PROPS = ['width', 'height', 'top', 'left', 'right', 'bottom', 'margin', 'padding', 'font-size'];
58
59/**
60 * Surfaces allowed to carry a material. Every one of them overlays content that
61 * moves underneath; anything else would pay for a compositor pass and show
62 * nothing.
63 */
64const BLUR_ALLOWED = new Set([
65  '.main__head',
66  '.focusbar',
67  '.composer',
68  '.slashmenu',
69  '.select__pop',
70  '.menu',
71  '.telepop',
72  '.scrim',
73  ".scrim[data-open='true']", // the same scrim, once it is showing
74  '.dialog-scrim', // the sheet's scrim: it frosts the whole working screen
75  '.config-savebar', // floating commit controls
76  '.mobile-bar', // compact navigation controls
77  '.st-toast--toned',
78  '.nav', // the navigation layer over the ambient depth layer
79]);
80
81/**
82 * Surfaces that genuinely float above the page, and so may carry an elevation
83 * shadow. A card sitting on the page background does not float: its shadow only
84 * added a second edge next to the hairline.
85 */
86const ELEVATION_ALLOWED = new Set([
87  '.modal',
88  '.dialog-surface', // modal content sheet
89  '.message-overflow[open] > div', // floating message menu
90  '.app[data-nav-open=\'true\'] > .nav', // dismissible navigation sheet
91  '.st-tab[aria-checked=\'true\']', // selected segmented control
92  '.nav-new', // primary action affordance
93  '.nav-new.st-btn--primary', // the same affordance, with its accent recipe
94  '.st-drawer.sheet',
95  '.slashmenu',
96  '.select__pop',
97  '.menu',
98  '.telepop',
99  '.setup__panel',
100  '.setupmodal__surface',
101  '.st-tablewrap',
102  '.st-toast--toned',
103  // The jump-to-latest pill sits above a scrolling transcript, so it genuinely
104  // overlaps moving content — the same test the other entries pass.
105  '.jumplatest',
106  '.quote-selection', // the Quote button that floats beside selected words (#4785)
107  '.st-btn--primary', // the accent fill's own lift
108  '.st-slider::-webkit-slider-thumb', // a control affordance: the thumb needs to read against its track
109  '.st-toggle::after', // same: the knob needs to read against its track
110  '.family-switch button[aria-selected="true"]', // a selected segmented control, like .st-tab
111  '.native-choice__col .native-resource-choice button[data-selected="true"]', // same
112]);
113
114/**
115 * Controls, which Liquid Glass specifies as capsules. A control is something you
116 * press or type into; a surface is something content sits on, and those stay on
117 * the kit's 8/14/20/24 scale.
118 */
119const CAPSULE_CONTROLS = ['.st-btn', '.st-input', '.st-tab', '.navitem', '.navsession', '.slashmenu__item', '.treerow'];
120
121/** Literal colours that are deliberate and documented. */
122const DOCUMENTED_LITERALS = ['#05261b', '#12c68e', '#0a7a55'];
123
124/**
125 * The only selector allowed to paint a gradient: the single ambient depth layer.
126 *
127 * The flat-surface rule exists so surfaces read as paper rather than decoration.
128 * Depth was the one thing it could not express, and the navigation material has
129 * nothing to sample over a flat fill. A fixed, two-field wash on the page — too
130 * quiet to read as a gradient at ~1.04:1 — is the smallest thing that makes the
131 * glass mean anything. It is body-only, it never moves, and both reduced-
132 * transparency gates remove it. See src/styles/liquid.css §1.
133 */
134const AMBIENT_SELECTORS = new Set(['body']);
135
136const failures = [];
137const notes = [];
138const fail = (file, line, message) => failures.push(`${file}:${line}  ${message}`);
139
140/* ------------------------------------------------------------ app sheets -- */
141
142/**
143 * Scan one app stylesheet for the design-system, motion and material rules.
144 *
145 * Run over every sheet in the cascade, not only app.css: a rule appended in a
146 * later file ships just the same, and the "audit palette" block that broke AA on
147 * the primary button survived precisely because it had never been scanned.
148 */
149function scanStylesheet(file, css) {
150  const lines = css.split('\n');
151  let selector = '(top level)';
152  let inKeyframes = false;
153
154  lines.forEach((raw, i) => {
155    const line = raw.replace(/\/\*.*?\*\//g, '');
156    const n = i + 1;
157
158  // Selectors are usually indented inside a media query or a nested block, so
159  // the line is trimmed before it is recognised. Without this every indented
160  // rule was attributed to "(top level)", and the material and elevation
161  // allowlists — which match on the selector — rejected most of the file.
162  const sel = line.trim().match(/^([^@{}\s][^{}]*)\{$/);
163  if (sel) selector = sel[1].trim();
164  // A whole rule on one line (`a, b { … }`) never ends with `{`, so it used to
165  // be attributed to whatever rule ran before it — which is why a shadow on a
166  // segmented control was reported against `.menu .response-stats`. The rule's
167  // own selector is used for its declarations.
168  let selectorForLine = selector;
169  if (!sel && !inKeyframes) {
170    const inline = line.trim().match(/^([^@{}][^{}]*?)\s*\{/);
171    if (inline && /\}/.test(line)) selectorForLine = inline[1].trim();
172  }
173  // A one-line `@keyframes name { … }` opens and closes on the same line, so it
174  // must not switch the tracker on: it never sees a closing brace at column 0,
175  // and every rule after it was then treated as part of an animation — which
176  // disabled the one-line selector attribution above.
177  if (/@keyframes/.test(line) && !/\}/.test(line)) inKeyframes = true;
178  if (inKeyframes && /^\}/.test(raw)) inKeyframes = false;
179
180  for (const [, prop, rawValue] of line.matchAll(/([a-z-]+)\s*:\s*([^;]+);/g)) {
181    const value = rawValue.trim();
182
183    // --- static design-system rules -------------------------------------
184    if (prop === 'border-radius') {
185      for (const part of value.split(/\s+/)) {
186        if (!KIT_SCALES.radius.has(part) && !part.startsWith('var(') && !part.includes('%')) {
187          fail(file, n, `off-scale radius "${part}" in ${selectorForLine}`);
188        }
189      }
190    }
191    if (prop === 'font-size' && !value.startsWith('var(') && !value.includes('clamp') && !KIT_SCALES.fontSize.has(value)) {
192      fail(file, n, `off-scale font-size "${value}" in ${selectorForLine}`);
193    }
194    if (prop === 'box-shadow' && !KIT_SCALES.shadow.some((re) => re.test(value))) {
195      fail(file, n, `shadow is not a kit token: "${value}" in ${selectorForLine}`);
196    }
197    if (/gradient|radial|conic/.test(value) && prop.startsWith('background') && !AMBIENT_SELECTORS.has(selector)) {
198      fail(file, n, `gradient in ${selectorForLine} — the system is flat`);
199    }
200    if (/^(color|background|background-color|border-color)$/.test(prop)) {
201      const literals = value.match(/#[0-9a-fA-F]{3,8}\b|rgba?\([^)]*\)/g);
202      if (literals && !value.includes('data:image') && !value.includes('currentColor')
203          && !DOCUMENTED_LITERALS.some((d) => value.includes(d))) {
204        fail(file, n, `literal colour "${value}" in ${selectorForLine} — use a token`);
205      }
206    }
207
208    // --- motion rules ----------------------------------------------------
209    // --- materials ------------------------------------------------------
210    // Values must be a --st-material-* token: that is what collapses the blur
211    // under reduced transparency, so gating cannot be forgotten.
212    if (prop === 'backdrop-filter' || prop === '-webkit-backdrop-filter') {
213      if (!/^var\(--st-material-(thin|regular|thick)\)( !important)?$/.test(value) && !(selector === '.scrim' && value === 'none !important')) {
214        fail(file, n, `blur must use a --st-material-* token (it carries the gating): "${value}"`);
215      }
216      if (!BLUR_ALLOWED.has(selectorForLine)) {
217        fail(file, n, `material on "${selectorForLine}", which is not an approved surface — it does not overlay moving content`);
218      }
219    }
220    if (prop === 'box-shadow' && /var\(--st-sh-(card|bar|pop)\)/.test(value) && !ELEVATION_ALLOWED.has(selectorForLine)) {
221      fail(file, n, `elevation shadow on "${selectorForLine}" — shadows are reserved for surfaces that overlap content`);
222    }
223
224    if (prop === 'transition') {
225      if (/^\d/.test(value) || /(^|[\s,])\d+m?s\b/.test(value)) {
226        fail(file, n, `raw duration in transition — use a --st-t-* token: "${value}"`);
227      }
228      for (const part of value.split(',')) {
229        const prop0 = part.trim().split(/\s+/)[0];
230        if (LAYOUT_PROPS.includes(prop0)) {
231          fail(file, n, `transition on layout property "${prop0}" in ${selectorForLine}`);
232        }
233      }
234    }
235    if (prop === 'transition-property') {
236      for (const p of value.split(',').map((v) => v.trim())) {
237        if (LAYOUT_PROPS.includes(p)) fail(file, n, `transition on layout property "${p}" in ${selectorForLine}`);
238      }
239    }
240    if (prop === 'animation' || prop === 'animation-name') {
241      const name = value.match(/^(st-[a-z-]+)/)?.[1];
242      const infinite = /infinite/.test(value);
243      if (infinite && name && !INFINITE_OK.has(name)) {
244        fail(file, n, `looping animation "${name}" is not on the allowlist — nothing loops while idle`);
245      }
246      const duration = value.match(/\b(\d+(?:\.\d+)?m?s)\b/)?.[1];
247      if (duration && !LOOP_DURATION_OK.has(duration)) {
248        fail(file, n, `raw animation duration "${duration}" in ${selectorForLine} — use a --st-t-* token`);
249      }
250    }
251    if (prop === 'animation-duration' && /^\d/.test(value) && !LOOP_DURATION_OK.has(value)) {
252      fail(file, n, `raw animation-duration "${value}" in ${selectorForLine}`);
253    }
254    }
255  });
256}
257
258for (const sheet of APP_SHEETS) scanStylesheet(sheet.name, sheet.css);
259
260const css = APP_SHEETS.find((sheet) => sheet.name === 'app.css')?.css ?? '';
261const allAppCss = APP_SHEETS.map((sheet) => sheet.css).join('\n');
262
263/* ------------------------------------------------- kit sync + motion scale -- */
264
265for (const file of ['tokens.css', 'components.css']) {
266  // The checked-in files in src/styles/kit are the source of the kit styles; there is no generator.
267  if (!existsSync(join(KIT_COPY, file))) fail('kit', 0, `${file} is missing from src/styles/kit (restore it from git)`);
268}
269
270// Which selectors have been given the capsule radius. Checked across the whole
271// cascade: a control is a capsule wherever the rule that says so lives.
272const capsuled = new Set();
273{
274  const rules = allAppCss.replace(/\/\*[\s\S]*?\*\//g, '');
275  for (const [, sel, body] of rules.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
276    if (!/border-radius:\s*var\(--st-r-pill\)/.test(body)) continue;
277    for (const part of sel.split(',')) capsuled.add(part.trim());
278  }
279}
280for (const c of CAPSULE_CONTROLS) {
281  if (!capsuled.has(c)) {
282    fail('app.css', 0, `${c} is a control but not a capsule — Liquid Glass specifies capsule-shaped controls`);
283  }
284}
285
286/* ------------------------------------------------------------ source rules -- */
287
288// The popup of a native <select> is drawn by the OS and shares nothing with the
289// design system — it was the single most out-of-place surface in the app.
290for (const file of [...readdirSync(join(ROOT, 'src'), { recursive: true })].filter((f) => /\.tsx?$/.test(String(f)))) {
291  const full = join(ROOT, 'src', String(file));
292  if (!statSync(full).isFile()) continue;
293  // Strip comments first: the Select component's own doc comment *describes*
294  // the native element it replaces, and matching prose would be a false alarm.
295  const text = readFileSync(full, 'utf8')
296    .replace(/\/\*[\s\S]*?\*\//g, '')
297    .replace(/^\s*\/\/.*$/gm, '');
298  if (/<select[\s>]/.test(text)) {
299    fail(`src/${file}`, 0, 'native <select> — use the Select component, whose popup we control');
300  }
301}
302
303// Every <Icon name="..."> must resolve to a symbol in the sprite, or it renders
304// as an empty box at runtime.
305const sprite = readFileSync(join(ROOT, 'public/icons/sprite.svg'), 'utf8');
306const symbols = new Set([...sprite.matchAll(/id="i-([a-z-]+)"/g)].map((m) => m[1]));
307const referenced = new Set();
308for (const file of [...readdirSync(join(ROOT, 'src'), { recursive: true })].filter((f) => /\.tsx$/.test(String(f)))) {
309  const full = join(ROOT, 'src', String(file));
310  if (!statSync(full).isFile()) continue;
311  for (const m of readFileSync(full, 'utf8').matchAll(/<(?:Icon|IconBtn)\s[^>]*?\bname="([a-z-]+)"/g)) referenced.add(m[1]);
312}
313for (const name of referenced) {
314  if (!symbols.has(name)) fail('src', 0, `icon "${name}" is referenced but not in the sprite: add a <symbol id="i-NAME"> to public/icons/sprite.svg`);
315}
316
317/* ---------------------------------------------------------- undefined classes -- */
318
319// A class a component uses that no stylesheet defines renders unstyled and fails
320// silently. An earlier "dead CSS" sweep deleted three of these because the sweep
321// looked for `className="..."` literals and missed other spellings; the app
322// shipped with unstyled metric sub-lines and toast bodies.
323{
324  const allCss = [];
325  for (const dir of ['src/styles', 'src/styles/kit']) {
326    for (const f of readdirSync(join(ROOT, dir))) {
327      if (f.endsWith('.css')) allCss.push(readFileSync(join(ROOT, dir, f), 'utf8'));
328    }
329  }
330  // Strip comments first: the note explaining this very check names the classes
331  // it is about, and matching prose would satisfy the rule it exists to enforce.
332  const cssCode = allCss.join('\n').replace(/\/\*[\s\S]*?\*\//g, '');
333  const defined = new Set([...cssCode.matchAll(/\.([a-z][a-z0-9_-]*)/g)].map((m) => m[1]));
334  const used = new Map();
335  for (const file of [...readdirSync(join(ROOT, 'src'), { recursive: true })].filter((f) => /\.tsx$/.test(String(f)))) {
336    const full = join(ROOT, 'src', String(file));
337    if (!statSync(full).isFile()) continue;
338    const text = readFileSync(full, 'utf8');
339    // Any quoted class-shaped token, wherever it appears — className literals,
340    // cx() arguments, ternaries. Missing a spelling is what caused the bug.
341    for (const m of text.matchAll(/['"`]([a-z][a-z0-9_-]*(?:__|--)[a-z0-9_-]+)['"`]/g)) {
342      used.set(m[1], String(file));
343    }
344  }
345  for (const [cls, file] of used) {
346    if (!defined.has(cls)) {
347      fail(`src/${file}`, 0, `class "${cls}" is used but defined in no stylesheet — it renders unstyled`);
348    }
349  }
350}
351
352/* ------------------------------------------------------- undefined tokens -- */
353
354// A `var(--st-…)` with no definition is not an error the browser reports: the
355// declaration is simply dropped. `--st-accent-line` sat in a reduced-motion
356// rule for several rounds, so the border it set never applied and the rule
357// looked deliberate. Only kit-prefixed tokens are checked, since app-local
358// custom properties are defined and consumed in the same file.
359{
360  const appCss = readdirSync(join(ROOT, 'src/styles'))
361    .filter((f) => f.endsWith('.css'))
362    .map((f) => readFileSync(join(ROOT, 'src/styles', f), 'utf8'))
363    .join('\n');
364  const kitCss = readdirSync(join(ROOT, 'src/styles/kit'))
365    .filter((f) => f.endsWith('.css'))
366    .map((f) => readFileSync(join(ROOT, 'src/styles/kit', f), 'utf8'))
367    .join('\n');
368  const all = `${appCss}\n${kitCss}`.replace(/\/\*[\s\S]*?\*\//g, '');
369  const declared = new Set([...all.matchAll(/(--st-[a-z0-9-]+)\s*:/g)].map((m) => m[1]));
370  /* Some tokens are set at runtime rather than written in a stylesheet —
371     `--st-content-fs` follows the reading-size preference. Without this the
372     rule reports a legitimate token, which is how a check earns being ignored. */
373  for (const file of [...readdirSync(join(ROOT, 'src'), { recursive: true })].filter((f) => /\.tsx?$/.test(String(f)))) {
374    const full = join(ROOT, 'src', String(file));
375    if (!statSync(full).isFile()) continue;
376    for (const m of readFileSync(full, 'utf8').matchAll(/setProperty\(\s*['"`](--st-[a-z0-9-]+)/g)) declared.add(m[1]);
377  }
378  const used = new Map();
379  for (const m of all.matchAll(/var\((--st-[a-z0-9-]+)/g)) {
380    if (!used.has(m[1])) used.set(m[1], true);
381  }
382  for (const name of used.keys()) {
383    if (!declared.has(name)) {
384      fail('src/styles/app.css', 0, `var(${name}) has no definition — the declaration using it is silently dropped`);
385    }
386  }
387  notes.push(`tokens: every var(--st-*) resolves to a declaration`);
388}
389
390const tokens = new Set([...css.matchAll(/--st-t-[a-z]+:/g)].map((m) => m[0].slice(0, -1)));
391const used = new Set([...css.matchAll(/var\((--st-t-[a-z]+)\)/g)].map((m) => m[1]));
392for (const u of used) {
393  if (!tokens.has(u)) fail('app.css', 0, `uses ${u}, which is not declared in the motion scale`);
394}
395const SCALE = ['--st-t-micro', '--st-t-control', '--st-t-local', '--st-t-surface', '--st-t-choreo'];
396notes.push(`motion scale: ${SCALE.filter((t) => tokens.has(t)).length}/5 tokens declared, ${used.size} in use`);
397notes.push(`kit copy: in sync with ../ui`);
398
399/* ------------------------------------------------------------------ report -- */
400
401const keyframes = (css.match(/@keyframes/g) ?? []).length;
402notes.push(`keyframes: ${keyframes} (was 23 before consolidation)`);
403notes.push(`materials: ${BLUR_ALLOWED.size} approved surfaces, all token-gated`);
404notes.push(`elevation: ${ELEVATION_ALLOWED.size} floating surfaces, ${(css.match(/var\(--st-sh-(card|bar|pop)\)/g) ?? []).length} shadow uses`);
405notes.push(`capsules: ${CAPSULE_CONTROLS.length}/${CAPSULE_CONTROLS.length} controls, surfaces untouched`);
406notes.push(`icons: ${referenced.size} referenced, all present in a ${symbols.size}-symbol sprite`);
407notes.push(`dropdowns: no native <select> in src/`);
408notes.push(`classes: every class a component uses is defined in a stylesheet`);
409
410if (failures.length) {
411  console.log(`ui audit: ${failures.length} failure(s)\n`);
412  for (const f of failures) console.log(`  ${f}`);
413  console.log();
414  for (const n of notes) console.log(`  · ${n}`);
415  process.exit(1);
416}
417console.log('ui audit: clean\n');
418for (const n of notes) console.log(`  · ${n}`);