Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

scripts: factor the UI theming guard into one shared helper (#458)

nyblnet352b9684b7a8
diff --git a/scripts/lib/ui-theme-guard.ts b/scripts/lib/ui-theme-guard.ts
new file mode 100644
index 00000000..b366e1fd
--- /dev/null
+++ b/scripts/lib/ui-theme-guard.ts
@@ -0,0 +1,113 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// THE SHARED THEMING GUARD for the kernel UI primitives. Factored out of
+// test-ui-menu.ts and test-ui-panel.ts, which each grew an identical copy
+// (the menu primitive landed first; the panel primitive reproduced it because
+// the menu's rig was not yet on main to import from).
+//
+// WHAT IT PINS — one property, stated plainly so this does not inherit the
+// "all four guards" overclaim shape the vouch rig's label once had: **every
+// colour a primitive's CSS paints must resolve, for each of the four apps, to a
+// token that app both DEFINES and THEMES.** That is the whole guarantee. It is
+// what makes a primitive adoptable without touching an app's palette: the
+// primitive reads through a `--<prefix>-*` custom property whose fallback chain
+// lands on the host app's own token, so the primitive commits to no colour and
+// no theme mechanism of its own.
+//
+// It does NOT pin how an app themes (the four use three mechanisms —
+// `[data-theme="dark"]`, a `prefers-color-scheme` media query, `light-dark()`),
+// only THAT the token it lands on is themed by one of them. And it says nothing
+// about non-colour values (radius, gap, z-index): those are the same in both
+// themes by design and their chains, being literals, carry no token to check.
+//
+// The check is returned as a list of results rather than asserted here, so each
+// rig reports them through its own `ok()` — the two rigs spell that helper with
+// opposite argument orders, and a shared guard should not care.
+
+import { readFileSync } from 'node:fs'
+
+export interface ThemeResult { pass: boolean; msg: string }
+
+/** Every `--<prefix>-<prop>` chain in the primitive's CSS, with the host tokens
+ * its fallback falls through to (in order). A chain whose fallback is a bare
+ * literal — a radius, a z-index — carries no token and is dropped. */
+export function themedChains(cssText: string, prefix: string): Array<{ prop: string; tokens: string[] }> {
+ const out: Array<{ prop: string; tokens: string[] }> = []
+ const re = new RegExp(`var\\(\\s*--${prefix}-([a-z0-9-]+)\\s*,([^\\n]*)`, 'g')
+ for (const m of cssText.matchAll(re)) {
+ // Digits are part of a token name (`--chrome-2`); an earlier version of this
+ // regex stopped at the digit and reported a token nobody defines.
+ // Exclude the primitive's OWN properties: a fallback like
+ // `calc(var(--bkm-bar-bottom, 56px) + var(--bkm-gap, 6px))` mentions
+ // --bkm-gap, which is ours, not a host token to resolve.
+ const tokens = [...m[2].matchAll(/var\(\s*(--[a-z0-9-]+)/g)]
+ .map((t) => t[1])
+ .filter((t) => !t.startsWith(`--${prefix}-`))
+ if (tokens.length) out.push({ prop: m[1], tokens })
+ }
+ return out
+}
+
+/** The tokens an app's stylesheet DEFINES, and the subset it THEMES — by any of
+ * the three mechanisms: `light-dark()` in the value, or a re-declaration inside
+ * a `[data-theme="dark"]` block or a dark `prefers-color-scheme` media query. */
+export function tokensOf(cssPath: string): { all: Set<string>; themed: Set<string> } {
+ const src = readFileSync(cssPath, 'utf8')
+ const all = new Set<string>()
+ const themed = new Set<string>()
+ for (const m of src.matchAll(/(--[a-z0-9-]+)\s*:\s*([^;]+);/g)) {
+ all.add(m[1])
+ if (m[2].includes('light-dark(')) themed.add(m[1])
+ }
+ // Brace-count from each dark block so a nested rule inside a media query is
+ // still counted as part of it.
+ for (const start of src.matchAll(/\[data-theme=["']dark["']\][^{]*\{|@media[^{]*prefers-color-scheme:\s*dark[^{]*\{/g)) {
+ let depth = 0
+ let i = start.index! + start[0].length - 1
+ for (; i < src.length; i++) {
+ if (src[i] === '{') depth++
+ else if (src[i] === '}') { depth--; if (!depth) break }
+ }
+ for (const m of src.slice(start.index!, i).matchAll(/(--[a-z0-9-]+)\s*:/g)) themed.add(m[1])
+ }
+ return { all, themed }
+}
+
+export interface GuardOpts {
+ /** Path to the primitive's CSS. */
+ cssPath: string
+ /** The primitive's custom-property prefix, e.g. 'bkm' or 'bkp'. */
+ prefix: string
+ /** Chain props whose landing token must be THEMED, not merely defined —
+ * the colours. A prop outside this set is only checked for "defines". */
+ colourProps: Set<string>
+ /** Paths to each app's stylesheet, keyed by app name for the messages. */
+ appStyles: Record<string, string>
+ /** Chain props to skip entirely — e.g. `shadow`, where the literal fallback
+ * is the intended value for apps with no shadow token. */
+ exempt?: Set<string>
+}
+
+/**
+ * Run the guard and return one result per assertion. `pass` false is a
+ * regression; `msg` names the chain and the app. The caller reports each
+ * through its own `ok()`.
+ */
+export function checkThemedChains(opts: GuardOpts): ThemeResult[] {
+ const results: ThemeResult[] = []
+ const chains = themedChains(readFileSync(opts.cssPath, 'utf8'), opts.prefix)
+ const exempt = opts.exempt ?? new Set<string>()
+ results.push({ pass: chains.length >= 1, msg: `found ${opts.prefix} colour chains to check (${chains.length})` })
+ for (const [app, stylePath] of Object.entries(opts.appStyles)) {
+ const { all, themed } = tokensOf(stylePath)
+ for (const { prop, tokens } of chains) {
+ if (exempt.has(prop)) continue
+ const defined = tokens.find((t) => all.has(t))
+ results.push({ pass: !!defined, msg: `${app}: --${opts.prefix}-${prop} reaches a token ${app} defines (${tokens.join(' → ')})` })
+ if (!defined || !opts.colourProps.has(prop)) continue
+ results.push({ pass: themed.has(defined), msg: `${app}: --${opts.prefix}-${prop} lands on ${defined}, which ${app} themes` })
+ }
+ }
+ return results
+}
diff --git a/scripts/test-ui-menu.ts b/scripts/test-ui-menu.ts
index d2f009ca..d18c1bd2 100644
--- a/scripts/test-ui-menu.ts
+++ b/scripts/test-ui-menu.ts
@@ -40,7 +40,9 @@
// the nested popup — which is how slides' ⋯ once came up with the entire
// language list already unrolled inside it.
+import { fileURLToPath } from 'node:url'
import { installDom, fireDoc } from './lib/dash-dom.ts'
+import { checkThemedChains } from './lib/ui-theme-guard.ts'
const { doc } = installDom()
const bar = doc.createElement('div')
@@ -259,88 +261,22 @@ const A = (el: unknown, k: string): string | null => (el as any).getAttribute(k)
inner.destroy()
}
-// ————— 10. EVERY THEMED FALLBACK CHAIN REACHES A TOKEN THE APP ACTUALLY THEMES
-//
-// menu.css styles CHROME, and chrome follows the theme. Each colour reads
-// through a chain like `var(--bkm-bg, var(--surface, var(--field, #fff)))`, and
-// the literal at the end is LIGHT-ONLY — it exists so the rule is never
-// invalid, not because any app should reach it. An app that defines none of the
-// tokens in a chain silently gets that light literal in DARK mode: a white menu
-// under light ink, which is the mirror of the dark-on-dark bug slides fixed with
-// `color-scheme: only light`.
-//
-// This was not hypothetical. `type` has no `--surface` at all — its chrome
-// surface token is `--field` — so the first version of the chain fell through
-// to `#fff` for the one app whose gap the comment had already noted and whose
-// fallback had not been fixed. A comment is not a guard. This is.
-//
-// The four apps theme by three different MECHANISMS (slides and type via
-// `[data-theme="dark"]`, spaces via both that and a media query, dash via
-// `light-dark()`), so "is this token themed" has to accept all three.
+// ————— 10. THE THEMING GUARD — every colour chain resolves, for each of the
+// four apps, to a token that app both DEFINES and THEMES. Shared with the panel
+// primitive's rig through scripts/lib/ui-theme-guard.ts; that file states what
+// the one property is and why. type having --field where the others have
+// --surface is the case that first made this a guard rather than a comment.
{
- const { readFileSync } = await import('node:fs')
- const APPS = ['slides', 'spaces', 'dash', 'type']
- const css = readFileSync(new URL('../kernel/src/ui/menu.css', import.meta.url), 'utf8')
-
- /** Every `--token` a chain falls through, in order, ignoring our own. */
- const chains: Array<{ prop: string; tokens: string[] }> = []
- for (const line of css.split('\n')) {
- const decl = /^\s*(background|color|border|box-shadow|outline)?[^:]*:\s*var\(--bkm-([a-z-]+),(.*)$/.exec(line)
- if (!decl) continue
- // `--[a-z-]+` stopped at the digit in `--chrome-2` and reported a token
- // nobody defines. Digits are part of a custom-property name.
- const tokens = [...decl[3].matchAll(/var\(\s*(--[a-z0-9-]+)/g)].map((m) => m[1])
- if (tokens.length) chains.push({ prop: decl[2], tokens })
- }
- ok('found the themed chains to check', chains.length >= 4)
-
- /** Tokens an app defines at all, and the subset it actually themes. */
- function tokensOf(app: string): { all: Set<string>; themed: Set<string> } {
- const src = readFileSync(new URL(`../${app}/src/styles.css`, import.meta.url), 'utf8')
- const all = new Set<string>()
- const themed = new Set<string>()
- for (const m of src.matchAll(/(--[a-z0-9-]+)\s*:\s*([^;]+);/g)) {
- all.add(m[1])
- // dash themes by resolving against color-scheme, in the value itself
- if (m[2].includes('light-dark(')) themed.add(m[1])
- }
- // …the other three theme by re-declaring inside a dark block. Brace-count
- // from each one so a nested rule inside a media query is still counted.
- for (const start of [...src.matchAll(/\[data-theme=["']dark["']\][^{]*\{|@media[^{]*prefers-color-scheme:\s*dark[^{]*\{/g)]) {
- let depth = 0
- let i = start.index! + start[0].length - 1
- for (; i < src.length; i++) {
- if (src[i] === '{') depth++
- else if (src[i] === '}') { depth--; if (!depth) break }
- }
- for (const m of src.slice(start.index!, i).matchAll(/(--[a-z0-9-]+)\s*:/g)) themed.add(m[1])
- }
- return { all, themed }
- }
-
- // Only the colour-bearing chains must be THEMED. A radius or a font size is
- // the same in both themes by design, so requiring it here would be noise.
- const COLOUR = new Set(['bg', 'border', 'ink', 'hover', 'ico', 'focus'])
-
- // `shadow` is deliberately exempt from BOTH checks. Only dash has a shadow
- // token (`--shadow-pop`); spaces has none at all, and slides and type write
- // their menu shadow as a literal today. So the literal here IS the intended
- // value for three of four apps rather than a gap — and unlike a background or
- // an ink, a translucent shadow that does not follow the theme is not a
- // legibility failure. If tier 4 mints a shared shadow token, move `shadow`
- // into COLOUR above and this becomes a real check.
- const EXEMPT = new Set(['shadow'])
-
- for (const app of APPS) {
- const { all, themed } = tokensOf(app)
- for (const { prop, tokens } of chains) {
- if (EXEMPT.has(prop)) continue
- const defined = tokens.find((t) => all.has(t))
- ok(`${app}: --bkm-${prop} reaches a token ${app} defines (${tokens.join(' → ')})`, defined)
- if (!defined || !COLOUR.has(prop)) continue
- ok(`${app}: --bkm-${prop} lands on ${defined}, which ${app} themes`, themed.has(defined))
- }
- }
+ const appStyles = Object.fromEntries(
+ ['slides', 'spaces', 'dash', 'type'].map((a) => [a, fileURLToPath(new URL(`../${a}/src/styles.css`, import.meta.url))]),
+ )
+ for (const r of checkThemedChains({
+ cssPath: fileURLToPath(new URL('../kernel/src/ui/menu.css', import.meta.url)),
+ prefix: 'bkm',
+ colourProps: new Set(['bg', 'border', 'ink', 'hover', 'ico', 'focus']),
+ exempt: new Set(['shadow']),
+ appStyles,
+ })) ok(r.msg, r.pass)
}
console.log(failures ? `\ntest-ui-menu: ${failures} FAILED of ${checks}` : `test-ui-menu: ${checks} checks OK`)
diff --git a/scripts/test-ui-panel.ts b/scripts/test-ui-panel.ts
index 9fabf620..b14b5707 100644
--- a/scripts/test-ui-panel.ts
+++ b/scripts/test-ui-panel.ts
@@ -15,6 +15,7 @@
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
+import { checkThemedChains } from './lib/ui-theme-guard.ts'
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
// ——— a DOM just big enough for panel.ts ———
@@ -224,46 +225,21 @@ const chevronOf = (p: P) => (p.resizer as unknown as El).children[0]
ok(R(p).parent === null || !R(p).parent, 'destroy removes the root')
}
-// ——— THEMING GUARD (reproduced from tier 1's test-ui-menu): every colour
-// chain in panel.css must reach a token each of the four apps both DEFINES and
-// THEMES. When both primitives land, factor this into one shared helper. ———
+// ——— THEMING GUARD — shared with the menu primitive's rig via
+// scripts/lib/ui-theme-guard.ts. It pins one property: every colour panel.css
+// paints resolves, for each of the four apps, to a token that app both defines
+// and themes. `--bkp-bg` chaining --surface → --chrome is why type (which has
+// --chrome, not --surface) resolves at all. ———
{
- const css = readFileSync(join(root, 'kernel/src/ui/panel.css'), 'utf8')
- const chains: Array<{ prop: string; tokens: string[] }> = []
- for (const line of css.split('\n')) {
- const m = /(background|color|border[a-z-]*|box-shadow)\s*:\s*var\(--bkp-([a-z-]+),(.*)$/.exec(line)
- if (!m) continue
- const tokens = [...m[3].matchAll(/var\(\s*(--[a-z0-9-]+)/g)].map((x) => x[1])
- if (tokens.length) chains.push({ prop: m[2], tokens })
- }
- ok(chains.length >= 3, 'found the themed chains to check')
-
- function tokensOf(app: string) {
- const src = readFileSync(join(root, `${app}/src/styles.css`), 'utf8')
- const all = new Set<string>(); const themed = new Set<string>()
- for (const m of src.matchAll(/(--[a-z0-9-]+)\s*:\s*([^;]+);/g)) {
- all.add(m[1]); if (m[2].includes('light-dark(')) themed.add(m[1])
- }
- for (const start of [...src.matchAll(/\[data-theme=["']dark["']\][^{]*\{|@media[^{]*prefers-color-scheme:\s*dark[^{]*\{/g)]) {
- let depth = 0, i = start.index! + start[0].length - 1
- for (; i < src.length; i++) { if (src[i] === '{') depth++; else if (src[i] === '}') { depth--; if (!depth) break } }
- for (const m of src.slice(start.index!, i).matchAll(/(--[a-z0-9-]+)\s*:/g)) themed.add(m[1])
- }
- return { all, themed }
- }
- // shadow is exempt (a translucent overlay shadow need not follow the theme,
- // and only some apps have a shadow token) — matches tier 1's exemption.
- const COLOUR = new Set(['bg', 'border', 'toggle-ink', 'resizer-hover'])
- for (const app of ['slides', 'spaces', 'dash', 'type']) {
- const { all, themed } = tokensOf(app)
- for (const { prop, tokens } of chains) {
- const defined = tokens.find((t) => all.has(t))
- ok(defined, `${app}: --bkp-${prop} reaches a token ${app} defines (${tokens.join(' → ')})`)
- if (!defined || !COLOUR.has(prop)) continue
- ok(themed.has(defined), `${app}: --bkp-${prop} lands on ${defined}, which ${app} themes`)
- }
- }
+ const appStyles = Object.fromEntries(
+ ['slides', 'spaces', 'dash', 'type'].map((a) => [a, join(root, `${a}/src/styles.css`)]),
+ )
+ for (const r of checkThemedChains({
+ cssPath: join(root, 'kernel/src/ui/panel.css'),
+ prefix: 'bkp',
+ colourProps: new Set(['bg', 'border', 'toggle-ink', 'resizer-hover']),
+ appStyles,
+ })) ok(r.pass, r.msg)
}
-
console.log(failures ? `\n${failures} FAILED of ${checks}` : `\ntest-ui-panel: ${checks} checks OK`)
process.exit(failures ? 1 : 0)