From f0e1e2bff0d5f902d5621240fedc6c08d11f99e5 Mon Sep 17 00:00:00 2001 From: rdrake Date: Sun, 15 Nov 2026 15:39:44 +0000 Subject: [PATCH 1/3] Themes: write the contract down and check it in CI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit themes.md § The theme contract: the tokens a theme sets, the attributes the app puts on for every theme (data-motion-rest was in none of the docs), and what a restated selector costs. test/tests/themeContract.ts reads the files, so it runs in CI where the browser scenarios cannot: every custom property a theme declares is read by client/ (panasync's --ansi-cyan-dim was not, and is gone), and each theme's :root tokens, resolved through its imports in light and dark and lowered to sRGB by Lightning CSS, hold 4.5:1 for text, muted text and links on the window and chat, on a highlighted row and on the rail, and 3:1 for the join line. Day's link blue is the one recorded exception. Also drops twenty rules in style.css that no component uses (the old settings sync panel, the push state dots, the session rows). --- client/css/style.css | 127 +----------- client/themes/panasync.css | 1 - client/themes/zelenzy.css | 7 +- docs/resources/themes.md | 25 +++ package.json | 1 + pnpm-lock.yaml | 3 + test/tests/themeContract.ts | 381 ++++++++++++++++++++++++++++++++++++ 7 files changed, 415 insertions(+), 130 deletions(-) create mode 100644 test/tests/themeContract.ts diff --git a/client/css/style.css b/client/css/style.css index fca9c3aa7..be5eacf9b 100644 --- a/client/css/style.css +++ b/client/css/style.css @@ -4470,35 +4470,6 @@ html[data-reduce-motion] #chat .media-veil-main:hover .media-veil-icon { width: 100%; } -#settings .settings-sync-panel { - padding: 10px; - margin-bottom: 16px; - border-radius: 2px; - background-color: #d9edf7; - color: #31708f; -} - -#settings .settings-sync-panel p:last-child { - margin-bottom: 0; -} - -#settings .settings-sync-panel .btn { - color: #007bff; - border-color: #007bff; - margin-bottom: 0; -} - -#settings .settings-sync-panel .btn:hover, -#settings .settings-sync-panel .btn:focus { - background-color: #007bff; - color: #fff; -} - -#settings .settings-sync-panel .btn:active, -#settings .settings-sync-panel .btn:focus { - box-shadow: 0 0 0 3px rgb(0 123 255 / 50%); -} - #settings .opt { display: block; padding-block: 5px; @@ -10332,71 +10303,7 @@ html[data-reduce-motion] #form .upload-bar-track.indeterminate .upload-bar-fill color: var(--body-color); } -/* Settings → Push Notifications: the on/off indicator dot + per-network rows */ -.push-state { - display: flex; - align-items: center; - gap: 8px; - margin-bottom: 8px; -} - -.push-state-dot { - width: 10px; - height: 10px; - border-radius: 50%; - background: var(--body-color-muted); - flex: 0 0 auto; -} - -.push-state-subscribed { - background: #2ea043; -} - -.push-state-unsubscribed, -.push-state-server-unsupported, -.push-state-not-installed { - background: #9e6a03; -} - -.push-state-denied, -.push-state-blocked, -.push-state-unsupported { - background: #c93c37; -} - -.push-networks { - margin: 8px 0 12px; -} - -.push-network { - padding: 5px 0; - border-bottom: 1px solid var(--body-color-muted); - display: flex; - align-items: baseline; - gap: 8px; -} - -.push-network-state { - margin-inline-start: auto; - font-size: 0.8125rem; - font-weight: bold; - color: var(--body-color-muted); - white-space: nowrap; -} - -.push-net-on { - color: #2ea043; -} - -.push-net-off, -.push-net-unsupported { - color: var(--body-color-muted); -} - -.push-net-ready { - color: #9e6a03; -} - +/* Settings → Notifications: the hints under its switches. */ .push-networks-hint, .keepalive-hint, .dnd-schedule-hint { @@ -10432,38 +10339,6 @@ html[data-reduce-motion] #form .upload-bar-track.indeterminate .upload-bar-fill border-radius: 0.25rem; } -.session-row { - padding: 6px 0; - border-bottom: 1px solid var(--body-color-muted); -} - -.session-state { - display: inline-block; - min-width: 4rem; - padding: 0 6px; - border-radius: 3px; - font-size: 0.8125rem; - font-weight: bold; - text-align: center; - margin-inline-end: 8px; - color: #fff; - background: var(--body-color-muted); -} - -.session-held { - background: #2ea043; -} - -.session-active { - background: #388bfd; -} - -.session-info { - color: var(--body-color-muted); - font-size: 0.8125rem; - margin-top: 2px; -} - /* The Mac app's sizes (data-platform="macos", set before the first paint by * loading-error-handlers.js): menus at AppKit's metrics, 13px text in 22px * items, and the sidebar's rows AppKit's shape, whatever the theme. A row's diff --git a/client/themes/panasync.css b/client/themes/panasync.css index 386bf1832..ab68c27b1 100644 --- a/client/themes/panasync.css +++ b/client/themes/panasync.css @@ -24,7 +24,6 @@ --ansi-black: #000; --ansi-blue: #00a; --ansi-bright-blue: #55f; - --ansi-cyan-dim: #0aa; --ansi-cyan: #5ff; --ansi-green: #5f5; --ansi-yellow: #ff5; diff --git a/client/themes/zelenzy.css b/client/themes/zelenzy.css index e31fa9597..13d8fbb0c 100644 --- a/client/themes/zelenzy.css +++ b/client/themes/zelenzy.css @@ -158,14 +158,15 @@ /* Only the chat window has the terminal panes. The dialogs — settings, help, * the connect form, the changelog, search results, the header popovers — are XP dialogs on the * face grey: the window tokens are re-mapped on those windows, so everything - * in them that reads a token follows. Black on the face 17.4:1, muted 5.6:1, - * the selection blue for links and buttons 4.6:1. */ + * in them that reads a token follows. Black on the face 17.4:1, muted 5.6:1; + * links take the selection blue a step darker, 4.9:1 (the blue itself is + * 4.3:1, too low for text), and buttons the blue itself. */ :is(.window:not(#chat), .header-popover) { --window-bg-color: var(--win-face); --body-color: #000; --body-color-muted: #5a5a5a; --window-heading-color: #000; - --link-color: var(--win-select); + --link-color: #2d62b6; --button-color: var(--win-select); --button-text-color-hover: #fff; diff --git a/docs/resources/themes.md b/docs/resources/themes.md index 7a365487d..880ea8fcc 100644 --- a/docs/resources/themes.md +++ b/docs/resources/themes.md @@ -85,6 +85,31 @@ Five themes come as a light/dark pair: Coffee/Creama, Cobalt/Frost, Princess\_/P `style.css` greys an own message's text to `--body-color-muted`, TheLounge's look, and a theme was free to band the row instead (the Princess pair). The grey is hard to read on an iPhone under a dark theme — a system setting there flattens it into the background, which Android and a desk do not do — so the choice is the user's, not the theme's: Settings → Appearance → Your own messages picks **greyed text** (the default, every theme as it was), a **highlighted row** (the text like everyone else's, the row on a band) or **nothing**. The value lands on `` (`client/js/helpers/ownMessages.ts`, `settings.ts`) and the three looks are rules in `style.css`, so no theme file needs to know about it. The three do not overlap: a band a theme paints on `.msg.self` itself (the Princess pair, Keeki) shows under **highlighted row** only, in the colour the theme names with `--own-bg` (without one the band is the text colour at 7% over the row). Own join and mode lines are `.self` as well and are left to the theme in every mode: the band is for what was said. Browser check: `tools/scenarios/own-messages.mjs` (coffee and princess, every setting, a reload). +## The theme contract + +What a theme may rely on, and what is checked. A theme is plain CSS loaded after `style.css` and before the user's own stylesheet; it changes the app's look through three things only. + +**Tokens.** Custom properties on `:root`. A theme on coffee's rules (every theme but `day` and `morning`) sets the tokens coffee and `style.css` read, in groups: the surfaces (`--chat-bg`, `--window-bg-color`, `--body-bg-color`, `--canvas-bg-color`, `--menu-bg`, `--composer-bg`), the text (`--chat-fg`, `--chat-fg-muted`, `--chat-fg-faint`, `--body-color`, `--body-color-muted`, `--link-color`), the rail (`--rail-*`), what a message means (`--event-join`, `--event-quit`, `--nick-default`, `--notice-color`, `--action-color`, `--highlight-bg-color`, and `--own-bg` where it bands own messages), the notice boxes (`--note-*`, `--warn-*`, `--error-*`, `--ok-*`), the tints (`--tint-soft`, `--tint-strong`, `--focus-ring`, and the optional `--accent-tint-*`) and the code colours (`--tok-*`). Coffee maps them onto TheLounge's names (`--body-color`, `--window-bg-color`, …), which is what `style.css` reads; `day` and `morning` set TheLounge's names directly. A token nothing reads is a mistake, and so is a pair that misses its floor. + +**Attributes on ``**, set by the app for every theme, for a theme's selectors: + +| Attribute | Values | Means | +| ------------------------------------ | ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `data-reduce-motion` | present | Reduce Motion: anything that moves goes behind `:not([data-reduce-motion])` (`helpers/systemAccessibility.ts`) | +| `data-contrast` | `more` | Increase Contrast: `style.css` folds the muted text tokens into the full colour; a theme that re-maps one below `:root` restates the reset (`test/tests/themeContrast.ts`) | +| `data-motion-rest` | present | Nobody attends to the window, or the device saves power: a theme's endless animations pause (`animation-play-state: paused`), as Keeki's drift does (`themeScene.ts` `installThemeSceneHooks`) | +| `data-own-messages` | `muted`, `band`, `plain` | How the user wants their own lines (§ Your own messages) | +| `data-input` | `pointer`, `touch` | The last pointer, for hover against press affordances (`helpers/inputModality.ts`) | +| `data-shell`, `data-platform` | `desktop`, `native`; `ios`, `android`, `macos`, `windows`, `linux` | The app around the page; absent in a browser (`native.ts`) | +| `data-system-text`, `data-font-size` | present; the font-size step | The text size setting (`helpers/systemTextSize.ts`, `settings.ts`) | +| `dir`, `lang` | | The interface language: new CSS uses logical properties (`docs/resources/i18n.md`) | + +`ps` adds its own (`data-ps-light`, `data-ps-text`, `data-ps-words`), which no other theme should read. + +**Selectors.** Where `style.css` still has a literal colour (the sidebar rows and badges, header icons, the input and context menu, message-type icons, the mIRC colour table, nick slots `.user.color-1`…`-32`), a theme restates that selector. Prefer a token where one exists: a restated selector is coupled to the markup, a token is not. + +**Checked without a browser** by `test/tests/themeContract.ts`, in CI: every custom property a theme declares is read by `client/` (ps's switched-off animal slots excepted), and each theme's resolved tokens, light and dark, hold their floors on the surfaces the app paints them on: text, muted text and links at 4.5:1 on the window and the chat, text on a highlighted row, the rail's text on the rail, the join line at 3:1. A translucent surface is measured over what it is painted on (a highlighted row over the window, the window, the chat and the rail over the page's own background), and a surface with nothing opaque under it in CSS must be named in the test as see-through. Besides `:root`, every block that re-maps both sides of a pair is checked as its own surface, with the blocks it sits inside: zelenzy's dialogs, ps by night and its night chat. Glass and pictures (ps, the macos material) are not a flat colour, so those two are measured in the browser as well (`tools/scenarios/theme-ps.mjs`, `themes.mjs`). Known exceptions are listed in the test with their reason: `day`'s link green is TheLounge's own. Not checked yet: muted text and links on a highlighted row, which several themes miss today (day, princess, morning, creama, frost). + ## Checking a theme `pnpm test` never loads a stylesheet. Build, serve `public/`, and look (`docs/resources/browser-testing.md`); the Appearance dropdown switches live. `tools/scenarios/themes.mjs` drives that dropdown through every theme against the dev ircd, checks the stylesheet link, the stored name and the browser chrome colour, measures the pairs above on the four handoff themes (text, timestamps, links, the join line, a nick on a highlighted row at ≥ 4.5:1; icons and the placeholder at ≥ 3:1) from computed styles, and leaves a screenshot of the chat under each theme. diff --git a/package.json b/package.json index 2a3dca48a..9454a09b6 100644 --- a/package.json +++ b/package.json @@ -87,6 +87,7 @@ "eruda": "3.4.3", "fuzzy": "0.1.3", "gemoji": "8.1.0", + "lightningcss": "1.33.0", "mocha": "12.0.3", "mousetrap": "1.6.5", "normalize.css": "8.0.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2072dad3b..ba7f9f2e8 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -120,6 +120,9 @@ importers: gemoji: specifier: 8.1.0 version: 8.1.0 + lightningcss: + specifier: 1.33.0 + version: 1.33.0 mocha: specifier: 12.0.3 version: 12.0.3 diff --git a/test/tests/themeContract.ts b/test/tests/themeContract.ts new file mode 100644 index 000000000..5aedbe39d --- /dev/null +++ b/test/tests/themeContract.ts @@ -0,0 +1,381 @@ +import {expect} from "chai"; +import fs from "fs"; +import path from "path"; +import {transform} from "lightningcss"; + +// The theme contract (docs/resources/themes.md § The theme contract), checked +// without a browser so it runs in CI: what a theme declares is read by +// something, and the colour pairs the app paints with each theme's tokens +// hold their contrast floor. tools/scenarios/themes.mjs measures rendered +// pages too, but needs a running ircd; this reads the files. + +const ROOT = process.cwd(); +const THEMES = path.join(ROOT, "client", "themes"); +const themeNames = fs + .readdirSync(THEMES) + .filter((f) => f.endsWith(".css")) + .map((f) => f.slice(0, -4)); + +const stripComments = (css: string) => css.replace(/\/\*[\s\S]*?\*\//g, ""); + +type Block = {prelude: string; body: string; at: string}; + +/** Every block with its prelude, its own body and the at-rules around it. */ +function blocks(css: string): Block[] { + const text = stripComments(css); + const out: Block[] = []; + const stack: {prelude: string; pos: number}[] = []; + let start = 0; + + for (let i = 0; i < text.length; i++) { + if (text[i] === "{") { + stack.push({prelude: text.slice(start, i).replace(/\s+/g, " ").trim(), pos: i + 1}); + start = i + 1; + } else if (text[i] === "}") { + const top = stack.pop(); + + if (top) { + out.push({ + prelude: top.prelude, + body: text.slice(top.pos, i), + at: stack.map((s) => s.prelude).join(" "), + }); + } + + start = i + 1; + } else if (text[i] === ";" && stack.length === 0) { + start = i + 1; + } + } + + return out; +} + +/** The custom properties a block body declares (its nested blocks left out). */ +function customProperties(body: string): Record { + const out: Record = {}; + + for (const decl of body.replace(/\{[^}]*\}/g, "").split(";")) { + const colon = decl.indexOf(":"); + const name = decl.slice(0, colon).trim(); + + if (colon > 0 && name.startsWith("--")) { + out[name] = decl.slice(colon + 1).trim(); + } + } + + return out; +} + +/** A theme and what it @imports, in cascade order, for one colour scheme. */ +function chain(file: string, scheme: "light" | "dark", seen = new Set()): string[] { + if (seen.has(file)) { + return []; + } + + seen.add(file); + const css = fs.readFileSync(path.join(THEMES, file), "utf8"); + const out: string[] = []; + + for (const m of stripComments(css).matchAll(/@import\s+"([^"]+)"\s*([^;]*);/g)) { + if (!m[2].trim() || m[2].includes(`prefers-color-scheme: ${scheme}`)) { + out.push(...chain(m[1], scheme, seen)); + } + } + + out.push(css); + return out; +} + +const inScheme = (at: string, scheme: "light" | "dark") => + !at.includes("prefers-color-scheme") || at.includes(`prefers-color-scheme: ${scheme}`); + +type Surface = {where: string; tokens: Record; own?: Set}; + +/** The tokens on :root once style.css and the theme's chain have cascaded, then each other + * block of the theme's chain that re-maps one of `names` (zelenzy's dialogs, ps by night, a + * contrast variant), as :root's tokens with that block's on top; `own` is what it re-maps. */ +function surfaces(theme: string, scheme: "light" | "dark", names: Set): Surface[] { + const base = fs.readFileSync(path.join(ROOT, "client", "css", "style.css"), "utf8"); + const themeCss = chain(`${theme}.css`, scheme); + const root: Record = {}; + const variants: Surface[] = []; + + for (const css of [base, ...themeCss]) { + for (const b of blocks(css)) { + if ( + b.prelude === ":root" && + (!b.at || b.at.includes(`prefers-color-scheme: ${scheme}`)) + ) { + Object.assign(root, customProperties(b.body)); + } + } + } + + // Every block with the same selector and conditions is one variant (ps + // declares its night palette across several). + const byWhere = new Map>(); + + for (const css of themeCss) { + for (const b of blocks(css)) { + if (b.prelude !== ":root" && !b.prelude.startsWith("@") && inScheme(b.at, scheme)) { + const where = b.at ? `${b.at} ${b.prelude}` : b.prelude; + byWhere.set(where, {...byWhere.get(where), ...customProperties(b.body)}); + } + } + } + + for (const [where, props] of byWhere) { + if (Object.keys(props).some((n) => names.has(n))) { + // A block scoped inside another variant's selector (ps's night + // chat under its night :root) inherits that variant's tokens too. + const outer = [...byWhere.keys()] + .filter( + (w) => + w !== where && where.startsWith(w) && /^[\s:[]/.test(where.slice(w.length)) + ) + .sort((a, b) => a.length - b.length) + .map((w) => byWhere.get(w)); + variants.push({ + where, + tokens: Object.assign({}, root, ...outer, props), + own: new Set(Object.keys(props)), + }); + } + } + + return [{where: ":root", tokens: root}, ...variants]; +} + +/** A value with every var() replaced, fallbacks included; undefined if one is missing. */ +function resolve(tokens: Record, value: string, depth = 0): string | undefined { + if (depth > 20) { + return undefined; + } + + let missing = false; + const out = value.replace( + /var\((--[\w-]+)(?:,\s*([^()]*(?:\([^()]*\))?[^()]*))?\)/g, + (_, name: string, fallback?: string) => { + const next = tokens[name] ?? fallback; + const resolved = next === undefined ? undefined : resolve(tokens, next, depth + 1); + + if (resolved === undefined) { + missing = true; + return ""; + } + + return resolved; + } + ); + + return missing ? undefined : out; +} + +type RGBA = [number, number, number, number]; + +/** Any CSS colour as sRGB: Lightning CSS lowers oklch(), color-mix() and the rest for an old + * target, then reads the lowered colour back (a name such as navy included) through a visitor. */ +function toRGBA(value: string): RGBA | undefined { + if (/currentcolor/i.test(value)) { + return undefined; + } + + const lowered = transform({ + filename: "colour.css", + code: Buffer.from(`a{color:${value}}`), + minify: true, + targets: {safari: 9 << 16}, + }).code.toString(); + const colour = /color:([^;}]+)/.exec(lowered)?.[1].trim() ?? ""; + + // light-dark() and the like lower to var() pairs, which are not one colour. + if (!colour || colour.includes("var(")) { + return undefined; + } + + let rgba: RGBA | undefined; + transform({ + filename: "colour.css", + code: Buffer.from(`a{color:${colour}}`), + visitor: { + Color(c) { + if (c.type === "rgb") { + rgba = [c.r, c.g, c.b, c.alpha]; + } + + return c; + }, + }, + }); + return rgba; +} + +const over = (fg: RGBA, bg: RGBA): RGBA => [ + fg[0] * fg[3] + bg[0] * (1 - fg[3]), + fg[1] * fg[3] + bg[1] * (1 - fg[3]), + fg[2] * fg[3] + bg[2] * (1 - fg[3]), + 1, +]; + +const luminance = (c: RGBA) => + [c[0], c[1], c[2]] + .map((x) => x / 255) + .map((x) => (x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4)) + .reduce((sum, x, i) => sum + x * [0.2126, 0.7152, 0.0722][i], 0); + +function contrast(a: RGBA, b: RGBA): number { + const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x); + return (hi + 0.05) / (lo + 0.05); +} + +describe("the theme contract (themes.md § The theme contract)", function () { + describe("every custom property a theme declares is read by something", function () { + const walk = (dir: string): string[] => + fs.readdirSync(dir, {withFileTypes: true}).flatMap((e) => { + const p = path.join(dir, e.name); + return e.isDirectory() ? walk(p) : /\.(css|ts|vue|js)$/.test(e.name) ? [p] : []; + }); + const sources = walk(path.join(ROOT, "client")) + .map((f) => stripComments(fs.readFileSync(f, "utf8"))) + .join("\n"); + const read = new Set([ + ...[...sources.matchAll(/var\(\s*(--[\w-]+)/g)].map((m) => m[1]), + // Read or written by name from script (getPropertyValue, setProperty). + ...[...sources.matchAll(/["'`](--[\w-]+)["'`]/g)].map((m) => m[1]), + ]); + // ps's animals are switched off, not removed (themes.md § The animals): + // their slots stay declared for the block that brings them back. + const KEPT = /^--ps-(horse|deer|puppy|bunny|kitten|frog|ladybug|bird)(-far|-h)?$/; + + for (const theme of themeNames) { + it(theme, function () { + const css = stripComments( + fs.readFileSync(path.join(THEMES, `${theme}.css`), "utf8") + ); + const declared = new Set( + [...css.matchAll(/(?:^|[;{\s])(--[\w-]+)\s*:/g)].map((m) => m[1]) + ); + const unread = [...declared].filter((name) => !read.has(name) && !KEPT.test(name)); + expect(unread, `${theme}.css declares what nothing reads`).to.deep.equal([]); + }); + } + }); + + describe("each theme's tokens hold their contrast floor", function () { + // [surface, ink, floor]: what the app paints the token on, at WCAG's + // 4.5:1 for text and 3:1 for the join line's marks. + const PAIRS: [string, string, number][] = [ + ["--window-bg-color", "--body-color", 4.5], + ["--window-bg-color", "--body-color-muted", 4.5], + ["--window-bg-color", "--link-color", 4.5], + ["--highlight-bg-color", "--body-color", 4.5], + ["--chat-bg", "--chat-fg", 4.5], + ["--chat-bg", "--chat-fg-muted", 4.5], + ["--chat-bg", "--event-join", 3], + ["--rail-bg-top", "--rail-fg", 4.5], + ]; + // Known and recorded, not to be copied: day is TheLounge's original + // light theme, kept as it was (docs/projects/accessibility.md). + const KNOWN: Record = { + "day --link-color on --window-bg-color": "TheLounge's own link green, 3.0:1", + }; + + // What each surface is painted over, out to the page's own canvas: a + // translucent surface is measured on what shows through it. + const GROUND: Record = { + "--highlight-bg-color": "--window-bg-color", + "--window-bg-color": "--body-bg-color", + "--chat-bg": "--body-bg-color", + "--rail-bg-top": "--body-bg-color", + }; + // Surfaces with nothing opaque under them in CSS (a shell's material or a + // scene would show through) have no ratio to compute from the files. None + // do today; one added here is a decision, not an accident. + const SEE_THROUGH = new Set(); + const LOUNGE_ONLY = new Set(["day", "morning"]); + const names = new Set(PAIRS.flatMap(([surface, ink]) => [surface, ink])); + + for (const theme of themeNames) { + it(theme, function () { + const failures: string[] = []; + const seeThrough = new Set(); + let checked = 0; + + for (const scheme of ["light", "dark"] as const) { + for (const {where, tokens, own} of surfaces(theme, scheme, names)) { + const colour = (token: string) => { + const value = resolve(tokens, tokens[token]); + const rgba = value && toRGBA(value); + expect( + rgba, + `${theme} ${token} in ${where} resolves (${value})` + ).to.not.equal(undefined); + return rgba as RGBA; + }; + // The surface laid over its grounds; undefined if it stays see-through. + const ground = (token: string): RGBA | undefined => { + const fill = colour(token); + const under = GROUND[token]; + + if (fill[3] >= 1) { + return fill; + } + + const below = + under && tokens[under] !== undefined ? ground(under) : undefined; + return below && over(fill, below); + }; + + for (const [surface, ink, floor] of PAIRS) { + const missing = [surface, ink].filter((t) => tokens[t] === undefined); + + if (missing.length) { + // day and morning set TheLounge's variables alone, so the + // handoff's pairs are not theirs; every other theme has them. + if (where === ":root" && !LOUNGE_ONLY.has(theme)) { + failures.push( + `${theme} defines no ${missing.join(" or ")} (${scheme})` + ); + } + + continue; + } + + // A block that re-maps only one side of a pair is painted over + // something this file cannot see (ps's light words go on the + // scene), so it is measured only where it sets both. + if (own && !(own.has(surface) && own.has(ink))) { + continue; + } + + const label = `${theme} ${ink} on ${surface}`; + const bg = ground(surface); + + if (!bg) { + seeThrough.add(`${theme} ${surface}`); + continue; + } + + const ratio = contrast(over(colour(ink), bg), bg); + checked++; + + if (ratio < floor && !KNOWN[label]) { + failures.push( + `${label} (${scheme}, ${where}): ${ratio.toFixed(2)} < ${floor}` + ); + } + } + } + } + + expect(checked, "pairs checked").to.be.greaterThan(0); + expect( + [...seeThrough].filter((s) => !SEE_THROUGH.has(s)), + "surfaces with nothing opaque under them" + ).to.deep.equal([]); + expect(failures).to.deep.equal([]); + }); + } + }); +}); From 7e72a6be59dec16bc125c3363307d65ff3fb523c Mon Sep 17 00:00:00 2001 From: rdrake Date: Sat, 21 Nov 2026 02:14:19 +0000 Subject: [PATCH 2/3] Theme contract: close the holes in the contrast check A :root under a width query is a surface of its own; a block that re-maps either side of a pair is measured with what it inherits, including the blocks that qualify it from above (zelenzy's dialogs under Increase Contrast); ps's light words and the chat's surfaces outside #chat are the named exceptions. Known exceptions carry today's ratio as their floor, a token that resolves to no colour fails instead of yielding NaN, and the rail is checked at both ends of its gradient. The docs say what the browser scenarios cover. --- docs/resources/themes.md | 4 +-- test/tests/themeContract.ts | 60 ++++++++++++++++++++++++++++++------- 2 files changed, 51 insertions(+), 13 deletions(-) diff --git a/docs/resources/themes.md b/docs/resources/themes.md index 880ea8fcc..2b035cf88 100644 --- a/docs/resources/themes.md +++ b/docs/resources/themes.md @@ -108,8 +108,8 @@ What a theme may rely on, and what is checked. A theme is plain CSS loaded after **Selectors.** Where `style.css` still has a literal colour (the sidebar rows and badges, header icons, the input and context menu, message-type icons, the mIRC colour table, nick slots `.user.color-1`…`-32`), a theme restates that selector. Prefer a token where one exists: a restated selector is coupled to the markup, a token is not. -**Checked without a browser** by `test/tests/themeContract.ts`, in CI: every custom property a theme declares is read by `client/` (ps's switched-off animal slots excepted), and each theme's resolved tokens, light and dark, hold their floors on the surfaces the app paints them on: text, muted text and links at 4.5:1 on the window and the chat, text on a highlighted row, the rail's text on the rail, the join line at 3:1. A translucent surface is measured over what it is painted on (a highlighted row over the window, the window, the chat and the rail over the page's own background), and a surface with nothing opaque under it in CSS must be named in the test as see-through. Besides `:root`, every block that re-maps both sides of a pair is checked as its own surface, with the blocks it sits inside: zelenzy's dialogs, ps by night and its night chat. Glass and pictures (ps, the macos material) are not a flat colour, so those two are measured in the browser as well (`tools/scenarios/theme-ps.mjs`, `themes.mjs`). Known exceptions are listed in the test with their reason: `day`'s link green is TheLounge's own. Not checked yet: muted text and links on a highlighted row, which several themes miss today (day, princess, morning, creama, frost). +**Checked without a browser** by `test/tests/themeContract.ts`, in CI: every custom property a theme declares is read by `client/` (ps's switched-off animal slots excepted; the check pools every file under `client/`, so it does not yet tell a token read by another theme only), and each theme's resolved tokens, light and dark, hold their floors on the surfaces the app paints them on: text, muted text and links at 4.5:1 on the window and the chat, text on a highlighted row, the rail's text on both ends of the rail's gradient, the join line at 3:1. A token that resolves to no colour (an empty value, a missing `var()`) fails. A translucent surface is measured over what it is painted on (a highlighted row over the window, the window, the chat and the rail over the page's own background), and a surface with nothing opaque under it in CSS must be named in the test as see-through. Besides `:root`, every block that re-maps either side of a pair is checked as its own surface, with the blocks it sits inside or that qualify it: a `:root` under a width query (a phone's palette), zelenzy's dialogs and the same dialogs under Increase Contrast, ps by night and its night chat. Two kinds of block are named in the test and left out: ps's light words, painted on the scene rather than on a token, and the chat's own surfaces (the chat pane, a highlighted row) in a block scoped away from `#chat`. Glass and pictures are not a flat colour, so ps is measured in the browser as well (`tools/scenarios/theme-ps.mjs`); `tools/scenarios/themes.mjs` measures the themes it lists, which leaves out `macos` (its material needs the Mac app, `html[data-platform="macos"]`) and `zelenzy`. Known exceptions are listed in the test with their own floor, today's ratio, so the colour stays as it is and anything worse fails: `day`'s link green is TheLounge's own (3.0:1). Not checked yet: muted text and links on a highlighted row, which several themes miss today (day, princess, morning, creama, frost). ## Checking a theme -`pnpm test` never loads a stylesheet. Build, serve `public/`, and look (`docs/resources/browser-testing.md`); the Appearance dropdown switches live. `tools/scenarios/themes.mjs` drives that dropdown through every theme against the dev ircd, checks the stylesheet link, the stored name and the browser chrome colour, measures the pairs above on the four handoff themes (text, timestamps, links, the join line, a nick on a highlighted row at ≥ 4.5:1; icons and the placeholder at ≥ 3:1) from computed styles, and leaves a screenshot of the chat under each theme. +`pnpm test` never loads a stylesheet. Build, serve `public/`, and look (`docs/resources/browser-testing.md`); the Appearance dropdown switches live. `tools/scenarios/themes.mjs` drives that dropdown through the themes in its list (all but `macos` and `zelenzy`) against the dev ircd, checks the stylesheet link, the stored name and the browser chrome colour, measures the pairs above on the four handoff themes (text, timestamps, links, the join line, a nick on a highlighted row at ≥ 4.5:1; icons and the placeholder at ≥ 3:1) from computed styles, and leaves a screenshot of the chat under each theme. diff --git a/test/tests/themeContract.ts b/test/tests/themeContract.ts index 5aedbe39d..7acba2d46 100644 --- a/test/tests/themeContract.ts +++ b/test/tests/themeContract.ts @@ -118,7 +118,14 @@ function surfaces(theme: string, scheme: "light" | "dark", names: Set): for (const css of themeCss) { for (const b of blocks(css)) { - if (b.prelude !== ":root" && !b.prelude.startsWith("@") && inScheme(b.at, scheme)) { + // :root under another condition (a width query, a contrast or platform + // attribute is a selector of its own) is a variant too: a phone's + // palette must hold its floors like the desk's. + const scoped = + b.prelude !== ":root" || + !!b.at.replace(/@media \(prefers-color-scheme: (light|dark)\)/g, "").trim(); + + if (scoped && !b.prelude.startsWith("@") && inScheme(b.at, scheme)) { const where = b.at ? `${b.at} ${b.prelude}` : b.prelude; byWhere.set(where, {...byWhere.get(where), ...customProperties(b.body)}); } @@ -128,11 +135,15 @@ function surfaces(theme: string, scheme: "light" | "dark", names: Set): for (const [where, props] of byWhere) { if (Object.keys(props).some((n) => names.has(n))) { // A block scoped inside another variant's selector (ps's night - // chat under its night :root) inherits that variant's tokens too. + // chat under its night :root) inherits that variant's tokens too, + // and so does one that qualifies it from above (zelenzy's dialogs + // under Increase Contrast, `html[data-contrast="more"] `). const outer = [...byWhere.keys()] .filter( (w) => - w !== where && where.startsWith(w) && /^[\s:[]/.test(where.slice(w.length)) + w !== where && + ((where.startsWith(w) && /^[\s:[]/.test(where.slice(w.length))) || + (where.endsWith(w) && /\s$/.test(where.slice(0, -w.length)))) ) .sort((a, b) => a.length - b.length) .map((w) => byWhere.get(w)); @@ -273,12 +284,17 @@ describe("the theme contract (themes.md § The theme contract)", function () { ["--chat-bg", "--chat-fg", 4.5], ["--chat-bg", "--chat-fg-muted", 4.5], ["--chat-bg", "--event-join", 3], + // The rail is a gradient between these two: both ends hold. ["--rail-bg-top", "--rail-fg", 4.5], + ["--rail-bg-bottom", "--rail-fg", 4.5], ]; // Known and recorded, not to be copied: day is TheLounge's original // light theme, kept as it was (docs/projects/accessibility.md). - const KNOWN: Record = { - "day --link-color on --window-bg-color": "TheLounge's own link green, 3.0:1", + // Each is a floor of its own, at today's ratio: the exception keeps the + // colour as it is, and anything worse still fails. + const KNOWN: Record = { + // TheLounge's own link green, 3.0:1. + "day --link-color on --window-bg-color": 2.95, }; // What each surface is painted over, out to the page's own canvas: a @@ -288,11 +304,21 @@ describe("the theme contract (themes.md § The theme contract)", function () { "--window-bg-color": "--body-bg-color", "--chat-bg": "--body-bg-color", "--rail-bg-top": "--body-bg-color", + "--rail-bg-bottom": "--body-bg-color", }; // Surfaces with nothing opaque under them in CSS (a shell's material or a // scene would show through) have no ratio to compute from the files. None // do today; one added here is a decision, not an accident. const SEE_THROUGH = new Set(); + // Blocks whose text is painted on a picture, not on the surface tokens: + // ps's light words sit on the scene, and tools/scenarios/theme-ps.mjs + // measures them there. Named, so any other block that re-maps one side + // of a pair is measured against what it inherits. + const ON_A_PICTURE = [/^ps .*\[data-ps-text="light"\]/]; + // The chat's own surfaces are painted inside #chat only (style.css's + // `#chat … .msg.highlight`, the chat pane), so a block scoped away from + // it (zelenzy's dialogs) has none of them. + const CHAT_ONLY = new Set(["--chat-bg", "--highlight-bg-color"]); const LOUNGE_ONLY = new Set(["day", "morning"]); const names = new Set(PAIRS.flatMap(([surface, ink]) => [surface, ink])); @@ -306,11 +332,11 @@ describe("the theme contract (themes.md § The theme contract)", function () { for (const {where, tokens, own} of surfaces(theme, scheme, names)) { const colour = (token: string) => { const value = resolve(tokens, tokens[token]); - const rgba = value && toRGBA(value); + const rgba = value ? toRGBA(value) : undefined; expect( - rgba, - `${theme} ${token} in ${where} resolves (${value})` - ).to.not.equal(undefined); + Array.isArray(rgba) && rgba.every((n) => Number.isFinite(n)), + `${theme} ${token} in ${where} resolves to a colour (${value})` + ).to.equal(true); return rgba as RGBA; }; // The surface laid over its grounds; undefined if it stays see-through. @@ -345,7 +371,15 @@ describe("the theme contract (themes.md § The theme contract)", function () { // A block that re-maps only one side of a pair is painted over // something this file cannot see (ps's light words go on the // scene), so it is measured only where it sets both. - if (own && !(own.has(surface) && own.has(ink))) { + if (own && !own.has(surface) && !own.has(ink)) { + continue; + } + + if ( + own && + (ON_A_PICTURE.some((re) => re.test(`${theme} ${where}`)) || + (CHAT_ONLY.has(surface) && where.includes(":not(#chat)"))) + ) { continue; } @@ -358,9 +392,13 @@ describe("the theme contract (themes.md § The theme contract)", function () { } const ratio = contrast(over(colour(ink), bg), bg); + expect( + Number.isFinite(ratio), + `${label} (${where}) is a number` + ).to.equal(true); checked++; - if (ratio < floor && !KNOWN[label]) { + if (ratio < (KNOWN[label] ?? floor)) { failures.push( `${label} (${scheme}, ${where}): ${ratio.toFixed(2)} < ${floor}` ); From f64ddf3e0a0c5216a3e394b6f46498dcf1128517 Mon Sep 17 00:00:00 2001 From: rdrake Date: Sat, 21 Nov 2026 03:02:59 +0000 Subject: [PATCH 3/3] Theme contract: cascade blocks before the ones below, measure blocks a broader one also matches A block on (a width query's :root, ps by night) cascades with :root and resolves there; the blocks below start from those computed values. A block whose selector narrows another's (ps's light words under the outline, rim and glow settings) now inherits it. The picture and chat-only exceptions apply only where the block leaves the surface alone or every branch is outside the chat. Day's link floor is its measured 3.03. --- docs/resources/themes.md | 2 +- test/tests/themeContract.ts | 134 +++++++++++++++++++++++++++++++----- 2 files changed, 118 insertions(+), 18 deletions(-) diff --git a/docs/resources/themes.md b/docs/resources/themes.md index 2b035cf88..e7ffe5ba9 100644 --- a/docs/resources/themes.md +++ b/docs/resources/themes.md @@ -108,7 +108,7 @@ What a theme may rely on, and what is checked. A theme is plain CSS loaded after **Selectors.** Where `style.css` still has a literal colour (the sidebar rows and badges, header icons, the input and context menu, message-type icons, the mIRC colour table, nick slots `.user.color-1`…`-32`), a theme restates that selector. Prefer a token where one exists: a restated selector is coupled to the markup, a token is not. -**Checked without a browser** by `test/tests/themeContract.ts`, in CI: every custom property a theme declares is read by `client/` (ps's switched-off animal slots excepted; the check pools every file under `client/`, so it does not yet tell a token read by another theme only), and each theme's resolved tokens, light and dark, hold their floors on the surfaces the app paints them on: text, muted text and links at 4.5:1 on the window and the chat, text on a highlighted row, the rail's text on both ends of the rail's gradient, the join line at 3:1. A token that resolves to no colour (an empty value, a missing `var()`) fails. A translucent surface is measured over what it is painted on (a highlighted row over the window, the window, the chat and the rail over the page's own background), and a surface with nothing opaque under it in CSS must be named in the test as see-through. Besides `:root`, every block that re-maps either side of a pair is checked as its own surface, with the blocks it sits inside or that qualify it: a `:root` under a width query (a phone's palette), zelenzy's dialogs and the same dialogs under Increase Contrast, ps by night and its night chat. Two kinds of block are named in the test and left out: ps's light words, painted on the scene rather than on a token, and the chat's own surfaces (the chat pane, a highlighted row) in a block scoped away from `#chat`. Glass and pictures are not a flat colour, so ps is measured in the browser as well (`tools/scenarios/theme-ps.mjs`); `tools/scenarios/themes.mjs` measures the themes it lists, which leaves out `macos` (its material needs the Mac app, `html[data-platform="macos"]`) and `zelenzy`. Known exceptions are listed in the test with their own floor, today's ratio, so the colour stays as it is and anything worse fails: `day`'s link green is TheLounge's own (3.0:1). Not checked yet: muted text and links on a highlighted row, which several themes miss today (day, princess, morning, creama, frost). +**Checked without a browser** by `test/tests/themeContract.ts`, in CI: every custom property a theme declares is read by `client/` (ps's switched-off animal slots excepted; the check pools every file under `client/`, so it does not yet tell a token read by another theme only), and each theme's resolved tokens, light and dark, hold their floors on the surfaces the app paints them on: text, muted text and links at 4.5:1 on the window and the chat, text on a highlighted row, the rail's text on both ends of the rail's gradient (ps's rail is clear, so its text is measured on the glass's solid colour, `--body-bg-color`, not on the glass the browser draws), the join line at 3:1. A token that resolves to no colour (an empty value, a missing `var()`) fails. A translucent surface is measured over what it is painted on (a highlighted row over the window, the window, the chat and the rail over the page's own background), and a surface with nothing opaque under it in CSS must be named in the test as see-through. Besides `:root`, every block that re-maps either side of a pair is checked as its own surface, with the blocks it sits inside, that qualify it, or that match wherever it does (ps's light words under the outline, rim and glow settings): a `:root` under a width query (a phone's palette), zelenzy's dialogs and the same dialogs under Increase Contrast, ps by night and its night chat. Two kinds of block are named in the test and left out: ps's light words, painted on the scene rather than on a token, and the chat's own surfaces (the chat pane, a highlighted row) in a block scoped away from `#chat`. Glass and pictures are not a flat colour, so ps is measured in the browser as well (`tools/scenarios/theme-ps.mjs`); `tools/scenarios/themes.mjs` measures the themes it lists, which leaves out `macos` (its material needs the Mac app, `html[data-platform="macos"]`) and `zelenzy`. Known exceptions are listed in the test with their own floor, today's ratio, so the colour stays as it is and anything worse fails: `day`'s link green is TheLounge's own (3.0:1). Not checked yet: muted text and links on a highlighted row, which several themes miss today (day, princess, morning, creama, frost). ## Checking a theme diff --git a/test/tests/themeContract.ts b/test/tests/themeContract.ts index 7acba2d46..dc6e5b2b0 100644 --- a/test/tests/themeContract.ts +++ b/test/tests/themeContract.ts @@ -143,21 +143,111 @@ function surfaces(theme: string, scheme: "light" | "dark", names: Set): (w) => w !== where && ((where.startsWith(w) && /^[\s:[]/.test(where.slice(w.length))) || - (where.endsWith(w) && /\s$/.test(where.slice(0, -w.length)))) + (where.endsWith(w) && /\s$/.test(where.slice(0, -w.length))) || + narrows(where, w)) ) - .sort((a, b) => a.length - b.length) - .map((w) => byWhere.get(w)); - variants.push({ - where, - tokens: Object.assign({}, root, ...outer, props), - own: new Set(Object.keys(props)), - }); + .sort((a, b) => a.length - b.length); + // Custom properties inherit their computed values: a block on a + // descendant (zelenzy's dialogs) gets the values :root resolved, not + // its declarations, while a block on itself (a width query's + // :root, ps by night) is cascaded with :root's and resolved with it. + // The blocks on cascade with :root and resolve there; the + // blocks below it (this one, and those it sits in or that qualify + // it) start from those computed values and resolve among themselves. + const layers = [...outer, where]; + const atRoot = Object.assign( + {}, + root, + ...layers.filter(onRoot).map((w) => byWhere.get(w)) + ); + const below = layers.filter((w) => !onRoot(w)).map((w) => byWhere.get(w)); + const resolved = below.length + ? resolveAll(Object.assign(resolveAll(atRoot), ...below)) + : resolveAll(atRoot); + + variants.push({where, tokens: resolved, own: new Set(Object.keys(props))}); } } return [{where: ":root", tokens: root}, ...variants]; } +/** The selector without its at-rule conditions, split at its top-level commas. */ +function branches(where: string): string[] { + return topLevel(where.replace(/^(@[^{]*?\)\s*)+/, ""), ","); +} + +/** Split at top-level occurrences of `sep` (a space or a comma), brackets and parens kept whole. */ +function topLevel(text: string, sep: string): string[] { + const out: string[] = []; + let depth = 0; + let start = 0; + + for (let i = 0; i < text.length; i++) { + const c = text[i]; + depth += c === "(" || c === "[" ? 1 : c === ")" || c === "]" ? -1 : 0; + + if (c === sep && depth === 0) { + out.push(text.slice(start, i).trim()); + start = i + 1; + } + } + + out.push(text.slice(start).trim()); + return out.filter(Boolean); +} + +const SIMPLE = /:{1,2}[\w-]+(?:\((?:[^()]|\([^()]*\))*\))?|\[[^\]]*\]|[.#]?[\w-]+|\*/g; + +/** Whether `where` is `outer` with more qualifiers on the same elements: the same at-rule + * conditions, one branch each, the same compounds, and each of `outer`'s compounds contained + * in `where`'s (ps's `:root[data-ps-text="light"] #chat .chat` under its shadow family's + * `:root:is(…)[data-ps-text="light"] #chat .chat`). Whatever matches `where` matches `outer`. */ +function narrows(where: string, outer: string): boolean { + const at = (w: string) => /^(@[^{]*?\)\s*)+/.exec(w)?.[0].trim() ?? ""; + + if (at(where) !== at(outer)) { + return false; + } + + const [inner] = branches(where); + const [wide] = branches(outer); + + if (branches(where).length !== 1 || branches(outer).length !== 1) { + return false; + } + + const a = topLevel(inner, " "); + const b = topLevel(wide, " "); + + return ( + a.length === b.length && + b.every((compound, i) => { + const have = new Set(a[i].match(SIMPLE) ?? []); + return (compound.match(SIMPLE) ?? []).every((s) => have.has(s)); + }) + ); +} + +/** Whether a block's selector names itself (no descendant in any branch). */ +function onRoot(where: string): boolean { + return branches(where).every((b) => + /^(:root|html)\S*$/.test(b.replace(/\[[^\]]*\]|\([^)]*\)/g, "")) + ); +} + +/** Every token with its var()s resolved where it is declared; a value that does not resolve is + * kept as written, so the check that reads it reports it. */ +function resolveAll(tokens: Record): Record { + const out: Record = {}; + + for (const [name, value] of Object.entries(tokens)) { + out[name] = resolve(tokens, value) ?? value; + } + + return out; +} + /** A value with every var() replaced, fallbacks included; undefined if one is missing. */ function resolve(tokens: Record, value: string, depth = 0): string | undefined { if (depth > 20) { @@ -293,8 +383,8 @@ describe("the theme contract (themes.md § The theme contract)", function () { // Each is a floor of its own, at today's ratio: the exception keeps the // colour as it is, and anything worse still fails. const KNOWN: Record = { - // TheLounge's own link green, 3.0:1. - "day --link-color on --window-bg-color": 2.95, + // TheLounge's own link green, 3.03:1. + "day --link-color on --window-bg-color": 3.03, }; // What each surface is painted over, out to the page's own canvas: a @@ -375,11 +465,17 @@ describe("the theme contract (themes.md § The theme contract)", function () { continue; } - if ( - own && - (ON_A_PICTURE.some((re) => re.test(`${theme} ${where}`)) || - (CHAT_ONLY.has(surface) && where.includes(":not(#chat)"))) - ) { + // Painted on the scene: a block that sets the ink and leaves + // the surface. One that sets both paints its own surface. + const onPicture = + ON_A_PICTURE.some((re) => re.test(`${theme} ${where}`)) && + !own?.has(surface); + // Scoped away from the chat in every branch of its selector. + const outsideChat = + CHAT_ONLY.has(surface) && + branches(where).every((b) => b.includes(":not(#chat)")); + + if (own && (onPicture || outsideChat)) { continue; } @@ -398,9 +494,13 @@ describe("the theme contract (themes.md § The theme contract)", function () { ).to.equal(true); checked++; - if (ratio < (KNOWN[label] ?? floor)) { + const effective = KNOWN[label] ?? floor; + + if (ratio < effective) { failures.push( - `${label} (${scheme}, ${where}): ${ratio.toFixed(2)} < ${floor}` + `${label} (${scheme}, ${where}): ${ratio.toFixed( + 2 + )} < ${effective}` ); } }