From 45a096d53ddb46afaf9ef3402b70aeb2326c5255 Mon Sep 17 00:00:00 2001 From: ArthurArthurArthur0817 Date: Tue, 17 Nov 2026 01:42:26 +0800 Subject: [PATCH] Mechanize UI color token enforcement Per review, extend theme.test.js to enforce CSS token usage. Prevent stacked var() declarations and strictly scope recording.css color literals to its own :root. Change-Id: I97464675e6d5bbbae3607e2989ba12e16b6f31cd --- tests/browser/theme.test.js | 188 ++++++++++++++++++++++++++++++++---- web/recording/recording.css | 12 ++- 2 files changed, 179 insertions(+), 21 deletions(-) diff --git a/tests/browser/theme.test.js b/tests/browser/theme.test.js index 14804622f..72edbe464 100644 --- a/tests/browser/theme.test.js +++ b/tests/browser/theme.test.js @@ -30,6 +30,11 @@ const sheets = Object.fromEntries( components.map((name) => [name, stripCssComments(read(`web/${name}`))]), ); const theme = stripCssComments(read("web/theme.css")); +const recordingCss = stripCssComments(read("web/recording/recording.css")); +// Extract theme tokens that represent length values (e.g., --focus-width) +const lengthTokens = new Set( + captures(theme, /(--[\w-]+)\s*:\s*-?[\d.]+[a-z%]*\s*;/g), +); /// Every CSS named color (CSS Color 4, 148 names). A system color such as /// Highlight is left out: it is the platform's, and forced-colors rules need it. @@ -59,6 +64,86 @@ const CSS_NAMED_COLORS = ` .trim() .split(/\s+/); +const colorFunction = + /\b(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\(|#[0-9a-f]{3,8}\b/i; +const namedColor = new RegExp(`\\b(?:${CSS_NAMED_COLORS.join("|")})\\b`, "i"); + +/// The declarations in a sheet that paint a color literal. Declarations, not +/// lines: a value wrapped onto the lines after its property is still read, and +/// a selector such as `#face-check` is not a hex color. +const paintedColors = (name, css) => + [...css.matchAll(/\{([^{}]*)\}/g)].flatMap(([, body]) => + body.split(";").flatMap((declaration) => { + const [, property, value] = + declaration.match(/^\s*([\w-]+)\s*:([\s\S]*)$/) ?? []; + // A mask paints coverage, not color: its stops are alpha only. + if (!property || /^(?:-webkit-)?mask$/.test(property)) return []; + if (!colorFunction.test(value) && !namedColor.test(value)) return []; + return [`${name}: ${property}:${value.replace(/\s+/g, " ")}`]; + }), + ); + +const SHORTHAND_RESETS = { + background: ["background-color"], + border: [ + "border-color", + "border-top-color", + "border-right-color", + "border-bottom-color", + "border-left-color", + ], + "border-color": [ + "border-top-color", + "border-right-color", + "border-bottom-color", + "border-left-color", + ], + "border-top": ["border-top-color"], + "border-right": ["border-right-color"], + "border-bottom": ["border-bottom-color"], + "border-left": ["border-left-color"], + outline: ["outline-color"], +}; + +const expandsTo = (property) => [ + property, + ...(SHORTHAND_RESETS[property] ?? []), +]; + +const shadowedTokenReads = (name, css) => { + const offending = []; + for (const [, body] of css.matchAll(/\{([^{}]*)\}/g)) { + const seen = new Map(); + for (const declaration of body.split(";")) { + const [, property, value] = + declaration.match(/^\s*([\w-]+)\s*:([\s\S]*)$/) ?? []; + if (!property) continue; + const hasVar = [...value.matchAll(/var\((--[\w-]+)/g)].some( + ([, token]) => !lengthTokens.has(token), + ); + const targets = expandsTo(property); + const conflict = targets.some((target) => seen.get(target) && !hasVar); + if (conflict) { + offending.push( + `${name} declares ${property} twice (or via shorthand) in one rule, one of them dropping a token read: ${value.trim()}`, + ); + } + for (const target of targets) { + seen.set(target, hasVar); + } + } + } + return offending; +}; + +const unusedThemeTokens = (themeCss, allCss) => { + const themed = declared(themeCss); + const readTokens = new Set( + captures(allCss, /var\(\s*(--[\w-]+)\s*(?=[,)])/g), + ); + return [...themed].filter((token) => !readTokens.has(token)); +}; + /// The stylesheets a page links, in order, whatever order a writes its /// attributes in. const linkedSheets = (html) => @@ -100,26 +185,95 @@ test("the shipped override file declares nothing", () => { }); test("component stylesheets paint no color a theme cannot override", () => { - const colorFunction = - /\b(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\(|#[0-9a-f]{3,8}\b/i; - const namedColor = new RegExp(`\\b(?:${CSS_NAMED_COLORS.join("|")})\\b`, "i"); - // Declarations, not lines: a value wrapped onto the lines after its property - // is still read, and a selector such as `#face-check` is not a hex color. for (const [name, css] of Object.entries(sheets)) { - for (const [, body] of css.matchAll(/\{([^{}]*)\}/g)) { - for (const declaration of body.split(";")) { - const [, property, value] = - declaration.match(/^\s*([\w-]+)\s*:([\s\S]*)$/) ?? []; - // A mask paints coverage, not color: its stops are alpha only. - if (!property || /^(?:-webkit-)?mask$/.test(property)) continue; - const where = `${name}: ${property}:${value.replace(/\s+/g, " ")}`; - assert.doesNotMatch(value, colorFunction, where); - assert.doesNotMatch(value, namedColor, where); - } - } + assert.deepEqual(paintedColors(name, css), [], `${name} paints colors`); } }); +test("a declaration does not shadow a token read in the same rule", () => { + // A later declaration (including shorthands) must not drop an earlier token read. + for (const [name, css] of Object.entries(sheets)) { + assert.deepEqual(shadowedTokenReads(name, css), []); + } + assert.deepEqual(shadowedTokenReads("recording.css", recordingCss), []); + assert.ok( + shadowedTokenReads( + "synthetic.css", + ".card { background-color: var(--page); background: none; }", + ).length > 0, + "shorthand background must be caught when dropping background-color token read", + ); + assert.ok( + shadowedTokenReads( + "synthetic.css", + ".card { border-top-color: var(--accent); border-top: none; }", + ).length > 0, + "side shorthand border-top must be caught when dropping border-top-color token read", + ); + assert.ok( + shadowedTokenReads( + "synthetic.css", + ".card { outline-color: var(--accent); outline: var(--focus-width) solid; }", + ).length > 0, + "outline shorthand reading a length token must be caught when shadowing outline-color", + ); + assert.ok( + shadowedTokenReads( + "synthetic.css", + ".card { box-shadow: var(--shadow-card); box-shadow: none; }", + ).length > 0, + "box-shadow reset must be caught when dropping a shadow token read", + ); +}); + +test("recording.css confines color literals and token declarations to its own :root", () => { + let rootBlock = ""; + const recordingRest = recordingCss.replace( + /:root\s*\{([^{}]*)\}/, + (_, body) => { + rootBlock = body; + return `{${body.replace(/--[\w-]+\s*:[^;]*;/g, "")}}`; + }, + ); + assert.deepEqual( + paintedColors("recording.css", recordingRest), + [], + "recording.css paints colors outside variables", + ); + assert.deepEqual( + [...declared(recordingRest)], + [], + "recording.css declares tokens outside :root", + ); + const recordingDeclared = declared(rootBlock); + const missing = [ + ...new Set(captures(recordingCss, /var\(\s*(--[\w-]+)\s*(?=[,)])/g)), + ].filter((token) => !recordingDeclared.has(token)); + assert.deepEqual(missing, [], "recording.css reads undeclared tokens"); +}); + +test("every theme token is read by at least one component or derived token", () => { + const allCss = [...Object.values(sheets), theme].join("\n"); + assert.deepEqual( + unusedThemeTokens(theme, allCss), + [], + "theme.css declares unused tokens", + ); + assert.deepEqual( + unusedThemeTokens(`${theme}\n:root { --obsolete: #fff; }`, allCss), + ["--obsolete"], + "orphan token in theme.css must be caught", + ); + assert.deepEqual( + unusedThemeTokens( + `${theme}\n:root { --fallback-read: #fff; }`, + `${allCss}\n.card { color: var(--fallback-read, currentColor); }`, + ), + [], + "a token read with a fallback must count as read", + ); +}); + test("a component sheet neither redeclares a theme role nor reads an undeclared one", () => { const themed = declared(theme); // peer.css sits on top of styles.css, so a component may read a layout @@ -133,7 +287,7 @@ test("a component sheet neither redeclares a theme role nor reads an undeclared assert.deepEqual(redeclared, [], `${name} redeclares theme roles`); // A read with a fallback, var(--x, value), is a value scripts set at // runtime (a measured height, a progress fraction), not a theme role. - const missing = [...new Set(captures(css, /var\((--[\w-]+)\)/g))].filter( + const missing = [...new Set(captures(css, /var\(\s*(--[\w-]+)\)/g))].filter( (token) => !known.has(token), ); assert.deepEqual(missing, [], `${name} reads undeclared tokens`); diff --git a/web/recording/recording.css b/web/recording/recording.css index e19c7711e..11e64d314 100644 --- a/web/recording/recording.css +++ b/web/recording/recording.css @@ -10,6 +10,10 @@ --edge: #232b34; --pass: #3fb950; --fail: #f85149; + --page: #0d1117; + --paper: #ffffff; + --video-fill: #000; + --avatar-fallback: #33332c; } * { @@ -25,7 +29,7 @@ body { margin: 0; - background: #0d1117; + background: var(--page); color: var(--ink); font: 16px/1.5 ui-monospace, @@ -64,7 +68,7 @@ body { display: block; width: 100%; aspect-ratio: 1600 / 1000; - background: #ffffff; + background: var(--paper); border: 1px solid var(--edge); border-radius: 8px; } @@ -125,7 +129,7 @@ body { .candidate { width: 100%; height: 100%; - background: #000; + background: var(--video-fill); border: 1px solid var(--edge); border-radius: 8px; object-fit: cover; @@ -171,7 +175,7 @@ body { width: 48px; height: 48px; border-radius: 999px; - background: #33332c; + background: var(--avatar-fallback); color: var(--ink); font-weight: 700; }