Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-9034: fix(appearance): theme check measures contrast at every select and toggle value (#10365)

Jiayuan Zhangd28b5cbc41f3
diff --git a/docs/theming.md b/docs/theming.md
index 54aa9a2845..5ff77c7834 100644
--- a/docs/theming.md
+++ b/docs/theming.md
@@ -308,6 +308,14 @@ families in font stacks and WCAG contrast in both modes, each with its line
in `theme.css`, and exits with status 1 when there is an error. Warnings,
such as a colour it cannot resolve, do not fail the check.
+Contrast is measured with every option at its default, then once for each
+other value of a `select` and the other state of a `toggle`, one option at a
+time with the rest at their defaults. Options are not combined. A failure
+names the value it comes from, for example
+`Contrast, dark mode (Screen = Amber): …`. Options that set a variable
+(`color`, `variable-select`, `number`, `slider`, `text`, `font`) are measured
+at their defaults only, so check the other values you offer yourself.
+
To see the theme the way the theme store shows it:
```sh
diff --git a/packages/core/appearance/theme-check.test.ts b/packages/core/appearance/theme-check.test.ts
index 329d9364a6..1ea7c5544a 100644
--- a/packages/core/appearance/theme-check.test.ts
+++ b/packages/core/appearance/theme-check.test.ts
@@ -21,7 +21,9 @@ describe("theme check", () => {
"passes %s, duplicated as a theme folder",
(_name, theme) => {
const report = checkThemeFiles(exportTheme(theme, themeCopyTarget(theme, [])), base);
- expect(report.issues).toEqual([]);
+ // An option value may set a colour the check cannot read (Pop's signal colours mix in color-mix()).
+ expect(report.issues.filter((i) => !i.message.startsWith("Contrast not checked ("))).toEqual([]);
+ expect(report.issues.every((i) => i.level === "warning")).toBe(true);
expect(report.contrast.length).toBeGreaterThan(0);
},
);
@@ -108,16 +110,102 @@ describe("theme check", () => {
expect(found.some((m) => /light mode: --foreground is below .*--page-canvas \(1\.00:1\)/.test(m))).toBe(true);
});
- it("measures option rules at the options' defaults", () => {
+ describe("option values", () => {
const options = [
- { id: "ink", type: "select", label: "Ink", default: "dark", choices: [{ value: "dark", label: "Dark" }, { value: "pale", label: "Pale" }] },
+ {
+ id: "ink",
+ type: "select",
+ label: { en: "Ink", "zh-Hans": "墨色" },
+ default: "dark",
+ choices: [
+ { value: "dark", label: "Dark" },
+ { value: "pale", label: { en: "Pale", "zh-Hans": "浅" } },
+ { value: "soft", label: "Soft" },
+ ],
+ },
{ id: "wash", type: "toggle", label: "Wash", default: true },
];
- // Only applies when the person picks "pale", so the default check skips it.
- expect(check(':root[data-theme-option-ink="pale"] { --foreground: #ffffff; }', { options }).issues).toEqual([]);
- expect(check(":root[data-theme-option-ink]:not([data-theme-option-ink=\"dark\"]) { --foreground: #ffffff; }", { options }).issues).toEqual([]);
- // The toggle is on by default, so this one applies.
- expect(errors(":root[data-theme-option-wash].theme-light { --page-canvas: #444444; }", { options }).length).toBeGreaterThan(0);
+
+ it("measures each other choice of a select, naming it", () => {
+ for (const css of [
+ ':root[data-theme-option-ink="pale"] { --foreground: #ffffff; }',
+ ':root[data-theme-option-ink]:not([data-theme-option-ink="dark"]):not([data-theme-option-ink="soft"]) { --foreground: #ffffff; }',
+ ]) {
+ expect(errors(css, { options })).toEqual([
+ expect.stringMatching(/^Contrast, light mode \(Ink = Pale\): --foreground is below 4\.5:1 on .*--page-canvas \(1\.0\d:1\)/),
+ ]);
+ }
+ const report = check(':root[data-theme-option-ink="soft"].theme-light { --muted-foreground: #bbbbbb; }', { options });
+ expect(report.issues.map((i) => i.message)).toEqual([
+ expect.stringMatching(/^Contrast, light mode \(Ink = Soft\): --muted-foreground is below 4\.5:1/),
+ ]);
+ expect(report.contrast.filter((c) => c.ratio < c.required).every((c) => c.variant?.option === "ink" && c.variant.value === "soft")).toBe(true);
+ });
+
+ it("measures the other state of a toggle", () => {
+ const off = errors(":root:not([data-theme-option-wash]).theme-light { --page-canvas: #444444; }", { options });
+ expect(off.length).toBeGreaterThan(0);
+ expect(off.every((m) => m.startsWith("Contrast, light mode (Wash = off): "))).toBe(true);
+ const on = errors(":root[data-theme-option-wash].theme-light { --page-canvas: #444444; }", {
+ options: [{ id: "wash", type: "toggle", label: "Wash", default: false }],
+ });
+ expect(on.length).toBeGreaterThan(0);
+ expect(on.every((m) => m.startsWith("Contrast, light mode (Wash = on): "))).toBe(true);
+ });
+
+ it("reports a failure at the defaults once, not again for every option value", () => {
+ const found = errors(".theme-light { --muted-foreground: #bbbbbb; }", { options });
+ expect(found).toEqual([expect.stringMatching(/^Contrast, light mode: --muted-foreground/)]);
+ });
+
+ it("changes one option at a time", () => {
+ // Fails only with ink "pale" and wash off together.
+ const css = ':root[data-theme-option-ink="pale"]:not([data-theme-option-wash]) { --foreground: #ffffff; }';
+ expect(check(css, { options }).issues).toEqual([]);
+ });
+
+ it("keeps variable options at their defaults", () => {
+ const found = errors("", {
+ options: [{ id: "muted-foreground", type: "variable-select", label: "Muted", default: "var(--foreground)", choices: [
+ { value: "var(--foreground)", label: "Strong" },
+ { value: "#888888", label: "Grey" },
+ ] }],
+ });
+ expect(found).toEqual([]);
+ });
+
+ it("follows frame rules behind an option", () => {
+ const frame = [
+ { id: "frame", type: "select", label: "Frame", default: "paper", choices: [{ value: "paper", label: "Paper" }, { value: "ink", label: "Ink" }] },
+ ];
+ const ink = ':root.theme-light[data-theme-option-frame="ink"]';
+ const rail = '[data-mc="app-rail"]';
+ // Without the frame rule, the ink shell would fail against the page's dark text.
+ const surfaces = ["background", "page-canvas", "surface", "surface-raised", "surface-hover", "surface-selected", "muted"]
+ .map((name) => `--${name}: #222222;`)
+ .join(" ");
+ const good = `${ink} { --app-shell: #111111; }\n${ink} ${rail} { ${surfaces} --foreground: #f5f5f5; --muted-foreground: #cccccc; --faint-foreground: #999999; --sidebar-accent: #333333; --sidebar-accent-foreground: #ffffff; }`;
+ expect(check(good, { options: frame }).issues).toEqual([]);
+ const bad = good.replace("--sidebar-accent-foreground: #ffffff", "--sidebar-accent-foreground: #444444");
+ expect(errors(bad, { options: frame })).toEqual([
+ expect.stringMatching(
+ /^Contrast, light mode \(frame, Frame = Ink\): --sidebar-accent-foreground is below 4\.5:1 on --sidebar-accent \(1\.\d\d:1\) and --rail-item-hover-background/,
+ ),
+ ]);
+ });
+
+ it("names the option values whose colours it could not read", () => {
+ const report = check(':root[data-theme-option-ink="pale"] { --surface: color-mix(in oklab, red, blue); }', { options });
+ expect(report.ok).toBe(true);
+ const warnings = report.issues.map((i) => i.message);
+ expect(warnings.every((m) => m.startsWith("Contrast not checked (Ink = Pale), "))).toBe(true);
+ expect(warnings).toEqual(
+ expect.arrayContaining([
+ expect.stringMatching(/, light: --surface is `color-mix/),
+ expect.stringMatching(/, dark: --surface is `color-mix/),
+ ]),
+ );
+ });
});
it("fills in a missing default the way import does: the first choice", () => {
@@ -182,6 +270,48 @@ describe("theme check", () => {
expect(found.some((m) => /light mode \(frame\): --foreground is below 4\.5:1 on --app-shell/.test(m))).toBe(true);
});
+ describe("rail items", () => {
+ const rail = (declarations: string) => `.theme-light [data-mc="app-rail"] { ${declarations} }`;
+ const fills = "--rail-item-hover-background: #000000; --rail-item-active-background: #000000;";
+
+ it("pairs the rail's own colours, as the rail paints them", () => {
+ expect(check(rail(`${fills} --rail-item-active-color: #ffffff;`)).issues).toEqual([]);
+ });
+
+ it("fails rail colours without enough contrast", () => {
+ expect(errors(rail(`${fills} --rail-item-active-color: #333333;`))).toEqual([
+ expect.stringMatching(
+ /^Contrast, light mode \(frame\): --rail-item-active-color is below 4\.5:1 on --rail-item-active-background \(1\.\d\d:1\) and --rail-item-hover-background \(1\.\d\d:1\)\.$/,
+ ),
+ ]);
+ // Without its own colour, the rail falls back to --sidebar-accent-foreground on the rail fills.
+ expect(errors(rail(fills))).toEqual([
+ expect.stringMatching(/^Contrast, light mode \(frame\): --sidebar-accent-foreground is below 4\.5:1 on --rail-item-active-background/),
+ ]);
+ expect(errors(rail("--rail-item-color: #dddddd;"))).toEqual([
+ expect.stringMatching(/^Contrast, light mode \(frame\): --rail-item-color is below 4\.5:1 on --app-shell/),
+ ]);
+ });
+
+ it("keeps --sidebar-accent-foreground on --sidebar-accent for the other frame controls", () => {
+ expect(errors(rail(`${fills} --rail-item-active-color: #ffffff; --sidebar-accent: #000000;`))).toEqual([
+ expect.stringMatching(/^Contrast, light mode \(frame\): --sidebar-accent-foreground is below 4\.5:1 on --sidebar-accent \(1\.\d\d:1\)\.$/),
+ ]);
+ });
+
+ it("measures rail colours behind a non-default option value", () => {
+ const options = [
+ { id: "frame", type: "select", label: "Frame", default: "paper", choices: [{ value: "paper", label: "Paper" }, { value: "ink", label: "Ink" }] },
+ ];
+ const ink = (color: string) =>
+ `:root.theme-light[data-theme-option-frame="ink"] [data-mc="app-rail"] { ${fills} --rail-item-active-color: ${color}; }`;
+ expect(check(ink("#ffffff"), { options }).issues).toEqual([]);
+ expect(errors(ink("#333333"), { options })).toEqual([
+ expect.stringMatching(/^Contrast, light mode \(frame, Frame = Ink\): --rail-item-active-color is below 4\.5:1/),
+ ]);
+ });
+ });
+
it("warns instead of guessing when a colour cannot be read", () => {
const report = check(".theme-light { --muted-foreground: color-mix(in oklab, red, blue); }");
expect(report.ok).toBe(true);
diff --git a/packages/core/appearance/theme-check.ts b/packages/core/appearance/theme-check.ts
index 80aeb3b878..56c4e6509c 100644
--- a/packages/core/appearance/theme-check.ts
+++ b/packages/core/appearance/theme-check.ts
@@ -1,13 +1,15 @@
import type { ArchiveFile } from "./theme-archive";
import { parseTheme, readThemeFiles, type ThemePackageInput } from "./theme-package";
import { THEME_VARIABLE_NAMES } from "./theme-variables";
-import { contrastRatio, resolveColor, type BasePalette } from "./theme-contrast";
+import { contrastRatio, paintOver, resolveColor, type BasePalette } from "./theme-contrast";
import {
THEME_OPTION_ATTR_PREFIX,
+ localizedText,
themeOptionAttributes,
themeOptionVariables,
type Theme,
type ThemeManifest,
+ type ThemeOptionValues,
} from "./themes";
/**
@@ -15,8 +17,9 @@ import {
* registry checks. On top of what import enforces (the manifest and the CSS
* sanitizer), it reports what import lets through but a theme should not
* do: set variables that are not public, name generic families in Latin
- * font stacks, or paint text without enough contrast. It reads the theme
- * with its default options.
+ * font stacks, or paint text without enough contrast. Contrast is measured
+ * with the options at their defaults, then once per other value of each
+ * `select` and `toggle` with the rest at their defaults.
*/
export interface ThemeCheckIssue {
@@ -24,6 +27,15 @@ export interface ThemeCheckIssue {
message: string;
}
+/** One option set to a value other than its default. */
+export interface ContrastVariant {
+ option: string;
+ /** The choice's value, or `on` / `off` for a toggle. */
+ value: string;
+ /** For messages: `Screen = MS-DOS Editor`. */
+ label: string;
+}
+
export interface ContrastCheck {
mode: "light" | "dark";
/** Where the pair is painted: the page, or the frame (rail, toolbar, tabs). */
@@ -32,6 +44,8 @@ export interface ContrastCheck {
background: string;
ratio: number;
required: number;
+ /** Set when one option was off its default for this measurement. */
+ variant?: ContrastVariant;
}
export interface ThemeCheckReport {
@@ -63,6 +77,7 @@ const BACKGROUNDS = [
"--sidebar-accent",
];
const READING_SURFACES = ["--background", "--page-canvas", "--surface", "--surface-raised"];
+/** Frame surfaces under the text tones. --sidebar-accent and the rail item fills carry their own text colours. */
const FRAME_BACKGROUNDS = [
"--app-shell",
"--background",
@@ -72,7 +87,6 @@ const FRAME_BACKGROUNDS = [
"--surface-hover",
"--surface-selected",
"--muted",
- "--sidebar-accent",
];
const GENERIC_FAMILY =
@@ -101,9 +115,8 @@ type Mode = "light" | "dark";
/**
* Where a selector on <html> applies and how specific it is, for the
* selectors the contrast check follows: `:root` or `html`, the mode
- * classes, and the theme's option attributes, read at their defaults.
- * `"inactive"` when the default options do not match; `null` for any
- * other selector.
+ * classes, and the theme's option attributes as given. `"inactive"` when
+ * those attributes do not match; `null` for any other selector.
*/
function rootSelector(
selector: string,
@@ -155,6 +168,29 @@ function splitSelectors(prelude: string): string[] {
return out;
}
+/**
+ * The modes a frame rule applies in: a selector on <html> that `rootSelector`
+ * follows, then a frame anchor below it. Empty for any other selector.
+ */
+function frameModes(selector: string, attributes: ReadonlyMap<string, string>): Mode[] {
+ let depth = 0;
+ let quote = "";
+ for (let i = 0; i < selector.length; i += 1) {
+ const c = selector[i]!;
+ if (quote) {
+ if (c === quote) quote = "";
+ } else if (c === '"' || c === "'") quote = c;
+ else if (c === "(" || c === "[") depth += 1;
+ else if (c === ")" || c === "]") depth = Math.max(0, depth - 1);
+ else if (/\s/.test(c) && depth === 0) {
+ if (!FRAME_ANCHOR.test(selector.slice(i))) return [];
+ const head = rootSelector(selector.slice(0, i), attributes);
+ return head && head !== "inactive" ? head.modes : [];
+ }
+ }
+ return [];
+}
+
/** A palette that records which variables a contrast check read. */
class ReadTracker extends Map<string, string> {
private readonly read: Set<string>;
@@ -262,16 +298,44 @@ function checkFonts(css: string, manifest: unknown, issues: ThemeCheckIssue[]) {
}
/**
- * Contrast with the options at their defaults, through the same helpers the
- * app uses to apply them. Without a parsed theme there are no options to apply.
+ * Every option value the contrast check tries besides the defaults: each
+ * other choice of a `select` and the other state of a `toggle`, one option
+ * at a time. Variable options (`color`, `variable-select` and the rest) stay
+ * at their defaults.
*/
-function checkContrast(
- css: string,
+function optionVariants(theme: ThemeManifest | undefined): { chosen: ThemeOptionValues; variant: ContrastVariant }[] {
+ const out: { chosen: ThemeOptionValues; variant: ContrastVariant }[] = [];
+ for (const option of theme?.options ?? []) {
+ const label = localizedText(option.label, "en");
+ if (option.type === "select") {
+ for (const choice of option.choices) {
+ if (choice.value === option.default) continue;
+ out.push({
+ chosen: { [option.id]: choice.value },
+ variant: { option: option.id, value: choice.value, label: `${label} = ${localizedText(choice.label, "en")}` },
+ });
+ }
+ } else if (option.type === "toggle") {
+ const value = option.default ? "off" : "on";
+ out.push({ chosen: { [option.id]: !option.default }, variant: { option: option.id, value, label: `${label} = ${value}` } });
+ }
+ }
+ return out;
+}
+
+/**
+ * Contrast with the options as chosen (the rest at their defaults), through
+ * the same helpers the app uses to apply them. Without a parsed theme there
+ * are no options to apply.
+ */
+function measureContrast(
+ clean: string,
+ parsed: readonly Rule[],
theme: ThemeManifest | undefined,
+ chosen: ThemeOptionValues | undefined,
base: BasePalette,
- issues: ThemeCheckIssue[],
-): ContrastCheck[] {
- const clean = stripComments(css);
+ variant: ContrastVariant | undefined,
+): { results: ContrastCheck[]; unresolved: Set<string> } {
// The cascade on <html>, per mode: the base tokens (`:root` and `.dark`),
// then the theme's root and mode rules by specificity and order.
const cascade = {
@@ -281,10 +345,10 @@ function checkContrast(
const frame = { light: [] as [string, string][], dark: [] as [string, string][] };
const unmodelled = new Map<string, string>();
const attributes = new Map<string, string>();
- for (const [name, value] of Object.entries(theme ? themeOptionAttributes(theme, undefined) : {})) {
+ for (const [name, value] of Object.entries(theme ? themeOptionAttributes(theme, chosen) : {})) {
if (value !== null) attributes.set(name.slice(THEME_OPTION_ATTR_PREFIX.length), value);
}
- for (const rule of rules(clean)) {
+ for (const rule of parsed) {
for (const selector of rule.selectors) {
const target = rule.nested ? null : rootSelector(selector, attributes);
if (target === "inactive") continue;
@@ -306,11 +370,11 @@ function checkContrast(
}
}
}
- const joined = rule.selectors.join(", ");
- const frameMode = /^(?::root|html)?\.theme-(light|dark)\s/.exec(joined)?.[1] as "light" | "dark" | undefined;
- if (!rule.nested && frameMode && FRAME_ANCHOR.test(joined)) frame[frameMode].push(...declarations(rule.body));
+ if (rule.nested) continue;
+ const modes = new Set(rule.selectors.flatMap((selector) => frameModes(selector, attributes)));
+ for (const m of modes) frame[m].push(...declarations(rule.body));
}
- const options = theme ? themeOptionVariables(theme, undefined) : { light: {}, dark: {} };
+ const options = theme ? themeOptionVariables(theme, chosen) : { light: {}, dark: {} };
const results: ContrastCheck[] = [];
const unresolved = new Set<string>();
const read = new Set<string>();
@@ -344,7 +408,15 @@ function checkContrast(
continue;
}
const ratio = contrastRatio(fg.color, bg.color);
- results.push({ mode: m, area, foreground, background, ratio: Math.round(ratio * 100) / 100, required });
+ results.push({
+ mode: m,
+ area,
+ foreground,
+ background,
+ ratio: Math.round(ratio * 100) / 100,
+ required,
+ ...(variant ? { variant } : {}),
+ });
}
};
const hasFrame = frame[m].length > 0;
@@ -359,35 +431,99 @@ function checkContrast(
}
if (hasFrame) {
const framePalette = new ReadTracker(read, [...palette, ...frame[m]]);
- for (const tone of ["--foreground", "--muted-foreground", "--sidebar-accent-foreground"]) {
+ for (const tone of ["--foreground", "--muted-foreground"]) {
measure("frame", framePalette, tone, FRAME_BACKGROUNDS, TEXT);
}
measure("frame", framePalette, "--faint-foreground", FRAME_BACKGROUNDS, NON_TEXT);
+ // Toolbar and layout buttons paint --sidebar-accent-foreground on --sidebar-accent on hover.
+ measure("frame", framePalette, "--sidebar-accent-foreground", ["--sidebar-accent"], TEXT);
+ // Rail items read their own variables, with the fallbacks in theme-variables.css:
+ // the label on the shell at rest, and the active colour on the active and hover fills.
+ if (framePalette.has("--rail-item-color")) measure("frame", framePalette, "--rail-item-color", ["--app-shell"], TEXT);
+ const railText = framePalette.has("--rail-item-active-color") ? "--rail-item-active-color" : "--sidebar-accent-foreground";
+ const railSurfaces = [
+ framePalette.has("--rail-item-active-background") ? "--rail-item-active-background" : "--sidebar-accent",
+ ];
+ if (framePalette.has("--rail-item-hover-background")) railSurfaces.push("--rail-item-hover-background");
+ else {
+ // The default hover is --sidebar-accent at 60% over the shell.
+ const accent = resolveColor(framePalette, "--sidebar-accent");
+ const shell = resolveColor(framePalette, "--app-shell");
+ if ("color" in accent && "color" in shell && shell.color.a === 1) {
+ const { r, g, b } = paintOver({ ...accent.color, a: accent.color.a * 0.6 }, shell.color);
+ framePalette.set("--rail-item-hover-background", `rgb(${r} ${g} ${b})`);
+ railSurfaces.push("--rail-item-hover-background");
+ }
+ }
+ measure(
+ "frame",
+ framePalette,
+ railText,
+ railSurfaces.filter((surface) => railText !== "--sidebar-accent-foreground" || surface !== "--sidebar-accent"),
+ TEXT,
+ );
}
}
for (const [name, where] of unmodelled) {
if (read.has(name)) unresolved.add(`${where}, which the check does not follow`);
}
+ return { results, unresolved };
+}
+const pairKey = (c: ContrastCheck) => `${c.mode} ${c.area} ${c.foreground} ${c.background}`;
+
+/** One error per mode, area and colour, listing the surfaces it fails on. */
+function reportFailing(checks: readonly ContrastCheck[], issues: ThemeCheckIssue[]) {
const failing = new Map<string, ContrastCheck[]>();
- for (const check of results) {
+ for (const check of checks) {
if (check.ratio >= check.required) continue;
const key = `${check.mode} ${check.area} ${check.foreground}`;
failing.set(key, [...(failing.get(key) ?? []), check]);
}
- for (const checks of failing.values()) {
- const { mode: m, area, foreground, required } = checks[0]!;
- const surfaces = checks.map((c) => `${c.background} (${c.ratio.toFixed(2)}:1)`);
+ for (const group of failing.values()) {
+ const { mode: m, area, foreground, required, variant } = group[0]!;
+ const surfaces = group.map((c) => `${c.background} (${c.ratio.toFixed(2)}:1)`);
const list = surfaces.length > 1 ? `${surfaces.slice(0, -1).join(", ")} and ${surfaces.at(-1)}` : surfaces[0];
+ const where = [...(area === "frame" ? ["frame"] : []), ...(variant ? [variant.label] : [])];
issues.push({
level: "error",
- message: `Contrast, ${m} mode${area === "frame" ? " (frame)" : ""}: ${foreground} is below ${required}:1 on ${list}.`,
+ message: `Contrast, ${m} mode${where.length > 0 ? ` (${where.join(", ")})` : ""}: ${foreground} is below ${required}:1 on ${list}.`,
});
}
- for (const reason of unresolved) {
+}
+
+/**
+ * Contrast at the default options, then once per other option value. An
+ * option value reports only what does not already fail at the defaults.
+ */
+function checkContrast(
+ css: string,
+ theme: ThemeManifest | undefined,
+ base: BasePalette,
+ issues: ThemeCheckIssue[],
+): ContrastCheck[] {
+ const clean = stripComments(css);
+ const parsed = rules(clean);
+ const defaults = measureContrast(clean, parsed, theme, undefined, base, undefined);
+ reportFailing(defaults.results, issues);
+ const failingByDefault = new Set(defaults.results.filter((c) => c.ratio < c.required).map(pairKey));
+ const results = [...defaults.results];
+ const unresolvedWith = new Map<string, string[]>();
+ for (const { chosen, variant } of optionVariants(theme)) {
+ const run = measureContrast(clean, parsed, theme, chosen, base, variant);
+ results.push(...run.results);
+ reportFailing(run.results.filter((c) => !failingByDefault.has(pairKey(c))), issues);
+ for (const reason of run.unresolved) {
+ if (!defaults.unresolved.has(reason)) unresolvedWith.set(reason, [...(unresolvedWith.get(reason) ?? []), variant.label]);
+ }
+ }
+ for (const reason of defaults.unresolved) {
issues.push({ level: "warning", message: `Contrast not checked, ${reason}.` });
}
+ for (const [reason, labels] of unresolvedWith) {
+ issues.push({ level: "warning", message: `Contrast not checked (${labels.join(", ")}), ${reason}.` });
+ }
return results;
}
diff --git a/packages/core/appearance/theme-contrast.ts b/packages/core/appearance/theme-contrast.ts
index 74828db3c9..edb6b52724 100644
--- a/packages/core/appearance/theme-contrast.ts
+++ b/packages/core/appearance/theme-contrast.ts
@@ -138,14 +138,14 @@ function luminance({ r, g, b }: Rgba): number {
}
/** `top` painted over an opaque `bottom`. */
-function over(top: Rgba, bottom: Rgba): Rgba {
+export function paintOver(top: Rgba, bottom: Rgba): Rgba {
const mix = (t: number, b: number) => Math.round(t * top.a + b * (1 - top.a));
return { r: mix(top.r, bottom.r), g: mix(top.g, bottom.g), b: mix(top.b, bottom.b), a: 1 };
}
/** The WCAG ratio of a foreground on an opaque background. */
export function contrastRatio(foreground: Rgba, background: Rgba): number {
- const a = luminance(over(foreground, background));
+ const a = luminance(paintOver(foreground, background));
const b = luminance(background);
const [lighter, darker] = a > b ? [a, b] : [b, a];
return (lighter + 0.05) / (darker + 0.05);
diff --git a/scripts/theme-check.mjs b/scripts/theme-check.mjs
index 358ac737e8..886fbf0d4b 100644
--- a/scripts/theme-check.mjs
+++ b/scripts/theme-check.mjs
@@ -2,7 +2,8 @@
/**
* Checks theme folders or .zip files the way the app and the theme store do:
* the manifest, the CSS sanitizer, public variables, Latin font stacks and
- * WCAG contrast against the app's own palette (packages/ui/styles/tokens.css).
+ * WCAG contrast against the app's own palette (packages/ui/styles/tokens.css),
+ * at the default options and at each other `select` and `toggle` value.
* The checks live in packages/core/appearance/theme-check.ts.
*
* Run: pnpm theme:check <theme folder or .zip>... [--json]
@@ -57,8 +58,10 @@ if (json) {
if (contrast.length > 0) {
const failing = contrast.filter((c) => c.ratio < c.required).length;
const lowest = [...contrast].sort((a, b) => a.ratio / a.required - b.ratio / b.required)[0];
+ const values = new Set(contrast.filter((c) => c.variant).map((c) => c.variant.label)).size;
+ const where = [lowest.mode, ...(lowest.area === "frame" ? ["frame"] : [])].join(" ");
console.log(
- ` contrast ${contrast.length} pairs checked, ${failing} below WCAG AA. Lowest: ${lowest.foreground} on ${lowest.background}, ${lowest.mode}${lowest.area === "frame" ? " frame" : ""}, ${lowest.ratio.toFixed(2)}:1 (needs ${lowest.required}:1)`,
+ ` contrast ${contrast.length} pairs checked at the default options${values > 0 ? ` and ${values} other option value${values === 1 ? "" : "s"}` : ""}, ${failing} below WCAG AA. Lowest: ${lowest.foreground} on ${lowest.background}, ${where}${lowest.variant ? ` (${lowest.variant.label})` : ""}, ${lowest.ratio.toFixed(2)}:1 (needs ${lowest.required}:1)`,
);
}
}
diff --git a/scripts/theme-check.test.mjs b/scripts/theme-check.test.mjs
index 90964d5748..3542dbd1a0 100644
--- a/scripts/theme-check.test.mjs
+++ b/scripts/theme-check.test.mjs
@@ -47,6 +47,32 @@ test("passes a good theme and fails a bad one, with every problem listed", (t) =
assert.match(messages, /--muted-foreground is below 4\.5:1 on .*--surface \(\d\.\d\d:1\)/);
});
+test("fails a theme on an option value other than the default", (t) => {
+ const dir = mkdtempSync(join(tmpdir(), "theme-check-"));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ const screens = theme(dir, "screens", {
+ manifest: {
+ options: [
+ { id: "screen", type: "select", label: "Screen", default: "prompt", choices: [
+ { value: "prompt", label: "Prompt" },
+ { value: "amber", label: "Amber" },
+ ] },
+ ],
+ },
+ css: ':root[data-theme-option-screen="amber"].theme-dark { --muted-foreground: #5a3e00; }\n',
+ });
+
+ const text = run(screens);
+ assert.equal(text.status, 1, text.stdout + text.stderr);
+ assert.match(text.stdout, /Contrast, dark mode \(Screen = Amber\): --muted-foreground is below 4\.5:1/);
+ assert.match(text.stdout, /pairs checked at the default options and 1 other option value, \d+ below WCAG AA\. Lowest: --muted-foreground on .*, dark \(Screen = Amber\)/);
+
+ const [report] = JSON.parse(run(screens, "--json").stdout);
+ const failing = report.contrast.filter((c) => c.ratio < c.required);
+ assert.ok(failing.length > 0);
+ assert.ok(failing.every((c) => c.variant?.option === "screen" && c.variant.value === "amber"));
+});
+
test("explains a path that is not a theme", () => {
const result = run(join(tmpdir(), "no-such-theme-folder"));
assert.equal(result.status, 1);