Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

refactor(ui): give accent glows a token scale read off design.pen (#1445)

Call White34f1e0b6d7fd
diff --git a/ui/scripts/cssDeclarations.mjs b/ui/scripts/cssDeclarations.mjs
new file mode 100644
index 000000000..054191d22
--- /dev/null
+++ b/ui/scripts/cssDeclarations.mjs
@@ -0,0 +1,49 @@
+// Where a stylesheet DECLARES something, as offsets into the text it was read
+// from.
+//
+// The scan this serves reads bytes, so it asked "is this a declaration?" with a
+// regex: a shadow property name followed by a colon. A property name followed by
+// a colon is also a pseudo-class, and `.box-shadow:hover { color: red }` is a
+// perfectly ordinary selector -- so the scan handed `hover { color: red` to the
+// shadow classifier and failed a stylesheet that draws no shadow at all. That is
+// the direction that costs a pull request rather than a glow.
+//
+// A tighter regex is not the fix, because the question is not about spelling. A
+// declaration is a POSITION in a grammar, and the parser that already reads
+// these files decides it for free -- a selector is a Rule, a declaration is a
+// Decl, and no amount of punctuation can make one look like the other. The same
+// argument `nonRenderingText.mjs` makes for TypeScript's parser, one language
+// over.
+//
+// Offsets rather than values, because the caller is a byte scan: it has already
+// matched, and what it needs to know is whether the place it matched is a place
+// CSS declares anything.
+
+import postcss from 'postcss';
+
+// `offset` and `into` let a caller fold several stretches of CSS into one list
+// while keeping the coordinates of the file they came from -- a `<style>` child
+// is CSS whose offsets are its position in a `.tsx` file, not in itself.
+//
+// Unparseable text keeps its whole range. That is the deny-by-default direction:
+// this module exists to prove a match is NOT in declaration position, and text
+// no parser can read proves nothing, so it stays exactly as scannable as it was
+// before this file existed.
+function declarationSpansIn(css, offset = 0, into = []) {
+ let root;
+ try {
+ root = postcss.parse(css);
+ } catch {
+ if (css.length > 0) into.push([offset, offset + css.length]);
+ return into;
+ }
+
+ root.walkDecls((decl) => {
+ into.push([offset + decl.source.start.offset, offset + decl.source.end.offset]);
+ });
+ return into;
+}
+
+const declaresAt = (spans, index) => spans.some(([start, end]) => index >= start && index < end);
+
+export { declarationSpansIn, declaresAt };
diff --git a/ui/scripts/cssDeclarations.test.mjs b/ui/scripts/cssDeclarations.test.mjs
new file mode 100644
index 000000000..666122e57
--- /dev/null
+++ b/ui/scripts/cssDeclarations.test.mjs
@@ -0,0 +1,87 @@
+import { describe, expect, it } from 'vitest';
+
+import { declarationSpansIn, declaresAt } from './cssDeclarations.mjs';
+
+// A property name followed by a colon is the SPELLING of a declaration, and the
+// scan that reads these files treated it as one wherever it appeared. Two things
+// wear that spelling and declare nothing: a pseudo-class on a class named after
+// a property, and any sentence that quotes CSS. The first failed a stylesheet
+// that drew no shadow at all -- `validate:theme` runs on every change, so that
+// is a correct pull request blocked by a guard.
+//
+// These cases are the property in both directions, because only stating both
+// keeps either honest: a position CSS declares at must be found, and a position
+// that merely looks like one must not -- and answering "no" everywhere would
+// silence the whole guard while every false-positive case below still passed.
+
+// The offset of a needle, so a case reads as "this spelling, at this place"
+// rather than as arithmetic.
+const at = (css, needle) => declaresAt(declarationSpansIn(css), css.indexOf(needle));
+
+describe('where a stylesheet declares', () => {
+ it.each([
+ ['a declaration in a rule', '.a { box-shadow: 0 0 4px red }', 'box-shadow'],
+ ['a custom property', ':root { --shadow-glow-x: 0 0 4px red }', '--shadow-glow-x'],
+ // `@theme` is where this tree's tokens live, so a declaration inside an
+ // at-rule block has to count exactly as one in a plain rule does.
+ ['a declaration inside an at-rule', '@theme { --shadow-glow-x: 0 0 4px red }', '--shadow-glow-x'],
+ ['a declaration nested under a media query', '@media (min-width: 1px) { .a { box-shadow: 0 0 4px red } }', 'box-shadow'],
+ // A bare declaration list is what an inline `style` attribute and
+ // `.style.cssText` both carry: CSS with no rule around it.
+ ['a bare declaration list', 'box-shadow: 0 0 4px red', 'box-shadow'],
+ ['the second of two on one line', '.a { color: red; box-shadow: 0 0 4px red }', 'box-shadow'],
+ ])('declares at %s', (_label, css, needle) => expect(at(css, needle)).toBe(true));
+
+ it.each([
+ // The reported case: a class named after a property, and the colon that
+ // follows it is a pseudo-class.
+ ['a pseudo-class on a property-named class', '.box-shadow:hover { color: red }', 'box-shadow'],
+ ['the same name in a plain selector', '.box-shadow { color: red }', 'box-shadow'],
+ ['an attribute selector', '[data-x="box-shadow: 0 0 4px red"] { color: red }', 'box-shadow'],
+ // A condition NAMES a value in order to test it; nothing is applied.
+ ['a feature query condition', '@supports (box-shadow: 0 0 4px red) { .a { color: red } }', 'box-shadow'],
+ ['a comment', '/* box-shadow: 0 0 4px red */\n.a { color: red }', 'box-shadow'],
+ ])('does not declare at %s', (_label, css, needle) => expect(at(css, needle)).toBe(false));
+});
+
+// Which direction being wrong points in. This module exists to PROVE a match is
+// not a declaration, so text no parser can read proves nothing -- and the caller
+// has to be left exactly as suspicious of it as it was before this file existed,
+// rather than let an unreadable stretch of CSS become a way past the guard.
+describe('text no parser can read', () => {
+ it('keeps its whole range scannable', () => {
+ const broken = '.a { box-shadow: 0 0 4px red';
+ expect(declarationSpansIn(broken)).toEqual([[0, broken.length]]);
+ expect(at(broken, 'box-shadow')).toBe(true);
+ });
+
+ // Not a span of length zero, which `declaresAt` would answer "no" to for the
+ // right reason and the wrong one at once.
+ it('claims nothing when there is nothing to claim', () => {
+ expect(declarationSpansIn('')).toEqual([]);
+ });
+});
+
+// Offsets, not values, because the caller is a byte scan that has already
+// matched -- and a caller folding several stretches of one file into one list
+// needs them in the coordinates of the FILE, not of the stretch. A `<style>`
+// child is CSS whose offsets are its position in a `.tsx` file.
+describe('offsets a caller can fold', () => {
+ it('reports them in the containing file coordinates', () => {
+ const file = 'const css = ".a { box-shadow: 0 0 4px red }";';
+ const start = file.indexOf('.a');
+ const spans = declarationSpansIn(file.slice(start, file.lastIndexOf('"')), start);
+
+ expect(spans).toHaveLength(1);
+ expect(file.slice(...spans[0])).toBe('box-shadow: 0 0 4px red');
+ });
+
+ it('accumulates into one list across stretches', () => {
+ const spans = declarationSpansIn('color: red', 0);
+ declarationSpansIn('box-shadow: 0 0 4px red', 100, spans);
+
+ expect(spans).toHaveLength(2);
+ expect(declaresAt(spans, 100)).toBe(true);
+ expect(declaresAt(spans, 50)).toBe(false);
+ });
+});
diff --git a/ui/scripts/cssLength.mjs b/ui/scripts/cssLength.mjs
new file mode 100644
index 000000000..8e001108b
--- /dev/null
+++ b/ui/scripts/cssLength.mjs
@@ -0,0 +1,39 @@
+// What this scan can read as a CSS length.
+//
+// The comment this used to sit under names the shape of its own bug three times
+// over: "each time the predicate checked something narrower than the error
+// message claimed: first the colour, by listing two literal spellings out of the
+// many CSS accepts; then the input, by reading one of the four channels a shadow
+// value arrives through; then the geometry". The line directly beneath it then
+// listed six units out of the thirty-odd CSS accepts, and the fourth instance
+// cost what the first three did: `box-shadow: 1cm 1cm 4px red` -- a directional
+// shadow, no glow anywhere in it -- was reported as "the offsets are not plain
+// lengths" and failed `validate:theme` for a pull request that was correct.
+//
+// `pt`, `vmin`, `lh`, `Q` and every viewport unit added since do the same. So
+// the enumeration is gone rather than extended to thirty: a CSS length is a
+// number followed by a unit, and stating the grammar covers the units nobody
+// has thought of yet -- which is the only version of this that stops being
+// wrong. Over-accepting is the safe direction here: an unrecognised length is
+// reported as unreadable, and that is a false positive, while a value this
+// admits and CSS does not still has to survive the zero and colour tests below.
+//
+// `i`, because CSS units are case-insensitive and one of them, `Q`, is normally
+// written in the case this pattern would otherwise reject outright.
+const LENGTH = /^[+-]?(\d+(\.\d+)?|\.\d+)(e[+-]?\d+)?[a-z]*$/i;
+
+const isLength = (part) => LENGTH.test(part);
+
+// Zero is a number, not a spelling. This used to be a regex matching the literal
+// `0` with an optional unit, which is one of the ways to write zero out of
+// several: `-0px`, `+0px`, `0.0`, `00px` and `0vw` are all the same offset, and
+// each of them was read as a DIRECTIONAL offset -- so `shadow-[-0px_0_93px_red]`
+// took the exemption that exists for light thrown to one side and drew a
+// centred glow with it. The exemption is the dangerous side of that question,
+// which is what makes the narrow spelling expensive rather than untidy. Every
+// caller has already established through isLength that the part is a length, so
+// the numeric component is whatever precedes the unit and the question can be
+// asked as arithmetic, where all the spellings converge by construction.
+const isZeroLength = (part) => Number.parseFloat(part) === 0;
+
+export { isLength, isZeroLength };
diff --git a/ui/scripts/cssLength.test.mjs b/ui/scripts/cssLength.test.mjs
new file mode 100644
index 000000000..b186b34df
--- /dev/null
+++ b/ui/scripts/cssLength.test.mjs
@@ -0,0 +1,92 @@
+import fs from 'node:fs';
+
+import { describe, expect, it } from 'vitest';
+
+import { isLength, isZeroLength } from './cssLength.mjs';
+
+// The unit list this replaces held six of the thirty-odd units CSS accepts, so
+// `box-shadow: 1cm 1cm 4px red` -- a directional shadow with no glow in it --
+// failed `validate:theme` for a pull request that was correct. Listing thirty
+// instead of six would only move the boundary: the units that break it next are
+// the ones not invented yet.
+//
+// So these cases are examples of a rule, not the rule itself. The rule is
+// asserted directly below them: whatever else changes, the unit may not become
+// an enumeration again.
+
+// One per family, including the ones the old list omitted and the ones added to
+// CSS most recently.
+const LENGTHS = [
+ '0',
+ '4px',
+ '1cm',
+ '2pt',
+ '3pc',
+ '0.5in',
+ '10mm',
+ '4Q',
+ '1.5rem',
+ '2em',
+ '3ex',
+ '4ch',
+ '1cap',
+ '2ic',
+ '1lh',
+ '2rlh',
+ '50vw',
+ '50vh',
+ '10vmin',
+ '10vmax',
+ '5svh',
+ '5lvh',
+ '5dvh',
+ '5vi',
+ '5vb',
+ '-4px',
+ '+4px',
+ '.5px',
+ '1e2px',
+];
+
+// A length is a number with a unit. Everything here fails that on its first
+// character or its last, and each is a value the scan must keep reading as
+// "not an offset" -- a colour in the offset slot is how a hand-drawn glow used
+// to pass, so admitting one here would be the expensive direction.
+const NOT_LENGTHS = ['red', '#fff', 'var(--mint)', 'calc(1px + 1px)', 'rgba(0,0,0,.5)', 'thick', '', '1px2', 'px'];
+
+describe('isLength', () => {
+ it.each(LENGTHS)('reads %s as a length', (part) => {
+ expect(isLength(part)).toBe(true);
+ });
+
+ it.each(NOT_LENGTHS)('does not read %s as a length', (part) => {
+ expect(isLength(part)).toBe(false);
+ });
+
+ // The property, stated so a future narrowing fails here rather than in a
+ // review round: the unit is any identifier, never a list of them. A pattern
+ // that spells `px|rem` has gone back to enumerating what CSS leaves open.
+ it('matches the unit as a grammar rather than a list', () => {
+ const source = fs.readFileSync(new URL('cssLength.mjs', import.meta.url), 'utf8');
+ const pattern = source.match(/^const LENGTH = (?<pattern>.+);$/m);
+
+ expect(pattern, 'LENGTH is no longer spelled that way').not.toBeNull();
+ expect(pattern.groups.pattern).not.toMatch(/\bpx\b/);
+
+ // Whatever it is spelled as, it accepts a unit nobody has heard of. This is
+ // the assertion the case list above cannot make about itself.
+ expect(isLength('7newunit')).toBe(true);
+ });
+});
+
+describe('isZeroLength', () => {
+ // Every spelling of zero is zero. Reading only the literal `0` let
+ // `-0px 0 93px red` take the exemption that exists for directional light.
+ it.each(['0', '0px', '-0px', '+0px', '0.0', '00px', '0vw', '0cm'])('reads %s as zero', (part) => {
+ expect(isZeroLength(part)).toBe(true);
+ });
+
+ it.each(['1px', '-4px', '.5rem', '0.1cm'])('does not read %s as zero', (part) => {
+ expect(isZeroLength(part)).toBe(false);
+ });
+});
diff --git a/ui/scripts/customProperties.mjs b/ui/scripts/customProperties.mjs
new file mode 100644
index 000000000..ef94f8ce9
--- /dev/null
+++ b/ui/scripts/customProperties.mjs
@@ -0,0 +1,85 @@
+// Every custom property a stylesheet declares, and what it is worth.
+//
+// Extracted for the reason `cssLength.mjs` and `styleWrite.mjs` were:
+// `validate-theme.mjs` runs its whole validation at import time, so nothing
+// inside it can be called from a test. This is the piece of that file which had
+// to answer a question about CSS grammar, and a question about grammar is
+// exactly the kind that wants cases rather than a careful reading.
+
+import postcss from 'postcss';
+
+// A name is declared by two different constructs, and only one of them is a
+// declaration. `@property --elevation { syntax: "*"; initial-value: none }`
+// registers the name in its PARAMS, so the only declarations inside it are
+// called `syntax`, `inherits` and `initial-value` -- none of which start with
+// `--`. Walking declarations alone therefore collected nothing from it, and a
+// later `box-shadow: var(--elevation)` was reported as resolving to a name no
+// stylesheet declares: the property is registered, the browser resolves it to a
+// glow-free initial value, and the guard failed correct CSS.
+//
+// A registration with no `initial-value` still registers the name. With
+// `syntax: "*"` that is legal, and `var()` on it is invalid at computed-value
+// time, so the declaration draws nothing at all. Recording the name against an
+// empty value set says exactly that -- declared, and resolving to nothing that
+// could carry a glow -- where omitting it would report the same false positive
+// one spelling further along.
+//
+// Values are accumulated per name rather than last-write-wins, because a
+// property is routinely declared several times -- dark, `prefers-color-scheme:
+// light`, `[data-theme="light"]` -- and a glow smuggled into just one of those
+// blocks is still a glow that ships. `into` lets a caller fold many stylesheets
+// into one map without the caller knowing how a name gets recorded.
+function customPropertiesIn(css, into = new Map()) {
+ const record = (name, value) => {
+ if (!name.startsWith('--')) return;
+ if (!into.has(name)) into.set(name, new Set());
+ if (value !== undefined) into.get(name).add(value);
+ };
+
+ const root = typeof css === 'string' ? postcss.parse(css) : css;
+ root.walkDecls((decl) => record(decl.prop, decl.value));
+ root.walkAtRules('property', (rule) => {
+ let initial;
+ rule.walkDecls('initial-value', (decl) => { initial = decl.value; });
+ record(rule.params.trim(), initial);
+ });
+
+ return into;
+}
+
+// A registration says more than what a name is worth: it says what a name is
+// ALLOWED to be worth. `@property --tint { syntax: "<color>" }` is a promise the
+// browser enforces -- a length assigned to that name is invalid at computed-value
+// time and never reaches the property -- so `box-shadow: 0 0 var(--tint)` has no
+// blur part at all, and reading its `var()` as "a name that could be any radius"
+// failed CSS whose radius is provably absent.
+//
+// Only a syntax whose every alternative is `<color>` earns it. That is a closed
+// rule rather than an enumeration of the ones that happen to be lengths: the
+// component types CSS can grow are open, so proving "no alternative here is a
+// length" by listing lengths would be wrong on the next spec release, while
+// proving "every alternative is a colour" stays true. The multipliers are
+// stripped because `<color>#` is a comma-separated list of colours and `<color>+`
+// a space-separated one -- neither introduces a component that is not a colour.
+//
+// Anything else -- `*`, `<length>`, `<color> | <length>` -- is simply not proven
+// here, and falls through to the classification it had before.
+const COLOUR_ONLY_SYNTAX = /^<color>[#+]?$/;
+
+function colourRegistrationsIn(css, into = new Set()) {
+ const root = typeof css === 'string' ? postcss.parse(css) : css;
+ root.walkAtRules('property', (rule) => {
+ let syntax;
+ rule.walkDecls('syntax', (decl) => { syntax = decl.value; });
+ if (syntax === undefined) return;
+
+ const alternatives = syntax.trim().replace(/^(['"])(.*)\1$/s, '$2').split('|');
+ if (alternatives.every((one) => COLOUR_ONLY_SYNTAX.test(one.trim()))) {
+ into.add(rule.params.trim());
+ }
+ });
+
+ return into;
+}
+
+export { colourRegistrationsIn, customPropertiesIn };
diff --git a/ui/scripts/customProperties.test.mjs b/ui/scripts/customProperties.test.mjs
new file mode 100644
index 000000000..79289f660
--- /dev/null
+++ b/ui/scripts/customProperties.test.mjs
@@ -0,0 +1,144 @@
+import { describe, expect, it } from 'vitest';
+
+import { colourRegistrationsIn, customPropertiesIn } from './customProperties.mjs';
+
+// `validate:theme` resolves `box-shadow: var(--x)` by looking `--x` up in
+// everything the scanned stylesheets declare, and reports a name it cannot find
+// as unresolvable. So "what declares a name" decides which correct stylesheets
+// the guard rejects: a construct this misses is not a miss at all, it is a
+// failure on CSS that renders exactly as intended.
+
+const valuesOf = (css, name) => {
+ const found = customPropertiesIn(css).get(name);
+ return found === undefined ? undefined : [...found];
+};
+
+describe('customPropertiesIn', () => {
+ it('collects an ordinary declaration', () => {
+ expect(valuesOf(':root { --glow: 0 0 8px red; }', '--glow')).toEqual(['0 0 8px red']);
+ });
+
+ // A property is declared once per theme, and a glow smuggled into just one of
+ // those blocks still ships. Last-write-wins would hide it behind whichever
+ // block the file happens to end with.
+ it('keeps every value a name is given, not the last one', () => {
+ const css = ':root { --glow: none; }\n[data-theme="light"] { --glow: 0 0 8px red; }\n';
+
+ expect(valuesOf(css, '--glow')).toEqual(['none', '0 0 8px red']);
+ });
+
+ it('records the same value once', () => {
+ expect(valuesOf(':root { --glow: none; }\n.a { --glow: none; }', '--glow')).toEqual(['none']);
+ });
+
+ it('ignores declarations that are not custom properties', () => {
+ expect(valuesOf('.a { box-shadow: 0 0 8px red; }', 'box-shadow')).toBeUndefined();
+ });
+
+ // The registration form. Its name is in the at-rule's params, and the only
+ // declarations inside it are `syntax`, `inherits` and `initial-value` -- so a
+ // walk over declarations alone collected nothing, and `var()` on a registered
+ // property was reported as naming something no stylesheet declares.
+ it('collects a name registered by @property, at its initial value', () => {
+ const css = '@property --elevation {\n syntax: "*";\n inherits: false;\n initial-value: none;\n}\n';
+
+ expect(valuesOf(css, '--elevation')).toEqual(['none']);
+ });
+
+ it('leaves @property\'s own parameters out of the declared names', () => {
+ const css = '@property --elevation { syntax: "*"; inherits: false; initial-value: none; }';
+ const collected = [...customPropertiesIn(css).keys()];
+
+ expect(collected).toEqual(['--elevation']);
+ });
+
+ // A registration with no initial value still registers the name. With
+ // `syntax: "*"` that is legal, and `var()` on it is invalid at computed-value
+ // time, so the declaration draws nothing -- declared, and resolving to nothing
+ // that could carry a glow. Omitting the name reports the same false positive
+ // one spelling further along.
+ it('declares a registered name that has no initial value, worth nothing', () => {
+ const css = '@property --elevation { syntax: "*"; inherits: false; }';
+
+ expect(valuesOf(css, '--elevation')).toEqual([]);
+ });
+
+ // A registration does not exempt the value it registers. `initial-value` is
+ // what an unset `var()` resolves to, so a glow written there renders.
+ it('carries a glow written as an initial value through to the value set', () => {
+ const css = '@property --elevation { syntax: "*"; initial-value: 0 0 93px red; }';
+
+ expect(valuesOf(css, '--elevation')).toEqual(['0 0 93px red']);
+ });
+
+ // Sorted, because these two values are found by different walks and their
+ // relative order is a fact about traversal rather than about CSS. Asserting
+ // it would be a test of how this module happens to be written -- which is the
+ // kind of assertion that fails on a change that preserved every behaviour.
+ it('lets a registration and a later declaration both count', () => {
+ const css = '@property --glow { syntax: "*"; initial-value: none; }\n:root { --glow: 0 0 8px red; }\n';
+
+ expect(valuesOf(css, '--glow').sort()).toEqual(['0 0 8px red', 'none']);
+ });
+
+ // The caller folds many stylesheets into one map, so accumulation has to be
+ // the module's business rather than each caller's.
+ it('folds several stylesheets into one map', () => {
+ const into = customPropertiesIn(':root { --a: 1px; }');
+ customPropertiesIn(':root { --b: 2px; }', into);
+
+ expect([...into.keys()]).toEqual(['--a', '--b']);
+ });
+});
+
+// A registration says what a name is ALLOWED to be worth, and the browser
+// enforces it: a length assigned to a `<color>` property is invalid at
+// computed-value time and never reaches it. So `box-shadow: 0 0 var(--tint)` has
+// no blur part AT ALL, and reading its `var()` as "a name that could be any
+// radius" failed a stylesheet whose radius is provably absent.
+//
+// What earns that proof is the shape of the rule rather than its membership.
+// Proving "no alternative here is a length" by listing the lengths CSS has today
+// would be wrong on the next spec release; proving "every alternative is a
+// colour" stays true however many component types are added.
+describe('colourRegistrationsIn', () => {
+ const registered = (syntax) => [...colourRegistrationsIn(`@property --tint { syntax: ${syntax}; }`)];
+
+ it.each([
+ ['a colour', '"<color>"'],
+ // The multipliers are a comma- and a space-separated LIST of colours.
+ // Neither introduces a component that is not one.
+ ['a comma-separated list of colours', '"<color>#"'],
+ ['a space-separated list of colours', '"<color>+"'],
+ ['alternatives that are all colours', '"<color> | <color>"'],
+ ['a single-quoted syntax', "'<color>'"],
+ ])('proves %s can hold no length', (_label, syntax) => {
+ expect(registered(syntax)).toEqual(['--tint']);
+ });
+
+ it.each([
+ ['a length', '"<length>"'],
+ // `*` accepts anything, which is the opposite of a proof.
+ ['the universal syntax', '"*"'],
+ // One alternative that is not a colour is enough: the browser will accept a
+ // length here, so a radius written through this name really can render.
+ ['a colour OR a length', '"<color> | <length>"'],
+ ])('proves nothing about %s', (_label, syntax) => {
+ expect(registered(syntax)).toEqual([]);
+ });
+
+ it('proves nothing about a registration with no syntax at all', () => {
+ expect([...colourRegistrationsIn('@property --tint { inherits: false; }')]).toEqual([]);
+ });
+
+ it('leaves an ordinary declaration unproven, however it is named', () => {
+ expect([...colourRegistrationsIn(':root { --tint: red; }')]).toEqual([]);
+ });
+
+ it('folds several stylesheets into one set', () => {
+ const into = colourRegistrationsIn('@property --a { syntax: "<color>"; }');
+ colourRegistrationsIn('@property --b { syntax: "<color>"; }', into);
+
+ expect([...into]).toEqual(['--a', '--b']);
+ });
+});
diff --git a/ui/scripts/glowScale.test.mjs b/ui/scripts/glowScale.test.mjs
new file mode 100644
index 000000000..d641f346f
--- /dev/null
+++ b/ui/scripts/glowScale.test.mjs
@@ -0,0 +1,323 @@
+import fs from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+import { describe, expect, it } from 'vitest';
+
+import postcss from 'postcss';
+
+import { customPropertiesIn } from './customProperties.mjs';
+import { intendedFiles } from './lintPolicy.mjs';
+import { typeScriptComments } from './nonRenderingText.mjs';
+import { GLOW_TOKEN } from './shadowLayer.mjs';
+import { eachStylesheet } from './stylesheets.mjs';
+import { WHOLE_TREE_SCAN } from './wholeTreeScan.mjs';
+
+// `validate:theme` already forces every glow in the tree to be a
+// `--shadow-glow-*` token. That check is about spelling: it says a call site
+// may not invent a value. It says nothing about whether the values it points at
+// are the design's.
+//
+// The first cut of this scale got that wrong in a way the guard could not see.
+// Each rung was set to roughly the middle of the literals it had to absorb, so
+// `sm` came out at spread -2px -- a number that appears nowhere in design.pen
+// and nowhere in this tree, where every 16px glow was already -4px. Every
+// converted site then moved off its frame to reach it, and the guard passed,
+// because a token was a token.
+//
+// design.pen does not carry three loose triples. It draws one shape: a glow is
+// centred, its spread is a quarter of its blur, and its colour is the accent at
+// #5BFFA070. diagPulse (16/-4), heroPulse (24/-6), diagHero (32/-8) and
+// StepCard (48/-12) all agree, and welCard at blur 64 holds -12, so -12 is the
+// cap rather than a fifth data point.
+//
+// So this asserts the rule, not the current numbers. A rung added later is
+// covered without editing the test, and a rung nudged off the rule fails here
+// instead of shipping.
+
+const UI_ROOT = fileURLToPath(new URL('../', import.meta.url));
+const SRC_ROOT = fileURLToPath(new URL('../src/', import.meta.url));
+const CSS = fs.readFileSync(new URL('../src/index.css', import.meta.url), 'utf8');
+
+// The roles that are deliberately not on the rule, each with the reason it is
+// off. This is a closed set -- the roles that exist -- not a list of exceptions
+// that grows when a value is inconvenient. A new role is on the rule unless it
+// is added here with a reason.
+//
+// A reason is not an assertion, and for three rounds this was only a reason.
+// Naming a role here removed it from every value check above, so the exception
+// meant "unchecked" rather than "checked differently": a wire token could be
+// changed to `0 0 32px -8px red`, a dot could grow a spread, the CTA alpha could
+// leave the value the owner set, and the suite stayed green -- and
+// `validate-theme.mjs` trusts these declarations too, so nothing else would have
+// caught it either. Each exception now carries the contract it is an exception
+// TO, so the escape from the general rule is itself a rule.
+// `holds` pins every number the general rule would have pinned. Leaving `\d+`
+// where the rule would have computed a value is the exception eating one field
+// wider than it was granted: `wire` is off the rule because `drop-shadow()`
+// takes no SPREAD, which says nothing about its blur, and a `\d+px` there let
+// the 4px design.pen draws become 40px with the suite green. An exception names
+// the field it excuses and fixes the rest.
+const OFF_RULE = {
+ dot: {
+ why: 'a spreadless status dot at blur 8, clamped to 0.9 because ours sit on lit panels',
+ holds: /^0 0 8px rgba\(\d+, \d+, \d+, 0\.9\)$/,
+ },
+ wire: {
+ why: 'a drop-shadow() filter at blur 4, which takes no spread at all',
+ holds: /^0 0 4px color-mix\(in srgb, var\(--[a-z]+\) 40%, transparent\)$/,
+ },
+ cta: {
+ why: 'owner-set: themed blur (2026-08-14) and 0.6 alpha, not from design.pen',
+ holds: /^0 0 var\(--brand-glow-blur\) -4px rgba\(\d+, \d+, \d+, 0\.6\)$/,
+ },
+};
+
+// What each role's blur IS, rather than which blurs the scale happens to
+// contain. A set says `md` and `lg` are both spellable while saying nothing
+// about which is 24 and which is 32, so swapping two rungs' blurs left every
+// assertion here green and every converted call site one rung off its frame.
+// A role is a name for a size; the mapping is the thing being asserted.
+const ROLE_BLUR = {
+ dot: 8, wire: 4, xs: 12, sm: 16, md: 24, lg: 32, xl: 48,
+};
+
+const SPREAD_CAP = 12;
+const GLOW_ALPHA = 0.44;
+
+// Over every stylesheet the validator reads, not `src/index.css` alone, and
+// with a parser rather than a line-anchored regex. Both halves of that were the
+// same gap: `collectTokenLayer()` sanctions `@theme` declarations from every
+// scanned stylesheet, so a component stylesheet could declare
+// `@theme { --shadow-glow-rogue-mint: 0 0 93px red }`, have a call site consume
+// it through `var(…)`, and have runtime validation trust it as managed while
+// nothing here ever checked its name, geometry, colour or role. The domain is
+// shared with the validator now (`eachStylesheet`), so the two cannot disagree
+// about which stylesheets exist any more than they can about what a managed
+// name is.
+const SHEETS = [...eachStylesheet(SRC_ROOT)];
+
+const RUNG_NAME = /^--shadow-glow-(?<role>[a-z]+)-(?<accent>[a-z]+)$/;
+
+const rungs = SHEETS.flatMap(([, sheet]) => {
+ const found = [];
+ sheet.walkDecls((decl) => {
+ const match = RUNG_NAME.exec(decl.prop);
+ if (match) found.push({ ...match.groups, token: decl.prop, value: decl.value });
+ });
+ return found;
+});
+
+// Every name the runtime validator will sanction, which is a wider set than the
+// one above can read. `validate:theme` accepts any `--shadow-glow-*` declared
+// in `@theme` -- managed is a PLACE -- while `rungs` requires a role AND an
+// accent, so `--shadow-glow-rogue: 0 0 93px red` was silently absent from every
+// assertion in this file and `shadow-[var(--shadow-glow-rogue)]` passed both
+// guards carrying geometry from nowhere.
+//
+// That gap is the enumeration failure this file's own header warns about, one
+// level up: the rules below are stated as properties, but they were applied to
+// whichever declarations a regex happened to match. A grammar that skips what
+// it cannot parse reports a clean scale by not looking at the exception.
+//
+// Which is why the widening is not another regex. A hand-written one closed the
+// role-and-accent gap and opened a smaller one in the same shape:
+// `--shadow-glow-[a-z0-9-]+` omits `_`, a character CSS allows in a custom
+// property and the validator sanctions without noticing, so
+// `--shadow-glow-rogue_name: 0 0 93px red` was again absent from every assertion
+// here while `shadow-[var(--shadow-glow-rogue_name)]` passed `validate:theme`.
+// The set is therefore read the way the validator reads it -- `@theme` walked
+// with a parser, names matched with the validator's OWN pattern -- so the two
+// cannot disagree about what a managed name is, whatever it is spelled with.
+const MANAGED = SHEETS.flatMap(([, sheet]) => {
+ const names = [];
+ sheet.walkAtRules('theme', (rule) => {
+ rule.walkDecls((decl) => {
+ if (GLOW_TOKEN.test(decl.prop)) names.push(decl.prop);
+ });
+ });
+ return names;
+});
+
+const sized = rungs.filter((rung) => !(rung.role in OFF_RULE));
+
+// The accent values as the dark theme declares them, which is what these tokens
+// carry. `@theme inline` is not themed, so a glow cannot route through
+// `var(--mint)` and follow the palette the way `--card-wash` does -- the RGB is
+// written out, and a written-out RGB is a copy that can go stale. Reading the
+// source it was copied FROM is what turns the copy back into a derivation.
+// The selector is matched WHOLE, per comma-separated part. A substring test
+// reads `:root:not([data-theme="dark"])` -- the light block, whose entire job is
+// to say it is not the dark one -- as a dark declaration, and then every accent
+// has two conflicting values and no assertion can be made about either. That is
+// the same mistake this scan's own history is made of: a structural question
+// answered by looking for characters.
+const DARK_ACCENTS = (() => {
+ const declared = new Map();
+ postcss.parse(CSS).walkRules((rule) => {
+ if (rule.selectors.some((one) => one.trim() === '[data-theme="dark"]')) {
+ customPropertiesIn(rule, declared);
+ }
+ });
+ return declared;
+})();
+
+// `#5bffa0` as `91, 255, 160` -- the one spelling difference between an accent
+// and the glow that carries it.
+const channels = (hex) => {
+ const digits = hex.trim().replace(/^#/, '');
+ if (!/^[0-9a-f]{6}$/i.test(digits)) return null;
+ return [0, 2, 4].map((at) => parseInt(digits.slice(at, at + 2), 16)).join(', ');
+};
+
+describe('the accent glow scale', () => {
+ it('has rungs to check', () => {
+ // Guards the two greps below: a regex that silently matched nothing would
+ // make every assertion here vacuously true.
+ expect(sized.length).toBeGreaterThan(0);
+ });
+
+ // The bridge between what the validator manages and what this file checks.
+ // Without it, a name off the grammar is not a failing rung -- it is no rung at
+ // all, and every `it.each` below simply never runs for it.
+ it('reads every managed glow name as a rung', () => {
+ expect(MANAGED.length).toBeGreaterThan(0);
+ expect(MANAGED.filter((token) => !rungs.some((rung) => rung.token === token))).toEqual([]);
+ });
+
+ // And the role a name parses into has to be one the scale defines. `role in
+ // ROLE_BLUR` already decides which blur is asserted, but its else-branch --
+ // "then it must carry a themed blur" -- describes `cta`, so an invented role
+ // spelled with `var(--…)` would satisfy it. A role is a name for a size; a
+ // name for no size is not a role.
+ it.each(rungs)('$token names a role the scale defines', ({ role }) => {
+ expect(role in ROLE_BLUR || role in OFF_RULE, `${role} is on neither the blur scale nor the off-rule list`).toBe(true);
+ });
+
+ it.each(sized)('$token is centred with spread = -blur/4', ({ value }) => {
+ const geometry = value.match(/^0 0 (?<blur>\d+)px (?<spread>-\d+)px /);
+ expect(geometry, `${value} is not "0 0 <blur>px -<spread>px <colour>"`).not.toBeNull();
+
+ const blur = Number(geometry.groups.blur);
+ expect(Number(geometry.groups.spread)).toBe(-Math.min(SPREAD_CAP, blur / 4));
+ });
+
+ it.each(sized)('$token carries the design alpha', ({ value }) => {
+ const alpha = value.match(/rgba\([^)]*,\s*([\d.]+)\)/);
+ expect(alpha, `${value} is not an rgba() literal`).not.toBeNull();
+ expect(Number(alpha[1])).toBe(GLOW_ALPHA);
+ });
+
+ // Every rung, not just the sized ones: `dot` and `cta` pin their alpha in
+ // `holds` and leave the RGB as `\d+, \d+, \d+`, so before this the colour of a
+ // status dot was unasserted in every theme. A token named for an accent that
+ // draws a different one is the same defect as a blur off its frame, and it is
+ // the harder one to see by eye.
+ it.each(rungs)('$token is its accent, as the dark theme declares it', ({ accent, value }) => {
+ const declared = DARK_ACCENTS.get(`--${accent}`);
+ expect(declared, `--${accent} is declared in no [data-theme="dark"] block`).toBeDefined();
+ expect([...declared], `--${accent} is declared more than once in dark`).toHaveLength(1);
+
+ // Two spellings, because `wire` mixes the live variable while the rest write
+ // the channels out. Both are "this token's colour is that accent"; only the
+ // second can drift, and asserting them apart is what let it.
+ const mixed = value.match(/color-mix\(in srgb, var\((--[a-z]+)\)/);
+ if (mixed) {
+ expect(mixed[1]).toBe(`--${accent}`);
+ return;
+ }
+
+ const written = value.match(/rgba\((\d+, \d+, \d+),/);
+ expect(written, `${value} is neither a color-mix() nor an rgba() literal`).not.toBeNull();
+ expect(written[1]).toBe(channels([...declared][0]));
+ });
+
+ // A role is a name for a size, so the size is the assertion. Membership in a
+ // set of blurs cannot see two roles trading values.
+ it.each(rungs)('$token has its role\'s blur', ({ role, value }) => {
+ if (!(role in ROLE_BLUR)) {
+ expect(value, `${role} has no fixed blur, so it must carry a themed one`).toMatch(/^0 0 var\(--[a-z-]+\) /);
+ return;
+ }
+ expect(Number(value.match(/^0 0 (\d+)px/)?.[1])).toBe(ROLE_BLUR[role]);
+ });
+
+ it.each(Object.entries(OFF_RULE))('states why %s is off the rule', (role, { why }) => {
+ expect(why.length).toBeGreaterThan(0);
+ expect(rungs.some((rung) => rung.role === role)).toBe(true);
+ });
+
+ // Every accent's token of an off-rule role, so a role is covered across the
+ // palette rather than at whichever accent happens to be first.
+ it.each(rungs.filter((rung) => rung.role in OFF_RULE))('$token holds its documented exception', ({ role, value }) => {
+ expect(value.trim(), OFF_RULE[role].why).toMatch(OFF_RULE[role].holds);
+ });
+
+ // Which comments count as design glow annotations, and what each one measures.
+ //
+ // A wash is `0 y<n>px`, and the card scale owns those; this scale is only ever
+ // centred, so an annotation naming a y-offset is not its. The offset can be
+ // written before or after the blur -- welCard puts it after -- so the whole
+ // comment is the unit, not a window around the word, which is why these are
+ // parsed rather than grepped.
+ //
+ // `blur` also names things that are not shadows -- a backdrop filter, a
+ // privacy blur on a screenshot -- and reading `blur 10` out of one of those
+ // would fail this suite over a number no shadow ever wanted. So the comment
+ // must also name what it is measuring. A sigil (`@design-glow`) would be
+ // sharper, but only until the annotation that forgets to carry it: that turns
+ // this false positive into a silent miss, which is the worse direction.
+ // Naming the shadow is what a design annotation already does -- every
+ // contributing one in this tree says "glow" or "shadow" -- so the marker
+ // maintains itself.
+ //
+ // A function rather than three lines inside the loop, because the whole-tree
+ // test can only ever report that some number leaked in; it cannot say which
+ // comment shape let it. The probes below say that.
+ const ANNOTATED_BLUR = (comment) => {
+ const blur = comment.match(/\bblur (?<blur>\d+)/);
+ if (!blur) return null;
+ if (!/\b(glow|shadow)\b/i.test(comment)) return null;
+ if (/\by\d/.test(comment)) return null;
+ return Number(blur.groups.blur);
+ };
+
+ it.each([
+ ['a glow annotation', '// diagPulse: mint glow, blur 16', 16],
+ ['a shadow annotation', '/* StepCard shadow at blur 48 */', 48],
+ ['either word cased as prose', '// Glow: blur 24', 24],
+ ['a backdrop filter', '// the sheet sits over a backdrop blur 10 panel', null],
+ ['a privacy blur', '// screenshots ship with the avatar under blur 12', null],
+ ['a wash, which the card scale owns', '// welCard: glow 0 y4px blur 64', null],
+ ['a comment naming no blur at all', '// mint glow at #5BFFA070', null],
+ ])('reads %s', (_, comment, expected) => {
+ expect(ANNOTATED_BLUR(comment)).toBe(expected);
+ });
+
+ // The rule fixes the shape of a rung; it does not decide which blurs exist.
+ // That is design.pen's, and the annotations are how it reaches the source: a
+ // component that names `blur 24` and then renders a 32px glow has been
+ // redesigned by a codemod. Checking that the scale can SPELL each annotated
+ // blur is the half that holds without guessing which element in a file an
+ // annotation refers to -- welCard's does not describe the shadow nearest it.
+ it('can spell every blur a design annotation names', () => {
+ const annotated = new Set();
+
+ for (const relative of intendedFiles(UI_ROOT, { extensions: ['.ts', '.tsx'] })) {
+ const source = fs.readFileSync(new URL(relative, new URL(UI_ROOT, 'file:')), 'utf8');
+ for (const comment of typeScriptComments(source, relative)) {
+ const blur = ANNOTATED_BLUR(comment);
+ if (blur !== null) annotated.add(blur);
+ }
+ }
+
+ expect(annotated.size).toBeGreaterThan(0);
+
+ // Read off ROLE_BLUR rather than off the declarations, so this asks the
+ // scale the test pins and not whatever index.css currently happens to say.
+ // Taking it from the file made the two agree by construction: a rung nudged
+ // to 40px became "spellable" in the same edit that broke its frame.
+ const spellable = new Set(Object.values(ROLE_BLUR));
+
+ expect([...annotated].filter((blur) => !spellable.has(blur)).sort((a, b) => a - b)).toEqual([]);
+ }, WHOLE_TREE_SCAN);
+});
diff --git a/ui/scripts/lintPolicy.mjs b/ui/scripts/lintPolicy.mjs
index 12ec80146..3a84abdf3 100644
--- a/ui/scripts/lintPolicy.mjs
+++ b/ui/scripts/lintPolicy.mjs
@@ -200,8 +200,13 @@ export const EXPECTED_POLICY = {
* can fix: a symlinked *file* is linted and so is walked, a symlinked
* *directory* is not descended into by either side. That also means the walk has
* no cycle to guard against.
+ *
+ * ``extensions`` exists so a non-lint gate can measure a different domain over
+ * the same tree — ``scripts/validate-theme.mjs`` reads stylesheets too. It
+ * defaults to the lint domain, so the invariant this module is named for is
+ * unaffected: only a caller that asks for something else gets something else.
*/
-export function intendedFiles(root, { excluded = DEPENDENCY_ROOTS } = {}) {
+export function intendedFiles(root, { excluded = DEPENDENCY_ROOTS, extensions = INTENDED_EXTENSIONS } = {}) {
const found = [];
const walk = (dir) => {
@@ -209,7 +214,7 @@ export function intendedFiles(root, { excluded = DEPENDENCY_ROOTS } = {}) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (!excluded.includes(entry.name)) walk(full);
- } else if (INTENDED_EXTENSIONS.some((extension) => entry.name.endsWith(extension))) {
+ } else if (extensions.some((extension) => entry.name.endsWith(extension))) {
found.push(path.relative(root, full).split(path.sep).join('/'));
}
}
diff --git a/ui/scripts/lintPolicy.test.mjs b/ui/scripts/lintPolicy.test.mjs
index 719c58591..e23719df0 100644
--- a/ui/scripts/lintPolicy.test.mjs
+++ b/ui/scripts/lintPolicy.test.mjs
@@ -6,6 +6,7 @@ import { fileURLToPath } from 'node:url';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { ESLint, Linter } from 'eslint';
import globals from 'globals';
+import ts from 'typescript';
import sharedConfig from '../eslint.config.js';
import { EXPECTED_BROWSER_GLOBALS } from './browserGlobals.mjs';
@@ -21,6 +22,7 @@ import {
policyDifferences,
withoutRules,
} from './lintPolicy.mjs';
+import { WHOLE_TREE_SCAN } from './wholeTreeScan.mjs';
// What the gate measures, measured. Every case here is a way the lint run could
// look at less than it claims to while `eslint-baseline.json` stays green — the
@@ -109,14 +111,14 @@ describe('the real UI tree is what the gate measures', () => {
// old hand-written contract listed left byte-identical, and `vite.config.ts`
// silently stopped being linted. It is in the domain by construction now.
expect(intendedFiles(UI_ROOT)).toContain('vite.config.ts');
- });
+ }, WHOLE_TREE_SCAN);
it('covers nested sources without anyone listing them', () => {
const found = intendedFiles(UI_ROOT);
expect(found.length).toBeGreaterThan(100);
expect(found.every((file) => file.endsWith('.ts') || file.endsWith('.tsx'))).toBe(true);
expect(found.some((file) => file.split('/').length > 3)).toBe(true);
- });
+ }, WHOLE_TREE_SCAN);
it('resolves exactly the pinned policy for every one of them', async () => {
const drifted = [];
@@ -125,6 +127,72 @@ describe('the real UI tree is what the gate measures', () => {
if (differences.length > 0) drifted.push({ file, differences });
}
expect(groupByDifferences(drifted)).toEqual([]);
+ }, WHOLE_TREE_SCAN);
+
+ // The rule those three are instances of, and the reason it is asserted rather
+ // than remembered: a test that walks the real tree is not a unit test, so
+ // vitest's default clock measures the runner's contention instead of the
+ // test's subject. The two that forgot did not fail on a defect -- they failed
+ // on a busy CI machine, six pushes in a row, on the one gate whose entire job
+ // is to tell a defect from a correct file.
+ //
+ // The members are found by asking the parser which `it()` reaches for the
+ // walk, rather than by listing the ones that happened to be slow the week this
+ // was written. That is the same lesson as the scan these tests guard: a
+ // question about structure answered by structure. A whole-tree test added
+ // later is covered without editing this, and one that drops its clock fails
+ // here instead of on someone else's pull request.
+ //
+ // Structural is not a preference here, it is the only thing that works. The
+ // first cut asked whether the test's TEXT contained `intendedFiles(` and
+ // `new URL('../'`, and this test failed on itself: those spellings are in the
+ // marker, so the guard read its own source and reported the search string as a
+ // finding. A call is a call and a string that spells one is not.
+ it('gives every whole-tree test a clock that measures a hang, not a busy runner', () => {
+ const untimed = [];
+ const misnamed = [];
+
+ for (const file of fs.readdirSync(SCRIPTS_ROOT).filter((name) => name.endsWith('.test.mjs'))) {
+ const source = fs.readFileSync(path.join(SCRIPTS_ROOT, file), 'utf8');
+ const tree = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);
+
+ const names = (node) =>
+ (ts.isIdentifier(node) && node.text === 'UI_ROOT') || Boolean(ts.forEachChild(node, names));
+
+ const walksTheTree = (node) =>
+ (ts.isCallExpression(node)
+ && node.expression.getText(tree) === 'intendedFiles'
+ && node.arguments.some(names))
+ || Boolean(ts.forEachChild(node, walksTheTree));
+
+ const visit = (node) => {
+ // The real tree has exactly one spelling, which is what makes the marker
+ // above complete: a walk introduced under some other name would be
+ // invisible to it, so the name itself is pinned here.
+ if (ts.isNewExpression(node)
+ && node.expression.getText(tree) === 'URL'
+ && node.arguments?.[0] && ts.isStringLiteral(node.arguments[0])
+ && node.arguments[0].text === '../') {
+ let bound = node.parent;
+ while (bound && !ts.isVariableDeclaration(bound)) bound = bound.parent;
+ const name = bound ? bound.name.getText(tree) : 'the tree root, bound to no name';
+ if (name !== 'UI_ROOT') misnamed.push(`${file} > ${name}`);
+ }
+
+ if (ts.isCallExpression(node) && ['it', 'test'].includes(node.expression.getText(tree))) {
+ const [name, body, timeout] = node.arguments;
+ if (body && walksTheTree(body) && timeout === undefined) {
+ untimed.push(`${file} > ${name.getText(tree)}`);
+ }
+ }
+
+ node.forEachChild(visit);
+ };
+ visit(tree);
+ }
+
+ expect(misnamed).toEqual([]);
+ expect(untimed).toEqual([]);
});
});
diff --git a/ui/scripts/nonRenderingText.mjs b/ui/scripts/nonRenderingText.mjs
new file mode 100644
index 000000000..82720b1ec
--- /dev/null
+++ b/ui/scripts/nonRenderingText.mjs
@@ -0,0 +1,651 @@
+// Text a file contains but never renders as CSS.
+//
+// This scan reads whole source files with regular expressions, so every byte is
+// a candidate declaration until something says otherwise. Most bytes are not:
+// a comment is removed before the file is a program, JSX text becomes copy on
+// the page, and a CSS string is a font name or a `content:` payload. None of
+// them can draw light, and reading them as if they could is how a guard starts
+// failing correct files.
+//
+// That failure mode is worse than the one this file exists to prevent. A missed
+// glow leaves the tree exactly where it already was; a false positive fails CI
+// for a pull request that was never wrong, in a workflow that runs
+// `validate:theme` on every change. So the boundary is drawn here, once, for
+// every language the scan reads -- it lived inline and applied only to `.css`,
+// which made a rule about rendering read as a rule about file suffixes.
+//
+// Every function preserves length and line breaks exactly, blanking bodies to
+// spaces rather than deleting them, so offsets and line numbers computed by the
+// caller still point where they did.
+
+import postcss from 'postcss';
+import ts from 'typescript';
+
+// A comment renders nothing, so a shadow spelled inside one is prose ABOUT a
+// glow, not a glow. Blanking comment bodies -- preserving length and line breaks
+// so every offset and line number below still points where it did -- lets a file
+// explain itself in the vocabulary it is explaining. index.css earns this
+// immediately: the note on the `wire` role has to name `drop-shadow(…)` to say
+// why the sized roles cannot be spelled into one.
+//
+// Widening the scan is what made this necessary and it is worth being clear that
+// it is not a hole. A commented-out declaration does not reach the page, so
+// nothing can be smuggled through here that could have drawn light. The quote
+// tracking is the part that matters: `/*` inside a string starts no comment, and
+// blanking from one would hide the real declarations after it.
+//
+// A CSS string body is blanked for the same reason, but on a narrower guarantee
+// than the one first written here. "No shadow value is ever quoted, because
+// `box-shadow: "0 0 8px red"` is not valid CSS at all" is true of a DECLARATION
+// and false of an at-rule prelude: Tailwind's `@source inline("shadow-[0_0_93px_red]")`
+// exists precisely to generate a utility from a string, so blanking it hides a
+// glow that really does reach the page. In a declaration a string still cannot
+// draw light -- it holds a font name, a `url(…)`, or a `content:` spelling a
+// declaration out as visible copy, and `content: "/* box-shadow: 0 0 93px red */"`
+// renders that text into a pseudo-element and draws nothing.
+//
+// So the boundary is where the string sits, not that it is quoted. A prelude runs
+// from `@` to the `{` or `;` that ends it. Keeping the quotes themselves means the
+// parse below still sees where the string was.
+//
+// Which prelude, though. Treating every at-rule alike was right about `@source`
+// and wrong about the rest, because a prelude does one of two opposite things:
+// it either GENERATES CSS from its contents, as `@source inline(…)` does, or it
+// TESTS a value and draws nothing, as `@supports (box-shadow: 0 0 93px red)`
+// does. The second was left intact and read as a declaration, so a feature query
+// -- the one construct in CSS whose entire purpose is to name a value without
+// applying it -- failed `validate:theme`.
+//
+// A condition is therefore blanked whole, not merely stripped of its strings.
+// Which polarity, though. Listing the GENERATORS and blanking everything else
+// was the first answer, and its cost arrived on schedule: `@apply
+// shadow-[0_0_93px_red]` generates a declaration from its prelude exactly as
+// `@source inline(…)` does, was not on the list, and was blanked through the
+// semicolon -- an untokenized glow into the built CSS, past a guard reporting
+// all-clear.
+//
+// The list was the wrong shape, not one entry short. Generators are an OPEN set:
+// Tailwind alone has `@source`, `@apply`, `@utility` and `@variant`, and a
+// framework can add another next release. Conditions are CLOSED -- the CSS
+// conditional rules are `@supports`, `@media` and `@container`, defined by a
+// spec rather than by a build tool -- so naming THEM is an enumeration that can
+// actually be finished, and an at-rule nobody here has thought of is kept rather
+// than blanked. That inverts the residual risk from a silent miss to a loud
+// failure, which is the direction this scan has been wrong in every time it was
+// wrong.
+//
+// The name comes from PostCSS rather than from the bytes after the `@`. The
+// prefix test it replaces matched `@sourcemap` as `@source`, which is the same
+// class of error one level down: a rule about structure answered by comparing
+// characters. `{` and `;` survive so the block structure the scan reads
+// afterwards is unchanged.
+const CONDITION_AT_RULES = new Set(['supports', 'media', 'container']);
+
+// Which `@` characters actually open an at-rule -- asked of a CSS parser rather
+// than of the bytes, for the same reason the TypeScript branch below asks the
+// compiler. `@` is not a reserved character in a declaration value, so
+// `filter: url([email protected]) drop-shadow(0 0 93px red)` carries one that opens
+// nothing; reading it as an at-rule blanked the rest of the declaration and took
+// a rendered glow with it. `@2x` in a retina asset name is the ordinary way to
+// write that, so this was a hole waiting on a filename.
+//
+// The decomposition is deliberate: PostCSS answers the STRUCTURAL question --
+// where an at-rule begins and therefore where a prelude runs -- and the scanner
+// below keeps the LEXICAL one, which spans are comments and strings. That
+// boundary is where CSS is genuinely simple: `/*` and a quote mean one thing
+// each, with none of the ambiguity that makes `/` un-scannable in JavaScript.
+//
+// PostCSS is not a new dependency, and this is not a new argument. It is a
+// direct devDependency, `validate-theme.mjs` already parses every one of these
+// files with it to collect custom properties, and this scan therefore read each
+// stylesheet twice -- once through a real tree, once through a hand-rolled
+// approximation of one. The findings all came from the second. Parse errors are
+// deliberately not caught: the same file is parsed unguarded by
+// `collectCustomProperties` before this runs, so an unreadable stylesheet
+// already fails the scan loudly rather than degrading into a silent miss here.
+function atRuleNames(source) {
+ const names = new Map();
+ // Case-folded, because CSS keywords are ASCII case-insensitive and
+ // `@SUPPORTS (filter: drop-shadow(…))` is the same rule as `@supports`. A
+ // case-sensitive lookup missed it, kept the prelude, and the drop-shadow
+ // channel read a FEATURE TEST -- text whose entire purpose is to ask whether
+ // a value is supported -- as an applied glow. That is the false-positive
+ // direction: a stylesheet spelled in valid CSS fails the gate.
+ postcss.parse(source).walkAtRules((rule) => names.set(rule.source.start.offset, rule.name.toLowerCase()));
+ return names;
+}
+
+function blankCssComments(source) {
+ const opens = atRuleNames(source);
+ let out = '';
+ let quote = null;
+ let index = 0;
+ let prelude = false;
+ let condition = false;
+ while (index < source.length) {
+ const char = source[index];
+ if (condition && char !== '{' && char !== ';') {
+ out += char === '\n' ? char : ' ';
+ index += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === '\\') {
+ // A line continuation must keep its newline, or every line number after
+ // this string shifts by one and the offences point at the wrong place.
+ out += prelude ? char : ' ';
+ if (index + 1 < source.length) {
+ out += prelude || source[index + 1] === '\n' ? source[index + 1] : ' ';
+ }
+ index += 2;
+ continue;
+ }
+ if (char === quote) { quote = null; out += char; index += 1; continue; }
+ out += prelude || char === '\n' ? char : ' ';
+ index += 1;
+ } else if (char === '"' || char === "'") {
+ quote = char;
+ out += char;
+ index += 1;
+ } else if (char === '/' && source[index + 1] === '*') {
+ const closed = source.indexOf('*/', index + 2);
+ const stop = closed === -1 ? source.length : closed + 2;
+ out += source.slice(index, stop).replace(/[^\n]/g, ' ');
+ index = stop;
+ } else {
+ if (char === '@' && opens.has(index)) {
+ prelude = !CONDITION_AT_RULES.has(opens.get(index));
+ condition = !prelude;
+ } else if (char === '{' || char === ';') {
+ prelude = false;
+ condition = false;
+ }
+ out += char;
+ index += 1;
+ }
+ }
+ return out;
+}
+
+// The same rule, for the other language this scan reads. Blanking comments in
+// stylesheets and then handing `.ts`/`.tsx` to the channels as raw bytes was the
+// half-applied inversion of round five wearing a different hat: `// box-shadow:
+// 0 0 8px red` in a TypeScript file is prose by exactly the argument the CSS
+// branch already accepted, and the declaration channel claimed it, so a source
+// comment failed `validate:theme` and -- because the lint workflow runs this --
+// would have failed CI for an unrelated PR. A guard that fails on text which
+// never renders is worse than one that misses: a miss leaves the tree where it
+// was, a false positive blocks work that was never wrong.
+//
+// TypeScript's own parser draws the boundary rather than a second hand-rolled
+// approximation of its grammar. That distinction is the whole lesson of this
+// file: `//` inside `'https://x'`, `/*` inside a template literal, a regex
+// literal holding either -- each is a spelling a hand-written scanner gets wrong
+// on some later round, and each is already decided correctly by the compiler
+// that actually reads these files. `typescript` is a direct devDependency here,
+// so this is the cheaper implementation as well as the exact one.
+//
+// JSX text goes with the comments. `<div>box-shadow: 0 0 8px red</div>` renders
+// as copy on the page and is never parsed as CSS, so it belongs to the same
+// class -- text in a position that cannot draw light -- and is closed here
+// rather than left for the round that would have found it next.
+// The parse, shared by the two callers that need it. Comments are kept apart
+// from the other non-rendering spans because one caller wants the boundary and
+// the other wants the prose: `glowScale.test.mjs` reads the design annotations
+// that document a component's frame, which are comments and never page copy.
+// The grammar follows the extension, because TSX is not a superset of TS. In a
+// `.ts` file `<T>(x: T) => …` is a generic arrow; read as TSX it is an unclosed
+// JSX element, everything after it becomes `JsxText`, and the blanking below
+// erases the rest of the file -- a real glow in it renders and is never seen.
+// Only `.ts` is narrowed: it is the one extension where the TSX grammar changes
+// what the bytes mean, and leaving everything else on TSX keeps JSX readable in
+// the files that may contain it.
+const scriptKind = (file) =>
+ /\.(m|c)?ts$/.test(file) ? ts.ScriptKind.TS : ts.ScriptKind.TSX;
+
+// A regular expression describes a shadow, it never draws one. `/box-shadow:
+// 0 0 8px red/` is a PATTERN: the only thing a browser can do with it is test a
+// string, and no assignment anywhere turns a regex literal into a declaration.
+// So it is prose about CSS by the same argument as a comment, and it joins them
+// here rather than being talked out of the scan one call site at a time.
+//
+// It is also the third node kind in a row that TypeScript already knew about
+// and this file had to be told. The parser draws every one of these boundaries
+// for free; the cost each round is that the scan below reads bytes, so a span
+// the tree has already classified has to be re-classified by hand to keep the
+// regexes off it.
+const NON_RENDERING_KINDS = new Set([
+ ts.SyntaxKind.RegularExpressionLiteral,
+]);
+
+// Page copy, whichever of the two ways it is written. `<code>box-shadow: 0 0
+// 93px red</code>` is `JsxText`, and `<code>{'box-shadow: 0 0 93px red'}</code>`
+// -- the spelling a lint rule pushes you to the moment the text contains a
+// brace or a quote -- is a `StringLiteral` inside a `JsxExpression`. They render
+// identically and neither can draw light, but only the first was blanked, so
+// documentation and diagnostic copy failed `validate:theme` for containing the
+// string it was documenting.
+//
+// The two were one rule all along, and splitting them was the defect: what makes
+// a span copy is its POSITION -- a child of a JSX element -- not the node kind
+// that happens to carry it there. Asking about position also keeps the answer
+// correct where kind cannot be: `className={'shadow-[0_0_93px_red]'}` is the
+// same `StringLiteral` in a `JsxExpression`, and it renders, because its
+// expression belongs to an attribute rather than to the element's children.
+//
+// And a position is reached, not adjoined. `{show ? 'box-shadow: …' : ''}` is
+// the same copy in the same place, but the literal's parent is the conditional
+// rather than the expression, so requiring a DIRECT `JsxExpression` parent
+// answered "is this copy" with "is this copy written without a branch" -- and
+// failed displayed text for containing the string it was displaying. What has
+// to be walked is the chain of operators that hand a value onward unchanged,
+// because that chain is exactly how the literal becomes the element's text.
+const HANDS_VALUE_ONWARD = (node, parent) => {
+ switch (parent.kind) {
+ case ts.SyntaxKind.ParenthesizedExpression:
+ return true;
+ // The branches render; the condition is read.
+ case ts.SyntaxKind.ConditionalExpression:
+ return node === parent.whenTrue || node === parent.whenFalse;
+ case ts.SyntaxKind.BinaryExpression:
+ switch (parent.operatorToken.kind) {
+ // Either side of a concatenation ends up in the output, and either side
+ // of `||` / `??` can be the value that survives.
+ case ts.SyntaxKind.PlusToken:
+ case ts.SyntaxKind.BarBarToken:
+ case ts.SyntaxKind.QuestionQuestionToken:
+ return true;
+ // `cond && 'text'` renders its right side only; the left is a test.
+ case ts.SyntaxKind.AmpersandAmpersandToken:
+ return node === parent.right;
+ default:
+ return false;
+ }
+ default:
+ return false;
+ }
+};
+
+// Deny by default, which is the safe direction here: an operator this does not
+// know stops the walk, so the span stays in the scan and a real glow is still
+// caught. Walking through anything at all -- a call, an arrow function, a
+// property assignment -- would be the opposite, blanking
+// `{items.map((i) => <span style={{ boxShadow: '0 0 93px red' }} />)}` because
+// it is somewhere under a JSX child.
+const isJsxChild = (node) => {
+ if (node.kind === ts.SyntaxKind.JsxText) return true;
+ const isLiteral = node.kind === ts.SyntaxKind.StringLiteral
+ || node.kind === ts.SyntaxKind.NoSubstitutionTemplateLiteral;
+ if (!isLiteral) return false;
+
+ let child = node;
+ let parent = node.parent;
+ while (parent && HANDS_VALUE_ONWARD(child, parent)) {
+ child = parent;
+ parent = parent.parent;
+ }
+
+ return parent?.kind === ts.SyntaxKind.JsxExpression
+ && (parent.parent?.kind === ts.SyntaxKind.JsxElement
+ || parent.parent?.kind === ts.SyntaxKind.JsxFragment);
+};
+
+// Except in the one element where JSX children are not copy. `<style>` hands
+// them to the CSS parser, so `.probe { box-shadow: 0 0 93px red }` written there
+// is a declaration that renders -- and blanking it removed a real glow before
+// any channel could see it. The parent decides, not the child: this is the same
+// question the surrounding module answers everywhere else, asked one node up,
+// and the tree already knows the answer.
+//
+// It climbs rather than checking one parent, because a `<style>` child is
+// routinely a string in an expression -- `<style>{'.a { … }'}</style>` -- which
+// sits one level deeper than the bare text it used to be written for.
+const isStyleElementChild = (node, tree) => {
+ for (let up = node.parent; up; up = up.parent) {
+ if (up.kind === ts.SyntaxKind.JsxElement) {
+ return up.openingElement?.tagName?.getText(tree) === 'style';
+ }
+ }
+ return false;
+};
+
+// The other half of that question, and the half a byte scan gets wrong in the
+// opposite direction: `<style>` is where a TypeScript file's text IS CSS, and
+// everywhere else it is text ABOUT CSS.
+//
+// Reading every `.ts` file as though it were a stylesheet failed
+// `const example = 'box-shadow: 0 0 93px red'` -- documentation, a log line, a
+// diagnostic string -- as a rendered glow. Nothing assigns it, no browser parses
+// it, and the guard blocked a pull request for containing a sentence. The same
+// class as the comment and the regex literal above, arriving at the one node
+// kind that can also be real.
+//
+// So the rule is where the text is handed to a CSS parser, not what the text
+// spells. Which calls do that is a fact about the web platform rather than
+// about this codebase, so it is a LIST -- there is no property of an expression
+// that separates `sheet.replaceSync(css)` from `log(css)`, and pretending
+// otherwise is how the list stayed short. Written once, here, with a test that
+// walks every member: a sink added to this array without a case is a failing
+// test, which is the cheap way to find out, and a sink missing from it is a
+// review round, which is the expensive one.
+//
+// The cost of a short list is worse than a miss now that a match can be REFUSED.
+// `sheet.replaceSync('.card { box-shadow: 0 0 93px red }')` was claimed by the
+// declaration channel, found outside every range, and therefore reported as
+// provably not CSS -- so an unrecognised sink did not merely go unread, it went
+// unread QUIETLY, past the completeness check that exists to make gaps loud.
+// Each entry below is one shape a string can sit in.
+const CSS_TEXT_SINKS = [
+ // `el.style.cssText = '…'` -- a whole declaration list, assigned.
+ { assignedTo: /(^|\.)cssText$/ },
+ // `el.setAttribute('style', '…')` -- the same list, through the attribute.
+ { called: /(^|\.)setAttribute$/, at: 1, guardedBy: /^(['"`])style\1$/ },
+ // `sheet.insertRule('…')`, and the identical spelling on a grouping rule.
+ { called: /(^|\.)insertRule$/ },
+ // `sheet.replaceSync('…')` -- a constructable stylesheet's entire text, which
+ // paints like any other once the sheet is adopted.
+ { called: /(^|\.)replaceSync$/ },
+ // `sheet.replace('…')` -- the async twin, and the one spelling here that
+ // another builtin also owns. `String.prototype.replace` is always given a
+ // replacement as well, so arity separates them without needing types: one
+ // argument is a stylesheet, two is a substitution.
+ { called: /(^|\.)replace$/, arity: 1 },
+];
+
+// What this cannot follow is a value that arrives through a variable:
+// `const rule = '…'; el.style.cssText = rule` hands CSS to CSS with no literal
+// at the sink to read. That is the dataflow limit this scan has everywhere --
+// the same one that leaves an aliased style object unread -- and it is recorded
+// as such rather than papered over by treating every string as a stylesheet.
+const HANDS_TEXT_TO_CSS = (node, tree) => {
+ const parent = node.parent;
+ if (!parent) return false;
+
+ if (parent.kind === ts.SyntaxKind.BinaryExpression) {
+ if (parent.operatorToken.kind !== ts.SyntaxKind.EqualsToken || node !== parent.right) return false;
+ const target = parent.left.getText(tree);
+ return CSS_TEXT_SINKS.some(({ assignedTo }) => assignedTo?.test(target));
+ }
+
+ if (parent.kind === ts.SyntaxKind.CallExpression) {
+ const callee = parent.expression.getText(tree);
+ return CSS_TEXT_SINKS.some(({ called, at, guardedBy, arity }) => {
+ if (!called?.test(callee)) return false;
+ if (arity !== undefined && parent.arguments.length !== arity) return false;
+ if (at === undefined) return parent.arguments.includes(node);
+ return node === parent.arguments[at]
+ && guardedBy.test(parent.arguments[at - 1]?.getText(tree) ?? '');
+ });
+ }
+
+ return false;
+};
+
+// A literal's CSS is its CONTENTS, so the quotes come off: they are not CSS, and
+// leaving them in makes the parser read the opening one as the start of a
+// selector. A template's backticks come off for the same reason, and what a
+// substitution leaves behind is deliberately not repaired -- `${x}` sits in a
+// value, where a CSS parser reads it as an ordinary token, and where it does not,
+// the range simply stays scannable.
+const cssTextRange = (node, tree) => [node.getStart(tree) + 1, node.getEnd() - 1];
+
+const CSS_TEXT_KINDS = new Set([
+ ts.SyntaxKind.StringLiteral,
+ ts.SyntaxKind.NoSubstitutionTemplateLiteral,
+ ts.SyntaxKind.TemplateExpression,
+]);
+
+// The children of a `<style>`, as text rather than as JavaScript.
+//
+// The element is still what decides -- its children are CSS however they are
+// spelled, and enumerating the ways a child can be written is how the JSX half
+// of this module has been wrong before. What this enumerates is one level down
+// and closed: a child is either text in the file or a literal holding text, and
+// `CSS_TEXT_KINDS` already names every literal that can hold any.
+//
+// Taking the raw span between the tags instead was nearly right, and wrong in
+// the one way that matters to a caller holding a parser: `<style>{'…'}</style>`
+// puts `{'` and `'}` inside that span, so postcss reads a JavaScript brace as
+// the start of a rule. A scanner never noticed, because every byte of the CSS
+// is in the span either way and a regex simply steps over the rest.
+const styleChildRanges = (element, tree, into) => {
+ const visit = (node) => {
+ if (node.kind === ts.SyntaxKind.JsxText) {
+ if (node.getText(tree).trim()) into.push([node.getStart(tree), node.getEnd()]);
+ return;
+ }
+ if (CSS_TEXT_KINDS.has(node.kind)) {
+ into.push(cssTextRange(node, tree));
+ return;
+ }
+ node.getChildren(tree).forEach(visit);
+ };
+
+ element.children.forEach(visit);
+};
+
+// Every stretch of a file whose text is CSS, in that file's own coordinates. A
+// `.css` file is CSS end to end; a TypeScript file is CSS where it hands text to
+// a parser, and inside a `<style>`.
+//
+// One answer for both kinds of caller. This file used to give a scanner the raw
+// span and had nobody else; now that the token layer folds these stretches
+// through postcss and the declaration spans are parsed out of them, a span that
+// is CSS "apart from the JavaScript around it" is not an answer -- and keeping
+// two nearly-identical range functions in step is the thing that has cost this
+// scan a round every time it was tried.
+function cssRangesIn(source, file) {
+ if (file.endsWith('.css')) return source.length > 0 ? [[0, source.length]] : [];
+
+ const tree = parseSource(source, file);
+ const ranges = [];
+
+ const visit = (node) => {
+ if (node.kind === ts.SyntaxKind.JsxElement
+ && node.openingElement?.tagName?.getText(tree) === 'style') {
+ styleChildRanges(node, tree, ranges);
+ } else if (CSS_TEXT_KINDS.has(node.kind) && HANDS_TEXT_TO_CSS(node, tree)) {
+ ranges.push(cssTextRange(node, tree));
+ }
+ node.getChildren(tree).forEach(visit);
+ };
+ visit(tree);
+
+ return ranges;
+}
+
+// A body is not a place, it is a promise to compute one later. `onClick={() =>
+// log('drop-shadow(…)')}` sits inside an attribute and hands that attribute
+// nothing; walking through it would call every string in every handler CSS.
+const DEFERS_ITS_BODY = new Set([
+ ts.SyntaxKind.ArrowFunction,
+ ts.SyntaxKind.FunctionExpression,
+ ts.SyntaxKind.FunctionDeclaration,
+ ts.SyntaxKind.MethodDeclaration,
+]);
+
+// `el.style.filter = '…'` -- the CSSOM half, where the property is named at the
+// assignment target rather than in the text, exactly as `styleWrite.mjs` reads
+// it one property over.
+const STYLE_TARGET = /(^|\.)style\.[A-Za-z][\w$]*$/;
+
+// Which attributes hand their text to the style system, which is a question
+// about the attribute's NAME and not about it being an attribute. Taking every
+// `JsxAttribute` was a false positive with a queue behind it: `<div title="filter:
+// drop-shadow(0 0 93px red)" />` is copy a screen reader speaks, `aria-label` and
+// `alt` and `placeholder` are the same, and each one would have failed CI over
+// text the browser never parses as CSS.
+//
+// Both entries are suffixes because React props compose. This codebase ships
+// `wrapperClassName`, `iconClassName`, `triggerClassName`, `rowClass`,
+// `containerClass`, `wrapperStyle` and `bodyStyle` alongside the plain ones, and
+// every one of them ends up on an element -- so matching `className` exactly
+// would have swapped this false positive for thirty misses. The suffix is the
+// naming convention itself, which is why it holds for the prop nobody has
+// written yet.
+const CSS_BEARING_ATTRIBUTES = [
+ // `className`, `class`, and every `…ClassName` / `…Class` prop that forwards
+ // one -- where a Tailwind arbitrary property such as
+ // `[filter:drop-shadow(…)]` lives.
+ /(^|[a-z])[Cc]lass([Nn]ame)?$/,
+ // `style`, and every `…Style` prop that forwards one -- where a style object's
+ // values live.
+ /(^|[a-z])[Ss]tyle$/,
+];
+
+const NAMES_A_STYLE_SINK = (attribute, tree) => {
+ const name = attribute.name?.getText(tree) ?? '';
+ return CSS_BEARING_ATTRIBUTES.some((shape) => shape.test(name));
+};
+
+const REACHES_A_RENDERER = (node, tree) => {
+ for (let current = node; current.parent; current = current.parent) {
+ const parent = current.parent;
+ if (DEFERS_ITS_BODY.has(parent.kind)) return false;
+ if (parent.kind === ts.SyntaxKind.JsxAttribute) return NAMES_A_STYLE_SINK(parent, tree);
+ if (parent.kind === ts.SyntaxKind.BinaryExpression
+ && parent.operatorToken.kind === ts.SyntaxKind.EqualsToken
+ && current === parent.right
+ && STYLE_TARGET.test(parent.left.getText(tree))) return true;
+ }
+ return false;
+};
+
+// Every stretch whose text reaches the browser AS CSS, which is a wider question
+// than the one above and has to be, because not all rendered CSS is a
+// stylesheet. `filter: drop-shadow(…)` ships three ways -- in a rule, in a
+// utility class, and as a style value -- and only the first is text a CSS parser
+// is handed whole.
+//
+// Reading it in none of those places was the bug: the `drop-shadow(` channel
+// asked nothing at all, so `log('filter: drop-shadow(0 0 93px red)')` -- a
+// sentence in a diagnostic -- failed the gate, which is CI rejecting a pull
+// request over a log line. Reading it only where `cssRangesIn` says would have
+// been the same mistake wearing the other sign, because a Tailwind arbitrary
+// property lives in a className and a style value lives in an object, and
+// neither is a stylesheet.
+//
+// So: a stylesheet, or a literal that reaches a style-sink attribute or a CSSOM
+// property without passing through a function body. What that still cannot see
+// is the same dataflow limit as everywhere else -- a class string assembled in a
+// variable, or a style value read out of a map -- recorded rather than guessed
+// at.
+//
+// A union of two answers, so a stretch both agree on -- `el.style.cssText = '…'`
+// is a sink AND a CSSOM write -- appears twice. Callers ask this whether an
+// offset is inside any range, which is membership rather than counting, so the
+// repeat costs nothing and deduplicating it would only hide that both said yes.
+function cssBearingRangesIn(source, file) {
+ if (file.endsWith('.css')) return cssRangesIn(source, file);
+
+ const tree = parseSource(source, file);
+ const ranges = cssRangesIn(source, file);
+
+ const visit = (node) => {
+ if (CSS_TEXT_KINDS.has(node.kind) && REACHES_A_RENDERER(node, tree)) {
+ ranges.push(cssTextRange(node, tree));
+ }
+ node.getChildren(tree).forEach(visit);
+ };
+ visit(tree);
+
+ return ranges;
+}
+
+// One parse of one file, shared. `styleWrite.mjs` needs the same tree to answer
+// where a style value ends, and parsing is the expensive part of this scan --
+// the cache keys on the exact source text, so a caller that hands over the same
+// blanked string gets the same tree rather than a second parse of it.
+let lastParse = { file: null, source: null, tree: null };
+
+function parseSource(source, file) {
+ if (lastParse.file !== file || lastParse.source !== source) {
+ lastParse = {
+ file,
+ source,
+ tree: ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, scriptKind(file)),
+ };
+ }
+ return lastParse.tree;
+}
+
+function nonRenderingRanges(source, file) {
+ const tree = parseSource(source, file);
+ const comments = [];
+ const literals = [];
+ const collect = (ranges) => {
+ for (const range of ranges ?? []) comments.push([range.pos, range.end]);
+ };
+
+ const visit = (node) => {
+ collect(ts.getLeadingCommentRanges(source, node.getFullStart()));
+ collect(ts.getTrailingCommentRanges(source, node.getEnd()));
+ if ((NON_RENDERING_KINDS.has(node.kind) || isJsxChild(node)) && !isStyleElementChild(node, tree)) {
+ literals.push([node.getStart(tree), node.getEnd()]);
+ }
+ node.getChildren(tree).forEach(visit);
+ };
+ visit(tree);
+
+ return { comments, literals };
+}
+
+// Every comment in a file, as text. A design annotation is a comment by
+// construction, so this is the same boundary read from the other side.
+function typeScriptComments(source, file) {
+ const seen = new Set();
+ return nonRenderingRanges(source, file)
+ .comments.filter(([start, end]) => !seen.has(`${start}:${end}`) && seen.add(`${start}:${end}`))
+ .map(([start, end]) => source.slice(start, end));
+}
+
+function blankTypeScriptComments(source, file) {
+ const { comments, literals } = nonRenderingRanges(source, file);
+ const blanks = [...comments, ...literals];
+
+ // `split('')`, not `[...source]`: the spread iterates code POINTS, while every
+ // offset TypeScript hands back counts UTF-16 code UNITS. An emoji anywhere
+ // earlier in the file desynchronises the two, and blanking then lands on the
+ // wrong characters. Three files in this tree already have one.
+ const out = source.split('');
+ for (const [start, end] of blanks) {
+ for (let index = start; index < end; index += 1) {
+ if (out[index] !== '\n') out[index] = ' ';
+ }
+ }
+ return out.join('');
+}
+
+// One rule, every extension the scan reads. The conditional this replaces named
+// `.css` and let everything else through, which is how a rule about rendering
+// became a rule about file suffixes.
+function withoutNonRenderingText(source, file) {
+ return file.endsWith('.css') ? blankCssComments(source) : blankTypeScriptComments(source, file);
+}
+
+// The same question at the granularity above bytes: a whole FILE can be text the
+// page never sees. A test never enters the bundle, so a fixture asserting on
+// `'box-shadow: 0 0 93px red'` documents a value rather than drawing one -- and
+// the scan failed on exactly that, which is a lint gate blocking a test for
+// containing the string it is testing.
+//
+// It lives here because "renders" already has a home, and answering it in the
+// scan's file loop instead is how this file's own lesson gets relearned: the
+// byte-level rule was inline and keyed off `.css` until that turned a rule about
+// rendering into a rule about suffixes. Two granularities, one module.
+const NON_RENDERING_FILES = /(^|\/)(__tests__|__mocks__)\/|\.(test|spec)\.[cm]?tsx?$/;
+
+const rendersAtAll = (file) => !NON_RENDERING_FILES.test(file.replaceAll('\\', '/'));
+
+export {
+ blankCssComments,
+ blankTypeScriptComments,
+ cssBearingRangesIn,
+ cssRangesIn,
+ CSS_BEARING_ATTRIBUTES,
+ CSS_TEXT_SINKS,
+ parseSource,
+ rendersAtAll,
+ typeScriptComments,
+ withoutNonRenderingText,
+};
diff --git a/ui/scripts/nonRenderingText.test.mjs b/ui/scripts/nonRenderingText.test.mjs
new file mode 100644
index 000000000..817b1e1ea
--- /dev/null
+++ b/ui/scripts/nonRenderingText.test.mjs
@@ -0,0 +1,455 @@
+import fs from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+import postcss from 'postcss';
+import { describe, expect, it } from 'vitest';
+
+import { intendedFiles } from './lintPolicy.mjs';
+import {
+ cssBearingRangesIn,
+ cssRangesIn,
+ CSS_BEARING_ATTRIBUTES,
+ CSS_TEXT_SINKS,
+ rendersAtAll,
+ withoutNonRenderingText,
+} from './nonRenderingText.mjs';
+import { WHOLE_TREE_SCAN } from './wholeTreeScan.mjs';
+
+// `validate:theme` reads whole source files with regular expressions, so the set
+// of bytes it treats as CSS is decided here and nowhere else. Ten review rounds
+// on that scan were misses -- a spelling it walked past. The eleventh was the
+// opposite, and worse: it failed on `// box-shadow: 0 0 8px red`, a comment,
+// which would have failed CI for a pull request that was correct. A miss leaves
+// the tree where it already was; a false positive blocks work that was never
+// wrong.
+//
+// So these cases are the property, stated in both directions. A position that
+// cannot render must be blanked, and -- the half that keeps the first half
+// honest -- a position that CAN render must survive intact right next to it.
+// Blanking too much would silence the whole guard while every case above it
+// still passed.
+
+const UI_ROOT = fileURLToPath(new URL('../', import.meta.url));
+
+// A glow no role in the scale carries, so its presence in the output is only
+// ever the fixture's own.
+const GLOW = '0 0 93px red';
+
+const NON_RENDERING = [
+ ['a TypeScript line comment', 'probe.ts', `const a = 1; // box-shadow: ${GLOW}\n`],
+ ['a TypeScript block comment', 'probe.ts', `/* box-shadow: ${GLOW} */\nconst a = 1;\n`],
+ ['a JSX comment', 'probe.tsx', `const a = <div>{/* box-shadow: ${GLOW} */}</div>;\n`],
+ ['JSX text', 'probe.tsx', `const a = <div>box-shadow: ${GLOW}</div>;\n`],
+ // Page copy, spelled as an expression. What makes a span copy is its POSITION
+ // -- a child of a JSX element -- and not the node kind, so listing `JsxText`
+ // and leaving the braces around it alone blanked one spelling of one thing.
+ ['a string a JSX element renders as copy', 'probe.tsx', `const a = <div>{'box-shadow: ${GLOW}'}</div>;\n`],
+ // The same copy, in the same place, reached through the operators that hand a
+ // value onward. Requiring the literal's DIRECT parent to be the expression
+ // asked whether the copy was written without a branch, which is not a
+ // question about whether it renders as text -- and every one of these failed
+ // `validate:theme` for displaying the string it was documenting.
+ ['copy in a conditional branch', 'probe.tsx', `const a = <div>{x ? 'box-shadow: ${GLOW}' : ''}</div>;\n`],
+ ['copy in the other conditional branch', 'probe.tsx', `const a = <div>{x ? '' : 'box-shadow: ${GLOW}'}</div>;\n`],
+ ['copy guarded by &&', 'probe.tsx', `const a = <div>{x && 'box-shadow: ${GLOW}'}</div>;\n`],
+ ['copy defaulted with ??', 'probe.tsx', `const a = <div>{x ?? 'box-shadow: ${GLOW}'}</div>;\n`],
+ ['copy concatenated with a value', 'probe.tsx', `const a = <div>{'box-shadow: ${GLOW}' + x}</div>;\n`],
+ ['copy inside parentheses', 'probe.tsx', `const a = <div>{('box-shadow: ${GLOW}')}</div>;\n`],
+ ['copy in a fragment', 'probe.tsx', `const a = <>{x ? 'box-shadow: ${GLOW}' : ''}</>;\n`],
+ // A pattern, not a value. Nothing assigns a regex literal to a style, so it
+ // describes CSS in exactly the sense a comment does.
+ ['a regular expression literal', 'probe.ts', `export const RE = /box-shadow: ${GLOW}/;\n`],
+ // A feature query names a value to ask whether the browser understands it.
+ // It is the one construct in CSS whose entire purpose is to write a
+ // declaration that does not apply.
+ ['an @supports condition', 'probe.css', `@supports (box-shadow: ${GLOW}) {\n .a { color: red; }\n}\n`],
+ ['a @media condition', 'probe.css', '@media (min-width: 93px) {\n .a { color: red; }\n}\n'],
+ ['a @container condition', 'probe.css', '@container (min-width: 93px) {\n .a { color: red; }\n}\n'],
+ ['a CSS comment', 'probe.css', `/* box-shadow: ${GLOW} */\n.a { color: red; }\n`],
+ ['a CSS string', 'probe.css', `.a { content: "box-shadow: ${GLOW}"; }\n`],
+ ['a comment opener inside a CSS string', 'probe.css', `.a { content: "/* box-shadow: ${GLOW} */"; }\n`],
+];
+
+const RENDERING = [
+ ['a Tailwind arbitrary value', 'probe.tsx', 'const a = <div className="shadow-[0_0_93px_red]" />;\n', '0_0_93px_red'],
+ // The other half of the position rule. This expression is a child of an
+ // ATTRIBUTE, not of an element, so it is a class name on its way to Tailwind
+ // rather than words on a page.
+ ['a class name written as an expression', 'probe.tsx', "const a = <div className={'shadow-[0_0_93px_red]'} />;\n", '0_0_93px_red'],
+ // Walking to the JSX position rather than checking one parent has to keep
+ // that half true: an attribute is still an attribute at the end of a branch.
+ ['a class name chosen by a conditional', 'probe.tsx', "const a = <div className={x ? 'shadow-[0_0_93px_red]' : ''} />;\n", '0_0_93px_red'],
+ // The limit of the walk, and the reason it is an allowlist. This literal sits
+ // under a JSX child, but a call and an arrow function stand between them, and
+ // what comes out the other end is an element that draws rather than text.
+ ['a style inside a mapped element', 'probe.tsx', `const a = <div>{xs.map((x) => <span style={{ boxShadow: '${GLOW}' }} />)}</div>;\n`, GLOW],
+ // A condition is read, not rendered. Blanking it would erase a declaration
+ // that a comparison merely happens to mention next to one that draws.
+ ['a glow tested in a condition', 'probe.tsx', `const a = <div>{s === 'box-shadow: ${GLOW}' ? 'y' : 'n'}</div>;\n`, GLOW],
+ ['an inline style object', 'probe.tsx', `const a = <div style={{ boxShadow: '${GLOW}' }} />;\n`, GLOW],
+ ['a template literal', 'probe.ts', `const a = { boxShadow: \`${GLOW}\` };\n`, GLOW],
+ ['a CSSOM setter', 'probe.ts', `el.style.setProperty('box-shadow', '${GLOW}');\n`, GLOW],
+ ['a CSS declaration', 'probe.css', `.a { box-shadow: ${GLOW}; }\n`, GLOW],
+ ['a declaration after a comment on the same line', 'probe.css', `/* note */ .a { box-shadow: ${GLOW}; }\n`, GLOW],
+ ['a declaration after a string on the same line', 'probe.css', `.a { content: "x"; box-shadow: ${GLOW}; }\n`, GLOW],
+ ['a URL whose // must not open a comment', 'probe.ts', `const u = 'https://x//y'; const a = { boxShadow: '${GLOW}' };\n`, GLOW],
+ // Blanking regex literals is only safe because the parser decides which
+ // slashes open one. A hand-rolled scanner reads `/ 2; const a = { boxShadow: '`
+ // as a regex and erases the declaration after it.
+ ['a division that is not a regex', 'probe.ts', `const n = 1 / 2; const a = { boxShadow: '${GLOW}' };\n`, GLOW],
+ // Blanking a condition must stop at the brace. The rule inside an @supports
+ // block renders exactly like any other rule.
+ ['a rule inside an @supports block', 'probe.css', `@supports (display: grid) {\n .a { box-shadow: ${GLOW}; }\n}\n`, GLOW],
+ // The at-rules that GENERATE CSS are an open set -- Tailwind adds to it, and
+ // the next release will add more -- while the ones that TEST it are the three
+ // above. Listing the generators to keep meant every at-rule nobody had listed
+ // was silently blanked, taking a real glow with it; naming the conditions
+ // instead makes that residual risk a loud failure rather than a quiet miss.
+ ['a utility pulled in by @apply', 'probe.css', '.a {\n @apply shadow-[0_0_93px_red];\n}\n', '0_0_93px_red'],
+ // The one element where JSX text is not page copy. `<style>` hands its
+ // children to the CSS parser, so blanking them removed a declaration that
+ // really does draw light.
+ ['CSS inside a JSX style element', 'probe.tsx', `const a = <style>{'.a'} {'{'} box-shadow: ${GLOW} {'}'}</style>;\n`, GLOW],
+ // `@` is an ordinary character in a declaration value, and `@2x` is how a
+ // retina asset is named. Reading it as an at-rule opener blanked the rest of
+ // the declaration and took the glow beside it along.
+ ['a glow beside an @ inside url()', 'probe.css', `.a { filter: url([email protected]) drop-shadow(${GLOW}); }\n`, GLOW],
+];
+
+describe('withoutNonRenderingText', () => {
+ it.each(NON_RENDERING)('blanks %s', (_label, file, source) => {
+ expect(withoutNonRenderingText(source, file)).not.toContain('93px');
+ });
+
+ it.each(RENDERING)('leaves %s intact', (_label, file, source, rendered) => {
+ expect(withoutNonRenderingText(source, file)).toContain(rendered);
+ });
+
+ // Every offence the scan reports is located by slicing the source up to a
+ // match index, so a blanked file that is one character shorter than its
+ // original moves every line number after it. Blanking replaces bodies with
+ // spaces for exactly this reason, and the property is asserted over the real
+ // tree rather than over fixtures: three files here contain astral characters,
+ // whose UTF-16 code units are what TypeScript's offsets count and what a
+ // code-point-wise rewrite silently loses.
+ it('preserves length and line breaks across every scanned file', () => {
+ const drifted = [];
+
+ for (const relative of intendedFiles(UI_ROOT, { extensions: ['.ts', '.tsx', '.css'] })) {
+ const raw = fs.readFileSync(new URL(relative, new URL(UI_ROOT, 'file:')), 'utf8');
+ const blanked = withoutNonRenderingText(raw, relative);
+ if (blanked.length !== raw.length || blanked.split('\n').length !== raw.split('\n').length) {
+ drifted.push(relative);
+ }
+ }
+
+ expect(drifted).toEqual([]);
+ }, WHOLE_TREE_SCAN);
+
+ // TSX is not a superset of TS. `<T>(x: T) => …` is a generic arrow in a `.ts`
+ // file and an unclosed JSX element in a `.tsx` one, so reading every file with
+ // the TSX grammar turns the rest of that file into `JsxText` -- and blanking
+ // then erases a real glow further down before the scan can ever see it. This
+ // is the same defect as reading a comment with the wrong language, arriving
+ // through the parser's configuration instead of through a hand-rolled regex.
+ it('reads each file with the grammar its extension implies', () => {
+ const source = 'const fn = <T>(x: T) => x;\nconst s = { boxShadow: "0 0 93px red" };\n';
+
+ expect(withoutNonRenderingText(source, 'probe.ts')).toContain('93px');
+ });
+
+ // Where the string sits, not that it is quoted. A quoted value cannot draw
+ // light in a declaration -- `box-shadow: "0 0 8px red"` is not valid CSS at
+ // all -- but an at-rule prelude is exactly where Tailwind's `@source inline(…)`
+ // generates a utility from such a string, and blanking it hides a glow that
+ // does reach the page.
+ it('keeps strings an at-rule can turn into CSS, and blanks the ones that render as copy', () => {
+ const prelude = '@source inline("shadow-[0_0_93px_red]");\n';
+ const declaration = '.a { content: "box-shadow: 0 0 93px red"; }\n';
+
+ expect(withoutNonRenderingText(prelude, 'probe.css')).toContain('93px');
+ expect(withoutNonRenderingText(declaration, 'probe.css')).not.toContain('93px');
+ });
+
+ // Which `@` opens an at-rule is a question about CSS structure, and the two
+ // spellings are indistinguishable byte by byte. Asking the parser is what
+ // separates them; the alternative is one more hand-rolled rule about where an
+ // `@` is allowed to mean something, which is the shape every finding on this
+ // scan has taken.
+ it('treats @ as an at-rule opener only where an at-rule actually begins', () => {
+ const atRule = '@supports (box-shadow: 0 0 93px red) {\n .a { color: red; }\n}\n';
+ const inValue = '.a { filter: url([email protected]) drop-shadow(0 0 93px red); }\n';
+
+ expect(withoutNonRenderingText(atRule, 'probe.css')).not.toContain('93px');
+ expect(withoutNonRenderingText(inValue, 'probe.css')).toContain('93px');
+ });
+
+ // An at-rule prelude either generates CSS or tests it, and the two want
+ // opposite treatment. Getting `@source` right by keeping every prelude was
+ // what let a feature query through as a declaration.
+ it('keeps a generator prelude and blanks a condition', () => {
+ const generator = '@source inline("shadow-[0_0_93px_red]");\n';
+ const condition = '@supports (box-shadow: 0 0 93px red) {\n .a { color: red; }\n}\n';
+
+ expect(withoutNonRenderingText(generator, 'probe.css')).toContain('93px');
+ expect(withoutNonRenderingText(condition, 'probe.css')).not.toContain('93px');
+ });
+
+ // CSS keywords are ASCII case-insensitive, so the case a stylesheet is
+ // written in is not a fact about what it means. Matching the name literally
+ // read `@SUPPORTS` as a name this scan has no opinion about, kept its
+ // prelude, and reported a FEATURE TEST -- text whose whole purpose is to ask
+ // whether a value is supported -- as an applied glow. That is the
+ // false-positive direction: valid CSS failing the gate, which is worse than a
+ // miss because it stops work that was correct.
+ it.each(['@supports', '@Supports', '@SUPPORTS'])('reads %s as the same condition', (spelling) => {
+ const condition = `${spelling} (box-shadow: 0 0 93px red) {\n .a { color: red; }\n}\n`;
+
+ expect(withoutNonRenderingText(condition, 'probe.css')).not.toContain('93px');
+ });
+
+ it('is applied to every extension the scan reads', () => {
+ const scan = fs.readFileSync(new URL('validate-theme.mjs', import.meta.url), 'utf8');
+ const extensions = scan.match(/extensions:\s*\[([^\]]*)\]/g) ?? [];
+ const scanned = extensions.at(-1) ?? '';
+
+ // The bug this replaces was a conditional naming one suffix, which turned a
+ // rule about rendering into a rule about file names. If the scan grows an
+ // extension, the dispatcher has to have an opinion about it.
+ for (const extension of scanned.match(/'\.\w+'/g) ?? []) {
+ const probe = `probe${extension.slice(1, -1)}`;
+ expect(withoutNonRenderingText('/* box-shadow: 0 0 93px red */\n', probe)).not.toContain('93px');
+ }
+ });
+});
+
+// The same question one granularity up: a file the bundler never reaches draws
+// nothing, whatever it contains. A test asserting on `'box-shadow: 0 0 93px
+// red'` documents a value; scanning it turns the gate into one that fails a
+// test for containing the string it tests.
+describe('rendersAtAll', () => {
+ it.each([
+ 'src/components/Dashboard.tsx',
+ 'src/index.css',
+ 'src/lib/testHelpers.ts',
+ 'src/components/protest/Banner.tsx',
+ ])('scans %s', (file) => {
+ expect(rendersAtAll(file)).toBe(true);
+ });
+
+ it.each([
+ 'src/components/settings/models/modelHubStylePolicy.test.ts',
+ 'src/lib/agentGraph.test.tsx',
+ 'src/lib/util.spec.ts',
+ 'src/__tests__/Dashboard.tsx',
+ 'src/__mocks__/server.ts',
+ ])('skips %s', (file) => {
+ expect(rendersAtAll(file)).toBe(false);
+ });
+});
+
+// The other half of "what is CSS", and the half the scan got wrong in the
+// opposite direction from everything above. Blanking answers WHICH TEXT CANNOT
+// RENDER; this answers WHICH TEXT IS A STYLESHEET -- and reading every `.ts`
+// file as though it were one failed `const example = 'box-shadow: 0 0 93px red'`,
+// a sentence, as a rendered glow.
+//
+// The rule is where the text is handed to a CSS parser, not what the text
+// spells. So the cases are stated as sinks and non-sinks: a string that reaches
+// a parser is CSS wherever it is written, and one that does not is prose however
+// exactly it quotes a declaration.
+describe('cssRangesIn', () => {
+ // The CSS a file contains, read back through the ranges, so a case says what
+ // it means -- `['box-shadow: 0 0 93px red']` -- instead of comparing offsets.
+ const cssIn = (source, file) => cssRangesIn(source, file)
+ .map(([start, end]) => source.slice(start, end).trim());
+
+ // Each row carries what it should extract, because the interesting one does
+ // not extract the same text as the others: a template with a substitution
+ // reaches a CSS parser with the `${…}` still in it, and that is what makes it
+ // a separate node kind rather than a spelling of the two above.
+ it.each([
+ ['an assignment to .style.cssText', 'probe.ts', `el.style.cssText = 'box-shadow: ${GLOW}';`, `box-shadow: ${GLOW}`],
+ ['a template assigned to .style.cssText', 'probe.ts', `el.style.cssText = \`box-shadow: ${GLOW}\`;`, `box-shadow: ${GLOW}`],
+ ['setAttribute with the style attribute', 'probe.ts', `el.setAttribute('style', 'box-shadow: ${GLOW}');`, `box-shadow: ${GLOW}`],
+ ['a template with a substitution', 'probe.ts', 'el.style.cssText = `box-shadow: 0 0 93px ${c}`;', 'box-shadow: 0 0 93px ${c}'],
+ ])('reads %s as CSS', (_label, file, source, css) => {
+ expect(cssIn(source, file)).toEqual([css]);
+ });
+
+ it.each([
+ ['a plain string', 'probe.ts', `const example = 'box-shadow: ${GLOW}';`],
+ ['a documented constant', 'probe.ts', `export const EXAMPLE = \`box-shadow: ${GLOW}\`;`],
+ ['a string passed to something else', 'probe.ts', `log('box-shadow: ${GLOW}');`],
+ // The attribute is what makes `setAttribute` a CSS sink, not the method.
+ ['setAttribute with another attribute', 'probe.ts', `el.setAttribute('title', 'box-shadow: ${GLOW}');`],
+ ['page copy', 'probe.tsx', `const a = <code>box-shadow: ${GLOW}</code>;`],
+ ])('reads %s as text about CSS', (_label, file, source) => {
+ expect(cssIn(source, file)).toEqual([]);
+ });
+
+ // `<style>` is still answered by the ELEMENT: its children are CSS however
+ // they are spelled, and asking each child kind in turn is how the JSX half of
+ // this module has been wrong before.
+ //
+ // What the children are read AS changed, and JSX is what bounds it. `{` opens
+ // an expression container, so a rule cannot be written unquoted inside a
+ // `<style>` at all -- every one in compiling TSX holds a literal. Reading the
+ // children therefore loses no CSS that can ship, where taking the raw span
+ // between the tags handed a parser the `{'` and `'}` around it and had it read
+ // a JavaScript brace as the start of a rule.
+ it.each([
+ ['bare text', '<style>@import url("a.css");</style>', '@import'],
+ ['a string in an expression', `<style>{'.a { box-shadow: ${GLOW} }'}</style>`, 'box-shadow'],
+ ['a template with a substitution', '<style>{`.a { box-shadow: 0 0 93px ${c} }`}</style>', 'box-shadow'],
+ ])('reads a <style> child written as %s as CSS', (_label, element, css) => {
+ expect(cssIn(`const a = ${element};`, 'probe.tsx').join('')).toContain(css);
+ });
+
+ // And reads it as text a parser accepts, which the raw span was not. Stated as
+ // a parse rather than as an offset, because the point is not where the range
+ // falls but that postcss can be handed what is inside it -- the token layer
+ // now folds exactly these stretches, and a stretch it cannot parse contributes
+ // no tokens at all while looking like it did.
+ it('reads a <style> child as text postcss accepts', () => {
+ const source = `const a = <style>{'.a { --tint: red }'}</style>;`;
+
+ const declared = cssRangesIn(source, 'probe.tsx')
+ .flatMap(([start, end]) => [...postcss.parse(source.slice(start, end)).nodes]);
+
+ expect(declared.map((node) => node.selector)).toEqual(['.a']);
+ });
+
+ // A `.css` file is CSS end to end, which is the boundary case a suffix test
+ // gets right and an empty file gets wrong: a range of length zero is a range,
+ // and a caller folding it would parse an empty stylesheet forever.
+ it('reads a stylesheet whole', () => {
+ expect(cssRangesIn('.a { color: red }', 'probe.css')).toEqual([[0, 17]]);
+ expect(cssRangesIn('', 'probe.css')).toEqual([]);
+ });
+
+ // Which calls hand text to a CSS parser is a fact about the web platform, not
+ // about this codebase, so it is a list -- and a list is the shape that is
+ // silently short. `replaceSync` was missing, and a constructable stylesheet
+ // full of glow read as prose; worse, once the declaration channel learned to
+ // REFUSE a match outside CSS, the same gap stopped being a miss and became a
+ // proof that the glow was not CSS at all.
+ //
+ // The array is the single declaration and this is the test that walks it: a
+ // sink added without a case fails here, which costs one edit, instead of
+ // shipping unread, which costs a review round.
+ const sinkKey = ({ assignedTo, called }) => String(assignedTo ?? called);
+
+ const SINK_PROBES = {
+ '/(^|\\.)cssText$/': `el.style.cssText = 'box-shadow: ${GLOW}';`,
+ '/(^|\\.)setAttribute$/': `el.setAttribute('style', 'box-shadow: ${GLOW}');`,
+ '/(^|\\.)insertRule$/': `sheet.insertRule('.a { box-shadow: ${GLOW} }');`,
+ '/(^|\\.)replaceSync$/': `sheet.replaceSync('.a { box-shadow: ${GLOW} }');`,
+ '/(^|\\.)replace$/': `sheet.replace('.a { box-shadow: ${GLOW} }');`,
+ };
+
+ it('reads every sink it enumerates, and enumerates every sink it reads', () => {
+ expect(Object.keys(SINK_PROBES).sort()).toEqual(CSS_TEXT_SINKS.map(sinkKey).sort());
+
+ for (const [sink, source] of Object.entries(SINK_PROBES)) {
+ expect(cssIn(source, 'probe.ts'), `${sink} is enumerated but not read`).not.toEqual([]);
+ }
+ });
+
+ // The one spelling on that list another builtin also owns. A stylesheet's
+ // `replace` is handed its whole text and nothing else, while a string's is
+ // always handed a replacement too, so arity tells them apart without types --
+ // and reading the string one as CSS would fail every file that edits a string.
+ it('reads a two-argument .replace as a substitution, not a stylesheet', () => {
+ expect(cssIn(`const s = css.replace('box-shadow: ${GLOW}', '');`, 'probe.ts')).toEqual([]);
+ });
+
+ // The limit, stated rather than guessed at. A value that arrives through a
+ // variable hands CSS to CSS with no literal at the sink to read, and treating
+ // every string as a possible stylesheet to cover it would fail every file that
+ // merely quotes a declaration. This is the dataflow boundary the whole scan
+ // has; recording it here is what keeps it a known gap instead of a surprise.
+ it('does not follow a value that reaches a sink through a variable', () => {
+ const source = `const rule = 'box-shadow: ${GLOW}';\nel.style.cssText = rule;`;
+
+ expect(cssIn(source, 'probe.ts')).toEqual([]);
+ });
+});
+
+// The wider question, and the reason it has to be asked separately. `cssRangesIn`
+// answers WHICH TEXT IS A STYLESHEET; this answers WHICH TEXT REACHES A RENDERER
+// AS CSS, which is weaker, because `filter: drop-shadow(…)` ships three ways --
+// in a rule, in a utility class and in a style object -- and only the first is
+// text a CSS parser is handed whole.
+//
+// The `drop-shadow(` channel asked neither and failed a log line; asking the
+// narrower one instead would have swapped that false positive for two misses.
+// Both directions are stated here, because either alone is satisfiable by the
+// wrong answer.
+describe('cssBearingRangesIn', () => {
+ const borne = (source, file) => cssBearingRangesIn(source, file)
+ .map(([start, end]) => source.slice(start, end).trim());
+
+ it.each([
+ ['a Tailwind arbitrary property', `const a = <div className="[filter:drop-shadow(${GLOW})]" />;`],
+ ['a style object value', `const a = <div style={{ filter: 'drop-shadow(${GLOW})' }} />;`],
+ ['a CSSOM property write', `el.style.filter = 'drop-shadow(${GLOW})';`],
+ ['a stylesheet handed to a parser', `sheet.replaceSync('.a { filter: drop-shadow(${GLOW}) }');`],
+ ])('bears %s', (_label, source) => {
+ expect(borne(source, 'probe.tsx').join('')).toContain('drop-shadow');
+ });
+
+ it.each([
+ ['a diagnostic', `log('filter: drop-shadow(${GLOW})');`],
+ ['a documented constant', `export const EXAMPLE = 'drop-shadow(${GLOW})';`],
+ // An attribute holding a function holds a promise to compute a value later,
+ // not a value. Walking through the body would read every string in every
+ // event handler as CSS.
+ ['a handler body inside an attribute', `const a = <div onClick={() => log('drop-shadow(${GLOW})')} />;`],
+ ['page copy', `const a = <code>drop-shadow(${GLOW})</code>;`],
+ ])('does not bear %s', (_label, source) => {
+ expect(borne(source, 'probe.tsx')).toEqual([]);
+ });
+
+ // Which attributes hand text to the style system, in both directions. Taking
+ // every attribute read `<div title="filter: drop-shadow(…)" />` -- a tooltip a
+ // screen reader speaks -- as CSS, and failed CI over text no parser is handed;
+ // matching `className` exactly would have swapped that for one miss per
+ // forwarding prop. The list is the single declaration, and this walks it, so a
+ // shape added without a case fails here instead of shipping unread.
+ const ATTRIBUTE_PROBES = {
+ '/(^|[a-z])[Cc]lass([Nn]ame)?$/': `const a = <div className="[filter:drop-shadow(${GLOW})]" />;`,
+ '/(^|[a-z])[Ss]tyle$/': `const a = <div style={{ filter: 'drop-shadow(${GLOW})' }} />;`,
+ };
+
+ it('bears every attribute shape it enumerates, and enumerates every one it bears', () => {
+ expect(Object.keys(ATTRIBUTE_PROBES).sort()).toEqual(CSS_BEARING_ATTRIBUTES.map(String).sort());
+
+ for (const [shape, source] of Object.entries(ATTRIBUTE_PROBES)) {
+ expect(borne(source, 'probe.tsx').join(''), `${shape} is enumerated but not read`).toContain('drop-shadow');
+ }
+ });
+
+ // A prop that forwards a class or a style is one whatever it is called, and
+ // React composition names them by suffix. These all ship in `src` today.
+ it.each([
+ 'className', 'class', 'wrapperClassName', 'iconClassName', 'triggerClassName',
+ 'labelClassName', 'rowClass', 'containerClass', 'style', 'wrapperStyle', 'bodyStyle',
+ ])('bears a value handed to %s', (prop) => {
+ expect(borne(`const a = <Tile ${prop}={'[filter:drop-shadow(${GLOW})]'} />;`, 'probe.tsx').join(''))
+ .toContain('drop-shadow');
+ });
+
+ // And the attributes that hold copy rather than style. Each is text a person
+ // reads or a machine speaks; each would have failed a correct pull request.
+ it.each(['title', 'aria-label', 'alt', 'placeholder', 'data-glow'])(
+ 'does not bear copy handed to %s',
+ (attribute) => {
+ expect(borne(`const a = <div ${attribute}="filter: drop-shadow(${GLOW})" />;`, 'probe.tsx')).toEqual([]);
+ },
+ );
+
+ it('reads a stylesheet whole, exactly as the narrower question does', () => {
+ expect(cssBearingRangesIn('.a { color: red }', 'probe.css')).toEqual([[0, 17]]);
+ });
+});
diff --git a/ui/scripts/shadowChannels.test.mjs b/ui/scripts/shadowChannels.test.mjs
new file mode 100644
index 000000000..099fb779f
--- /dev/null
+++ b/ui/scripts/shadowChannels.test.mjs
@@ -0,0 +1,264 @@
+import fs from 'node:fs';
+
+import { describe, expect, it } from 'vitest';
+
+// `validate:theme` reads a source file twice: the CHANNELS extract the values a
+// shadow can be introduced with, and SHADOW_MENTION measures whether every place
+// one could have been introduced was reached by some channel. The second exists
+// to make the first's gaps loud instead of silent.
+//
+// That only works while the two agree on what a shadow property is. They did
+// not: the CSS declaration channel read `box-shadow` and only it, while the
+// mention matcher read any `*shadow`, so `text-shadow: var(--shadow-glow-md-mint)`
+// -- correct, fully tokenized CSS -- was measured as a mention, matched by no
+// channel, and reported as an unscanned channel. The guard failed a file that had
+// done exactly what it asks for.
+//
+// The comment above SHADOW_MENTION had already predicted this ("the two must
+// narrow together"). A comment is not a mechanism. They now derive from one
+// SHADOW_PROPERTY constant, and this asserts that they still do -- so the next
+// property that ends in the word is covered by both sides at once, rather than
+// by whichever one someone remembered to widen.
+const SCAN = fs.readFileSync(new URL('validate-theme.mjs', import.meta.url), 'utf8');
+
+// Each reader sliced out by its own name, so an assertion about one cannot be
+// satisfied by the other -- counting `${SHADOW_PROPERTY}` across the whole file
+// is exactly the check that stays green while one of the two drifts off.
+//
+// The closing delimiter is searched FROM the opening one. `indexOf('\n];')` from
+// zero finds an earlier array, and the empty slice that leaves matches nothing
+// and passes for the wrong reason; the non-vacuity assertions below are what
+// makes a slice that failed to find its target fail the test instead.
+const section = (opening, closing) => {
+ const start = SCAN.indexOf(opening);
+ expect(start, `\`${opening}\` is no longer spelled that way`).toBeGreaterThan(-1);
+
+ const end = SCAN.indexOf(closing, start);
+ expect(end, `\`${opening}\` is not closed by \`${closing.trim()}\``).toBeGreaterThan(start);
+
+ return SCAN.slice(start, end);
+};
+
+const channels = () => section('const SHADOW_CHANNELS = [', '\n];');
+const mention = () => section('const SHADOW_MENTIONS = [', '\n];');
+
+// One entry per channel: the text from its `pattern:` to the next channel's.
+// That span carries the pattern together with the `valuesOf` and
+// `provablyNotAShadow` that interpret it, which is the unit these assertions are
+// about -- a pattern is only half of what a channel reads.
+const eachChannel = () => {
+ const entries = channels().split('pattern:').slice(1);
+ expect(entries.length, 'SHADOW_CHANNELS has no entries').toBeGreaterThan(0);
+ return entries;
+};
+
+const propertyFlags = () => {
+ const match = SCAN.match(/^const PROPERTY_FLAGS = '([a-z]*)';/m);
+ expect(match, 'PROPERTY_FLAGS is no longer spelled that way').not.toBeNull();
+ return match[1];
+};
+
+describe('the shadow channels and the completeness matcher', () => {
+ it('define what a shadow property is exactly once', () => {
+ expect([...SCAN.matchAll(/^const SHADOW_PROPERTY = /gm)]).toHaveLength(1);
+ });
+
+ // Directly, or through CSS_SHADOW_PROPERTY -- which is that same constant with
+ // a hyphen required, asserted below to be spelled exactly that way, so the
+ // tail rule still has one home either way.
+ it('both derive their property name from it', () => {
+ expect(channels()).toMatch(/\$\{(?:CSS_)?SHADOW_PROPERTY\}/);
+ expect(mention()).toContain('${SHADOW_PROPERTY}');
+ });
+
+ // The way back to two spellings is for a channel to name a property inline
+ // again. A declaration is a name followed by a colon, which is the shape that
+ // diverged; naming one inside a comment or an offence message is prose and
+ // stays free.
+ it('leaves no channel matching a hardcoded property name', () => {
+ const hardcoded = [...channels().matchAll(/pattern:.*?[A-Za-z-]+shadow\\s\*:/g)].map((match) =>
+ match[0].trim()
+ );
+
+ expect(hardcoded).toEqual([]);
+ });
+
+ // The flags are half of what a matcher means, and they diverged after the
+ // pattern stopped being able to: the CSS channels ran case-sensitively while
+ // the mention matcher ran `gi`, so `BOX-SHADOW:` -- valid CSS, property names
+ // being ASCII case-insensitive -- was measured as a mention no channel read.
+ it('reads CSS property names case-insensitively, like the mention matcher does', () => {
+ expect(propertyFlags()).toContain('i');
+ expect(mention()).toContain("'gi'");
+
+ const css = eachChannel().filter((channel) => channel.includes('${CSS_SHADOW_PROPERTY}'));
+
+ expect(css.length).toBeGreaterThanOrEqual(2);
+ for (const channel of css) expect(channel).toContain('PROPERTY_FLAGS');
+ });
+
+ // And the same fact for the other language, which is why that `i` cannot be
+ // one flag over the whole matcher. CSS folds case; JavaScript does not, so
+ // `BOXSHADOW` and `boxshadow` are keys that address no CSS property and draw
+ // nothing at all. Measuring them case-blind reported two names the channel
+ // could not claim -- a false positive on code with no CSS in it -- and hid
+ // that the real CSSOM spelling `webkitBoxShadow` was missing from the property
+ // list, by matching its capitalised alias case-blind instead.
+ //
+ // Asserted as the shared EXPRESSION rather than as two flags that agree
+ // today: the JS half of the measurement is the JS channel's pattern, written
+ // the same way in both places, so neither can gain an `i` without the other.
+ // That is the same discipline the test below applies to the key itself, one
+ // level down -- a copy that has to be edited twice is a copy that will be
+ // edited once.
+ it('measures JavaScript keys case-sensitively, because JavaScript is', () => {
+ const jsPattern = "new RegExp(SHADOW_KEY, 'g')";
+
+ expect(mention()).toContain(jsPattern);
+ expect(channels()).toContain(jsPattern);
+ });
+
+ // What makes that `i` safe. One set of channels reads three languages, so a
+ // case-insensitive CSS property name also matches the camelCase JS key -- and
+ // reading a JS expression with CSS's terminators stops at the first quote,
+ // which fails the tree this guard is guarding. Every CSS shadow property
+ // carries a hyphen and no JS style key does, so requiring it separates them.
+ it('keeps the CSS channels off camelCase style keys', () => {
+ expect(SCAN).toContain('const CSS_SHADOW_PROPERTY = `(?=[A-Za-z-]*-shadow)${SHADOW_PROPERTY}`');
+
+ for (const channel of eachChannel()) {
+ if (channel.includes('PROPERTY_FLAGS')) expect(channel).toContain('${CSS_SHADOW_PROPERTY}');
+ }
+ });
+
+ // A style property's value is its own expression. Capturing `[^;\n]*` -- the
+ // rest of the line -- swept the NEXT property up as a second shadow layer, so
+ // `style={{ boxShadow: 'none', color: 'red' }}` failed on `red`.
+ //
+ // What that expression actually reads is asserted in `styleWrite.test.mjs`,
+ // where `propertyExpression` can be called; this is the half that has to stay
+ // here, because "which reader this channel uses" is a fact about the channel.
+ it('reads a style property\'s own expression rather than the rest of the line', () => {
+ // Selected by how its pattern STARTS, not by mentioning the key: the
+ // preceding channel's trailing comment quotes that spelling in prose, and a
+ // substring search happily returns the wrong channel.
+ const inline = eachChannel().find((channel) =>
+ channel.trimStart().startsWith('new RegExp(SHADOW_KEY')
+ );
+
+ expect(inline, 'the inline-style channel is no longer spelled this way').toBeDefined();
+ expect(inline).not.toContain('[^;\\n]');
+ expect(inline).toContain('styleExpression');
+ });
+
+ // The third thing the two readers have to agree on, after the property name
+ // and the flags: which JavaScript is a style write at all. `const cardShadow =
+ // 'compact'` was read as one by both, and narrowing only the channel would
+ // have left the mention counting a span nothing claims -- the "unscanned
+ // channel" failure this file was written about, arriving from the other side.
+ //
+ // Sharing a constant was the first answer and it was not enough. The two still
+ // COMPOSED it differently -- one added a quote here, the other a bracket there
+ // -- and three rounds of keeping those compositions in step by hand produced
+ // three rounds of them drifting. The mention matcher now embeds the channel's
+ // whole key, so there is no composition left to keep in step: they are one
+ // regex, and a spelling the channel gains is a spelling the measurement gains
+ // in the same edit.
+ // The fifth quantity, after the property name, the flags, the key and the
+ // case rules: WHERE a match begins. A channel may legitimately claim less
+ // text than the mention points at -- `drop-shadow-[…]` is read for what is
+ // inside the brackets, so the claim starts at `shadow-[` while the mention
+ // starts at `drop-` -- and comparing start offsets called that unscanned,
+ // failing a correct, fully tokenized utility. Two spans that cover the same
+ // text is what "some channel read this" actually means.
+ it('counts a mention as claimed when a channel read the same text', () => {
+ const loop = section('for (const pattern of SHADOW_MENTIONS) {', '\n }');
+
+ expect(loop).toContain('from < end && to > start');
+ expect(loop).not.toContain('mention.index >= start');
+ });
+
+ // The sixth quantity, and the one the pattern is structurally unable to hold:
+ // WHETHER A MATCH DECLARES ANYTHING. `.box-shadow:hover { color: red }` is a
+ // selector and `const example = 'box-shadow: …'` is a sentence, and both spell
+ // a declaration exactly -- so the channel failed correct CSS and correct
+ // TypeScript, which is CI blocking a pull request that was never wrong.
+ //
+ // A declaration is a POSITION in a grammar, so the parsers that already read
+ // these files decide it and the channel asks. Asserted as "asks" rather than
+ // as any particular tightening, because the three rounds before this one each
+ // answered a position question with a narrower character class and each bought
+ // one round.
+ //
+ // And it refuses through `provablyNotAShadow`, which is not a detail: a
+ // channel that stopped MATCHING would leave the mention matcher counting a
+ // span nothing claims, turning this false positive into the unscanned-channel
+ // failure one file over. Claiming the span and proving it declares nothing is
+ // the difference between "no glow here" and "nobody looked".
+ it('asks a parser whether a CSS declaration declares anything', () => {
+ const declaration = eachChannel().find((channel) =>
+ channel.trimStart().startsWith('new RegExp(`(?<!\\\\[)${CSS_SHADOW_PROPERTY}')
+ );
+
+ expect(declaration, 'the CSS declaration channel is no longer spelled this way').toBeDefined();
+ expect(declaration).toContain('where.declares(match.index)');
+ expect(declaration).toContain('provablyNotAShadow');
+ });
+
+ // The seventh quantity, and the reason the sixth could not just be reused:
+ // WHETHER TEXT REACHES A RENDERER AS CSS AT ALL, which is a weaker question
+ // than "is this a declaration in a stylesheet". `drop-shadow(` asked neither,
+ // so `log('filter: drop-shadow(0 0 93px red)')` -- a sentence in a diagnostic
+ // -- failed the gate; but answering it with `declares` would have swapped that
+ // false positive for two misses, because `[filter:drop-shadow(…)]` lives in a
+ // className and `{ filter: '…' }` lives in an object, and no stylesheet
+ // contains either.
+ it('asks the wider question where a shadow need not be a declaration', () => {
+ const dropShadow = eachChannel().find((channel) =>
+ channel.trimStart().startsWith('/drop-shadow\\(/gi')
+ );
+
+ expect(dropShadow, 'the drop-shadow channel is no longer spelled this way').toBeDefined();
+ expect(dropShadow).toContain('where.bears(match.index)');
+ expect(dropShadow).not.toContain('where.declares');
+ });
+
+ // And the two are answered by two different readers, which is the whole claim.
+ // Pointing `bears` at the declaration spans would satisfy every assertion above
+ // while reintroducing the misses -- so the sources are named here, once.
+ it('answers the two questions from two different readers', () => {
+ const dispatch = section('const declarations = cssRangesIn(raw, file)', '\n const claimed');
+
+ expect(dispatch).toContain('declares: (index) => declaresAt(declarations, index)');
+ expect(dispatch).toContain('const bearing = cssBearingRangesIn(raw, file)');
+ expect(dispatch).toContain('bears: (index) => declaresAt(bearing, index)');
+ });
+
+ // Both hooks, or the refusals above land in the wrong branch: `valuesOf`
+ // yielding nothing without a `provablyNotAShadow` that agrees is reported as
+ // unreadable, which is the same false positive wearing a different message.
+ it('hands those answers to both of a channel\'s readers', () => {
+ expect(SCAN).toContain('valuesOf(match, tree, where)');
+ expect(SCAN).toContain('provablyNotAShadow?.(match, tree, where)');
+ });
+
+ // Stated over every channel rather than over the two that ask today. Which
+ // channels consult a position is exactly the set that keeps growing -- it was
+ // one last round and is two now -- and each addition that forgot its proof
+ // bought a review round on its own.
+ it('pairs every positional refusal with a proof, not a silent empty read', () => {
+ const asking = eachChannel().filter((channel) => /\bwhere\.\w+\(/.test(channel));
+
+ expect(asking.length, 'no channel asks where its match is').toBeGreaterThanOrEqual(2);
+ for (const channel of asking) expect(channel).toContain('provablyNotAShadow');
+ });
+
+ it('measures a style write with the very key the channel reads it by', () => {
+ expect(mention()).toContain('SHADOW_KEY');
+
+ const inline = eachChannel().find((channel) =>
+ channel.trimStart().startsWith('new RegExp(SHADOW_KEY')
+ );
+ expect(inline, 'the inline-style channel is no longer spelled this way').toBeDefined();
+ });
+});
diff --git a/ui/scripts/shadowLayer.mjs b/ui/scripts/shadowLayer.mjs
new file mode 100644
index 000000000..7435424e1
--- /dev/null
+++ b/ui/scripts/shadowLayer.mjs
@@ -0,0 +1,323 @@
+import { isLength, isZeroLength } from './cssLength.mjs';
+
+// Whether a shadow value is a glow drawn by hand.
+//
+// A glow is a shadow layer drawn at the element's own position: both offsets
+// zero, a blur, and an accent colour. Written as a literal it is invisible to
+// every assertion in `validate-theme.mjs` -- which is how 72 of them accumulated
+// 52 distinct spellings of the same four shapes, and how the eight card washes
+// came to retype `--shadow-mint-card`'s value and so keep the dark frame's neon
+// on a white page. A token cannot drift that way: it is one value, it is read
+// against design.pen, and light re-anchors it in one place. So a glow names a
+// token, and this asserts the property rather than listing the spellings,
+// because the next literal will be a spelling nobody listed.
+//
+// Only the glow layer is held to it. An offset shadow is directional light, not
+// a glow, and `0 0 0 2px` is a ring -- no blur, nothing to colour-manage.
+//
+// This lives in its own module for the reason the other four extractions did:
+// it is the rule the whole gate is about, and inside `validate-theme.mjs` --
+// a script that reads the tree the moment it is imported -- there was no way to
+// ask it a question. Ten documented rounds of holes in it were found by a
+// reviewer rather than by a test, which is the cost of a rule that cannot be
+// called.
+
+// Top-level split, blind to anything inside parentheses. Layers are separated
+// by commas in every syntax the scan reads; the parts of one layer are
+// separated by spaces in CSS and by `_` in a Tailwind arbitrary value, so one
+// splitter reads either and no channel needs its own normalisation step.
+function splitTopLevel(value, isSeparator) {
+ const parts = [];
+ let depth = 0;
+ let start = 0;
+ for (let i = 0; i < value.length; i += 1) {
+ if (value[i] === '(') depth += 1;
+ else if (value[i] === ')') depth -= 1;
+ else if (depth === 0 && isSeparator(value[i])) {
+ parts.push(value.slice(start, i));
+ start = i + 1;
+ }
+ }
+ parts.push(value.slice(start));
+ return parts.filter((part) => part !== '');
+}
+
+const shadowLayers = (value) => splitTopLevel(value, (char) => char === ',');
+const layerParts = (layer) => splitTopLevel(layer, (char) => char === '_' || /\s/.test(char));
+
+const CSS_WIDE_KEYWORDS = new Set(['none', 'inherit', 'initial', 'unset', 'revert', 'revert-layer']);
+
+// Which names this layer owns. Exported because two separate things decide what
+// a managed glow is -- the runtime check below, which sanctions a literal for
+// living under such a name, and the scale test, which asserts every such name is
+// on the ladder -- and they were spelled apart. The test re-derived the rule as
+// `--shadow-glow-[a-z0-9-]+`, which is a NARROWER set: `--shadow-glow-cta_mint`
+// is a legal custom property that this file sanctions and that file could not
+// see, so an off-ladder radius under it passed both. A name is not two things,
+// so it is written once and read by both.
+export const GLOW_TOKEN = /^--shadow-glow-/;
+const VAR_REFERENCE = /^var\(\s*(--[A-Za-z0-9_-]+)\s*(?:,([\s\S]*))?\)$/;
+// A length this scan can read is a literal. These two spell the ways one can
+// arrive without being readable: computed, or named. Neither is rejected for
+// being exotic -- they are rejected because a glow is what they might be.
+const MATH_FUNCTION = /\b(calc|min|max|clamp)\s*\(/;
+const INDIRECT = /\bvar\s*\(/;
+const MAX_INDIRECTION = 8;
+
+// `inset` is a keyword of the shadow grammar, and both of its freedoms are
+// freedoms the parser has to grant: the spec allows it before the lengths or
+// after the colour, and CSS keywords are ASCII case-insensitive. Removing it
+// only in first position, only lowercase, made `box-shadow:
+// var(--shadow-glow-md-mint) inset` -- the managed token this whole gate exists
+// to require -- read as a two-part hand-written shadow and fail, while the
+// identical leading spelling passed. A guard that rejects one word order of the
+// thing it is asking for is the false positive that is hardest to argue with.
+const INSET = /^inset$/i;
+
+// What a colour LOOKS like, which is a different question from what a blur does
+// not look like -- and the difference is the sixth round of this file. The blur
+// slot used to be tested by elimination: not a length, not a `var()`, therefore
+// harmless. `0 0 ${blur}px red` is neither of those two things and is also a
+// glow, so it walked out through the bottom of the test. That is the same
+// implicit accept the layer-level default was inverted to close; it had simply
+// survived one level further down, inside the branch that does the inverting.
+//
+// A bare identifier counts because a <length> always carries a digit, so a name
+// with none provably is not one. The function list is an enumeration and would
+// be a liability on the reject side; here it sits on the ACCEPT side, where a
+// colour syntax missing from it costs a spurious failure and a one-line fix
+// rather than a glow that ships. Order matters: `color-mix(…, var(--x) …)` is a
+// colour that happens to contain a name, so this is asked before INDIRECT.
+//
+// That one-line fix has now been called in, which is the enumeration behaving as
+// designed rather than failing: `box-shadow: 0 0 light-dark(red, blue)` is a
+// valid blur-free shadow, and an unlisted colour function put the colour in the
+// blur slot and blocked it. The names below are CSS Color's functional
+// notations as they stand; the cost of the next one arriving is exactly this
+// again -- a spurious failure, loudly, rather than a glow nobody sees.
+export const COLOUR = new RegExp(
+ '^(#[0-9A-Fa-f]{3,8}'
+ + '|[A-Za-z][A-Za-z0-9-]*'
+ + '|(rgba?|hsla?|hwb|lab|lch|oklab|oklch|color|color-mix|light-dark|contrast-color|device-cmyk)'
+ + '\\([\\s\\S]*\\))$',
+ 'i',
+);
+
+// Whether a part is provably a colour, which is the question the blur slot asks
+// when it wants to prove there is no blur: a layer whose third part is its
+// colour skipped the blur, and that is the ring-spacer shape.
+//
+// A literal answers it directly. A NAME answers it when `@property --tint
+// { syntax: "<color>" }` registers it, because the browser then rejects a length
+// assigned to that name -- the registration turns "could be any radius" from a
+// fact about the spelling into a fact about the value.
+//
+// The fallback is part of the value, not a separate spelling to exclude. This
+// used to accept a registration only with no fallback at all, which read
+// `var(--tint, blue)` as unprovable and failed a shadow where NEITHER possible
+// value can occupy the blur slot -- the registered name cannot hold a length,
+// and `blue` is a colour. So the same question is asked of the fallback, which
+// is also what makes it recursive: a fallback may itself be a registered name
+// with a fallback, and each hop is strictly shorter text than the one that
+// contains it. Order is load-bearing and unchanged -- `color-mix(…, var(--x) …)`
+// is a colour that happens to contain a name, so COLOUR is asked first.
+const isProvableColour = (part, tokens) => {
+ const trimmed = part.trim();
+ if (COLOUR.test(trimmed)) return true;
+ const reference = trimmed.match(VAR_REFERENCE);
+ if (!reference || !tokens.colours.has(reference[1])) return false;
+ return reference[2] === undefined || isProvableColour(reference[2], tokens);
+};
+
+// The classification is DENY BY DEFAULT, and that is the whole point of it.
+// Three review rounds each found another spelling that fell past a check built
+// to recognise glows and reject them -- an unlisted colour syntax, an unread
+// input channel, hand-picked geometry behind a managed colour -- because
+// anything the parser failed to recognise landed in an implicit "accept". A
+// fourth then found the cheapest fall-through of all: `shadow-[var(--anything)]`
+// is a single part, so it had no offsets to test and was waved through, which
+// let `--rogue-glow: 0 0 93px var(--mint)` ship a hand-drawn glow behind a name.
+// Widening the recogniser a fourth time would just relocate the gap, so the
+// default is inverted instead: every layer must land in a form named here, and
+// a layer this scan cannot classify FAILS asking to be made legible. A name is
+// not taken at face value either -- indirection is resolved and the same test
+// runs on what it resolves to, so a glow cannot hide one alias deeper.
+// `!important` is a property of the DECLARATION, not of any layer in it, so it
+// is dropped here rather than in the six channels that would each have to
+// remember. This is the fact round ten already established -- `setProperty('box-
+// shadow', 'none', 'important')` had swept the priority up as a second layer --
+// taught to the branch that had not heard it: written in CSS instead of in
+// CSSOM, `box-shadow: var(--shadow-glow-md-mint) !important` parsed `!important`
+// as a layer part and failed correct, fully tokenized CSS. A guard that rejects
+// the very spelling it is asking for is worse than one that misses.
+const IMPORTANT = /\s*!\s*important\s*$/i;
+
+// `tokens` is what the stylesheets declare, gathered once by the caller:
+// `values` maps a custom property to every value declared for it, `managed` to
+// the values declared inside an `@theme` block, and `colours` holds the names
+// registered as `<color>` by `@property`.
+export function glowOffencesInValue(value, tokens, seen = new Set(), depth = 0) {
+ return shadowLayers(value.replace(IMPORTANT, '')).flatMap((layer) =>
+ glowOffencesInLayer(layer, tokens, seen, depth)
+ );
+}
+
+function glowOffencesInLayer(layer, tokens, seen, depth) {
+ const parts = layerParts(layer).filter((part) => !INSET.test(part));
+ const shown = layer.trim();
+
+ if (parts.length === 1) {
+ const only = parts[0];
+ if (CSS_WIDE_KEYWORDS.has(only.toLowerCase())) return [];
+ const reference = only.match(VAR_REFERENCE);
+ if (!reference) return [`${shown} -- not a length triple, a keyword or a var() this scan can read`];
+ const [, name, fallback] = reference;
+ if (depth >= MAX_INDIRECTION) return [`${shown} -- indirection deeper than ${MAX_INDIRECTION} hops`];
+ if (seen.has(name)) return [];
+ const declared = tokens.values.get(name);
+ if (!declared) return [`${shown} -- ${name} is declared in no scanned stylesheet, so its value cannot be checked`];
+ const next = new Set(seen).add(name);
+ // The sanctioned home for a shadow literal, and the only stop condition
+ // here: a managed glow token is read against design.pen and re-anchored for
+ // light in one place, which is exactly what a call site cannot do. It stops
+ // the recursion, not the check -- the name still has to exist, and a
+ // fallback beside it is a second value that renders whenever it does not,
+ // so the fallback is classified even when the token it guards is managed.
+ //
+ // Managed is a PLACE, not a prefix. This used to stop on the name matching
+ // `--shadow-glow-`, which let anything satisfy the check by naming itself
+ // after the thing being checked: `--shadow-glow-rogue: 0 0 93px red`
+ // declared in any component stylesheet was resolved, found, and then
+ // deliberately discarded unread. Requiring the declaration to live in an
+ // `@theme` block asks the question the prefix was standing in for, because
+ // that block is what design.pen is read against -- and a name that only
+ // looks managed now falls through to the ordinary classification, where its
+ // geometry is judged like any other literal.
+ //
+ // The sanction attaches to the DECLARATION, not to the name: subtracting
+ // the `@theme` values from everything collected for this name leaves
+ // exactly the declarations made somewhere else, and those are classified.
+ // A token declared only in `@theme` subtracts to nothing and stops the
+ // recursion as before; a managed name redeclared in a component stylesheet
+ // keeps the override in the list, which is what the cascade does too.
+ const sanctioned = GLOW_TOKEN.test(name) ? tokens.managed.get(name) : undefined;
+ const resolved = sanctioned ? [...declared].filter((value) => !sanctioned.has(value)) : [...declared];
+ const deeper = [...resolved, ...(fallback ? [fallback] : [])]
+ .flatMap((declaredValue) => glowOffencesInValue(declaredValue, tokens, next, depth + 1));
+ return deeper.map((offence) => `${offence} <- reached through ${shown}`);
+ }
+
+ // CSS lets the colour lead instead of trail, so move a leading non-length to
+ // the back and let the offsets line up. This used to exempt a leading `var()`,
+ // which quietly reopened the same hole from the other end: `var(--mint) 0 0
+ // 93px` kept its colour in the offset slot and drew whatever geometry it liked.
+ if (!isLength(parts[0])) parts.push(parts.shift());
+
+ const [x, y, third] = parts;
+
+ // Only the offsets decide whether a layer is centred, so they are the parts
+ // that have to be readable. A non-zero offset is directional light whatever
+ // the blur does, and that is provable from the offset alone.
+ //
+ // Asking this FIRST is the fix for a false positive the uncertainty rule
+ // below caused: it rejected a math function anywhere in the layer, so
+ // `0 4px calc(8px) red` was blocked -- a directional shadow whose literal 4px
+ // already settles the question, with the arithmetic confined to a blur that
+ // cannot unsettle it. Uncertainty about a part that cannot change the answer
+ // is not uncertainty about the answer, and blocking a correct shadow costs
+ // more than the miss it was guarding against.
+ const readableOffsets = isLength(x ?? '') && isLength(y ?? '');
+ if (readableOffsets && (!isZeroLength(x) || !isZeroLength(y))) return [];
+
+ // Past that point the layer is centred or unreadable, and a multi-part layer
+ // passes only if it can be shown NOT to be a glow. That is the same inversion
+ // the single-part branch makes, and this branch was left out of it -- the
+ // check still asked "is this a glow" and accepted silence as a no.
+ // `calc(0px) calc(0px) 93px red` is what that costs: both offsets compute to
+ // zero, neither is the literal `0` a zero-test looks for, so the question
+ // answers no and a hand-drawn glow ships. Asked the other way round, an
+ // offset this scan cannot evaluate has no innocent answer to give.
+ if (parts.some((part) => MATH_FUNCTION.test(part))) {
+ return [`${shown} -- a computed length cannot be evaluated here, so this cannot be shown not to be a glow`];
+ }
+ if (!readableOffsets) {
+ return [`${shown} -- the offsets are not plain lengths, so this cannot be shown not to be a glow`];
+ }
+ // Both offsets are zero, so the third part decides, and it has to prove itself
+ // the same way the layer does. Absent means there is no blur part at all; a
+ // colour means the same thing, since a layer whose third part is its colour
+ // skipped the blur -- that is the ring-spacer shape. A name is not an answer:
+ // it could hold any radius, so it is unprovable rather than innocent. Anything
+ // else is unreadable and fails, which is the point -- this branch used to end
+ // in a bare `return []`, and every spelling that reached it was accepted for
+ // no better reason than that the two tests above had not recognised it.
+ if (third === undefined) return [];
+ if (isLength(third)) return isZeroLength(third) ? [] : [shown];
+ if (isProvableColour(third, tokens)) return [];
+ if (INDIRECT.test(third)) {
+ return [`${shown} -- a name in the blur slot could be any radius, so this cannot be shown not to be a glow`];
+ }
+ return [`${shown} -- the blur slot is neither a length nor a colour this scan can read, so this cannot be shown not to be a glow`];
+}
+
+// A shadow's fourth length is its spread, and `drop-shadow()` has no slot for
+// one: a filter function given a length too many is invalid, so the browser
+// drops the whole layer and the glow does not render AT ALL. The gate's own
+// error message has been telling call sites this since the roles were named --
+// "inside drop-shadow() only the spreadless roles fit, dot and wire" -- while
+// nothing checked it, which is the enumeration-instead-of-invariant failure
+// stated in the guard's own words: a rule written where it is read rather than
+// where it is enforced.
+//
+// It asks the property, not the role. `drop-shadow(var(--shadow-glow-md-mint))`
+// is the spelling the reviewer found, but a hand-written
+// `drop-shadow(2px 2px 4px 2px red)` disappears the same way and names no role
+// at all, and a role added later is covered without editing anything.
+//
+// It is a separate walk rather than a mode of the one above because the two
+// stop in OPPOSITE places. The glow walk stops at a managed token: its geometry
+// is read against design.pen in one place, so a call site naming it is answered.
+// That is exactly the wrong stop here, because the constraint belongs to the
+// CALL SITE -- the token cannot know which function it will be spliced into --
+// so this walk has to open the token the other one is finished with. Threading
+// that contradiction through one function as a flag would make each stop
+// condition read as an exception to the other.
+export function spreadOffencesInDropShadow(value, tokens, seen = new Set(), depth = 0) {
+ return shadowLayers(value.replace(IMPORTANT, '')).flatMap((layer) => {
+ const parts = layerParts(layer).filter((part) => !INSET.test(part));
+ const shown = layer.trim();
+
+ if (parts.length === 1) {
+ const reference = parts[0].match(VAR_REFERENCE);
+ // A name that resolves to nothing, or resolves too deep, is already the
+ // glow walk's finding to report; saying it twice would only double it.
+ if (!reference || depth >= MAX_INDIRECTION) return [];
+ const [, name, fallback] = reference;
+ if (seen.has(name)) return [];
+ const next = new Set(seen).add(name);
+ return [...(tokens.values.get(name) ?? []), ...(fallback ? [fallback] : [])]
+ .flatMap((declared) => spreadOffencesInDropShadow(declared, tokens, next, depth + 1))
+ .map((offence) => `${offence} <- reached through ${shown}`);
+ }
+
+ return parts.filter(isLength).length > 3
+ ? [`${shown} -- drop-shadow() takes no spread, so a layer carrying one is invalid and draws nothing at all; use a spreadless role, dot or wire`]
+ : [];
+ });
+}
+
+// Whether a channel's match lands inside a `drop-shadow()`, which decides
+// whether the rule above applies to the values it yielded.
+//
+// It is a question about the SPELLING, not about the channel that found it, and
+// that distinction is the whole reason it is a function rather than a flag on
+// the channel list: `drop-shadow-[var(--shadow-glow-wire-mint)]` is read by the
+// bracket channel, whose pattern begins at `shadow-[` and so leaves the `drop-`
+// prefix outside its own match. A flag per channel would answer for that
+// channel's other spelling too and restrict every `shadow-[…]` on the page.
+//
+// So both sides of the match are asked, which reads all four spellings at once
+// -- the function, the custom-property shorthand, and the two Tailwind prefixes
+// -- without giving any channel a second idea of what it is looking at.
+export const readsIntoDropShadow = (source, index, matched) => /^drop-shadow/i.test(matched)
+ || /drop-$/i.test(source.slice(Math.max(0, index - 5), index));
diff --git a/ui/scripts/shadowLayer.test.mjs b/ui/scripts/shadowLayer.test.mjs
new file mode 100644
index 000000000..177f52d8b
--- /dev/null
+++ b/ui/scripts/shadowLayer.test.mjs
@@ -0,0 +1,291 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ glowOffencesInValue,
+ readsIntoDropShadow,
+ spreadOffencesInDropShadow,
+} from './shadowLayer.mjs';
+
+// The rule the whole gate is about: a glow may not be written by hand, and a
+// layer that cannot be shown not to be one fails asking to be made legible.
+//
+// Ten documented rounds of holes in this classifier were found by a reviewer
+// rather than by a test, because it lived inside a script that reads the tree
+// the moment it is imported -- there was nothing to call. Both directions cost
+// real rounds. A hole ships a hand-drawn glow that light cannot re-anchor; a
+// false positive fails a pull request that spelled the required token exactly
+// right, and this round produced two of those at once.
+//
+// So the cases below are the property in both directions, stated as the rules
+// they are examples of rather than as the spellings that happened to be found.
+
+// The stylesheet declarations the classifier resolves names against. Built per
+// test rather than shared, so one test's token cannot leak into another's.
+const declaring = ({ values = {}, managed = {}, colours = [] } = {}) => ({
+ values: new Map(Object.entries(values).map(([name, list]) => [name, new Set([list].flat())])),
+ managed: new Map(Object.entries(managed).map(([name, list]) => [name, new Set([list].flat())])),
+ colours: new Set(colours),
+});
+
+const MANAGED = declaring({
+ values: { '--shadow-glow-md-mint': '0 0 16px -4px rgba(91, 255, 160, 0.44)' },
+ managed: { '--shadow-glow-md-mint': '0 0 16px -4px rgba(91, 255, 160, 0.44)' },
+});
+
+const offences = (value, tokens = MANAGED) => glowOffencesInValue(value, tokens);
+const accepts = (value, tokens = MANAGED) => expect(offences(value, tokens)).toEqual([]);
+const rejects = (value, tokens = MANAGED) => expect(offences(value, tokens).length).toBeGreaterThan(0);
+
+describe('what the classifier accepts', () => {
+ // The shape this gate exists to require. Everything else in this block is a
+ // spelling of it, or a shadow that provably is not a glow.
+ it('accepts a managed glow token', () => {
+ accepts('var(--shadow-glow-md-mint)');
+ });
+
+ it.each([
+ ['none', 'none'],
+ ['inherit', 'inherit'],
+ ])('accepts the CSS-wide keyword %s', (_label, value) => accepts(value));
+
+ it('accepts an offset shadow, which is directional light rather than a glow', () => {
+ accepts('0 2px 8px rgba(0, 0, 0, 0.4)');
+ });
+
+ // Whether a layer is centred is decided by its OFFSETS and nothing else, so a
+ // part that cannot move them cannot make the answer uncertain. The
+ // deny-by-default rule below rejected a math function anywhere in the layer
+ // before the offsets were read at all, so a directional shadow whose literal
+ // `4px` already settled the question failed for computing a blur, a spread or
+ // a colour channel -- three spellings of one mistake, which is why they are
+ // stated as three rather than as the reported one.
+ it.each([
+ ['blur', '0 4px calc(8px) red'],
+ ['spread', '0 4px 8px calc(2px) red'],
+ ['colour channel', '0 4px 8px rgb(calc(255 / 2) 0 0)'],
+ ])('accepts a shadow whose offsets prove it directional while its %s computes', (_label, value) =>
+ accepts(value)
+ );
+
+ it('accepts a ring, which has no blur to colour-manage', () => {
+ accepts('0 0 0 2px rgba(0, 0, 0, 0.4)');
+ });
+
+ // `!important` belongs to the DECLARATION, not to any layer in it. Round ten
+ // taught this to the CSSOM branch and left the CSS one behind, so the same
+ // token failed depending on which language wrote it.
+ it('accepts a managed token carrying !important', () => {
+ accepts('var(--shadow-glow-md-mint) !important');
+ });
+
+ // This round's first false positive, and the one that is hardest to argue
+ // with: the guard rejected a word order of the very thing it is asking for.
+ // `inset` is a keyword of the shadow grammar with two freedoms the parser has
+ // to grant -- the spec allows it before the lengths or after the colour, and
+ // CSS keywords are ASCII case-insensitive.
+ //
+ // Stated as all four spellings rather than the one that was reported, because
+ // the reported one was only the position half; filtering position without
+ // case would have closed the finding and left the other half open.
+ it.each([
+ ['leading', 'inset var(--shadow-glow-md-mint)'],
+ ['trailing', 'var(--shadow-glow-md-mint) inset'],
+ ['leading, capitalised', 'INSET var(--shadow-glow-md-mint)'],
+ ['trailing, mixed case', 'var(--shadow-glow-md-mint) Inset'],
+ ])('accepts a managed token with %s inset', (_label, value) => accepts(value));
+
+ // The second false positive. The blur slot is proved innocent by showing the
+ // part in it is a COLOUR, and that recogniser is an enumeration of CSS
+ // Color's functional notations -- deliberately, because it sits on the accept
+ // side, where a missing name costs a spurious failure rather than a glow that
+ // ships. `light-dark()` arriving is that enumeration behaving as designed.
+ it.each([
+ ['light-dark', '0 0 light-dark(red, blue)'],
+ ['oklch', '0 0 oklch(0.7 0.2 150)'],
+ ['color-mix', '0 0 color-mix(in oklab, red, blue)'],
+ ['contrast-color', '0 0 contrast-color(red)'],
+ ['device-cmyk', '0 0 device-cmyk(0 0.5 1 0)'],
+ ])('accepts a blur-free layer coloured with %s()', (_label, value) => accepts(value));
+
+ it('accepts a name registered as a colour in the blur slot', () => {
+ accepts('0 0 var(--tint)', declaring({ colours: ['--tint'] }));
+ });
+
+ // The fallback is part of the value, not a separate spelling to exclude.
+ // Accepting the registration only when it stood alone read `var(--tint, blue)`
+ // as unprovable and failed a shadow where NEITHER possible value can occupy
+ // the blur slot -- the registered name cannot hold a length, and `blue` is a
+ // colour. Both halves have to be answered, and each hop asks the same
+ // question, so a fallback that is itself a registered name is answered too.
+ it('accepts a registered colour whose fallback is also a colour', () => {
+ accepts('0 0 var(--tint, blue)', declaring({ colours: ['--tint'] }));
+ });
+
+ it('accepts a registered colour whose fallback is a colour function', () => {
+ accepts('0 0 var(--tint, color-mix(in oklab, red, blue))', declaring({ colours: ['--tint'] }));
+ });
+
+ it('accepts a registered colour falling back to another registered colour', () => {
+ accepts('0 0 var(--tint, var(--other))', declaring({ colours: ['--tint', '--other'] }));
+ });
+});
+
+describe('what the classifier rejects', () => {
+ it('rejects a hand-written glow', () => {
+ rejects('0 0 16px -4px rgba(91, 255, 160, 0.44)');
+ });
+
+ // The colour is allowed to lead in CSS, and exempting a leading `var()`
+ // reopened the hole from the other end: the geometry went unread.
+ it('rejects a hand-written glow whose colour leads', () => {
+ rejects('var(--mint) 0 0 93px');
+ });
+
+ // Deny by default, one level down: an offset this scan cannot evaluate has no
+ // innocent answer to give, and `calc(0px)` is not the literal `0` a zero-test
+ // looks for. The exemption above is for maths that provably cannot reach the
+ // offsets; maths IN one of them, or beside two zeroes, is the case the
+ // exemption must not widen to cover.
+ it('rejects offsets it cannot evaluate', () => {
+ rejects('calc(0px) calc(0px) 93px red');
+ });
+
+ it('rejects a centred layer whose blur is computed', () => {
+ rejects('0 0 calc(93px) red');
+ });
+
+ // A name could hold any radius, so it is unprovable rather than innocent --
+ // unless `@property` has registered it as a colour, which the accepting test
+ // above covers.
+ it('rejects a name in the blur slot', () => {
+ rejects('0 0 var(--blur)');
+ });
+
+ // The other half of reading the fallback: it is a second value that renders
+ // whenever the registration does not, so it has to be a colour too. A
+ // registration cannot vouch for a value it does not constrain.
+ it('rejects a registered colour whose fallback is a length', () => {
+ rejects('0 0 var(--tint, 93px)', declaring({ colours: ['--tint'] }));
+ });
+
+ it('rejects a registered colour falling back to an unregistered name', () => {
+ rejects('0 0 var(--tint, var(--blur))', declaring({ colours: ['--tint'] }));
+ });
+
+ // Managed is a PLACE, not a prefix. A name that only looks managed falls
+ // through to the ordinary classification.
+ it('rejects a glow hidden behind a name that merely looks managed', () => {
+ rejects('var(--shadow-glow-rogue)', declaring({
+ values: { '--shadow-glow-rogue': '0 0 93px red' },
+ }));
+ });
+
+ it('rejects a glow one alias deeper', () => {
+ rejects('var(--card)', declaring({
+ values: { '--card': 'var(--rogue)', '--rogue': '0 0 93px red' },
+ }));
+ });
+
+ it('rejects a name declared in no scanned stylesheet', () => {
+ rejects('var(--nowhere)');
+ });
+
+ // A fallback renders whenever the token it guards does not, so it is a second
+ // value and is classified even beside a managed name.
+ it('rejects a glow in a fallback beside a managed token', () => {
+ rejects('var(--shadow-glow-md-mint, 0 0 93px red)');
+ });
+
+ // Every layer is classified, so a glow cannot ride along beside an innocent
+ // one.
+ it('rejects a glow in the second layer of a list', () => {
+ rejects('0 2px 8px rgba(0, 0, 0, 0.4), 0 0 93px red');
+ });
+});
+
+// `drop-shadow()` has no spread slot. A filter function given a length too many
+// is invalid, so the browser drops the layer whole and the glow does not render
+// AT ALL -- a silent nothing rather than a wrong something, which is why the
+// glow classifier could never see it: the value it reads is a correct, managed
+// token. The constraint belongs to the CALL SITE, and these are the two facts
+// that follow from that.
+describe('what drop-shadow() refuses to carry', () => {
+ const SIZED = declaring({
+ values: {
+ '--shadow-glow-md-mint': '0 0 24px -6px rgba(91, 255, 160, 0.44)',
+ '--shadow-glow-wire-mint': '0 0 4px rgba(91, 255, 160, 0.44)',
+ '--indirect': 'var(--shadow-glow-md-mint)',
+ },
+ managed: {
+ '--shadow-glow-md-mint': '0 0 24px -6px rgba(91, 255, 160, 0.44)',
+ '--shadow-glow-wire-mint': '0 0 4px rgba(91, 255, 160, 0.44)',
+ },
+ });
+ const spreads = (value) => spreadOffencesInDropShadow(value, SIZED);
+
+ // The whole point of the separate walk: the glow classifier stops AT a managed
+ // token because its geometry is read against design.pen, and that is exactly
+ // the wrong stop for a question the token cannot answer about itself.
+ it('opens a managed token the glow walk is finished with', () => {
+ expect(spreads('var(--shadow-glow-md-mint)').length).toBe(1);
+ expect(glowOffencesInValue('var(--shadow-glow-md-mint)', SIZED)).toEqual([]);
+ });
+
+ it('follows a spread one alias deeper', () => {
+ expect(spreads('var(--indirect)').length).toBe(1);
+ });
+
+ // Stated as the property, so a hand-written layer that names no role at all
+ // fails for the same reason a sized token does.
+ it('rejects a hand-written layer carrying a spread', () => {
+ expect(spreads('2px 2px 4px 2px red').length).toBe(1);
+ });
+
+ it('accepts a spreadless role', () => {
+ expect(spreads('var(--shadow-glow-wire-mint)')).toEqual([]);
+ });
+
+ it('accepts a spreadless hand-written layer', () => {
+ expect(spreads('0 0 4px red')).toEqual([]);
+ });
+
+ // A keyword and a priority are both parts that are not lengths, and either one
+ // left in place turns a one-part layer into a multi-part one -- which is a
+ // count of lengths that never reaches the token, so the spread inside it goes
+ // unread. Both are dropped for the same reason the glow walk drops them, and
+ // this is the direction that matters: a MISS, not a spurious failure.
+ it('reads the token behind a keyword', () => {
+ expect(spreads('inset var(--shadow-glow-md-mint)').length).toBe(1);
+ });
+
+ it('reads the token behind !important', () => {
+ expect(spreads('var(--shadow-glow-md-mint) !important').length).toBe(1);
+ });
+
+ // Every layer is asked, so a spread cannot ride along beside a spreadless one.
+ it('finds a spread in the second layer of a list', () => {
+ expect(spreads('0 0 4px red, 0 0 4px 2px blue').length).toBe(1);
+ });
+});
+
+// Which matches that rule applies to. The four spellings all reach the same
+// function, and only two of them carry the `drop-` prefix inside the match --
+// which is why this is asked of the source text rather than of the channel.
+describe('which spellings read into drop-shadow()', () => {
+ const reads = (source, needle) => readsIntoDropShadow(source, source.indexOf(needle), needle);
+
+ it.each([
+ ['the filter function', 'filter: drop-shadow(0 0 4px red)', 'drop-shadow('],
+ ['the custom-property shorthand', '<i class="drop-shadow-(--x)" />', 'drop-shadow-(--x)'],
+ ['the Tailwind prefix, whose match starts after it', 'class="drop-shadow-[var(--x)]"', 'shadow-[var(--x)]'],
+ ['a capitalised filter function', 'filter: DROP-SHADOW(0 0 4px red)', 'DROP-SHADOW('],
+ ])('reads %s', (_label, source, needle) => expect(reads(source, needle)).toBe(true));
+
+ // And the half that has to stay false: `box-shadow` DOES take a spread, so
+ // answering yes here would restrict every sized token on the page.
+ it.each([
+ ['a box-shadow utility', 'class="shadow-[var(--x)]"', 'shadow-[var(--x)]'],
+ ['a box-shadow declaration', 'box-shadow: 0 0 4px 2px red', 'box-shadow:'],
+ ['a shorthand with no prefix', '<i class="shadow-(--x)" />', 'shadow-(--x)'],
+ ])('does not read %s', (_label, source, needle) => expect(reads(source, needle)).toBe(false));
+});
diff --git a/ui/scripts/styleWrite.mjs b/ui/scripts/styleWrite.mjs
new file mode 100644
index 000000000..aa0d3d8bd
--- /dev/null
+++ b/ui/scripts/styleWrite.mjs
@@ -0,0 +1,285 @@
+import ts from 'typescript';
+
+// Where a style write starts, whether it is one at all, and where its value
+// ends.
+//
+// Two questions the scan asks of JavaScript, both of which it used to answer by
+// reading the bytes around a match, and both of which produced a false positive
+// in the same review round: a name ending in `Shadow` was read as a style
+// property when it was a variable, and a value written on the line below its key
+// was read as absent when it was a token. This module is the pair of answers,
+// extracted for the reason `cssLength.mjs` was: `validate-theme.mjs` runs its
+// whole validation at import time, so nothing inside it can be called from a
+// test, and an assertion about a regex's SOURCE is not an assertion about its
+// behaviour. What lives here can be reverse-verified by introducing the defect
+// it names and watching a test fail.
+//
+// The boundary is deliberately not "everything about style writes". It is the
+// two spans -- the key and the value -- that the scan cannot locate correctly by
+// eye, kept next to each other because a change to one is nearly always a change
+// to the other.
+
+// A style write's TARGET, not its name. `box-shadow`, `text-shadow` and
+// `drop-shadow` all end in the word, so requiring the word at the tail of an
+// identifier looked like it separated properties from variables -- and it does
+// not: `const cardShadow = 'compact'` ends in the word too, and was read as a
+// style property, classified as a shadow layer, and failed `validate:theme` for
+// a variable that never reaches a browser.
+//
+// The difference is not in the name at all. A property in an object literal is a
+// candidate style key, because `style={{ boxShadow: … }}` is the whole reason
+// the channel exists; an ASSIGNMENT reaches the browser through exactly one
+// door, `element.style`, spelled `.style.boxShadow =` or `.style['boxShadow'] =`.
+// An assignment to a bare identifier is a variable, and a variable is not a
+// declaration however it is named.
+//
+// The gap this admits -- `const s = el.style; s.boxShadow = glow` -- is a MISS,
+// and that direction is settled: a miss leaves the tree where it already was,
+// while a false positive fails a pull request that was correct.
+const STYLE_ASSIGNMENT = String.raw`(?<=\.style\s*[.[]\s*['"\`]?)`;
+
+// The properties a shadow can be written to, spelled every way JavaScript
+// spells them. This is a CLOSED set and closed for a reason that is not a
+// judgement call: a style object and `element.style` both address real CSS
+// properties, so a key that is not one of these draws nothing whatever it is
+// called. `const opts = { cardShadow: 'compact' }` is a variable-shaped object
+// that happens to end in the word, and reading it as a declaration failed
+// `validate:theme` on `compact` -- a false positive, in CI, on code with no CSS
+// in it at all.
+//
+// The rule it replaces was `[A-Za-z]*[Ss]hadow`: "the name ends in the word".
+// That is a guess about intent, and every round of this review has found another
+// name that satisfies it without being a property. The CSS spec's list does not
+// have that problem -- it is finite, published, and changes on a timescale where
+// a missed addition is a MISS rather than a false positive.
+//
+// `filter` and `backdrop-filter` are deliberately NOT here, even though
+// `drop-shadow()` reaches the page through them. Adding them would widen this
+// channel onto every ordinary `{ filter: 'blur(2px)' }` in the tree and ask it
+// to classify a value that is not a shadow at all -- trading the false positive
+// below for a larger one. `drop-shadow(` is already counted and read where it is
+// unambiguous: by the function name, one channel over.
+const SHADOW_PROPERTIES = ['box-shadow', 'text-shadow', '-webkit-box-shadow', '-moz-box-shadow'];
+
+// Every spelling of each, because the same property is written three ways
+// depending on where it is: `box-shadow` in a stylesheet or in
+// `element.style['box-shadow']`, `boxShadow` in a style object, and -- for the
+// vendor-prefixed pair -- TWO camel spellings rather than one. CSSOM defines the
+// attribute with the prefix lowercased, `element.style.webkitBoxShadow`, while
+// the capitalised `WebkitBoxShadow` is the IDL alias that React's style objects
+// use. Deriving only the capitalised one was not a missing spelling in a list,
+// it was half a property: `el.style.webkitBoxShadow = 'var(--shadow-glow-md-
+// mint)'` -- a correct, fully tokenised write -- failed `validate:theme`,
+// because the completeness matcher counted a mention that the channel could not
+// claim.
+//
+// Sorted longest-first so `box-shadow` cannot match as the tail of
+// `-webkit-box-shadow` and leave the prefix outside the match.
+const camel = (property) => property.replace(/^-/, '').replace(/-(\w)/g, (_, next) => next.toUpperCase());
+const capitalised = (name) => name[0].toUpperCase() + name.slice(1);
+
+const IDENTIFIER_NAMES = [
+ ...new Set(SHADOW_PROPERTIES.flatMap((property) => {
+ const js = camel(property);
+ return property.startsWith('-') ? [js, capitalised(js)] : [js];
+ })),
+];
+
+const SHADOW_PROPERTY_NAMES = [...new Set([...SHADOW_PROPERTIES, ...IDENTIFIER_NAMES])]
+ .sort((a, b) => b.length - a.length);
+
+// The JS spelling of the key, up to but not including the punctuation that hands
+// it a value. The colon and the equals sign take different prefixes now, so the
+// name they share has to be one string rather than two that agree today.
+//
+// Two spellings, and the quote is what separates them rather than decorating
+// them. A hyphenated name is not a JavaScript identifier, so `box-shadow` can
+// only ever be a key QUOTED -- `el.style['box-shadow']`, `{'box-shadow': …}` --
+// and a bare one is CSS. Accepting the hyphenated names bare read every
+// `box-shadow:` declaration in every stylesheet as a JS style write, handed it to
+// a channel that reads JavaScript expressions, and got nothing back: four
+// correct declarations reported as values the scan cannot read. The quote is not
+// a detail of how the key is written; it is the whole difference between the two
+// languages this scan reads.
+//
+// The delimiter accepts all three of JavaScript's string quotes. That is an
+// enumeration, and it is a safe one for the same reason the property list is: the
+// language has exactly three, so a backtick-quoted computed key is not the next
+// spelling nobody imagined, it is the last one. Missing it let a hardcoded glow
+// ship with every guard green.
+const QUOTE = String.raw`['"\x60]`;
+
+const JS_SHADOW_KEY = String.raw`(?<![\w-])(?:(?:${IDENTIFIER_NAMES.join('|')})(?![\w-])${QUOTE}?`
+ + String.raw`|(?<=${QUOTE})(?:${SHADOW_PROPERTY_NAMES.join('|')})(?![\w-])${QUOTE})\s*\]?\s*`;
+
+// The two spellings, composed. `{ boxShadow: … }` and `el.style.boxShadow = …`
+// are one channel to everything downstream, and this is the only place that
+// knows they are written differently.
+const SHADOW_KEY = `${JS_SHADOW_KEY}:|${STYLE_ASSIGNMENT}${JS_SHADOW_KEY}=`;
+
+// Whether the key found at `index` is a style write at all.
+//
+// `SHADOW_KEY` locates a key by the punctuation after it, and a colon is the
+// most overloaded character in TypeScript. `interface Props { boxShadow: string
+// }` declares a TYPE, `const { boxShadow: current } = style` DESTRUCTURES one,
+// and both spell a real CSS property followed by a colon -- so both were read as
+// rendered assignments, found no shadow string, and failed `validate:theme` as
+// unreadable. Neither reaches a browser: one is erased before the file runs, the
+// other reads a value rather than writing one.
+//
+// The rule this restates is the module's own, at the top of this file: a style
+// write is a property in an OBJECT LITERAL, or an assignment through
+// `element.style`. That was always the intent; the regex was an approximation of
+// it built from the characters nearby, and every round of this review has found
+// another construct those characters cannot tell apart. The parser has already
+// read the file and knows which one this is.
+//
+// The accept list is closed by the language rather than by whoever last thought
+// about it: those two constructs are how a CSS property gets a value in
+// JavaScript. Anything else -- a type member, a binding, a class field, a label
+// -- is not a style write, which keeps the residual risk on the MISS side that
+// this module has already settled, and off the side that fails a correct pull
+// request.
+function isStyleWrite(index, tree) {
+ if (!tree) return false;
+
+ // The innermost node containing the key. Containing rather than starting at:
+ // for a quoted key the match begins INSIDE the string literal, one character
+ // past the node's own start.
+ let key = null;
+ const visit = (node) => {
+ if (node.getStart(tree) > index || node.getEnd() <= index) return;
+ key = node;
+ node.getChildren(tree).forEach(visit);
+ };
+ visit(tree);
+
+ while (key && !ts.isIdentifier(key) && !ts.isStringLiteralLike(key)) key = key.parent;
+ const parent = key?.parent;
+ if (!parent) return false;
+
+ // `{ boxShadow: value }` -- and the name position specifically, so a style
+ // object held as the VALUE of some other key is not claimed by its own key.
+ if (ts.isPropertyAssignment(parent)) return parent.name === key;
+
+ // `el.style.boxShadow = value` and `el.style['box-shadow'] = value`. The
+ // lookbehind in STYLE_ASSIGNMENT has already required the `.style` target;
+ // this requires the assignment itself, so a READ of the same property is not a
+ // write.
+ if (ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) {
+ const assignment = parent.parent;
+ return Boolean(assignment)
+ && ts.isBinaryExpression(assignment)
+ && assignment.operatorToken.kind === ts.SyntaxKind.EqualsToken
+ && assignment.left === parent;
+ }
+
+ return false;
+}
+
+// The expression beginning at `start`, ending at the first terminator that is
+// not nested inside a call, a bracket or a string. Null when it never
+// terminates, so an unreadable expression stays loud instead of quietly yielding
+// nothing.
+//
+// A terminator only ends an expression that has BEGUN. `\n` is a terminator for
+// a property because a statement can end without a semicolon, but a value is
+// free to start on the line after its key -- `boxShadow:\n 'var(--shadow-glow-
+// md-mint)'` is what a formatter produces once the line is long enough -- and
+// reading that newline as the end returned an empty expression, no string
+// literals, and "this scan cannot read it" for a site spelling the required
+// token correctly. Leading whitespace is skipped rather than terminating, which
+// costs the call-argument caller nothing: whitespace is not in its set at all.
+function expressionUpTo(source, start, terminators) {
+ let depth = 0;
+ let quote = null;
+ let begun = false;
+ for (let index = start; index < source.length; index += 1) {
+ const char = source[index];
+ if (!begun && !quote) {
+ if (/\s/.test(char)) continue;
+ begun = true;
+ }
+ if (quote) {
+ if (char === '\\') index += 1;
+ else if (char === quote) quote = null;
+ continue;
+ }
+ if (char === "'" || char === '"' || char === '`') quote = char;
+ else if (char === '(' || char === '[' || char === '{') depth += 1;
+ else if (depth === 0 && terminators.includes(char)) return source.slice(start, index);
+ else if (char === ')' || char === ']' || char === '}') depth -= 1;
+ }
+ return null;
+}
+
+// A call argument ends at the comma before the next one, or at the paren that
+// closes the call. `setProperty` takes a third argument, `priority`, and reading
+// "every string literal after the property name" swept it up as a second layer
+// -- so the entirely valid `setProperty('box-shadow', 'none', 'important')`
+// accepted `none` and then failed on `important`.
+const valueArgument = (source, start) => expressionUpTo(source, start, ',)');
+
+// A style property's own expression, ended by the compiler.
+//
+// Every previous answer here was a rule about punctuation, and each one was
+// right about the case that prompted it and wrong about the next. `[^;\n]*` swept
+// the following property up as a second layer, so `style={{ boxShadow: 'none',
+// color: 'red' }}` failed on `red`. Adding `,` and `}` fixed that and left `\n`
+// behind to stop a runaway, so a value a formatter wrapped onto the next line
+// read as absent. Removing `\n` fixes the wrap and reopens the runaway: a
+// semicolon-less assignment swallows the statements after it.
+//
+// That last pair does not have a punctuation answer. Whether a newline ends a
+// statement is JavaScript's automatic semicolon insertion, which is defined in
+// terms of the parse -- `x = a\n ? b : c` continues because `?` cannot begin a
+// statement, and `x = a\n const y = 1` does not. Any scanner that decides it by
+// looking at characters is re-implementing the grammar, badly, one review round
+// at a time. Six rounds of this file's history are that re-implementation.
+//
+// So the question goes to the parser that has already read the file. The tree is
+// the enumeration: it knows where the expression that starts here ends, for
+// every spelling at once, including the ones nobody has written yet. The
+// outermost node starting at the value is the whole value -- at `a ? b : c` both
+// `a` and the conditional start on the same character, and it is the conditional
+// that was assigned.
+//
+// The tree and the text are deliberately two arguments rather than one parse of
+// one string. The tree is the file AS WRITTEN, because blanking a regex literal
+// to spaces leaves `const re = ;`, which is no longer a program and parses
+// into error nodes whose boundaries answer nothing. The text is the file with
+// its non-rendering spans removed, because a value is allowed to carry a comment
+// -- `boxShadow: /* red */ 'none'` -- and reading the comment back would hand a
+// colour to the caller that never renders. Offsets agree between the two by
+// construction: every blank in `nonRenderingText.mjs` preserves length.
+function propertyExpression(source, start, tree) {
+ if (!tree) return null;
+ const begin = source.slice(start).search(/\S/);
+ if (begin < 0) return null;
+ const at = start + begin;
+
+ let end = -1;
+ const visit = (node) => {
+ const nodeStart = node.getStart(tree);
+ if (nodeStart > at || node.getEnd() <= at) {
+ if (nodeStart <= at) node.getChildren(tree).forEach(visit);
+ return;
+ }
+ if (nodeStart === at) end = Math.max(end, node.getEnd());
+ node.getChildren(tree).forEach(visit);
+ };
+ visit(tree);
+
+ return end < 0 ? null : source.slice(start, end);
+}
+
+export {
+ JS_SHADOW_KEY,
+ SHADOW_KEY,
+ SHADOW_PROPERTIES,
+ SHADOW_PROPERTY_NAMES,
+ STYLE_ASSIGNMENT,
+ isStyleWrite,
+ propertyExpression,
+ valueArgument,
+};
diff --git a/ui/scripts/styleWrite.test.mjs b/ui/scripts/styleWrite.test.mjs
new file mode 100644
index 000000000..012345f4a
--- /dev/null
+++ b/ui/scripts/styleWrite.test.mjs
@@ -0,0 +1,287 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseSource, withoutNonRenderingText } from './nonRenderingText.mjs';
+import { SHADOW_KEY, isStyleWrite, propertyExpression, valueArgument } from './styleWrite.mjs';
+
+// Both halves of this module produced a false positive in one review round, and
+// both were the same mistake in different clothes: the scan decided what a span
+// MEANT by looking at the bytes beside it. A name ending in `Shadow` was read as
+// a style property when it was a variable, and a value on the line below its key
+// was read as absent when it was a token. Each failed `validate:theme` for code
+// that was correct, which is the failure mode this guard cannot afford -- a
+// missed glow leaves the tree where it was, a false positive blocks a pull
+// request that never had one.
+//
+// So the cases below are the property in both directions. What is a style write
+// must still be found, and -- the half that keeps the first half honest -- what
+// is not one must be left alone.
+
+const key = () => new RegExp(SHADOW_KEY, 'g');
+
+// A style write, and the browser can see it.
+const WRITES = [
+ ['an inline style property', "<div style={{ boxShadow: '0 0 8px red' }} />"],
+ ['a quoted property', "const s = { 'boxShadow': '0 0 8px red' };"],
+ ['a computed property', "const s = { ['boxShadow']: '0 0 8px red' };"],
+ // The third of JavaScript's three string quotes. Missing it let a hardcoded
+ // glow ship with every guard green, and there is no fourth: the language has
+ // exactly these, so this enumeration is closed by the grammar rather than by
+ // whoever last thought about it.
+ ['a backtick computed property', "const s = { [`boxShadow`]: '0 0 8px red' };"],
+ ['a text-shadow property', "const s = { textShadow: '0 0 8px red' };"],
+ // A hyphenated name is not a JavaScript identifier, so these two spellings can
+ // only ever appear quoted -- and quoted, they are style writes like any other.
+ ['a hyphenated object key', "const s = { 'box-shadow': '0 0 8px red' };"],
+ ['a hyphenated CSSOM key', "el.style['box-shadow'] = '0 0 8px red';"],
+ // A vendor-prefixed property has TWO camel spellings, and deriving one of
+ // them was not a missing entry in a list -- it was half a property. CSSOM
+ // defines the attribute with the prefix lowercased, `element.style
+ // .webkitBoxShadow`; the capitalised `WebkitBoxShadow` is the IDL alias that
+ // React's style objects use. Both are real, and a case-blind matcher upstream
+ // hid the gap by matching either one against whichever was listed.
+ ['a vendor-prefixed property', "const s = { WebkitBoxShadow: '0 0 8px red' };"],
+ ['a vendor-prefixed CSSOM property', "el.style.webkitBoxShadow = '0 0 8px red';"],
+ ['a CSSOM member assignment', "el.style.boxShadow = '0 0 8px red';"],
+ ['a CSSOM bracket assignment', "el.style['boxShadow'] = '0 0 8px red';"],
+ ['a CSSOM assignment with spaces', "el.style . boxShadow = '0 0 8px red';"],
+];
+
+// Not a style write, and no spelling of the name makes it one.
+const NOT_WRITES = [
+ // The finding this split exists for. The word is at the tail, exactly where a
+ // property has it, and the statement is still a variable.
+ ['a variable whose name ends in the word', "const cardShadow = 'compact';"],
+ // The same name as a KEY, which is the branch that outlived the assignment
+ // fix: an options object is shaped exactly like a style object, and only the
+ // name can tell them apart. `cardShadow` is not a CSS property, so it draws
+ // nothing whatever it is nested in.
+ ['an options object with a key ending in the word', "const config = { cardShadow: 'compact' };"],
+ ['a let binding', "let hoverShadow = 'none';"],
+ ['a reassigned variable', "cardShadow = 'compact';"],
+ // The finding before it, which moving the word to the tail did fix.
+ ['a variable whose name starts with the word', "const shadowPreset = 'compact';"],
+ ['a shadow root property', 'const root = el.shadowRoot;'],
+ // JavaScript folds no case, so these two address no CSS property and draw
+ // nothing whatever they are nested in. They are here because the completeness
+ // matcher used to measure them case-blind and report a file with no CSS in it
+ // -- the same rule read as CSS's rule, in a language that does not have it.
+ ['a key that only misspells the property\'s case', 'const s = { BOXSHADOW: \'compact\' };'],
+ ['a CSSOM member that only misspells the property\'s case', "el.style.boxshadow = 'x';"],
+ // CSS, not JavaScript. Accepting the hyphenated names BARE here handed every
+ // stylesheet declaration in the tree to a channel that reads JS expressions,
+ // which returned nothing -- four correct declarations reported as values the
+ // scan cannot read, in CI, on a pull request with no defect in it.
+ ['a CSS declaration', '.a { box-shadow: 0 0 8px red; }'],
+ ['a vendor-prefixed CSS declaration', '.a { -webkit-box-shadow: 0 0 8px red; }'],
+ ['a CSS declaration after a string', '.a { content: "x"; box-shadow: 0 0 8px red; }'],
+];
+
+describe('SHADOW_KEY', () => {
+ it.each(WRITES)('finds %s', (_label, source) => {
+ expect(source.match(key())).not.toBeNull();
+ });
+
+ it.each(NOT_WRITES)('leaves %s alone', (_label, source) => {
+ expect(source.match(key())).toBeNull();
+ });
+
+ // The rules, not the spellings above them. Stated separately because a list
+ // can only ever hold the spellings someone thought of, and these are the two
+ // sentences those spellings are examples of.
+ it('requires an assignment to go through .style', () => {
+ expect('el.style.boxShadow = x'.match(key())).not.toBeNull();
+ expect('el.boxShadow = x'.match(key())).toBeNull();
+ });
+
+ // The second rule, and the one that makes the first affordable. A style object
+ // and `element.style` both address real CSS properties, so a key that is not
+ // one of those draws nothing whatever it is called -- which is why the list of
+ // properties can be closed at all. `[A-Za-z]*[Ss]hadow` was the guess it
+ // replaces, and every round of this review found another name satisfying it
+ // without being a property.
+ it('reads only names that are CSS properties', () => {
+ expect('el.style.boxShadow = x'.match(key())).not.toBeNull();
+ expect('el.style.rogueShadow = x'.match(key())).toBeNull();
+ });
+
+ // The rule the three CSS rows above are examples of, and the reason it is a
+ // rule rather than three exceptions: a hyphenated name is not a JavaScript
+ // identifier, so the quote is not decoration on how a key is written -- it is
+ // the whole boundary between the two languages this scan reads.
+ it('requires a quote around a name JavaScript cannot spell bare', () => {
+ expect("const s = { 'box-shadow': x };".match(key())).not.toBeNull();
+ expect('.a { box-shadow: x; }'.match(key())).toBeNull();
+ });
+});
+
+describe('isStyleWrite', () => {
+ // Asked exactly the way the scan asks it: the key regex over the blanked
+ // text, the tree of the file as written.
+ const at = (source, file = 'probe.tsx') => {
+ const match = new RegExp(SHADOW_KEY, 'g').exec(withoutNonRenderingText(source, file));
+
+ expect(match, `no shadow key in ${source}`).not.toBeNull();
+
+ return isStyleWrite(match.index, parseSource(source, file));
+ };
+
+ // The two constructs that put a value on a CSS property in JavaScript. This
+ // list is closed by the language, not by whoever last thought about it, which
+ // is what makes the rejecting half below affordable.
+ it.each([
+ ['an object literal property', "const s = { boxShadow: '0 0 8px red' };"],
+ ['a quoted object literal property', "const s = { 'box-shadow': '0 0 8px red' };"],
+ ['an inline style prop', "<div style={{ boxShadow: '0 0 8px red' }} />"],
+ ['a CSSOM member assignment', "el.style.boxShadow = '0 0 8px red';"],
+ ['a CSSOM bracket assignment', "el.style['box-shadow'] = '0 0 8px red';"],
+ ])('reads %s as a style write', (_label, source) => expect(at(source)).toBe(true));
+
+ // A colon is the most overloaded character in TypeScript, and `SHADOW_KEY`
+ // locates a key by the punctuation after it. These three spell a real CSS
+ // property followed by a colon and are byte-identical at the key, so the
+ // regex claimed all of them; the first two then found no shadow string and
+ // failed `validate:theme` as unreadable, for constructs that never reach a
+ // browser at all -- one is erased before the file runs, the other reads a
+ // value rather than writing one.
+ it.each([
+ ['a type member', 'interface Props { boxShadow: string }'],
+ ['a destructuring binding', 'const { boxShadow: current } = style;'],
+ ['a type annotation on a declaration', 'const boxShadow: string = compute();'],
+ // The fourth thing a colon makes, reached by the same match and rejected by
+ // the same rule -- listed because the accept side is closed by the language
+ // rather than by this list, so a construct nobody enumerated is already
+ // answered.
+ ['a labelled statement', "boxShadow: draw('0 0 8px red');"],
+ ])('leaves %s alone', (_label, source) => expect(at(source)).toBe(false));
+
+ // The rule, not the spellings above it: what makes a style write is the
+ // assignment, and `=` is a prefix of two operators that do not assign. The
+ // lookbehind in `STYLE_ASSIGNMENT` has already required the `.style` target,
+ // so this is the half it cannot see -- where the name appears versus what is
+ // being done with it, which is the question only the parser can answer.
+ it('claims an assignment through .style, not a comparison with one', () => {
+ expect(at('el.style.boxShadow = value;')).toBe(true);
+ expect(at("if (el.style.boxShadow === '0 0 8px red') return;")).toBe(false);
+ });
+
+ // CSS has no tree, so it gets no answer rather than a guess. Nothing in a
+ // stylesheet should reach here -- the key regex hands CSS to the declaration
+ // channel -- and this is the second lock on that door.
+ it('reads nothing without a tree', () => {
+ expect(isStyleWrite(0, null)).toBe(false);
+ });
+});
+
+describe('propertyExpression', () => {
+ // Composed the way the scan composes it -- key regex, blanked text, tree of
+ // the file as written -- rather than from a hand-counted offset. That is not
+ // tidiness: the offset used to be `indexOf(':') + 1`, which finds the
+ // TERNARY's colon in `boxShadow = on ? a : b` and finds nothing at all in an
+ // assignment, so the ASI case below ran from offset 0 and passed while
+ // asserting nothing about the question it was named for.
+ const after = (source, file = 'probe.ts') => {
+ const blanked = withoutNonRenderingText(source, file);
+ const key = new RegExp(SHADOW_KEY, 'g').exec(blanked);
+
+ expect(key, `no style write in ${source}`).not.toBeNull();
+
+ return propertyExpression(blanked, key.index + key[0].length, parseSource(source, file));
+ };
+
+ it('reads a value on the same line', () => {
+ expect(after("const s = { boxShadow: '0 0 8px red' };")).toContain('0 0 8px red');
+ });
+
+ // The finding. A formatter breaks the line once it is long enough, and the
+ // newline was read as the end of the expression -- so a site spelling the
+ // required token correctly was reported as one this scan cannot read.
+ it('reads a value that starts on the next line', () => {
+ expect(after("const s = {\n boxShadow:\n 'var(--shadow-glow-md-mint)',\n};")).toContain('--shadow-glow-md-mint');
+ });
+
+ it('still ends at the newline once the value has begun', () => {
+ // Without a semicolon the statement ends at the line break, and reading past
+ // it would sweep the next statement's value up as a second shadow layer.
+ expect(after("el.style.boxShadow = a\nel.style.color = 'red';")).not.toContain('red');
+ });
+
+ // The pair that has no punctuation answer, and the reason this asks the
+ // parser at all. Both values are an assignment with no semicolon and a line
+ // break after it; the first line break ends the statement and the second does
+ // not, because `?` cannot begin one. Any rule about characters gets one of
+ // these two wrong, and six rounds of this module's history are that rule being
+ // rewritten.
+ it('follows a value across the line breaks that do not end the statement', () => {
+ const source = "el.style.boxShadow = on\n ? 'var(--shadow-glow-md-mint)'\n : 'none'\nel.style.color = 'red';";
+ const expression = after(source);
+
+ expect(expression).toContain('--shadow-glow-md-mint');
+ expect(expression).toContain('none');
+ expect(expression).not.toContain('red');
+ });
+
+ it('reads both branches of a ternary written across lines', () => {
+ const source = "const s = {\n boxShadow: on\n ? 'var(--shadow-glow-md-mint)'\n : 'none',\n color: 'red',\n};";
+ const expression = after(source);
+
+ expect(expression).toContain('--shadow-glow-md-mint');
+ expect(expression).not.toContain('red');
+ });
+
+ it('ends at the next property rather than swallowing it', () => {
+ expect(after("const s = { boxShadow: 'none', color: 'red' };")).not.toContain('red');
+ });
+
+ it.each([
+ ['a call', "const s = { boxShadow: rgba(0, 0, 0, 0.5), color: 'red' };", 'rgba'],
+ ['an array', "const s = { boxShadow: [a, b].join(','), color: 'red' };", 'join'],
+ ['an object', "const s = { boxShadow: pick({ a: 1, b: 2 }), color: 'red' };", 'pick'],
+ ['a string holding a terminator', "const s = { boxShadow: '0 0 8px red, 0 0 4px', color: 'red' };", '0 0 4px'],
+ ])('reads through %s without stopping inside it', (_label, source, kept) => {
+ const expression = after(source);
+ expect(expression).toContain(kept);
+ expect(expression).not.toContain("color: 'red'");
+ });
+
+ // A value is allowed to carry a comment, so the span comes from the BLANKED
+ // text while its boundary comes from the tree of the file as written. Reading
+ // the comment back would hand the caller a colour that never renders -- the
+ // guard's own defect, one layer down.
+ it('skips a comment between the key and the value', () => {
+ const expression = after("const s = { boxShadow: /* red */ 'none' };");
+
+ expect(expression).toContain('none');
+ expect(expression).not.toContain('red');
+ });
+
+ // The tree is what answers the question, so a language that has none gets no
+ // answer rather than a guess. Nothing in a stylesheet should reach here at all
+ // -- the key regex hands CSS to the declaration channel -- and this is the
+ // second lock on that door, because the round where it opened turned four
+ // correct declarations into CI failures.
+ it('reads nothing without a tree', () => {
+ const css = '.a { box-shadow: 0 0 8px red; }';
+
+ expect(propertyExpression(css, css.indexOf(':') + 1, null)).toBeNull();
+ });
+});
+
+describe('valueArgument', () => {
+ const after = (source) => valueArgument(source, source.indexOf(',') + 1);
+
+ it('reads the value argument', () => {
+ expect(after("setProperty('box-shadow', '0 0 8px red')")).toContain('0 0 8px red');
+ });
+
+ // `setProperty` takes a third argument. Reading every literal after the
+ // property name accepted `none` and then failed the tree on `important`.
+ it('stops before the priority argument', () => {
+ expect(after("setProperty('box-shadow', 'none', 'important')")).not.toContain('important');
+ });
+
+ // A newline is not a terminator here, so a call argument written across lines
+ // is read whole.
+ it('reads an argument written across lines', () => {
+ expect(after("setProperty('box-shadow',\n 'var(--shadow-glow-md-mint)')")).toContain('--shadow-glow-md-mint');
+ });
+});
diff --git a/ui/scripts/stylesheets.mjs b/ui/scripts/stylesheets.mjs
new file mode 100644
index 000000000..8a7bf8c97
--- /dev/null
+++ b/ui/scripts/stylesheets.mjs
@@ -0,0 +1,80 @@
+// Every stretch of stylesheet text the project ships, parsed once each.
+//
+// Extracted for the reason `customProperties.mjs` and `cssDeclarations.mjs`
+// were: `validate-theme.mjs` runs its whole validation at import time, so
+// nothing inside it can be called from a test. This one had a second caller
+// waiting -- `glowScale.test.mjs` was deriving the sanctioned token set from
+// `src/index.css` alone while the validator sanctioned `@theme` declarations
+// from every stylesheet, so a component stylesheet could declare
+// `--shadow-glow-rogue-mint: 0 0 93px red`, have the validator trust it as
+// managed, and have every rule in the scale test skip it. Two answers to "which
+// stylesheets are there" is the shape that produced that gap, so there is one.
+//
+// `.css` was the wrong unit for it. That is a FILE EXTENSION, and the question
+// being asked is the same one the scan asks about its call sites -- where in
+// this project is text CSS -- which `cssRangesIn` answers and no extension can.
+// A `<style>` body and a string handed to `insertRule` are stylesheets that
+// ship, so a token declared in one was invisible while a call site reading that
+// token was scanned; the name resolved to nothing and the gate reported correct
+// CSS as unanchored. That is a false positive, which fails somebody else's pull
+// request over code that is right.
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+import postcss from 'postcss';
+
+import { intendedFiles } from './lintPolicy.mjs';
+import { cssRangesIn, rendersAtAll } from './nonRenderingText.mjs';
+
+/**
+ * Yield ``[origin, root]`` for every stylesheet under ``root``.
+ *
+ * ``origin`` is a human-readable place to report, and ``root`` a parsed postcss
+ * tree. One walk feeds every fold that wants the token layer, where it used to
+ * be a read and a parse of every stylesheet per question about the same tree.
+ */
+function* eachStylesheet(root) {
+ for (const relative of intendedFiles(root, { extensions: ['.ts', '.tsx', '.css'] })) {
+ // A fixture stylesheet is not the token layer, by the same argument that
+ // keeps a test file out of the scan: it documents values rather than
+ // shipping them.
+ if (!rendersAtAll(relative)) continue;
+
+ const file = path.join(root, relative);
+ const source = fs.readFileSync(file, 'utf8');
+
+ // `origin` names the stretch, not just the file, because a `.tsx` file can
+ // hold several and a line number inside one of them counts from its own
+ // start. For the two `.css` files this project actually has, that is the
+ // path and nothing more.
+ const ranges = cssRangesIn(source, file);
+ for (const [start, end] of ranges) {
+ const text = source.slice(start, end);
+ const origin = ranges.length > 1 ? `${relative} (offset ${start})` : relative;
+
+ // A `.css` file is parsed unguarded on purpose, and `nonRenderingText.mjs`
+ // depends on that: text a stylesheet cannot parse is a broken stylesheet,
+ // and the gate should say so out loud. A stretch lifted out of TypeScript
+ // carries no such promise -- a template can interpolate a whole rule, and
+ // `` `${rules} .a {}` `` is CSS only after the substitution runs -- so one
+ // that will not parse is a stretch this fold cannot read, not a file that
+ // is wrong, and failing the build over it would be the same false positive
+ // one layer along. What it cannot read it also cannot scan, so the miss is
+ // symmetric; `src` has no such stretch today.
+ if (file.endsWith('.css')) {
+ yield [origin, postcss.parse(text)];
+ continue;
+ }
+ let sheet;
+ try {
+ sheet = postcss.parse(text);
+ } catch {
+ continue;
+ }
+ yield [origin, sheet];
+ }
+ }
+}
+
+export { eachStylesheet };
diff --git a/ui/scripts/validate-theme.mjs b/ui/scripts/validate-theme.mjs
index 43f85aba5..f57db99da 100644
--- a/ui/scripts/validate-theme.mjs
+++ b/ui/scripts/validate-theme.mjs
@@ -1,7 +1,27 @@
import fs from 'node:fs';
+import path from 'node:path';
import vm from 'node:vm';
import postcss from 'postcss';
+import {
+ COLOUR,
+ glowOffencesInValue,
+ readsIntoDropShadow,
+ spreadOffencesInDropShadow,
+} from './shadowLayer.mjs';
+import { SHADOW_KEY, isStyleWrite, propertyExpression, valueArgument } from './styleWrite.mjs';
+import { intendedFiles } from './lintPolicy.mjs';
+import { colourRegistrationsIn, customPropertiesIn } from './customProperties.mjs';
+import { declarationSpansIn, declaresAt } from './cssDeclarations.mjs';
+import {
+ cssBearingRangesIn,
+ cssRangesIn,
+ parseSource,
+ rendersAtAll,
+ withoutNonRenderingText,
+} from './nonRenderingText.mjs';
+import { eachStylesheet } from './stylesheets.mjs';
+
const html = fs.readFileSync('index.html', 'utf8');
const css = fs.readFileSync('src/index.css', 'utf8');
// The Model Hub carries its own theme-token layer (design.pen's dark frame plus
@@ -475,6 +495,691 @@ function assertAccentAliasesKeepTheirTokenName(source) {
}
assertAccentAliasesKeepTheirTokenName(css);
+
+// What a glow is, and why a literal one cannot be allowed, is stated in
+// `shadowLayer.mjs` -- along with the classifier that answers it. That rule is
+// the one this file exists to enforce; what stays here is everything about
+// WHERE a value can come from, which is the other half of the gate.
+
+// A glow layer has exactly one legal spelling: a reference to a --shadow-glow-*
+// token, as the whole layer. Not "a managed colour with any geometry" -- that
+// was this test's third hole in as many rounds, and the three share one shape.
+// Each time the predicate checked something narrower than the error message
+// claimed: first the colour, by listing two literal spellings out of the many
+// CSS accepts; then the input, by reading one of the four channels a shadow
+// value arrives through; then the geometry, by passing `0 0 93px var(--mint)`
+// because every part was individually well-formed while the shape it draws was
+// invented on the spot. Checking the parts one axis at a time is what keeps
+// leaving an axis uncovered, so they are not checked one axis at a time any
+// more. A glow names a token; a layer that spells out any of its own offsets,
+// blur, spread or colour is an offender however each piece is written. That
+// leaves no fourth axis to hide behind and makes the predicate say precisely
+// what the message below says.
+//
+// Lengths are still recognised, but only to tell a hand-written glow apart from
+// a token reference so it can be rejected -- never to bless one part of it. The
+// grammar itself lives in cssLength.mjs, with its own tests: it is a rule about
+// CSS rather than about this scan, and the enumeration it replaces was the
+// fourth time this file checked something narrower than its message claimed.
+
+// Every channel a shadow value reaches the page through. The first cut of this
+// scan read only `shadow-[...]`, which repeated one level up the mistake the
+// colour test above was written to stop: it enumerated its own input, so a
+// `[box-shadow:...]` written the next day would have walked straight past the
+// assertion meant to catch it. The fix then claimed this list "can genuinely be
+// closed -- a shadow is a Tailwind arbitrary value, a Tailwind arbitrary
+// property, a CSS declaration or an inline style object, and the stack offers no
+// fifth way to write one", and pointed at SHADOW_MENTION as the measurement that
+// kept the claim honest.
+//
+// `filter: drop-shadow(0 0 4px …)` was the fifth way, and it did not merely slip
+// the channels -- it slipped the measurement too, silently, because the mention
+// regex was written by listing the same spellings the channels already read. A
+// completeness check assembled from the list it is policing cannot discover that
+// the list is short; it can only confirm the entries it was handed. That is why
+// three hand-drawn wire glows sat in modelHubSurface.css through five rounds of
+// this guard reporting all-clear.
+//
+// So the claim is retired rather than re-made: this list is NOT closed by
+// argument, and no amount of thinking about the stack will close it. It is held
+// closed from the outside by SHADOW_MENTION, which now derives from the word
+// itself instead of from these entries, so the next spelling nobody here has
+// imagined arrives as a loud failure the day it lands.
+
+// The one shape where the property is NAMED rather than written: CSSOM's
+// `setProperty(name, value)` passes `box-shadow` as a string argument, so the
+// word is followed by the quote that closes it and then a comma -- never by the
+// `:`, `=` or opening delimiter that every other spelling puts there. Both the
+// channel and SHADOW_MENTION key off that introducing punctuation, so this went
+// unread AND uncounted: the exact double silence they exist to prevent.
+//
+// The narrow anchor on `.setProperty(` is deliberate and is not the enumeration
+// that cost the earlier rounds. Those were open sets -- property names, quote
+// styles, delimiters -- where the next member was always someone's next idea.
+// This one is closed by the DOM: `setProperty` is the only by-name setter on
+// CSSStyleDeclaration, and `style.boxShadow =` / `style['boxShadow'] =` are
+// assignments the channel above already reads. Widening it to "any quoted
+// property name followed by a comma" was tried and is wrong in the other
+// direction: `cn('shadow-mint-card', …)` is a class list, not an assignment,
+// and three of those already ship.
+//
+// `\x60` is a backtick -- a template-literal property name is exotic, but
+// "exotic" is the argument that lost the last six rounds.
+// The `(?!--)` is the same judgement `SHADOW_MENTION` already made on the CSS
+// side, brought to the branch that had not heard it: `--shadow-color` is a
+// custom property, not a shadow property, and `setProperty('--shadow-color',
+// '#fff')` therefore draws nothing. Reading its value as a whole box-shadow
+// failed `validate:theme` on a colour -- a false positive, in CI, on a file that
+// was correct.
+//
+// Excluding the NAME was the wrong repair, and the argument for it was wrong in
+// a way worth keeping written down: "a custom property is inert, it renders only
+// where some declaration spends it, and that declaration IS scanned" holds for
+// the value a stylesheet declares and not for the one assigned at runtime.
+// `--x: none` with `box-shadow: var(--x)` is scanned, innocent, and complete --
+// and then `setProperty('--x', '0 0 93px red')` supplies the glow from outside
+// the stylesheet, past a scan that already read every declaration and found
+// nothing. The static half is not where the value comes from.
+//
+// So the name is read again and the exemption moves to the VALUE, which is where
+// the original false positive actually lived: `setProperty('--shadow-color',
+// '#fff')` is innocent because a colour carries no geometry, not because a
+// custom property cannot draw. That is the same judgement `shadow-(color:--x)`
+// already makes one channel up, made with the same COLOUR recogniser, so it adds
+// no new notion of what a glow is -- which was the real objection to matching on
+// "values that look like glow geometry", and it is not what this does: anything
+// that is not provably a colour stays readable and gets classified.
+const CSSOM_SETTER = /\.setProperty\(\s*(?<quote>['"\x60])(?<property>[^'"\x60]*shadow[^'"\x60]*)\k<quote>\s*,/;
+
+// What counts as a shadow PROPERTY, written once. `box-shadow`, `text-shadow`
+// and `drop-shadow` all end in the word; `shadowPreset` and `shadowRoot` only
+// start with it and are not properties at all, and a `--*` declaration is a
+// custom property rather than a shadow one.
+//
+// This used to be spelled twice: the CSS declaration channel read `box-shadow`
+// and only it, while the completeness matcher read any `*shadow`. The comment on
+// SHADOW_MENTION already said "the two must narrow together" -- but saying so is
+// not a mechanism, and they diverged anyway, in the direction that fails correct
+// files: `text-shadow: var(--shadow-glow-md-mint)` was counted as a mention, read
+// by no channel, and reported as an unscanned channel, so a fully tokenized
+// declaration blocked validate:theme. Sharing the source is that discipline in
+// the form that cannot be forgotten, which is what CSSOM_SETTER is already doing
+// one definition down.
+const SHADOW_PROPERTY = `(?<![\\w-])(?!--)[A-Za-z-]*shadow(?![A-Za-z])`;
+
+// Sharing the pattern closed the divergence by NAME and left it open by FLAG:
+// the CSS channels ran case-sensitively while SHADOW_MENTION ran `gi`, so
+// `BOX-SHADOW: var(--shadow-glow-sm-mint)` -- a valid declaration, CSS property
+// names being ASCII case-insensitive -- was measured as a mention, read by no
+// channel, and reported as an unscanned channel. The same failure as the
+// `text-shadow` one, arriving through the argument that was not shared.
+//
+// Case-insensitivity alone is not safe here, and the reason is worth keeping:
+// this scan runs one set of channels over three languages, so `i` also lets the
+// CSS channels match `boxShadow:` in a `.tsx` file -- where the value is a JS
+// expression, and reading it with CSS's terminators stops at the first quote.
+// `boxShadow: active ? `…` : undefined` then yields `active ?` and the guard
+// fails the tree it is guarding. That is not hypothetical; it is what this
+// change did on its first draft.
+//
+// The hyphen is what separates the two languages. Every CSS shadow property has
+// one -- `box-shadow`, `text-shadow`, `-webkit-box-shadow` -- and no JS style
+// key does, because camelCase is the whole point of the JS spelling. Requiring
+// it here is what makes `i` safe, and it removes an overlap that was previously
+// avoided only by the accident of `boxShadow`'s capital S. Written as a
+// lookahead over the shared definition, so the rule about where the word sits
+// still has exactly one home.
+const CSS_SHADOW_PROPERTY = `(?=[A-Za-z-]*-shadow)${SHADOW_PROPERTY}`;
+const PROPERTY_FLAGS = 'gi';
+
+const cssomArgument = (match) => valueArgument(match.input, match.index + match[0].length) ?? '';
+
+// The expression a style property is given, read from where the match ends. An
+// empty string when it never terminates, which yields no values and excuses
+// nothing, so the site is reported as unreadable rather than passed over.
+const styleExpression = (match, tree) =>
+ propertyExpression(match.input, match.index + match[0].length, tree) ?? '';
+
+// A custom property assigned a bare colour contributes no shadow value: it tints
+// geometry that some scanned declaration still has to supply. Both halves of the
+// channel below ask through this one function, because "what this match yields"
+// and "why yielding nothing is innocent rather than unreadable" are the same
+// judgement, and the two spellings of it are exactly what drifts apart.
+//
+// Only `--*` earns it. `setProperty('box-shadow', '#fff')` names the shadow
+// property itself, and a colour there is a value to read, not one to excuse.
+const isTint = (match) => {
+ if (!match.groups?.property?.startsWith('--')) return false;
+ const values = stringLiterals(cssomArgument(match));
+ return values.length > 0 && values.every((value) => COLOUR.test(value.trim()));
+};
+
+const SHADOW_CHANNELS = [
+ // `shadow-[0_0_16px_-4px_var(--x)]`, including variants such as `hover:shadow-[…]`.
+ { pattern: /shadow-\[([^\]]*)\]/g, valuesOf: (match) => [match[1]] },
+ // `[box-shadow:0_0_16px_-4px_var(--x)]` -- Tailwind's arbitrary *property*.
+ {
+ pattern: new RegExp(`\\[${CSS_SHADOW_PROPERTY}\\s*:([^\\]]*)\\]`, PROPERTY_FLAGS),
+ valuesOf: (match) => [match[1]],
+ },
+ // `shadow-(--x)` and `drop-shadow-(--x)` -- Tailwind's custom-property
+ // shorthand, which compiles to `box-shadow: var(--x)` and to the same inside
+ // `drop-shadow()`. Parentheses instead of brackets is the whole difference
+ // from the arbitrary-value form above, and it is enough to park a glow in:
+ // `--rogue-glow: 0 0 93px red` rendered through `shadow-(--rogue-glow)` was
+ // read by no channel. The name is handed on as a `var()` so it resolves
+ // through exactly the same indirection as every other reference -- this
+ // channel translates a spelling, it does not get its own idea of what a glow
+ // is.
+ {
+ pattern: /(?<![\w-])(?:drop-)?shadow-\(([^)]*)\)/g,
+ valuesOf: (match) => [CUSTOM_PROPERTY.test(match[1].trim()) ? `var(${match[1].trim()})` : ''],
+ // `shadow-(color:--x)` sets the shadow COLOUR and carries no geometry, so it
+ // cannot draw a glow by itself; the geometry it tints still has to come from
+ // a utility this scan reads. Anything else inside the parentheses is a form
+ // this scan cannot follow, and stays unreadable rather than accepted.
+ provablyNotAShadow: (match) => match[1].trim().startsWith('color:'),
+ },
+ // `box-shadow: 0 0 16px -4px var(--x);` in a stylesheet. The lookbehind hands
+ // the arbitrary-property spelling to the channel above rather than matching it
+ // twice, once with a stray `]` glued to the colour. A declaration also ends at
+ // a quote, because this same spelling appears inside assertion strings in the
+ // `.ts` files scanned alongside the CSS -- and a shadow value of its own never
+ // contains one, so the quotes cost nothing to stop at and stop the closing one
+ // from being read as part of the colour.
+ //
+ // A property name followed by a colon is the SPELLING of a declaration, and
+ // this channel used to treat it as one wherever it appeared. Two things are
+ // spelled that way and declare nothing: a pseudo-class on a class named after
+ // a property -- `.box-shadow:hover { color: red }`, whose `hover { color: red`
+ // went to the shadow classifier and failed valid CSS -- and any sentence in a
+ // `.ts` file, where `const example = 'box-shadow: 0 0 93px red'` is text about
+ // CSS rather than CSS. Both are answered by asking where the match IS instead
+ // of what it looks like, and both parsers already know: `cssDeclarations.mjs`
+ // says which offsets a stylesheet declares at, `nonRenderingText.mjs` says
+ // which stretches of a TypeScript file are a stylesheet at all.
+ //
+ // The match is still claimed, and refused with a reason rather than dropped.
+ // Claiming keeps the completeness check honest -- the mention matcher counts
+ // this spelling, so a channel that stopped matching it would turn a false
+ // positive into a different failure with a stranger message -- and refusing it
+ // through `provablyNotAShadow` says what is actually true: not that the value
+ // is innocent, but that there is no declaration here to have a value.
+ {
+ pattern: new RegExp(`(?<!\\[)${CSS_SHADOW_PROPERTY}\\s*:([^;}'"\`]*)`, PROPERTY_FLAGS),
+ valuesOf: (match, tree, where) => (where.declares(match.index) ? [match[1]] : []),
+ provablyNotAShadow: (match, tree, where) => !where.declares(match.index),
+ },
+ // `filter: drop-shadow(0 0 4px …)`. Matched at the FUNCTION rather than at the
+ // property, because the property is not the thing there is only one of: a drop
+ // shadow can arrive through `filter`, `-webkit-filter`, `backdrop-filter`, a
+ // Tailwind arbitrary property or an inline style object, and reading it at
+ // `drop-shadow(` covers all of them at once instead of collecting five more
+ // entries here that would then need a sixth. The argument list is taken by
+ // balancing parentheses because a shadow colour is routinely a `color-mix(…)`
+ // and a `[^)]*` would stop inside it.
+ //
+ // Covering five spellings at once is only sound while the match is somewhere
+ // CSS renders, and this channel used to ask nothing: `log('filter:
+ // drop-shadow(0 0 93px red)')` is a diagnostic string that no browser reads,
+ // and the gate failed the file for containing it. That is the same defect the
+ // declaration channel above carried, one language and one round apart -- but
+ // it does NOT take the same oracle, because the three places a drop shadow
+ // ships from are a rule, a utility class and a style value, and only the first
+ // is a stylesheet. `cssBearingRangesIn` is the wider question, and asking the
+ // narrower one here would have swapped a false positive for two misses.
+ {
+ pattern: /drop-shadow\(/gi,
+ valuesOf: (match, tree, where) => (where.bears(match.index)
+ ? [balancedArgument(match.input, match.index + match[0].length - 1)]
+ : []),
+ provablyNotAShadow: (match, tree, where) => !where.bears(match.index),
+ },
+ // `style={{ boxShadow: … }}` and `el.style.boxShadow = …`. What follows is an
+ // expression rather than a value, so read the string literals out of it: a
+ // ternary's two branches are two shadows and both of them render. Any
+ // camelCase identifier carrying `shadow` is read, not `boxShadow` alone --
+ // `textShadow` and `dropShadow` are the same channel, and enumerating them one
+ // by one is how this list fell short the first time. The hyphen in the
+ // lookbehind keeps CSS's `box-shadow` with the declaration channel above.
+ {
+ // The optional quote and bracket carry the same three spellings
+ // SHADOW_MENTION accepts -- `boxShadow:`, `'boxShadow':`, `['boxShadow'] =`
+ // -- so the channel reads exactly what the measurement counts. Widening one
+ // without the other is how a spelling becomes scanned-but-unreported or
+ // reported-but-unscannable, and both of those are silence.
+ //
+ // The identifier ENDS at the word -- and, for an assignment, the target is
+ // `element.style`. Both halves are the same finding arriving twice:
+ // `[Ss]hadow[A-Za-z]*` matched any name merely containing the word, so
+ // `const shadowPreset = 'compact'` was read as a style property; ending at
+ // the word fixed that spelling and left `const cardShadow = 'compact'`
+ // reading as one, because a name cannot answer the question. STYLE_ASSIGNMENT
+ // answers it where the answer lives, at the assignment target, and is shared
+ // with SHADOW_MENTION so the two cannot drift apart.
+ pattern: new RegExp(SHADOW_KEY, 'g'),
+ valuesOf: (match, tree) => (isStyleWrite(match.index, tree)
+ ? stringLiterals(styleExpression(match, tree))
+ : []),
+ // Two ways to be provably not a shadow, and they answer different questions.
+ //
+ // `isStyleWrite` asks whether this is a style write AT ALL. The pattern
+ // finds a key by the punctuation after it, and a colon in TypeScript also
+ // makes a type member and a destructuring binding -- `interface Props {
+ // boxShadow: string }` and `const { boxShadow: current } = style` were both
+ // claimed as rendered assignments and then failed as unreadable, for two
+ // constructs that never reach a browser.
+ //
+ // NON_STRING_LITERAL asks, of a real style write, whether its value can be
+ // a CSS shadow: a CSS shadow is a string, so `scrollbar: { useShadows:
+ // false }` is a Monaco flag. That one is deliberately narrower than "no
+ // string literal here" -- `boxShadow: glow` is an identifier that could hold
+ // anything, and stays unreadable rather than becoming innocent.
+ provablyNotAShadow: (match, tree) => !isStyleWrite(match.index, tree)
+ || NON_STRING_LITERAL.test(styleExpression(match, tree)),
+ },
+ // `el.style.setProperty('box-shadow', '0 0 93px red')`. Read through the
+ // shared CSSOM_SETTER source rather than a pattern of its own, because the
+ // measurement below has to recognise the identical span: these two have been
+ // widened in lockstep by hand for three rounds, and a shared source is the
+ // version of that discipline which cannot be forgotten.
+ {
+ pattern: new RegExp(CSSOM_SETTER.source, 'gi'),
+ valuesOf: (match) => (isTint(match) ? [] : stringLiterals(cssomArgument(match))),
+ provablyNotAShadow: (match) => isTint(match) || NON_STRING_LITERAL.test(cssomArgument(match)),
+ },
+];
+
+// The string literals in an expression: a ternary's two branches are two
+// shadows and both of them render.
+function stringLiterals(expression) {
+ if (expression === null) return [];
+ return [...expression.matchAll(/'([^']*)'|"([^"]*)"|`([^`]*)`/g)]
+ .map(([, single, double, template]) => single ?? double ?? template);
+}
+
+
+// The parenthesis-balanced span starting at `openIndex`, or null when it never
+// closes -- null is not a quiet skip, it lands in the unreadable bucket.
+function balancedArgument(source, openIndex) {
+ let depth = 0;
+ for (let index = openIndex; index < source.length; index += 1) {
+ if (source[index] === '(') depth += 1;
+ else if (source[index] === ')' && (depth -= 1) === 0) return source.slice(openIndex + 1, index);
+ }
+ return null;
+}
+
+// The whole expression is one non-string literal. Anchored on where the literal
+// ENDS rather than on the punctuation trailing it: written as "the rest of the
+// capture is closing syntax" it turned on how the surrounding JSX happened to be
+// spelled, and it has to close the value instead, so that `false || glow` -- a
+// literal followed by something that could hold anything -- stays unreadable.
+const CUSTOM_PROPERTY = /^--[A-Za-z0-9_-]+$/;
+const NON_STRING_LITERAL =/^\s*(true|false|null|undefined|[+-]?\d+(\.\d+)?)\s*($|[,;}\])])/;
+
+// A glow is a *value*, and there are only so many ways to introduce one: a `:`
+// in a declaration or an object literal, an `=` in an assignment, a `(` opening
+// a filter function, and Tailwind's `shadow-[`. Naming the property without
+// carrying a value cannot hide a glow -- `transition-[background-color,
+// box-shadow]`, `will-change: box-shadow`, a sentence in a comment -- so those
+// are not mentions. What the measurement pins is exactly what failed before:
+// every place a shadow value is INTRODUCED is also a place it is READ.
+//
+// The name is matched as ANY identifier containing the word, not as the three
+// spellings the channels happen to read. That difference is the entire value of
+// this line. Written the old way it listed `shadow-[`, `box-shadow:` and
+// `boxShadow`, which is to say it asked the channels what to look for and then
+// confirmed they were looking for it -- so `filter: drop-shadow(…)` was not
+// reported as an unscanned spelling, it was not reported at all, and the guard
+// that exists to make a missing channel loud stayed silent about the one channel
+// it was missing. Derived from the word instead, the check can fail in the
+// direction that matters: it does not need to know what a shadow may be called
+// tomorrow to notice that something called one went unread.
+//
+// Custom-property DECLARATIONS are excluded, and only they. `--x-shadow: 0 0 …`
+// is the token layer -- the one sanctioned home for a shadow literal -- and it
+// is not skipped so much as reached from the other end: call sites resolve their
+// names into it, so a glow parked in a token is caught when something uses it,
+// and a token nothing uses draws no light on any page.
+//
+// The punctuation between the name and its `:`/`=` is optional because JS lets
+// a property be spelled three ways that mean one thing: `boxShadow:`,
+// `'boxShadow':` and `['boxShadow'] =`. Requiring the colon to touch the name
+// read the quote as the end of the mention, so `el.style['boxShadow'] = '0 0
+// 93px red'` was not scanned AND not reported -- the exact silent gap this line
+// exists to close, reopened by the punctuation rather than by the word.
+//
+// What follows the word is an OPENING DELIMITER or an ASSIGNMENT, which is the
+// grammar of "this name is about to be given a value" -- not a list of the three
+// spellings that grammar happened to take. Written as a list it read `(`, `-[`
+// and `:`/`=`, and Tailwind's `shadow-(--x)` shorthand fell between them: the
+// `-(` is neither of the first two, so a glow parked in `--rogue-glow` and used
+// as `shadow-(--rogue-glow)` was, once again, not scanned and not reported. The
+// enumeration had moved out of the word and into the punctuation after it.
+//
+// The second branch is CSSOM_SETTER's own source, not a copy of it. The first
+// branch says "the word, then punctuation that hands it a value", which is the
+// grammar of every spelling written as syntax; `setProperty('box-shadow', …)`
+// names the property instead of writing it, so it has no such punctuation and
+// no restatement of the first branch can reach it. Sharing the source is what
+// keeps the channel and this measurement describing one span: widen one alone
+// and a spelling becomes either scanned-but-uncounted or counted-but-unscannable,
+// and both of those are silence.
+//
+// A colon means two different things in the two languages this scan reads, and
+// measuring both with one rule is what made `{ cardShadow: 'compact' }` a
+// finding. In CSS a colon makes a DECLARATION, so the property before it is
+// whatever the spec says it is -- the word rule has to stay open there, or the
+// next shadow property CSS grows goes uncounted. In JavaScript a colon makes an
+// OBJECT KEY, and an object key only paints when it names a real CSS property:
+// `cardShadow` is a variable, `style.cardShadow = x` draws nothing, and there is
+// no future spelling of it that will. So the CSS half keeps the open word rule
+// and the JS half takes the closed list, which is what SHADOW_KEY already is.
+//
+// The JS half is not merely read from the same list as the channel, it IS the
+// channel's pattern. That is the one narrowing the error message below warns
+// against making by hand -- "do NOT narrow SHADOW_MENTION to make this pass" --
+// and sharing the pattern is what makes it safe rather than forbidden: a mention
+// counted here and claimed by no channel is a loud failure, a mention claimed by
+// a channel and not counted here is a silent one, and the two cannot land on
+// opposite sides of that line while they are the same string. Three rounds of
+// widening these in lockstep by hand ended in a drift anyway; a copy that has to
+// be edited twice is a copy that will be edited once.
+// Two patterns rather than one, because case sensitivity is a property of the
+// LANGUAGE and not of this matcher. CSS folds the case of a property name --
+// `BOX-SHADOW: red` renders -- so the CSS half must be case-insensitive or it
+// misses. JavaScript does not fold anything: `boxShadow` and `BOXSHADOW` are two
+// different keys, and only one of them is a CSS property.
+//
+// One `i` flag over both halves therefore claimed to measure what the channel
+// checks and did not, in the one direction that costs a pull request. The JS
+// channel matches case-sensitively, as it must; the mention matcher counted
+// `const o = { BOXSHADOW: 'compact' }` and `el.style.boxshadow = x` all the same
+// -- names that address no CSS property and draw nothing -- and reported them as
+// spellings no channel reads. It also hid the finding underneath: the real
+// CSSOM spelling `webkitBoxShadow` was missing from the property list, and the
+// `i` flag had been papering over its absence by matching the capitalised alias
+// case-blind.
+//
+// So the JS half is the channel's own pattern, flags included, which is what
+// makes the promise above -- that a mention and a channel cannot land on
+// opposite sides of the line -- true rather than nearly true.
+const SHADOW_MENTIONS = [
+ new RegExp(
+ `${CSS_SHADOW_PROPERTY}\\s*:`
+ + `|${SHADOW_PROPERTY}-?[([]`
+ + `|${CSSOM_SETTER.source}`,
+ 'gi',
+ ),
+ new RegExp(SHADOW_KEY, 'g'),
+];
+
+// The token layer, in three answers that want one walk.
+//
+// `values`: every custom property declared anywhere, name to the set of values
+// it is given. A name is collected once per distinct value rather than
+// last-write-wins, because a property is routinely declared several times --
+// dark, `prefers-color-scheme: light`, `[data-theme="light"]` -- and a glow
+// smuggled into just one of those blocks is still a glow that ships. What counts
+// as a declaration of a name lives in `customProperties.mjs`, where it can be
+// called from a test; this is only the fold.
+//
+// `colours`: the names a registration constrains to colours, which is the one
+// thing that can prove a `var()` in a shadow's third slot holds no radius.
+// Answered in `customProperties.mjs` for the same reason -- what a registration
+// promises is a question about CSS grammar, and a question about grammar wants
+// cases.
+//
+// `managed`: the VALUES declared inside an `@theme` block -- the token layer
+// itself, as opposed to everything that merely looks like it. Separate from
+// `values` because the two ask different questions: that one asks what a name is
+// worth anywhere, this one asks which of those worths were sanctioned.
+//
+// Values rather than names, because a name is not a place either. Recording
+// membership as a name made the sanction transferable: `--shadow-glow-wire-cyan`
+// is declared in `@theme`, so the name is managed forever, and a component
+// stylesheet redeclaring it as `0 0 93px red` inherited that trust -- the
+// override was collected, marked managed and discarded unread, while the
+// cascade handed the call site the override at runtime. Asking which
+// declarations are sanctioned rather than which names appear closes it, because
+// an out-of-theme declaration is then a value the set does not contain and falls
+// through to ordinary classification.
+function collectTokenLayer(root) {
+ const values = new Map();
+ const colours = new Set();
+ const managed = new Map();
+
+ for (const [, sheet] of eachStylesheet(root)) {
+ customPropertiesIn(sheet, values);
+ colourRegistrationsIn(sheet, colours);
+ sheet.walkAtRules('theme', (rule) => {
+ rule.walkDecls((decl) => {
+ if (!decl.prop.startsWith('--')) return;
+ if (!managed.has(decl.prop)) managed.set(decl.prop, new Set());
+ managed.get(decl.prop).add(decl.value);
+ });
+ });
+ }
+
+ return { values, managed, colours };
+}
+
+
+// Token definitions (`--shadow-glow-cta-mint: …`) name none of the channel
+// spellings and so are never scanned as call sites, which is the point: the
+// token layer is the one place a literal is allowed to live, because it is the
+// one place light can re-anchor it. What this walks is call sites -- but it now
+// follows their names into that layer, so defining a glow under some other name
+// is not a way around it.
+function assertGlowsReadThroughTokens(root) {
+ const offenders = [];
+ const unscanned = [];
+ const unreadable = [];
+ const tokens = collectTokenLayer(root);
+
+ for (const relative of intendedFiles(root, { extensions: ['.ts', '.tsx', '.css'] })) {
+ // A test is not a page. Its strings document values rather than drawing
+ // them, and Vite never bundles the file, so scanning it turns this gate into
+ // one that fails a test for containing the string it is testing.
+ if (!rendersAtAll(relative)) continue;
+
+ const file = path.join(root, relative);
+ const raw = fs.readFileSync(file, 'utf8');
+ const source = withoutNonRenderingText(raw, file);
+
+ // The tree of the file AS WRITTEN, which the JS channels need to say where a
+ // value ends. `withoutNonRenderingText` has already parsed exactly this text,
+ // so the memo makes it the same tree rather than a second parse. CSS has no
+ // tree here and no channel that asks for one.
+ const tree = file.endsWith('.css') ? null : parseSource(raw, file);
+
+ // And where the file DECLARES, for the one channel whose spelling a selector
+ // and a sentence can both wear. Two parsers answer it between them: which
+ // stretches of this file are CSS at all, then which offsets inside those
+ // stretches CSS declares at, folded back into the coordinates of the file
+ // they came from.
+ //
+ // The file AS WRITTEN, like the tree above and for a sharper reason. Blanking
+ // preserves offsets but not grammar -- a blanked `@media (…)` is an `@`
+ // followed by spaces, which is not a stylesheet any parser will read -- so
+ // asking the blanked text would fail every parse and, deny-by-default, call
+ // the whole file a declaration. Nothing is lost by asking the real text:
+ // blanking has already been applied to the matches themselves, so a span that
+ // does not render produces no match to ask about.
+ //
+ // Two questions, not one, because CSS reaches a browser two ways. `declares`
+ // asks whether an offset is a declaration in a stylesheet -- the question a
+ // property name followed by a colon poses. `bears` asks the weaker thing:
+ // whether the text there reaches a renderer as CSS at all, which is also
+ // true of a utility class and of a style value, neither of which any
+ // stylesheet contains. They are handed over as one `where` so the next
+ // question about position joins them instead of lengthening this call.
+ const declarations = cssRangesIn(raw, file).reduce(
+ (spans, [start, end]) => declarationSpansIn(raw.slice(start, end), start, spans),
+ [],
+ );
+ const bearing = cssBearingRangesIn(raw, file);
+ const where = {
+ declares: (index) => declaresAt(declarations, index),
+ bears: (index) => declaresAt(bearing, index),
+ };
+ const claimed = [];
+
+ for (const { pattern, valuesOf, provablyNotAShadow } of SHADOW_CHANNELS) {
+ for (const match of source.matchAll(pattern)) {
+ claimed.push([match.index, match.index + match[0].length]);
+
+ // Matching a mention silences the completeness check below, so a channel
+ // that matches and then yields nothing is the one way left to be scanned
+ // and unchecked at the same time. `style={{ boxShadow: glow }}` is that
+ // case: the expression holds no string literal, so there is no value to
+ // test, and moving a literal into a constant would slip the gate. A
+ // channel that claims a mention owes a value, and owing nothing fails.
+ const values = valuesOf(match, tree, where).filter((value) => value && value.trim());
+ if (values.length === 0) {
+ if (provablyNotAShadow?.(match, tree, where)) continue;
+ unreadable.push(`${file}:${source.slice(0, match.index).split('\n').length}: ${
+ match[0].split('\n')[0].slice(0, 80)}`);
+ continue;
+ }
+
+ // `drop-shadow()` takes no spread, and a layer carrying one is dropped
+ // whole rather than drawn wrong, so the call site adds a constraint the
+ // token layer cannot know about.
+ const dropShadow = readsIntoDropShadow(source, match.index, match[0]);
+
+ for (const value of values) {
+ for (const offence of glowOffencesInValue(value, tokens)) {
+ offenders.push(`${file}: ${offence}`);
+ }
+ if (!dropShadow) continue;
+ for (const offence of spreadOffencesInDropShadow(value, tokens)) {
+ offenders.push(`${file}: ${offence}`);
+ }
+ }
+ }
+ }
+
+ // A mention is claimed when some channel READ THE SAME TEXT, which is an
+ // overlap of two spans and not the containment of one offset in the other.
+ //
+ // The two matchers now share the property name, the flags, the style key and
+ // the case rules -- four rounds, each closing one quantity they had spelled
+ // twice. This is the fifth and last: WHERE the match begins. A channel is
+ // free to claim less text than the mention points at, because a utility's
+ // prefix carries no value -- `drop-shadow-[var(--shadow-glow-wire-mint)]` is
+ // read for what is inside the brackets, so the claim starts at `shadow-[`
+ // while the mention starts at `drop-`. Comparing start offsets called that
+ // unscanned and failed a correct, fully tokenized utility; comparing spans
+ // asks the question the measurement was always for.
+ //
+ // Overlap cannot loosen the check, because the mention list does not check
+ // anything -- the channels do. Its only job is to make a channel's gaps
+ // loud, and a channel that read this text has no gap here.
+ for (const pattern of SHADOW_MENTIONS) {
+ for (const mention of source.matchAll(pattern)) {
+ const [from, to] = [mention.index, mention.index + mention[0].length];
+ if (!claimed.some(([start, end]) => from < end && to > start)) {
+ unscanned.push(`${file}:${source.slice(0, mention.index).split('\n').length}: ${
+ source.slice(mention.index, mention.index + 60).split('\n')[0]}`);
+ }
+ }
+ }
+ }
+
+ if (unreadable.length > 0) {
+ throw new Error(
+ `${unreadable.length} shadow value(s) are introduced through an expression this scan cannot read, `
+ + `so nothing checks whether they hold a glow. Inline the value, or name it with a `
+ + `--shadow-glow-* token this scan can follow. Do NOT satisfy this by making the channel stop `
+ + `matching: a mention that matches nothing at all is caught by the completeness check below, `
+ + `while one that matches and yields nothing is scanned and unchecked at once, which is the `
+ + `state this exists to make impossible.\n `
+ + unreadable.join('\n '),
+ );
+ }
+
+ if (unscanned.length > 0) {
+ throw new Error(
+ `${unscanned.length} place(s) introduce a shadow value through a spelling no channel of this `
+ + `scan reads, so nothing checks whether they hold a glow colour inline. Teach SHADOW_CHANNELS `
+ + `the spelling; do NOT narrow SHADOW_MENTION to make this pass, because a mention it stops `
+ + `matching is exactly the silent gap these two lists exist to close.\n `
+ + unscanned.join('\n '),
+ );
+ }
+
+ if (offenders.length > 0) {
+ throw new Error(
+ `${offenders.length} shadow layer(s) either draw a glow themselves or cannot be shown not to. `
+ + `Spelled-out geometry drifts from design.pen exactly the way a spelled-out colour does: `
+ + `neither can be re-anchored for light, and blur, spread and alpha have no scale left to be `
+ + `checked against -- so a managed colour does not redeem hand-picked offsets, and neither `
+ + `does a tidy name wrapped around them. Pick the token whose blur this is nearest -- dot, `
+ + `wire, xs, sm, md, lg, xl or cta -- and use shadow-glow-<role>-<accent>, or `
+ + `var(--shadow-glow-<role>-<accent>) as a whole layer inside a composite shadow. Inside `
+ + `drop-shadow() only the spreadless roles fit, dot and wire, because that function takes no `
+ + `spread and silently drops a layer carrying one. Add the token to @theme if that accent does `
+ + `not have one yet. A layer reported as unreadable rather than as a glow is not asking to be `
+ + `special-cased: give it a form this scan can classify, or it keeps its own geometry `
+ + `unexamined.\n `
+ + offenders.join('\n '),
+ );
+ }
+}
+
+// Tailwind substitutes an `@theme inline` entry's VALUE into every utility it
+// generates from that entry, so the utility never reads the custom property at
+// runtime and redeclaring that same token later -- in `:root`, in a light block,
+// anywhere -- compiles to nothing. This is not a tidiness rule: it is how
+// `--shadow-mint-card` kept the dark frame's neon on a white page while three
+// light overrides sat directly above it looking correct. Theming therefore
+// happens in the variable an alias POINTS AT, never in the alias, and a dead
+// redeclaration now fails here instead of rendering.
+//
+// Across every stylesheet, not the entry one: substitution is a property of the
+// BUILD, so a component stylesheet redeclaring an inlined token is dead in
+// exactly the same way and was the only half this could not see. Reading one
+// file was the third spelling of this round's mistake -- a place assumed rather
+// than asked -- and it is the cheapest of the three to stop assuming.
+function assertInlineThemeTokensAreNotRedeclared(root) {
+ const sheets = [...eachStylesheet(root)];
+ const inlined = new Set();
+
+ for (const [, sheet] of sheets) {
+ sheet.walkAtRules('theme', (atRule) => {
+ if (!atRule.params.split(/\s+/).includes('inline')) return;
+ atRule.walkDecls((decl) => {
+ if (decl.prop.startsWith('--')) inlined.add(decl.prop);
+ });
+ });
+ }
+
+ const dead = [];
+ for (const [origin, sheet] of sheets) {
+ sheet.walkDecls((decl) => {
+ if (!inlined.has(decl.prop)) return;
+ for (let node = decl.parent; node; node = node.parent) {
+ if (node.type === 'atrule' && node.name === 'theme') return;
+ }
+ dead.push(`${origin} line ${decl.source?.start?.line}: ${decl.prop}`);
+ });
+ }
+
+ if (dead.length > 0) {
+ throw new Error(
+ `${dead.length} declaration(s) override a token that @theme inline has already substituted into `
+ + `its utilities, so they change nothing at all. Point the @theme entry at a runtime variable `
+ + `(the shape every other entry uses -- \`--color-mint: var(--mint)\`) and move the override `
+ + `onto that variable.\n `
+ + dead.join('\n '),
+ );
+ }
+}
+
+assertGlowsReadThroughTokens('src');
+assertInlineThemeTokensAreNotRedeclared('src');
assertEveryAcceptedRatioStillExists();
const modelHub = (options) => resolveThemeTokens({ ...options, source: modelHubCss });
diff --git a/ui/scripts/wholeTreeScan.mjs b/ui/scripts/wholeTreeScan.mjs
new file mode 100644
index 000000000..a943c48db
--- /dev/null
+++ b/ui/scripts/wholeTreeScan.mjs
@@ -0,0 +1,19 @@
+// How long a test that walks the whole UI tree may run before it is treated as
+// hung.
+//
+// vitest's 5s default is a UNIT test's clock, and these are not unit tests. They
+// read and parse every source file in the repository on purpose: the properties
+// they assert -- that blanking non-rendering text preserves every file's length,
+// that the glow scale can spell every blur design.pen annotates, that the lint
+// domain resolves one policy for every file in it -- are about the real tree and
+// cannot be stated over fixtures. Three of the files they cover contain astral
+// characters, which is exactly the case a hand-written fixture does not have.
+//
+// So the number is a hang detector, not a performance budget. The work is under
+// two seconds on a developer machine; a CI runner executing 213 test files over
+// a shared pair of cores multiplies that enough to cross five, which is how
+// these tests spent six pushes failing intermittently -- red CI naming no defect
+// at all, on the one gate whose whole purpose is to tell a defect from a
+// correct file. Under a minute is contention. Over it is a loop that will not
+// end on its own.
+export const WHOLE_TREE_SCAN = 60_000;
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index 90a0695c6..b2decbce6 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -80,7 +80,7 @@ const ShellNavLink: React.FC<{ item: ShellNavItem }> = ({ item }) => {
className={clsx(
'group flex items-center gap-2.5 rounded-lg px-3 py-2.5 text-[13px] font-medium transition-colors',
active
- ? 'border border-mint/30 bg-mint/[0.08] text-foreground shadow-[0_0_16px_-4px_rgba(91,255,160,0.5)]'
+ ? 'border border-mint/30 bg-mint/[0.08] text-foreground shadow-glow-sm-mint'
: 'border border-transparent text-muted hover:bg-foreground/[0.04] hover:text-foreground'
)}
>
@@ -146,7 +146,7 @@ const MobileNavLink: React.FC<{ item: ShellNavItem }> = ({ item }) => {
// Emphasized green circle — the back-to-workbench tab, mirroring the
// desktop sidebar's distinct mint mode-switch button. Sized to fill the
// slot so it sits on the same baseline as the plain icons.
- <span className="grid size-7 place-items-center rounded-full border border-mint/45 bg-mint/[0.14] shadow-[0_0_12px_-3px_rgba(91,255,160,0.6)]">
+ <span className="grid size-7 place-items-center rounded-full border border-mint/45 bg-mint/[0.14] shadow-glow-xs-mint">
<Icon className="size-4 text-mint-ink" />
</span>
) : (
@@ -595,7 +595,7 @@ export const AppShell: React.FC = () => {
<img
src={logoImg}
alt="avibe logo"
- className="size-8 rounded-lg border border-mint/35 bg-mint/[0.08] object-cover shadow-[0_0_16px_-4px_rgba(91,255,160,0.5)] transition-shadow group-hover:shadow-[0_0_20px_-3px_rgba(91,255,160,0.65)]"
+ className="size-8 rounded-lg border border-mint/35 bg-mint/[0.08] object-cover shadow-glow-sm-mint transition-shadow group-hover:shadow-glow-md-mint"
/>
<div className="min-w-0 leading-tight">
<div className="truncate text-[13px] font-semibold text-foreground">{t('appShell.title')}</div>
@@ -685,7 +685,7 @@ export const AppShell: React.FC = () => {
<span
className={clsx(
'size-2 shrink-0 rounded-full',
- isRunning ? 'bg-mint shadow-[0_0_8px_rgba(91,255,160,0.9)]' : 'bg-muted'
+ isRunning ? 'bg-mint shadow-glow-dot-mint' : 'bg-muted'
)}
/>
{isRunning ? t('common.running') : t('common.stopped')}
diff --git a/ui/src/components/AppsLauncher.tsx b/ui/src/components/AppsLauncher.tsx
index a6f7a2e19..aef3a3666 100644
--- a/ui/src/components/AppsLauncher.tsx
+++ b/ui/src/components/AppsLauncher.tsx
@@ -131,8 +131,8 @@ export const AppsLauncher: React.FC = () => {
className={clsx(
'group flex w-full items-center gap-2.5 rounded-full border bg-cyan-soft px-4 py-2.5 text-[13px] font-bold text-foreground transition-colors',
visible
- ? 'border-cyan shadow-[0_0_22px_-4px_rgba(63,224,229,0.7)]'
- : 'border-cyan/45 shadow-[0_0_14px_-5px_rgba(63,224,229,0.55)] hover:border-cyan/70',
+ ? 'border-cyan shadow-glow-md-cyan'
+ : 'border-cyan/45 shadow-glow-sm-cyan hover:border-cyan/70',
)}
>
<LayoutGrid className="size-4 shrink-0 text-cyan-ink" />
diff --git a/ui/src/components/Dashboard.tsx b/ui/src/components/Dashboard.tsx
index 69e6545c3..ad148dd89 100644
--- a/ui/src/components/Dashboard.tsx
+++ b/ui/src/components/Dashboard.tsx
@@ -286,7 +286,7 @@ export const Dashboard: React.FC = () => {
<div
className={clsx(
'flex flex-wrap items-center justify-between gap-6 rounded-2xl border bg-surface-2 px-6 py-7 md:px-8',
- 'shadow-[0_24px_48px_-12px_rgba(91,255,160,0.078)]',
+ 'shadow-mint-card',
isRunning ? 'border-mint/30' : 'border-border'
)}
>
@@ -296,7 +296,7 @@ export const Dashboard: React.FC = () => {
className={clsx(
'flex size-[52px] shrink-0 items-center justify-center rounded-full border',
isRunning
- ? 'border-mint/35 bg-mint/[0.08] shadow-[0_0_24px_-6px_rgba(91,255,160,0.44)]'
+ ? 'border-mint/35 bg-mint/[0.08] shadow-glow-md-mint'
: 'border-border bg-foreground/[0.04]'
)}
>
@@ -318,7 +318,7 @@ export const Dashboard: React.FC = () => {
<span
className={clsx(
'size-1.5 rounded-full',
- isRunning ? 'bg-mint shadow-[0_0_8px_rgba(91,255,160,0.9)]' : 'bg-muted'
+ isRunning ? 'bg-mint shadow-glow-dot-mint' : 'bg-muted'
)}
/>
{isRunning ? t('dashboard.runningTitle') : t('dashboard.stoppedTitle')}
diff --git a/ui/src/components/InstallHint.tsx b/ui/src/components/InstallHint.tsx
index 654add4ab..77d39051f 100644
--- a/ui/src/components/InstallHint.tsx
+++ b/ui/src/components/InstallHint.tsx
@@ -64,7 +64,7 @@ export const InstallHint: React.FC = () => {
aria-label={t('installHint.cta')}
className="relative size-7 shrink-0 hover:bg-transparent"
>
- <span className="size-2.5 rounded-full bg-gold shadow-[0_0_8px_rgba(245,200,92,0.9)]" />
+ <span className="size-2.5 rounded-full bg-gold shadow-glow-dot-gold" />
<span className="absolute inline-flex size-2.5 animate-ping rounded-full bg-gold/60" />
</Button>
</PopoverTrigger>
diff --git a/ui/src/components/RemoteAccess.tsx b/ui/src/components/RemoteAccess.tsx
index cc4011cbf..84bc6cb09 100644
--- a/ui/src/components/RemoteAccess.tsx
+++ b/ui/src/components/RemoteAccess.tsx
@@ -396,7 +396,7 @@ export const RemoteAccess: React.FC = () => {
return (
<section
id="remote-access"
- className="scroll-mt-24 overflow-hidden rounded-xl border border-cyan/45 bg-cyan/[0.06] shadow-[0_0_40px_-10px_rgba(63,224,229,0.45)]"
+ className="scroll-mt-24 overflow-hidden rounded-xl border border-cyan/45 bg-cyan/[0.06] shadow-glow-lg-cyan"
>
<div className="flex items-start justify-between gap-4 border-b border-cyan/20 bg-cyan/[0.07] px-5 py-4">
<div className="min-w-0 space-y-2">
diff --git a/ui/src/components/Workbench.tsx b/ui/src/components/Workbench.tsx
index 14d4aa373..c8dba17f7 100644
--- a/ui/src/components/Workbench.tsx
+++ b/ui/src/components/Workbench.tsx
@@ -71,7 +71,7 @@ export const Workbench: React.FC = () => {
<div className="flex flex-col items-center gap-5 md:min-h-[calc(100dvh-7rem)] md:justify-center">
{/* Hero panel — a centered card, not a full-bleed fill. */}
<div className="flex w-full max-w-[640px] flex-col items-center gap-6 rounded-2xl border border-border bg-surface-2 px-6 py-10">
- <div className="flex size-14 items-center justify-center rounded-2xl border border-mint/40 bg-mint-soft text-mint-ink shadow-[0_0_24px_-6px_rgba(91,255,160,0.6)]">
+ <div className="flex size-14 items-center justify-center rounded-2xl border border-mint/40 bg-mint-soft text-mint-ink shadow-glow-md-mint">
<Sparkles className="size-6" />
</div>
<div className="flex max-w-[520px] flex-col items-center gap-3 text-center">
diff --git a/ui/src/components/settings/SettingsPlatformsPage.tsx b/ui/src/components/settings/SettingsPlatformsPage.tsx
index 89778092c..4ba240710 100644
--- a/ui/src/components/settings/SettingsPlatformsPage.tsx
+++ b/ui/src/components/settings/SettingsPlatformsPage.tsx
@@ -434,7 +434,7 @@ const PlatformCard: React.FC<{
<section
className={clsx(
'overflow-hidden rounded-xl border bg-surface-2 transition-colors',
- expanded ? 'border-mint/35 shadow-[0_8px_32px_-8px_rgba(91,255,160,0.078)]' : 'border-border'
+ expanded ? 'border-mint/35 shadow-mint-card-sm' : 'border-border'
)}
>
<div className="flex items-stretch gap-3 px-5 py-4">
diff --git a/ui/src/components/settings/SettingsPrimitives.tsx b/ui/src/components/settings/SettingsPrimitives.tsx
index 13b2d6ef1..34738be8a 100644
--- a/ui/src/components/settings/SettingsPrimitives.tsx
+++ b/ui/src/components/settings/SettingsPrimitives.tsx
@@ -133,7 +133,7 @@ export const ToggleSwitch: React.FC<{ enabled: boolean; onClick: () => void; dis
className={clsx(
'relative inline-flex h-5 w-9 shrink-0 items-center rounded-full border transition-colors focus:outline-none focus:ring-2 focus:ring-mint/40 disabled:opacity-50',
enabled
- ? 'border-mint/50 bg-mint shadow-[0_0_12px_-2px_rgba(91,255,160,0.6)]'
+ ? 'border-mint/50 bg-mint shadow-glow-xs-mint'
: 'border-border-strong bg-border-strong'
)}
>
diff --git a/ui/src/components/settings/SettingsServicePage.tsx b/ui/src/components/settings/SettingsServicePage.tsx
index 5743d815b..3a7a777dd 100644
--- a/ui/src/components/settings/SettingsServicePage.tsx
+++ b/ui/src/components/settings/SettingsServicePage.tsx
@@ -191,7 +191,7 @@ export const SettingsServicePage: React.FC = () => {
<span
className={clsx(
'size-1.5 rounded-full',
- isRunning ? 'bg-mint shadow-[0_0_8px_rgba(91,255,160,0.9)]' : 'bg-muted'
+ isRunning ? 'bg-mint shadow-glow-dot-mint' : 'bg-muted'
)}
/>
{isRunning ? t('common.running') : t('common.stopped')}
diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.css
index 5cedb149c..edffb6d4a 100644
--- a/ui/src/components/settings/models/modelHubSurface.css
+++ b/ui/src/components/settings/models/modelHubSurface.css
@@ -1328,13 +1328,13 @@
.model-hub-wire--native {
stroke: var(--cyan);
stroke-width: var(--model-hub-wire-active-width);
- filter: drop-shadow(0 0 4px color-mix(in srgb, var(--cyan) 40%, transparent));
+ filter: drop-shadow(var(--shadow-glow-wire-cyan));
}
.model-hub-wire--gateway {
stroke: var(--mint);
stroke-width: var(--model-hub-wire-active-width);
- filter: drop-shadow(0 0 4px color-mix(in srgb, var(--mint) 40%, transparent));
+ filter: drop-shadow(var(--shadow-glow-wire-mint));
}
.model-hub-wire--connected_unused {
@@ -1345,7 +1345,7 @@
.model-hub-wire--takeover {
stroke: var(--violet);
stroke-width: var(--model-hub-wire-active-width);
- filter: drop-shadow(0 0 4px color-mix(in srgb, var(--violet) 40%, transparent));
+ filter: drop-shadow(var(--shadow-glow-wire-violet));
}
.model-hub-wire--unavailable {
diff --git a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx b/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
index 39280795d..f05c428af 100644
--- a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
+++ b/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
@@ -1231,7 +1231,7 @@ export const OpencodeProviderConfig: React.FC<{
key={provider.id}
className={clsx(
'flex flex-col rounded-lg border bg-surface transition-colors',
- expanded ? 'border-mint/40 shadow-[0_0_24px_-12px_rgba(91,255,160,0.6)]' : 'border-border hover:border-border-strong',
+ expanded ? 'border-mint/40 shadow-glow-md-mint' : 'border-border hover:border-border-strong',
expanded && 'md:col-span-2'
)}
>
diff --git a/ui/src/components/shared/RoutingConfigPanel.tsx b/ui/src/components/shared/RoutingConfigPanel.tsx
index 195781982..c3a852165 100644
--- a/ui/src/components/shared/RoutingConfigPanel.tsx
+++ b/ui/src/components/shared/RoutingConfigPanel.tsx
@@ -284,7 +284,7 @@ export const RoutingConfigPanel: React.FC<RoutingConfigPanelProps> = ({
<span
className={clsx(
'size-1.5 rounded-full',
- checked ? 'bg-mint shadow-[0_0_6px_rgba(91,255,160,0.7)]' : 'bg-muted/50'
+ checked ? 'bg-mint shadow-glow-dot-mint' : 'bg-muted/50'
)}
/>
{label}
diff --git a/ui/src/components/shared/WizardStep.tsx b/ui/src/components/shared/WizardStep.tsx
index 01d6d31e2..a01c149a5 100644
--- a/ui/src/components/shared/WizardStep.tsx
+++ b/ui/src/components/shared/WizardStep.tsx
@@ -12,7 +12,7 @@ export const StepShell: React.FC<StepShellProps> = ({ active, children }) => (
className={clsx(
'overflow-hidden rounded-xl border transition-colors',
active
- ? 'border-mint/35 bg-surface-2 shadow-[0_8px_32px_-8px_rgba(91,255,160,0.078)]'
+ ? 'border-mint/35 bg-surface-2 shadow-mint-card-sm'
: 'border-border bg-background'
)}
>
diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsx
index 9477bd647..599079466 100644
--- a/ui/src/components/steps/ChannelList.tsx
+++ b/ui/src/components/steps/ChannelList.tsx
@@ -1599,7 +1599,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
className={clsx(
'rounded-xl border transition-colors',
expanded
- ? 'border-mint/30 bg-surface-2/70 shadow-[0_0_32px_-8px_rgba(91,255,160,0.45)]'
+ ? 'border-mint/30 bg-surface-2/70 shadow-glow-lg-mint'
: 'border-border bg-background hover:border-border-strong'
)}
>
@@ -1666,7 +1666,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
<span
className={clsx(
'size-1.5 rounded-full',
- channelEnabled ? 'bg-mint shadow-[0_0_6px_rgba(91,255,160,0.7)]' : 'bg-muted'
+ channelEnabled ? 'bg-mint shadow-glow-dot-mint' : 'bg-muted'
)}
/>
{channelEnabled ? t('common.enabled') : t('common.disabled')}
@@ -1857,7 +1857,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
className={clsx(
'rounded-full border px-3 py-1.5 text-[12px] font-medium transition-colors',
platform === candidate
- ? 'border-mint/50 bg-mint/[0.16] text-mint-ink shadow-[0_0_20px_-4px_rgba(91,255,160,0.4)]'
+ ? 'border-mint/50 bg-mint/[0.16] text-mint-ink shadow-glow-md-mint'
: 'border-border bg-foreground/[0.04] text-foreground hover:border-border-strong'
)}
>
diff --git a/ui/src/components/steps/DiscordConfig.tsx b/ui/src/components/steps/DiscordConfig.tsx
index 0c8ddd5d1..1047ff3e0 100644
--- a/ui/src/components/steps/DiscordConfig.tsx
+++ b/ui/src/components/steps/DiscordConfig.tsx
@@ -460,7 +460,7 @@ export const DiscordConfig: React.FC<DiscordConfigProps> = ({ data, onNext, onBa
key={i}
className={clsx(
'h-1 w-5 rounded-full',
- i < completedCount ? 'bg-mint shadow-[0_0_8px_rgba(91,255,160,0.6)]' : 'bg-foreground/[0.08]'
+ i < completedCount ? 'bg-mint shadow-glow-dot-mint' : 'bg-foreground/[0.08]'
)}
/>
))}
diff --git a/ui/src/components/steps/DoctorPanel.tsx b/ui/src/components/steps/DoctorPanel.tsx
index d391570ef..2deceb191 100644
--- a/ui/src/components/steps/DoctorPanel.tsx
+++ b/ui/src/components/steps/DoctorPanel.tsx
@@ -94,9 +94,13 @@ export const DoctorPanel: React.FC<DoctorPanelProps> = ({
return (
<div className={clsx('flex w-full flex-col gap-5', isPage && 'h-full')}>
{/* diagHero */}
+ {/* Not `shadow-mint-card-sm`: design.pen draws this card at y16, and that
+ rung is y8. Card washes are not this change's scope -- 41 of them are
+ still literals -- so it keeps its own value rather than being snapped
+ to the nearest rung. */}
<div className="flex flex-wrap items-center justify-between gap-4 rounded-2xl border border-mint/30 bg-surface-2 px-6 py-5 shadow-[0_16px_32px_-8px_rgba(91,255,160,0.078)]">
<div className="flex min-w-0 items-center gap-3.5">
- <div className="flex size-[42px] shrink-0 items-center justify-center rounded-full border border-mint/35 bg-mint/[0.08] shadow-[0_0_16px_-4px_rgba(91,255,160,0.44)]">
+ <div className="flex size-[42px] shrink-0 items-center justify-center rounded-full border border-mint/35 bg-mint/[0.08] shadow-glow-sm-mint">
<Activity className="size-5 text-mint-ink" strokeWidth={2.25} />
</div>
<div className="flex min-w-0 flex-col gap-0.5">
diff --git a/ui/src/components/steps/LarkConfig.tsx b/ui/src/components/steps/LarkConfig.tsx
index 0ce17e234..8a392c326 100644
--- a/ui/src/components/steps/LarkConfig.tsx
+++ b/ui/src/components/steps/LarkConfig.tsx
@@ -244,7 +244,7 @@ export const LarkConfig: React.FC<LarkConfigProps> = ({ data, onNext, onBack, em
className={clsx(
'flex-1 rounded-lg border px-3 py-2 text-[12px] font-semibold transition',
domain === opt
- ? 'border-mint/45 bg-mint/[0.08] text-mint-ink shadow-[0_0_24px_-4px_rgba(91,255,160,0.4)]'
+ ? 'border-mint/45 bg-mint/[0.08] text-mint-ink shadow-glow-md-mint'
: 'border-border bg-foreground/[0.04] text-muted hover:border-border-strong hover:text-foreground'
)}
>
@@ -559,7 +559,7 @@ export const LarkConfig: React.FC<LarkConfigProps> = ({ data, onNext, onBack, em
key={i}
className={clsx(
'h-1 w-4 rounded-full',
- i < completedCount ? 'bg-mint shadow-[0_0_8px_rgba(91,255,160,0.6)]' : 'bg-foreground/[0.08]'
+ i < completedCount ? 'bg-mint shadow-glow-dot-mint' : 'bg-foreground/[0.08]'
)}
/>
))}
diff --git a/ui/src/components/steps/LogsPanel.tsx b/ui/src/components/steps/LogsPanel.tsx
index 5f6ed4788..f89e76d79 100644
--- a/ui/src/components/steps/LogsPanel.tsx
+++ b/ui/src/components/steps/LogsPanel.tsx
@@ -219,7 +219,7 @@ export const LogsPanel: React.FC<LogsPanelProps> = ({
className={clsx(
'inline-flex h-7 items-center gap-1 rounded-full border px-3 text-[11px] font-medium transition-colors',
selectedSource === source.key
- ? 'border-mint/35 bg-mint/[0.08] text-mint-ink shadow-[0_0_12px_-4px_rgba(91,255,160,0.5)]'
+ ? 'border-mint/35 bg-mint/[0.08] text-mint-ink shadow-glow-xs-mint'
: 'border-border bg-foreground/[0.04] text-muted hover:border-border-strong hover:text-foreground'
)}
>
diff --git a/ui/src/components/steps/SlackConfig.tsx b/ui/src/components/steps/SlackConfig.tsx
index aceacdc3b..6a1e93302 100644
--- a/ui/src/components/steps/SlackConfig.tsx
+++ b/ui/src/components/steps/SlackConfig.tsx
@@ -391,7 +391,7 @@ export const SlackConfig: React.FC<SlackConfigProps> = ({ data, onNext, onBack,
key={i}
className={clsx(
'h-1 w-5 rounded-full',
- i < completedCount ? 'bg-mint shadow-[0_0_8px_rgba(91,255,160,0.6)]' : 'bg-foreground/[0.08]'
+ i < completedCount ? 'bg-mint shadow-glow-dot-mint' : 'bg-foreground/[0.08]'
)}
/>
))}
diff --git a/ui/src/components/steps/Summary.tsx b/ui/src/components/steps/Summary.tsx
index c61bde63f..ba31bc2b4 100644
--- a/ui/src/components/steps/Summary.tsx
+++ b/ui/src/components/steps/Summary.tsx
@@ -197,7 +197,7 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {
return (
<div className="flex w-full justify-center">
<WizardCard accent size="hero" className="items-center gap-6 text-center">
- <div className="flex size-[72px] items-center justify-center rounded-full border-2 border-mint/40 bg-mint/[0.08] text-mint-ink shadow-[0_0_48px_-6px_rgba(91,255,160,0.7)]">
+ <div className="flex size-[72px] items-center justify-center rounded-full border-2 border-mint/40 bg-mint/[0.08] text-mint-ink shadow-glow-xl-mint">
<Check size={36} strokeWidth={2.4} />
</div>
<div className="space-y-2">
@@ -246,7 +246,7 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {
<div className="flex w-full justify-center">
<WizardCard accent size="hero" className="gap-6">
<div className="flex flex-col items-center gap-5 text-center">
- <div className="flex size-[72px] items-center justify-center rounded-full border-2 border-mint/40 bg-mint/[0.08] text-mint-ink shadow-[0_0_48px_-6px_rgba(91,255,160,0.7)]">
+ <div className="flex size-[72px] items-center justify-center rounded-full border-2 border-mint/40 bg-mint/[0.08] text-mint-ink shadow-glow-xl-mint">
<Check size={36} strokeWidth={2.4} />
</div>
<div className="space-y-2">
diff --git a/ui/src/components/steps/TelegramConfig.tsx b/ui/src/components/steps/TelegramConfig.tsx
index 0bf9119a5..ae94c7988 100644
--- a/ui/src/components/steps/TelegramConfig.tsx
+++ b/ui/src/components/steps/TelegramConfig.tsx
@@ -398,7 +398,7 @@ export const TelegramConfig: React.FC<TelegramConfigProps> = ({ data, onNext, on
key={i}
className={clsx(
'h-1 w-4 rounded-full',
- i < completedCount ? 'bg-mint shadow-[0_0_8px_rgba(91,255,160,0.6)]' : 'bg-foreground/[0.08]'
+ i < completedCount ? 'bg-mint shadow-glow-dot-mint' : 'bg-foreground/[0.08]'
)}
/>
))}
diff --git a/ui/src/components/steps/UserList.tsx b/ui/src/components/steps/UserList.tsx
index 688fe1e7d..b52ddc852 100644
--- a/ui/src/components/steps/UserList.tsx
+++ b/ui/src/components/steps/UserList.tsx
@@ -778,7 +778,7 @@ export const UserList: React.FC = () => {
className={clsx(
'rounded-xl border transition-colors',
expanded
- ? 'border-mint/30 bg-surface-2/70 shadow-[0_0_32px_-8px_rgba(91,255,160,0.45)]'
+ ? 'border-mint/30 bg-surface-2/70 shadow-glow-lg-mint'
: userConfig.enabled
? 'border-border bg-background hover:border-border-strong'
: 'border-border bg-background/60 opacity-70'
diff --git a/ui/src/components/steps/WeChatConfig.tsx b/ui/src/components/steps/WeChatConfig.tsx
index 624db3335..999c55865 100644
--- a/ui/src/components/steps/WeChatConfig.tsx
+++ b/ui/src/components/steps/WeChatConfig.tsx
@@ -367,7 +367,7 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({
{isAlreadyBound && (
<div className="rounded-xl border border-border bg-background px-6 py-6">
<div className="flex flex-col items-center gap-4 text-center">
- <div className="flex size-16 items-center justify-center rounded-full border border-mint/30 bg-mint/[0.08] text-mint-ink shadow-[0_0_32px_-6px_rgba(91,255,160,0.5)]">
+ <div className="flex size-16 items-center justify-center rounded-full border border-mint/30 bg-mint/[0.08] text-mint-ink shadow-glow-lg-mint">
<Check size={32} />
</div>
<div>
@@ -424,9 +424,9 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({
{/* QR */}
{(loginState === 'qr_ready' || loginState === 'scanning' || loginState === 'confirming') && (
- <div className="rounded-xl border border-mint/35 bg-surface-2 px-6 py-6 shadow-[0_8px_32px_-8px_rgba(91,255,160,0.078)]">
+ <div className="rounded-xl border border-mint/35 bg-surface-2 px-6 py-6 shadow-mint-card-sm">
<div className="flex flex-col items-center gap-4">
- <div className="rounded-xl border border-border bg-white p-4 shadow-[0_0_24px_-4px_rgba(91,255,160,0.4)]">
+ <div className="rounded-xl border border-border bg-white p-4 shadow-glow-md-mint">
<QRCodeSVG value={qrCodeUrl} size={224} level="M" includeMargin={false} />
</div>
<div
@@ -471,9 +471,9 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({
{/* Connected */}
{loginState === 'connected' && (
- <div className="rounded-xl border border-mint/35 bg-surface-2 px-6 py-6 shadow-[0_8px_32px_-8px_rgba(91,255,160,0.078)]">
+ <div className="rounded-xl border border-mint/35 bg-surface-2 px-6 py-6 shadow-mint-card-sm">
<div className="flex flex-col items-center gap-4 text-center">
- <div className="flex size-16 items-center justify-center rounded-full border border-mint/30 bg-mint/[0.08] text-mint-ink shadow-[0_0_32px_-6px_rgba(91,255,160,0.5)]">
+ <div className="flex size-16 items-center justify-center rounded-full border border-mint/30 bg-mint/[0.08] text-mint-ink shadow-glow-lg-mint">
<Check size={32} />
</div>
<div>
@@ -557,7 +557,7 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({
key={i}
className={clsx(
'h-1 w-6 rounded-full',
- i < completedDots ? 'bg-mint shadow-[0_0_8px_rgba(91,255,160,0.6)]' : 'bg-foreground/[0.08]'
+ i < completedDots ? 'bg-mint shadow-glow-dot-mint' : 'bg-foreground/[0.08]'
)}
/>
))}
diff --git a/ui/src/components/steps/Welcome.tsx b/ui/src/components/steps/Welcome.tsx
index 13743482e..b00771cf0 100644
--- a/ui/src/components/steps/Welcome.tsx
+++ b/ui/src/components/steps/Welcome.tsx
@@ -44,7 +44,7 @@ export const Welcome: React.FC<WelcomeProps> = ({ onNext }) => {
>
{/* welBigLogo (A3aTA) */}
<div
- className="mx-auto flex size-20 items-center justify-center rounded-[20px] border-2 border-mint/40 bg-mint/[0.16] shadow-[0_0_48px_-8px_rgba(91,255,160,0.44)]"
+ className="mx-auto flex size-20 items-center justify-center rounded-[20px] border-2 border-mint/40 bg-mint/[0.16] shadow-glow-xl-mint"
aria-hidden
>
<Radio className="size-10 text-mint-ink" strokeWidth={1.75} />
diff --git a/ui/src/components/ui/badge-variants.ts b/ui/src/components/ui/badge-variants.ts
index 4a431c0da..1a8666597 100644
--- a/ui/src/components/ui/badge-variants.ts
+++ b/ui/src/components/ui/badge-variants.ts
@@ -19,7 +19,7 @@ export const badgeVariants = cva(
'max-w-[140px] shrink-0 whitespace-normal rounded-full border px-[7px] py-0.5 text-center text-[10px] font-semibold leading-[1.2] tracking-normal',
// Eyebrow — JetBrains Mono cyan w/ glow (design.pen Badge/Eyebrow mtcmf).
eyebrow:
- 'rounded-full border border-cyan/50 bg-cyan/[0.16] px-3 py-1.5 font-mono text-[11px] font-bold uppercase tracking-[0.14em] text-cyan-ink shadow-[0_0_24px_-4px_rgba(63,224,229,0.33)]',
+ 'rounded-full border border-cyan/50 bg-cyan/[0.16] px-3 py-1.5 font-mono text-[11px] font-bold uppercase tracking-[0.14em] text-cyan-ink shadow-glow-md-cyan',
},
},
defaultVariants: {
diff --git a/ui/src/components/ui/button-variants.ts b/ui/src/components/ui/button-variants.ts
index 8300f8a70..2427e3aba 100644
--- a/ui/src/components/ui/button-variants.ts
+++ b/ui/src/components/ui/button-variants.ts
@@ -35,13 +35,13 @@ export const buttonVariants = cva(
// always a CSS variable. design.pen has no glow on any Button, so the value is
// ours to hold, not the design's; keep the four in lockstep.
brand:
- 'gap-2 bg-mint font-bold text-primary-foreground shadow-[0_0_var(--brand-glow-blur)_-4px_rgba(91,255,160,0.6)] hover:bg-mint-hover disabled:shadow-none',
+ 'gap-2 bg-mint font-bold text-primary-foreground shadow-glow-cta-mint hover:bg-mint-hover disabled:shadow-none',
'brand-cyan':
- 'gap-2 bg-cyan font-bold text-accent-foreground shadow-[0_0_var(--brand-glow-blur)_-4px_rgba(63,224,229,0.6)] hover:bg-cyan-hover disabled:shadow-none',
+ 'gap-2 bg-cyan font-bold text-accent-foreground shadow-glow-cta-cyan hover:bg-cyan-hover disabled:shadow-none',
'brand-gold':
- 'gap-2 bg-gold font-bold text-gold-foreground shadow-[0_0_var(--brand-glow-blur)_-4px_rgba(255,200,87,0.55)] hover:bg-gold-hover disabled:shadow-none',
+ 'gap-2 bg-gold font-bold text-gold-foreground shadow-glow-cta-gold hover:bg-gold-hover disabled:shadow-none',
'brand-violet':
- 'gap-2 bg-violet font-bold text-violet-foreground shadow-[0_0_var(--brand-glow-blur)_-4px_rgba(124,91,255,0.55)] hover:bg-violet-hover disabled:shadow-none',
+ 'gap-2 bg-violet font-bold text-violet-foreground shadow-glow-cta-violet hover:bg-violet-hover disabled:shadow-none',
secondary: 'gap-1.5 border border-border bg-secondary text-secondary-foreground hover:border-border-strong',
// Outline — bg matches page surface so it sits cleanly on glow gradients.
outline:
diff --git a/ui/src/components/visual/BrandLogo.tsx b/ui/src/components/visual/BrandLogo.tsx
index d7ec1a4a1..4c7ea9a31 100644
--- a/ui/src/components/visual/BrandLogo.tsx
+++ b/ui/src/components/visual/BrandLogo.tsx
@@ -16,7 +16,7 @@ export const BrandLogo: React.FC<BrandLogoProps> = ({
<span
className={cn(
'inline-flex shrink-0 items-center justify-center overflow-hidden rounded-xl border border-mint/30 bg-mint/[0.08]',
- withGlow && 'shadow-[0_0_24px_-4px_rgba(91,255,160,0.45)]',
+ withGlow && 'shadow-glow-md-mint',
className
)}
style={{ width: size, height: size }}
diff --git a/ui/src/components/visual/EmbeddedConfigShell.tsx b/ui/src/components/visual/EmbeddedConfigShell.tsx
index dbf3728c2..fa054ee46 100644
--- a/ui/src/components/visual/EmbeddedConfigShell.tsx
+++ b/ui/src/components/visual/EmbeddedConfigShell.tsx
@@ -38,7 +38,7 @@ export const EmbeddedConfigShell: React.FC<EmbeddedConfigShellProps> = ({
key={i}
className={clsx(
'h-1 w-4 rounded-full',
- i < completed ? 'bg-mint shadow-[0_0_8px_rgba(91,255,160,0.6)]' : 'bg-foreground/[0.08]'
+ i < completed ? 'bg-mint shadow-glow-dot-mint' : 'bg-foreground/[0.08]'
)}
/>
))}
diff --git a/ui/src/components/visual/EyebrowBadge.tsx b/ui/src/components/visual/EyebrowBadge.tsx
index 4efe8cf4a..4994dce72 100644
--- a/ui/src/components/visual/EyebrowBadge.tsx
+++ b/ui/src/components/visual/EyebrowBadge.tsx
@@ -10,10 +10,10 @@ interface EyebrowBadgeProps extends React.HTMLAttributes<HTMLSpanElement> {
// Mirrors design.pen Badge/Eyebrow (mtcmf): JetBrains Mono, 11px, weight 700,
// letterSpacing 1.4, cyan glow shadow. Used for `01 — STEP` style labels.
const TONE_CLASSES: Record<Tone, string> = {
- cyan: 'border-cyan/50 bg-cyan/[0.16] text-cyan-ink shadow-[0_0_24px_-4px_rgba(63,224,229,0.33)]',
- mint: 'border-mint/50 bg-mint/[0.16] text-mint-ink shadow-[0_0_24px_-4px_rgba(91,255,160,0.33)]',
- violet: 'border-violet/50 bg-violet/[0.16] text-violet-ink shadow-[0_0_24px_-4px_rgba(124,91,255,0.33)]',
- gold: 'border-gold/50 bg-gold/[0.16] text-gold-ink shadow-[0_0_24px_-4px_rgba(255,200,87,0.33)]',
+ cyan: 'border-cyan/50 bg-cyan/[0.16] text-cyan-ink shadow-glow-md-cyan',
+ mint: 'border-mint/50 bg-mint/[0.16] text-mint-ink shadow-glow-md-mint',
+ violet: 'border-violet/50 bg-violet/[0.16] text-violet-ink shadow-glow-md-violet',
+ gold: 'border-gold/50 bg-gold/[0.16] text-gold-ink shadow-glow-md-gold',
};
export const EyebrowBadge = React.forwardRef<HTMLSpanElement, EyebrowBadgeProps>(
diff --git a/ui/src/components/visual/ProgressBar.tsx b/ui/src/components/visual/ProgressBar.tsx
index e0c52ddaa..597c79680 100644
--- a/ui/src/components/visual/ProgressBar.tsx
+++ b/ui/src/components/visual/ProgressBar.tsx
@@ -31,7 +31,7 @@ export const ProgressBar: React.FC<ProgressBarProps> = ({
className={cn(
'h-1 flex-1 rounded-full transition-all duration-300',
filled
- ? 'bg-mint shadow-[0_0_12px_rgba(91,255,160,0.45)]'
+ ? 'bg-mint shadow-glow-dot-mint'
: 'bg-foreground/[0.06]'
)}
/>
diff --git a/ui/src/components/visual/StatusPill.tsx b/ui/src/components/visual/StatusPill.tsx
index 26fd96dfb..a37bb400f 100644
--- a/ui/src/components/visual/StatusPill.tsx
+++ b/ui/src/components/visual/StatusPill.tsx
@@ -10,7 +10,7 @@ interface StatusPillProps extends React.HTMLAttributes<HTMLSpanElement> {
}
const TONE_CLASSES: Record<Tone, { wrapper: string; dot: string }> = {
- running: { wrapper: 'border-mint/40 bg-mint/[0.12] text-foreground', dot: 'bg-mint shadow-[0_0_8px_rgba(91,255,160,0.6)]' },
+ running: { wrapper: 'border-mint/40 bg-mint/[0.12] text-foreground', dot: 'bg-mint shadow-glow-dot-mint' },
stopped: { wrapper: 'border-border-strong bg-surface-2 text-muted', dot: 'bg-muted' },
warning: { wrapper: 'border-gold/40 bg-gold/[0.12] text-gold-ink', dot: 'bg-gold' },
idle: { wrapper: 'border-border bg-surface text-muted', dot: 'bg-muted' },
diff --git a/ui/src/components/visual/StepCard.tsx b/ui/src/components/visual/StepCard.tsx
index 4d30f3ff3..47c33ac6e 100644
--- a/ui/src/components/visual/StepCard.tsx
+++ b/ui/src/components/visual/StepCard.tsx
@@ -25,7 +25,7 @@ export const StepCard: React.FC<StepCardProps> = ({
<div
className={cn(
'flex flex-col gap-4 rounded-xl border border-mint/[0.20] bg-surface-2 p-8',
- 'shadow-[0_24px_48px_-12px_rgba(91,255,160,0.078)]',
+ 'shadow-mint-card',
className
)}
{...props}
diff --git a/ui/src/components/visual/WizardCard.tsx b/ui/src/components/visual/WizardCard.tsx
index 9b4a56972..f44d5a607 100644
--- a/ui/src/components/visual/WizardCard.tsx
+++ b/ui/src/components/visual/WizardCard.tsx
@@ -28,7 +28,7 @@ export const WizardCard: React.FC<WizardCardProps> = ({
// padding kick in from sm up. On phones the wizard goes full-bleed on the
// page background with no card — matches the mobile wizard frames in
// design.pen (Tbqur / byTzd); the page gutter supplies the side spacing.
- 'sm:rounded-2xl sm:border sm:bg-surface-2 sm:shadow-[0_32px_64px_-12px_rgba(91,255,160,0.078)]',
+ 'sm:rounded-2xl sm:border sm:bg-surface-2 sm:shadow-mint-card-lg',
accent ? 'sm:border-mint/35' : 'sm:border-border',
size === 'hero' ? 'sm:p-12 md:p-16' : 'sm:px-6 sm:py-8 md:px-12 md:py-10',
className
diff --git a/ui/src/components/workbench/AgentGraphNodeCard.tsx b/ui/src/components/workbench/AgentGraphNodeCard.tsx
index f3593467a..9f58653ca 100644
--- a/ui/src/components/workbench/AgentGraphNodeCard.tsx
+++ b/ui/src/components/workbench/AgentGraphNodeCard.tsx
@@ -17,7 +17,7 @@ import {
// hint; everything else the neutral surface. Non-live nodes are dimmed by the
// caller via ``faded``.
function shellClass(node: AgentGraphNode, selected: boolean): string {
- if (selected) return 'border-mint/70 bg-mint-soft shadow-[0_0_20px_-6px_rgba(91,255,160,0.55)]';
+ if (selected) return 'border-mint/70 bg-mint-soft shadow-glow-md-mint';
const tone = statusMeta(node.status).tone;
if (tone === 'destructive') return 'border-destructive/40 bg-destructive/[0.05]';
if (node.status === 'active') return 'border-mint/40 bg-surface';
diff --git a/ui/src/components/workbench/AgentGraphTriggerChip.tsx b/ui/src/components/workbench/AgentGraphTriggerChip.tsx
index de7706529..658c0d9d2 100644
--- a/ui/src/components/workbench/AgentGraphTriggerChip.tsx
+++ b/ui/src/components/workbench/AgentGraphTriggerChip.tsx
@@ -43,7 +43,7 @@ export const AgentGraphTriggerChip: React.FC<AgentGraphTriggerChipProps> = ({
className={clsx(
'flex h-full w-full items-center gap-2 rounded-xl border bg-violet-soft px-3 py-2 text-left transition hover:brightness-110',
// Selected mirrors the session card's colored-border + glow (violet here).
- selected ? 'border-violet shadow-[0_0_20px_-6px_rgba(124,91,255,0.6)]' : 'border-violet/40',
+ selected ? 'border-violet shadow-glow-md-violet' : 'border-violet/40',
faded ? 'opacity-25' : disabled && 'opacity-60',
className,
)}
diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsx
index 78d480fb1..de3a4581b 100644
--- a/ui/src/components/workbench/AgentsPage.tsx
+++ b/ui/src/components/workbench/AgentsPage.tsx
@@ -779,7 +779,7 @@ const AgentRow: React.FC<AgentRowProps> = ({ agent, isSelected, isDefault, onSel
className={clsx(
'flex items-center gap-3 rounded-xl border px-4 py-3 text-left transition',
isSelected
- ? 'border-mint/40 bg-mint-soft shadow-[0_0_18px_-10px_rgba(91,255,160,0.6)]'
+ ? 'border-mint/40 bg-mint-soft shadow-glow-sm-mint'
: 'border-border bg-surface hover:border-border-strong hover:bg-surface-2',
)}
>
diff --git a/ui/src/components/workbench/CreateViaChatDialog.tsx b/ui/src/components/workbench/CreateViaChatDialog.tsx
index 0dc350268..20754e47a 100644
--- a/ui/src/components/workbench/CreateViaChatDialog.tsx
+++ b/ui/src/components/workbench/CreateViaChatDialog.tsx
@@ -100,7 +100,7 @@ export const CreateViaChatDialog: React.FC<CreateViaChatDialogProps> = ({ kind,
onClick={onClose}
>
<div
- className="flex w-full max-w-[500px] flex-col items-center gap-5 rounded-2xl border border-violet/30 bg-surface p-7 shadow-[0_24px_48px_-6px_rgba(0,0,0,0.8),0_0_32px_-12px_rgba(124,91,255,0.55)]"
+ className="flex w-full max-w-[500px] flex-col items-center gap-5 rounded-2xl border border-violet/30 bg-surface p-7 shadow-[0_24px_48px_-6px_rgba(0,0,0,0.8),var(--shadow-glow-lg-violet)]"
onClick={(e) => e.stopPropagation()}
>
<button
@@ -113,7 +113,7 @@ export const CreateViaChatDialog: React.FC<CreateViaChatDialogProps> = ({ kind,
</button>
{/* Hero icon — 64x64 violet-soft tile with glow */}
- <div className="flex size-16 items-center justify-center rounded-2xl border border-violet/30 bg-violet-soft text-violet-ink shadow-[0_0_28px_-6px_rgba(124,91,255,0.6)]">
+ <div className="flex size-16 items-center justify-center rounded-2xl border border-violet/30 bg-violet-soft text-violet-ink shadow-glow-md-violet">
<Sparkles className="size-[30px]" />
</div>
diff --git a/ui/src/components/workbench/HarnessPage.tsx b/ui/src/components/workbench/HarnessPage.tsx
index d069081a4..d040501ce 100644
--- a/ui/src/components/workbench/HarnessPage.tsx
+++ b/ui/src/components/workbench/HarnessPage.tsx
@@ -606,7 +606,7 @@ export const HarnessPage: React.FC = () => {
<CapabilityTabs />
{/* Header */}
<div className="flex items-center gap-4">
- <div className="flex size-12 shrink-0 items-center justify-center rounded-2xl border border-violet/30 bg-violet/[0.08] text-violet-ink shadow-[0_0_24px_-6px_rgba(124,91,255,0.5)]">
+ <div className="flex size-12 shrink-0 items-center justify-center rounded-2xl border border-violet/30 bg-violet/[0.08] text-violet-ink shadow-glow-md-violet">
<Activity className="size-5" />
</div>
<div className="flex flex-1 flex-col">
@@ -989,7 +989,7 @@ const TasksList: React.FC<TasksListProps> = ({
// their second line *says*, never in how the row is built. ``definitionRowLine``
// owns that difference so this component stays a single anatomy.
const STATE_DOT_CLASS: Record<HarnessLifecycleState, string> = {
- running: 'bg-mint shadow-[0_0_5px_rgba(52,211,153,0.7)]',
+ running: 'bg-mint shadow-glow-dot-mint',
waiting: 'bg-cyan',
paused: 'bg-muted/70',
finished: 'bg-border-strong',
diff --git a/ui/src/components/workbench/InboxPage.tsx b/ui/src/components/workbench/InboxPage.tsx
index 59cbae2e3..d23714b09 100644
--- a/ui/src/components/workbench/InboxPage.tsx
+++ b/ui/src/components/workbench/InboxPage.tsx
@@ -120,7 +120,7 @@ export const InboxPage: React.FC = () => {
<div className="mx-auto flex w-full max-w-4xl flex-col gap-6 py-2">
{/* Header */}
<div className="flex flex-wrap items-center gap-4">
- <div className="flex size-12 shrink-0 items-center justify-center rounded-2xl border border-mint/30 bg-mint/[0.08] text-mint-ink shadow-[0_0_24px_-6px_rgba(91,255,160,0.5)]">
+ <div className="flex size-12 shrink-0 items-center justify-center rounded-2xl border border-mint/30 bg-mint/[0.08] text-mint-ink shadow-glow-md-mint">
<Inbox className="size-5" />
</div>
<div className="flex flex-1 flex-col">
@@ -181,7 +181,7 @@ export const InboxPage: React.FC = () => {
className={clsx(
'flex flex-1 items-center justify-center gap-1.5 rounded-md px-3 py-1.5 text-[12px] font-semibold transition sm:flex-none',
filter === key
- ? 'bg-mint/[0.10] text-mint-ink shadow-[0_0_12px_-4px_rgba(91,255,160,0.5)]'
+ ? 'bg-mint/[0.10] text-mint-ink shadow-glow-xs-mint'
: 'text-muted hover:text-foreground',
)}
>
@@ -241,7 +241,7 @@ export const InboxPage: React.FC = () => {
className={clsx(
'flex flex-col gap-3 rounded-xl border p-4 transition',
unread > 0
- ? 'border-mint/30 bg-mint/[0.05] shadow-[0_0_24px_-12px_rgba(91,255,160,0.4)]'
+ ? 'border-mint/30 bg-mint/[0.05] shadow-glow-md-mint'
: 'border-border bg-surface',
)}
>
diff --git a/ui/src/components/workbench/MorePage.tsx b/ui/src/components/workbench/MorePage.tsx
index 0138bf963..228b8cf6c 100644
--- a/ui/src/components/workbench/MorePage.tsx
+++ b/ui/src/components/workbench/MorePage.tsx
@@ -91,7 +91,7 @@ export const MoreConnectionSection: React.FC = () => {
<span
className={clsx(
'size-2.5 shrink-0 rounded-full',
- isRunning ? 'bg-mint shadow-[0_0_9px_rgba(91,255,160,0.9)]' : 'bg-muted',
+ isRunning ? 'bg-mint shadow-glow-dot-mint' : 'bg-muted',
)}
/>
<span className="flex-1 text-sm font-semibold">
diff --git a/ui/src/components/workbench/ProjectsPage.tsx b/ui/src/components/workbench/ProjectsPage.tsx
index 46dcc2bca..33cb7e503 100644
--- a/ui/src/components/workbench/ProjectsPage.tsx
+++ b/ui/src/components/workbench/ProjectsPage.tsx
@@ -39,7 +39,7 @@ import { useSessionActions } from './useSessionActions';
import { SessionPinIndicator } from './SessionPinIndicator';
const DOT: Record<string, string> = {
- running: 'bg-mint shadow-[0_0_7px_rgba(91,255,160,0.9)]',
+ running: 'bg-mint shadow-glow-dot-mint',
failed: 'bg-destructive',
idle: 'bg-muted',
};
diff --git a/ui/src/components/workbench/ShowPageAnnotateControl.tsx b/ui/src/components/workbench/ShowPageAnnotateControl.tsx
index 630756d41..fefb942fe 100644
--- a/ui/src/components/workbench/ShowPageAnnotateControl.tsx
+++ b/ui/src/components/workbench/ShowPageAnnotateControl.tsx
@@ -148,7 +148,7 @@ export const ShowPageAnnotateControl: React.FC<ShowPageAnnotateControlProps> = (
{!compact && (
<div className="hidden items-center md:flex">
{enabled ? (
- <div className="flex h-7 items-center gap-0.5 rounded-lg border border-mint/40 bg-mint/[0.06] p-0.5 shadow-[0_0_16px_-6px_rgba(91,255,160,0.5)]">
+ <div className="flex h-7 items-center gap-0.5 rounded-lg border border-mint/40 bg-mint/[0.06] p-0.5 shadow-glow-sm-mint">
<Button
type="button"
variant="default"
diff --git a/ui/src/components/workbench/WorkbenchModulePlaceholder.tsx b/ui/src/components/workbench/WorkbenchModulePlaceholder.tsx
index 010fd506a..0d5a39109 100644
--- a/ui/src/components/workbench/WorkbenchModulePlaceholder.tsx
+++ b/ui/src/components/workbench/WorkbenchModulePlaceholder.tsx
@@ -21,7 +21,7 @@ export const WorkbenchModulePlaceholder: React.FC<WorkbenchModulePlaceholderProp
return (
<div className="mx-auto flex max-w-2xl flex-col items-center gap-5 py-16 text-center">
- <div className="flex size-14 items-center justify-center rounded-2xl border border-mint/30 bg-mint/[0.08] text-mint-ink shadow-[0_0_24px_-6px_rgba(91,255,160,0.5)]">
+ <div className="flex size-14 items-center justify-center rounded-2xl border border-mint/30 bg-mint/[0.08] text-mint-ink shadow-glow-md-mint">
{icon}
</div>
<div className="font-mono text-[10px] font-bold uppercase tracking-[0.18em] text-mint-ink">
diff --git a/ui/src/components/workbench/WorkbenchPageHeader.tsx b/ui/src/components/workbench/WorkbenchPageHeader.tsx
index 4453587c9..a875d0ccc 100644
--- a/ui/src/components/workbench/WorkbenchPageHeader.tsx
+++ b/ui/src/components/workbench/WorkbenchPageHeader.tsx
@@ -6,10 +6,10 @@ type Accent = 'mint' | 'cyan' | 'violet' | 'gold';
// Accent-driven icon-box surface. The mint variant is the canonical workbench
// page header (Agents, Skills); cyan/violet/gold are available for siblings.
const ACCENT_BOX: Record<Accent, string> = {
- mint: 'border-mint/40 bg-mint-soft text-mint-ink shadow-[0_0_18px_-6px_rgba(91,255,160,0.5)]',
- cyan: 'border-cyan/40 bg-cyan-soft text-cyan-ink shadow-[0_0_18px_-6px_rgba(63,224,229,0.5)]',
- violet: 'border-violet/40 bg-violet-soft text-violet-ink shadow-[0_0_18px_-6px_rgba(124,91,255,0.5)]',
- gold: 'border-gold/40 bg-gold/[0.12] text-gold-ink shadow-[0_0_18px_-6px_rgba(255,200,87,0.5)]',
+ mint: 'border-mint/40 bg-mint-soft text-mint-ink shadow-glow-sm-mint',
+ cyan: 'border-cyan/40 bg-cyan-soft text-cyan-ink shadow-glow-sm-cyan',
+ violet: 'border-violet/40 bg-violet-soft text-violet-ink shadow-glow-sm-violet',
+ gold: 'border-gold/40 bg-gold/[0.12] text-gold-ink shadow-glow-sm-gold',
};
export interface WorkbenchPageHeaderProps {
diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsx
index 207f6d866..d72611eb2 100644
--- a/ui/src/components/workbench/WorkbenchSidebar.tsx
+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx
@@ -196,8 +196,8 @@ const InboxHoverPopover: React.FC<{
// gray / green / red: idle → muted (gray), running → mint (green) + glow,
// failed → destructive (red) + glow. Tokens resolve from src/index.css.
const STATUS_DOT_CLASS: Record<string, string> = {
- running: 'bg-mint shadow-[0_0_6px_0_rgba(91,255,160,0.65)]',
- failed: 'bg-destructive shadow-[0_0_6px_0_rgba(255,107,107,0.6)]',
+ running: 'bg-mint shadow-glow-dot-mint',
+ failed: 'bg-destructive shadow-glow-dot-destructive',
idle: 'bg-muted',
};
@@ -773,7 +773,7 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
// Cyan active state per design.pen ze15A — mint is reserved
// for sessions / projects so the two reads stay distinct.
isActive
- ? 'border-cyan/40 bg-cyan-soft text-foreground shadow-[0_0_16px_-4px_rgba(63,224,229,0.5)]'
+ ? 'border-cyan/40 bg-cyan-soft text-foreground shadow-glow-sm-cyan'
: 'border-border-strong text-foreground hover:bg-foreground/[0.04]',
)
}
@@ -783,7 +783,7 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
<Inbox className={clsx('size-4', isActive ? 'text-cyan-ink' : 'text-foreground')} />
<span className="flex-1">{t('workbench.nav.inbox')}</span>
{badge && (
- <span className="inline-flex min-w-[1.25rem] items-center justify-center rounded-full bg-cyan px-1.5 py-0.5 font-mono text-[9px] font-bold text-accent-foreground shadow-[0_0_10px_-2px_rgba(63,224,229,0.7)]">
+ <span className="inline-flex min-w-[1.25rem] items-center justify-center rounded-full bg-cyan px-1.5 py-0.5 font-mono text-[9px] font-bold text-accent-foreground shadow-glow-xs-cyan">
{badge}
</span>
)}
@@ -826,7 +826,7 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
clsx(
'group flex items-center gap-2.5 rounded-lg px-3 py-2 text-[13px] font-medium transition-colors',
isActive
- ? 'border border-mint/30 bg-mint/[0.08] text-foreground shadow-[0_0_16px_-4px_rgba(91,255,160,0.5)]'
+ ? 'border border-mint/30 bg-mint/[0.08] text-foreground shadow-glow-sm-mint'
: 'border border-transparent text-muted hover:bg-foreground/[0.04] hover:text-foreground',
)
}
diff --git a/ui/src/components/workbench/skills/SkillDetailPanel.tsx b/ui/src/components/workbench/skills/SkillDetailPanel.tsx
index 65df5d0ed..8c8e5ceee 100644
--- a/ui/src/components/workbench/skills/SkillDetailPanel.tsx
+++ b/ui/src/components/workbench/skills/SkillDetailPanel.tsx
@@ -53,7 +53,7 @@ export function SkillDetailPanel({
return (
<div className="flex flex-col gap-3.5 self-start rounded-2xl border border-border-strong bg-surface p-5">
<div className="flex items-start gap-3">
- <span className="flex size-10 shrink-0 items-center justify-center rounded-[10px] border border-mint/40 bg-mint-soft text-mint-ink shadow-[0_0_18px_-6px_rgba(91,255,160,0.5)]">
+ <span className="flex size-10 shrink-0 items-center justify-center rounded-[10px] border border-mint/40 bg-mint-soft text-mint-ink shadow-glow-sm-mint">
<WandSparkles className="size-5" />
</span>
<div className="flex min-w-0 flex-1 flex-col">
diff --git a/ui/src/components/workbench/skills/SkillRow.tsx b/ui/src/components/workbench/skills/SkillRow.tsx
index 9b6a93fe8..c2d6d8b96 100644
--- a/ui/src/components/workbench/skills/SkillRow.tsx
+++ b/ui/src/components/workbench/skills/SkillRow.tsx
@@ -26,7 +26,7 @@ export function SkillRow({ skill, selected, inherited, updateAvailable, onSelect
className={clsx(
'group flex w-full items-center gap-3 rounded-lg border px-[14px] py-3 text-left transition',
selected
- ? 'border-mint/40 bg-mint-soft shadow-[0_0_18px_-10px_rgba(91,255,160,0.6)]'
+ ? 'border-mint/40 bg-mint-soft shadow-glow-sm-mint'
: 'border-border bg-surface hover:border-border-strong hover:bg-surface-2',
inherited && 'opacity-[0.66]',
)}
diff --git a/ui/src/features/organization/OrganizationShell.tsx b/ui/src/features/organization/OrganizationShell.tsx
index e5284dd5c..023bfbfe9 100644
--- a/ui/src/features/organization/OrganizationShell.tsx
+++ b/ui/src/features/organization/OrganizationShell.tsx
@@ -170,7 +170,7 @@ function OrganizationNavbar() {
<div className="hidden items-center gap-2 sm:flex">
<div className="rounded-lg border border-mint/30 bg-mint/10 px-3 py-2">
<div className="flex items-center gap-2 text-[12px] font-semibold">
- <span className="size-2 rounded-full bg-mint shadow-[0_0_8px_rgba(91,255,160,0.8)]" />
+ <span className="size-2 rounded-full bg-mint shadow-glow-dot-mint" />
{t('organization.sidebar.cloudConnected')}
<span className="font-mono text-[10px] font-normal text-muted">
· {t('organization.sidebar.sessionRemaining', { minutes: Math.max(1, Math.ceil((session?.expires_in ?? 0) / 60)) })}
diff --git a/ui/src/index.css b/ui/src/index.css
index b433ccad4..c63fab61d 100644
--- a/ui/src/index.css
+++ b/ui/src/index.css
@@ -104,9 +104,94 @@
--radius-2xl: 20px;
--radius-3xl: 24px;
- /* Card glow shadows (matches design.pen). */
- --shadow-mint-card: 0 24px 48px -12px rgba(91, 255, 160, 0.078);
- --shadow-mint-card-lg: 0 32px 64px -12px rgba(91, 255, 160, 0.078);
+ /* Card wash shadows (matches design.pen). The colour is `--card-wash` rather
+ than a literal because this block is `@theme inline`: Tailwind substitutes
+ each entry's value into the generated utility, so a light-theme override of
+ the token itself would compile to nothing and the wash would keep the dark
+ neon on a white page. Every other entry here is the same shape for the same
+ reason -- `--color-mint: var(--mint)` and friends -- so theming happens in
+ the runtime variable, never in the token. */
+ --shadow-mint-card-sm: 0 8px 32px -8px var(--card-wash);
+ --shadow-mint-card: 0 24px 48px -12px var(--card-wash);
+ --shadow-mint-card-lg: 0 32px 64px -12px var(--card-wash);
+
+ /* The accent glow scale, read off design.pen: `dot` is the Landing Page's
+ status dot, `xs` a control track, `sm` its icon tile and the Doctor pulse,
+ `md` its nav CTA, eyebrow badge and the Dashboard hero pulse, `lg` its hero
+ button, `xl` the Welcome logo. Geometry and alpha come from those frames,
+ with one departure: the dot glows at full alpha over near-black, and ours
+ also sit on lit panels, so `dot` is clamped to 0.9 -- the brightest value
+ the call sites were already using.
+
+ `cta` is the exception that is not from design.pen. Its blur is themed
+ because a neon that reads on black barely registers over a white card
+ (owner decision 2026-08-14); its 0.6 is likewise owner-set.
+
+ The colour, unlike the blur, does NOT vary by theme. design.pen's Light
+ frame recolours the card washes above to the light brand mint and keeps
+ every glow on the dark neon, so these stay literal instead of routing
+ through a runtime variable the way `--card-wash` does. */
+ --shadow-glow-dot-mint: 0 0 8px rgba(91, 255, 160, 0.9);
+ --shadow-glow-dot-gold: 0 0 8px rgba(255, 200, 87, 0.9);
+ --shadow-glow-dot-destructive: 0 0 8px rgba(255, 107, 107, 0.9);
+
+ /* `wire` is the drop-shadow role: the Model Hub connection wires glow through
+ `filter: drop-shadow(…)`, which takes no spread, so none of the sized roles
+ above can be spelled into one. Like `dot` it is named for its use rather
+ than its size, which is what the no-spread roles have in common.
+
+ These three are a verbatim capture of what already shipped in
+ modelHubSurface.css, down to the `color-mix`, so the wires render exactly as
+ before -- the point of moving them was that a glow written as a filter
+ escaped the guard entirely, not that the light was wrong. That does leave
+ `wire` as the one role whose colour follows the theme, through `--mint` and
+ friends, while every role above stays on the dark neon by design. Aligning
+ them would repaint the wires in Light, so it is a design.pen decision and
+ not this file's to take. */
+ --shadow-glow-wire-mint: 0 0 4px color-mix(in srgb, var(--mint) 40%, transparent);
+ --shadow-glow-wire-cyan: 0 0 4px color-mix(in srgb, var(--cyan) 40%, transparent);
+ --shadow-glow-wire-violet: 0 0 4px color-mix(in srgb, var(--violet) 40%, transparent);
+
+ /* The sized rungs are derived from one rule design.pen follows, not chosen
+ one triple at a time: a glow is centred, its spread is a quarter of its
+ blur, and its colour is the accent at #5BFFA070. Five annotated frames
+ agree -- diagPulse 16/-4, heroPulse 24/-6, diagHero 32/-8, StepCard 48/-12
+ -- and welCard, at blur 64, still holds -12, so that is the cap.
+
+ Reading the rule off the design rather than off the call sites is what
+ makes the rungs land on their frames. The first cut of this scale did the
+ opposite: it took each rung from the middle of the literals it had to
+ absorb, which produced `sm` at -2px -- a spread written nowhere in
+ design.pen and nowhere in this tree -- and every 16px glow moved off its
+ frame to reach it. glowScale.test.mjs asserts the rule so a rung cannot be
+ nudged back off it.
+
+ The rungs stop at the blurs design.pen actually draws. `xs` and `xl` exist
+ because 12px and 48px glows are in the tree; without them a hero logo gets
+ snapped to 32px, which is not a token conversion but a redesign. */
+ --shadow-glow-xs-mint: 0 0 12px -3px rgba(91, 255, 160, 0.44);
+ --shadow-glow-xs-cyan: 0 0 12px -3px rgba(63, 224, 229, 0.44);
+
+ --shadow-glow-sm-mint: 0 0 16px -4px rgba(91, 255, 160, 0.44);
+ --shadow-glow-sm-cyan: 0 0 16px -4px rgba(63, 224, 229, 0.44);
+ --shadow-glow-sm-violet: 0 0 16px -4px rgba(124, 91, 255, 0.44);
+ --shadow-glow-sm-gold: 0 0 16px -4px rgba(255, 200, 87, 0.44);
+
+ --shadow-glow-md-mint: 0 0 24px -6px rgba(91, 255, 160, 0.44);
+ --shadow-glow-md-cyan: 0 0 24px -6px rgba(63, 224, 229, 0.44);
+ --shadow-glow-md-violet: 0 0 24px -6px rgba(124, 91, 255, 0.44);
+ --shadow-glow-md-gold: 0 0 24px -6px rgba(255, 200, 87, 0.44);
+
+ --shadow-glow-lg-mint: 0 0 32px -8px rgba(91, 255, 160, 0.44);
+ --shadow-glow-lg-cyan: 0 0 32px -8px rgba(63, 224, 229, 0.44);
+ --shadow-glow-lg-violet: 0 0 32px -8px rgba(124, 91, 255, 0.44);
+
+ --shadow-glow-xl-mint: 0 0 48px -12px rgba(91, 255, 160, 0.44);
+
+ --shadow-glow-cta-mint: 0 0 var(--brand-glow-blur) -4px rgba(91, 255, 160, 0.6);
+ --shadow-glow-cta-cyan: 0 0 var(--brand-glow-blur) -4px rgba(63, 224, 229, 0.6);
+ --shadow-glow-cta-violet: 0 0 var(--brand-glow-blur) -4px rgba(124, 91, 255, 0.6);
+ --shadow-glow-cta-gold: 0 0 var(--brand-glow-blur) -4px rgba(255, 200, 87, 0.6);
}
:root,
@@ -193,6 +278,11 @@
because it is the one part of that glow that differs per theme. */
--brand-glow-blur: 16px;
+ /* Colour of the card wash shadows (`--shadow-mint-card*`). design.pen writes it
+ as the frame's own brand mint at 0.078, which is why it is the one part of
+ those shadows that moves between themes. */
+ --card-wash: rgba(91, 255, 160, 0.078);
+
/* Page-family gradients (mirror design.pen 1:1). Layers ordered top-most first. */
--gradient-console:
radial-gradient(50% 40% at 5% 5%, rgba(91, 255, 160, 0.20), rgba(91, 255, 160, 0) 100%),
@@ -338,9 +428,9 @@
--bg-page: var(--gradient-console);
- /* Light card glow — much softer than dark. */
- --shadow-mint-card: 0 12px 24px -16px rgba(16, 185, 129, 0.20);
- --shadow-mint-card-lg: 0 16px 32px -16px rgba(16, 185, 129, 0.22);
+ /* design.pen's Light frame keeps the dark frame's geometry and 0.078 and
+ swaps only the hue to the light brand mint. */
+ --card-wash: rgba(16, 185, 129, 0.078);
/* Wider CTA glow than dark: the same neon spreads far less over a white card,
so 16px read as almost nothing here (owner decision 2026-08-14). */
@@ -442,9 +532,9 @@
--bg-page: var(--gradient-console);
- /* Light card glow — much softer than dark. */
- --shadow-mint-card: 0 12px 24px -16px rgba(16, 185, 129, 0.20);
- --shadow-mint-card-lg: 0 16px 32px -16px rgba(16, 185, 129, 0.22);
+ /* design.pen's Light frame keeps the dark frame's geometry and 0.078 and
+ swaps only the hue to the light brand mint. */
+ --card-wash: rgba(16, 185, 129, 0.078);
/* Wider CTA glow than dark: the same neon spreads far less over a white card,
so 16px read as almost nothing here (owner decision 2026-08-14). */