feat(theme): Light/Dark/System, reduced motion, and one radius scale
CI / verify (pull_request) Successful in 1m10s
CI / infrastructure-smoke (pull_request) Successful in 34s
CI / package-release (pull_request) Successful in 52s
CI / migration-smoke (pull_request) Successful in 2m20s
CI / image-build (pull_request) Successful in 1m5s
CI / deploy-smoke (same-origin) (pull_request) Successful in 50s
CI / package-publication (pull_request) Successful in 58s
CI / deploy-smoke (split) (pull_request) Successful in 2m38s

The theme foundation DESIGN.md requires (ADR 0060):

- A design token may carry a `dark` value and a `reduced` value. The
  token stylesheet selects them in CSS alone: dark under
  prefers-color-scheme unless the host chose light, or when it chose
  dark; motion durations zero under prefers-reduced-motion unless it
  allowed motion, or when it chose reduce. `color-scheme` travels with
  the tokens. System is live, an explicit choice wins, and every module
  root follows through custom-property inheritance, with no module
  contract change.
- @ekklesia/design-tokens adds a small appearance API: system/light/dark
  and system/reduce/allow, parsers for untrusted stored values,
  resolvers, and a controller that applies the attributes immediately.
  The shell applies it before React renders. That is the hook the
  account preferences work will feed; nothing is persisted. The
  Dashboard page declares `color-scheme: light dark` so a dark system
  never flashes white. Displays stay light.
- A designed dark theme: teal-tinted charcoal, never pure black or
  white, the same teal accent.
- WCAG AA contrast is tested for 41 element pairings in both schemes.
  Two light pairings failed and are fixed visibly: text.muted darkens,
  and form controls get a new border.control (3:1).
  background.placeholder keeps skeletons visible in dark.
- Motion tokens (duration-short, duration-ambient) replace literal
  durations and every per-element reduced-motion rule. radius.scale
  multiplies sm/md/lg, unchanged at its default of 1.
- The sign-in card and module loading/error text move from literal
  colours to tokens. Guards keep raw colours and literal radii out of
  Dashboard product source and @ekklesia/ui.
- Fixes ConfirmationDialog's phrase input, which used a class that
  does not exist (`ek-input`) and so was unstyled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
ekklesia
2026-10-14 20:00:39 -05:00
co-authored by Claude Opus 5.5
parent e3e2a901a7
commit d42b64a093
25 changed files with 1294 additions and 78 deletions
@@ -0,0 +1,129 @@
import { describe, expect, it } from "vitest";
import {
type DesignTokenColorScheme,
type EkklesiaDesignTokenName,
ekklesiaDesignTokens,
} from "../src/index.js";
/**
* WCAG 2.2 AA contrast for every text, control, and focus pairing Ekklesia's elements actually use,
* in both colour schemes (ADR 0060). 4.5:1 for text (§1.4.3); 3:1 for the boundary that identifies a
* form control and for focus indication (§1.4.11). These are computed from the token values, which
* is necessary but not sufficient: representative screens are also rendered in a real browser.
*/
function channels(hex: string): readonly [number, number, number] {
const match = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/u.exec(hex);
if (!match) {
throw new Error(`not an opaque hex colour: ${hex}`);
}
return [match[1], match[2], match[3]].map((part) => Number.parseInt(part ?? "0", 16) / 255) as [
number,
number,
number,
];
}
function luminance(hex: string): number {
const [r, g, b] = channels(hex).map((value) =>
value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4,
) as [number, number, number];
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
function contrastRatio(first: string, second: string): number {
const [lighter, darker] = [luminance(first), luminance(second)].sort((a, b) => b - a) as [
number,
number,
];
return (lighter + 0.05) / (darker + 0.05);
}
type Pairing = readonly [EkklesiaDesignTokenName, EkklesiaDesignTokenName, number, string];
const TEXT = 4.5;
const NON_TEXT = 3;
/** Foreground, background, required ratio, and where it appears. */
const PAIRINGS: readonly Pairing[] = [
["text.primary", "background.page", TEXT, "body text on the page"],
["text.primary", "background.canvas", TEXT, "sidebar and empty states"],
["text.primary", "background.surface", TEXT, "panels, inputs"],
["text.primary", "background.raised", TEXT, "dialogs, menus, toasts"],
["text.primary", "background.inset", TEXT, "technical details"],
["text.secondary", "background.page", TEXT, "descriptions on the page"],
["text.secondary", "background.canvas", TEXT, "quiet navigation items"],
["text.secondary", "background.surface", TEXT, "panel descriptions"],
["text.secondary", "background.raised", TEXT, "dialog descriptions, toast bodies"],
["text.secondary", "background.inset", TEXT, "technical detail text"],
["text.secondary", "state.hover-background", TEXT, "hovered quiet button"],
["text.primary", "state.pressed-background", TEXT, "pressed button"],
["text.muted", "background.page", TEXT, "hints and metadata on the page"],
["text.muted", "background.canvas", TEXT, "group labels in the sidebar"],
["text.muted", "background.surface", TEXT, "field hints, placeholders"],
["text.muted", "background.raised", TEXT, "menu captions, phrase status"],
["accent.foreground", "accent.base", TEXT, "primary button"],
["accent.foreground", "accent.hover", TEXT, "primary button, hovered"],
["accent.foreground", "accent.active", TEXT, "primary button, pressed"],
["accent.strong", "background.page", TEXT, "eyebrow and accent text"],
["accent.strong", "background.surface", TEXT, "accent text in a panel"],
["state.selected-foreground", "state.selected-background", TEXT, "the open page in navigation"],
["text.danger", "status.danger-background", TEXT, "danger button and badge"],
["text.danger", "background.surface", TEXT, "field error"],
["text.danger", "background.canvas", TEXT, "error state title"],
["text.danger", "background.raised", TEXT, "error in a dialog"],
["text.warning", "status.warning-background", TEXT, "warning badge and notice"],
["text.success", "status.success-background", TEXT, "success badge and notice"],
["text.primary", "status.info-background", TEXT, "information notice"],
["text.primary", "status.warning-background", TEXT, "warning notice body"],
["text.primary", "status.danger-background", TEXT, "danger notice body"],
["text.primary", "status.success-background", TEXT, "success notice body"],
["text.primary", "accent.subtle", TEXT, "selected tab"],
["border.control", "background.surface", NON_TEXT, "an input's boundary"],
["border.control", "background.page", NON_TEXT, "an input on the page"],
["border.control", "background.raised", NON_TEXT, "an input in a dialog"],
["text.danger", "background.surface", NON_TEXT, "an invalid input's boundary"],
["accent.focus", "background.page", NON_TEXT, "focus ring on the page"],
["accent.focus", "background.canvas", NON_TEXT, "focus ring in the sidebar"],
["accent.focus", "background.surface", NON_TEXT, "focus ring in a panel"],
["accent.focus", "background.raised", NON_TEXT, "focus ring in a dialog"],
];
describe.each([
"light",
"dark",
] as const satisfies readonly DesignTokenColorScheme[])("WCAG 2.2 AA contrast, %s", (scheme) => {
it.each(PAIRINGS)("%s on %s ≥ %s:1 (%s)", (foreground, background, required) => {
const ratio = contrastRatio(
ekklesiaDesignTokens.valueFor(foreground, scheme),
ekklesiaDesignTokens.valueFor(background, scheme),
);
expect(Number(ratio.toFixed(2))).toBeGreaterThanOrEqual(required);
});
});
describe("the contrast calculator", () => {
it("agrees with WCAG's reference values", () => {
expect(contrastRatio("#000000", "#ffffff")).toBeCloseTo(21, 5);
expect(contrastRatio("#ffffff", "#ffffff")).toBeCloseTo(1, 5);
expect(contrastRatio("#767676", "#ffffff")).toBeCloseTo(4.54, 2);
});
});
describe("decorative placeholders stay visible in both schemes", () => {
// A skeleton is hidden from assistive technology, so WCAG sets no ratio for it; it still has to be
// seen against what it sits on, or it is a blank page rather than a shape of what is coming.
it.each(["light", "dark"] as const)("%s", (scheme) => {
for (const background of [
"background.page",
"background.surface",
"background.canvas",
] as const) {
const ratio = contrastRatio(
ekklesiaDesignTokens.valueFor("background.placeholder", scheme),
ekklesiaDesignTokens.valueFor(background, scheme),
);
expect(ratio, background).toBeGreaterThanOrEqual(1.1);
}
});
});
@@ -98,11 +98,17 @@ describe("the Ekklesia design token registry", () => {
expect(ekklesiaDesignTokens.variable("text.primary")).toBe("--ekklesia-text-primary");
});
it("emits a stylesheet declaring every registered token exactly once", () => {
it("emits a stylesheet declaring every token once in its base rule, and again only where it varies", () => {
const stylesheet = ekklesiaDesignTokenStylesheet();
const base = stylesheet.slice(0, stylesheet.indexOf("}"));
for (const token of ekklesiaDesignTokens.list()) {
expect(stylesheet.split(`${token.cssVariable}:`).length).toBe(2);
expect(base.split(`${token.cssVariable}:`).length, token.name).toBe(2);
// Once more in each of the two dark rules (system and explicit), and in each of the two
// reduced-motion rules, and nowhere else (ADR 0060).
const expected =
1 + (token.dark === undefined ? 0 : 2) + (token.reduced === undefined ? 0 : 2);
expect(stylesheet.split(`${token.cssVariable}:`).length - 1, token.name).toBe(expected);
}
});
+325
View File
@@ -0,0 +1,325 @@
import { describe, expect, it, vi } from "vitest";
import {
createDesignTokenRegistry,
createEkklesiaThemeController,
DESIGN_TOKEN_APPEARANCE_ATTRIBUTE,
DESIGN_TOKEN_MOTION_ATTRIBUTE,
DesignTokenError,
EKKLESIA_DARK_SCHEME_QUERY,
EKKLESIA_REDUCED_MOTION_QUERY,
type EkklesiaMediaQueryList,
ekklesiaDesignTokens,
ekklesiaDesignTokenStylesheet,
parseEkklesiaAppearance,
parseEkklesiaMotionPreference,
resolveEkklesiaColorScheme,
resolveEkklesiaReducedMotion,
} from "../src/index.js";
/** A media query a test can flip, as a running OS would. */
function mediaQuery(initial = false) {
const listeners = new Set<() => void>();
const query: EkklesiaMediaQueryList & { set(matches: boolean): void } = {
addEventListener: (_type, listener) => listeners.add(listener),
matches: initial,
removeEventListener: (_type, listener) => listeners.delete(listener),
set(matches) {
(query as { matches: boolean }).matches = matches;
for (const listener of [...listeners]) {
listener();
}
},
};
return { listeners, query };
}
function environment(options: { dark?: boolean; reduced?: boolean } = {}) {
const dark = mediaQuery(options.dark);
const reduced = mediaQuery(options.reduced);
const attributes = new Map<string, string>();
const target = {
setAttribute: vi.fn((name: string, value: string) => attributes.set(name, value)),
};
const matchMedia = (query: string) => {
if (query === EKKLESIA_DARK_SCHEME_QUERY) {
return dark.query;
}
if (query === EKKLESIA_REDUCED_MOTION_QUERY) {
return reduced.query;
}
throw new Error(`unexpected query ${query}`);
};
return { attributes, dark, matchMedia, reduced, target };
}
const COLOUR_CATEGORIES = new Set(["background", "text", "accent", "status", "state"]);
const isColour = (value: string) => /^(?:#[0-9a-f]{6}|rgba\()/u.test(value);
describe("light and dark token sets", () => {
it("gives every colour and shadow a dark value, so no semantic token is missing in either theme", () => {
const colours = ekklesiaDesignTokens
.list()
.filter((token) => isColour(token.value) || token.category === "shadow");
expect(colours.length).toBeGreaterThan(35);
for (const token of colours) {
if (token.name === "shadow.none") {
continue;
}
expect(token.dark, token.name).toBeDefined();
expect(token.dark, token.name).not.toBe(token.value);
}
});
it("varies only colour, shadow, and border-colour tokens by scheme", () => {
for (const token of ekklesiaDesignTokens.list()) {
if (token.dark === undefined) {
continue;
}
expect(
COLOUR_CATEGORIES.has(token.category) ||
token.category === "shadow" ||
(token.category === "border" && isColour(token.value)),
token.name,
).toBe(true);
}
});
it("is a designed dark theme, not an inversion: no pure black or pure white surfaces or text", () => {
for (const name of [
"background.page",
"background.canvas",
"background.surface",
"background.raised",
"text.primary",
] as const) {
expect(ekklesiaDesignTokens.valueFor(name, "dark"), name).not.toMatch(
/^#(?:000000|ffffff)$/u,
);
}
});
it("answers a token's value per scheme, falling back to its single value", () => {
expect(ekklesiaDesignTokens.valueFor("background.page", "light")).toBe("#f3f7f6");
expect(ekklesiaDesignTokens.valueFor("background.page", "dark")).toBe("#0e1615");
expect(ekklesiaDesignTokens.valueFor("spacing.md", "dark")).toBe("0.75rem");
expect(() => ekklesiaDesignTokens.valueFor("nope" as "spacing.md", "dark")).toThrow(
DesignTokenError,
);
});
it("validates a dark or reduced value exactly like a default value", () => {
for (const hostile of ["red; color: blue", "url(x)", "#fff !important", "a{b}"]) {
expect(() =>
createDesignTokenRegistry([
{ dark: hostile, description: "d", label: "l", name: "text.x", value: "#fff" },
]),
).toThrow(DesignTokenError);
expect(() =>
createDesignTokenRegistry([
{ description: "d", label: "l", name: "motion.x", reduced: hostile, value: "1s" },
]),
).toThrow(DesignTokenError);
}
});
});
describe("the theme stylesheet resolves appearance and motion in CSS", () => {
const stylesheet = ekklesiaDesignTokenStylesheet();
it("is deterministic", () => {
expect(ekklesiaDesignTokenStylesheet()).toBe(stylesheet);
});
it("is light by default and says so to the browser", () => {
expect(stylesheet.startsWith(":root {\n color-scheme: light;\n")).toBe(true);
expect(stylesheet).toContain("--ekklesia-background-page: #f3f7f6;");
});
it("follows the system into dark unless light was chosen, and goes dark when dark was chosen", () => {
expect(stylesheet).toContain(
`@media (prefers-color-scheme: dark) {\n:root:not([${DESIGN_TOKEN_APPEARANCE_ATTRIBUTE}="light"]) {\n color-scheme: dark;\n`,
);
expect(stylesheet).toContain(
`:root[${DESIGN_TOKEN_APPEARANCE_ATTRIBUTE}="dark"] {\n color-scheme: dark;\n`,
);
const darkRule = stylesheet.slice(
stylesheet.indexOf(`:root[${DESIGN_TOKEN_APPEARANCE_ATTRIBUTE}="dark"]`),
);
expect(darkRule).toContain("--ekklesia-background-page: #0e1615;");
});
it("zeroes every motion duration when the system asks, unless motion was allowed, and when reduce was chosen", () => {
expect(stylesheet).toContain(
`@media (prefers-reduced-motion: reduce) {\n:root:not([${DESIGN_TOKEN_MOTION_ATTRIBUTE}="allow"]) {\n --ekklesia-motion-duration-short: 0ms;\n --ekklesia-motion-duration-ambient: 0s;\n}\n}`,
);
expect(stylesheet).toContain(
`:root[${DESIGN_TOKEN_MOTION_ATTRIBUTE}="reduce"] {\n --ekklesia-motion-duration-short: 0ms;\n --ekklesia-motion-duration-ambient: 0s;\n}`,
);
for (const token of ekklesiaDesignTokens.listByCategory("motion")) {
expect(token.reduced, token.name).toMatch(/^0m?s$/u);
}
});
it("uses the same rules on an isolated root's host element", () => {
const host = ekklesiaDesignTokenStylesheet("host");
expect(host.startsWith(":host {")).toBe(true);
expect(host).toContain(`:host(:not([${DESIGN_TOKEN_APPEARANCE_ATTRIBUTE}="light"]))`);
expect(host).toContain(`:host([${DESIGN_TOKEN_APPEARANCE_ATTRIBUTE}="dark"])`);
expect(host).toContain(`:host([${DESIGN_TOKEN_MOTION_ATTRIBUTE}="reduce"])`);
});
});
describe("radius", () => {
it("scales the small, medium, and large radii from one multiplier, keeping today's values", () => {
expect(ekklesiaDesignTokens.get("radius.scale")?.value).toBe("1");
expect(ekklesiaDesignTokens.get("radius.sm")?.value).toBe(
"calc(0.25rem * var(--ekklesia-radius-scale))",
);
expect(ekklesiaDesignTokens.get("radius.md")?.value).toBe(
"calc(0.625rem * var(--ekklesia-radius-scale))",
);
expect(ekklesiaDesignTokens.get("radius.lg")?.value).toBe(
"calc(0.875rem * var(--ekklesia-radius-scale))",
);
expect(ekklesiaDesignTokens.get("radius.pill")?.value).toBe("9999px");
expect(ekklesiaDesignTokens.get("radius.none")?.value).toBe("0");
});
});
describe("appearance and motion preferences", () => {
it("default to system, and read untrusted values safely", () => {
expect(parseEkklesiaAppearance(undefined)).toBe("system");
expect(parseEkklesiaAppearance("dark")).toBe("dark");
expect(parseEkklesiaAppearance("DARK")).toBe("system");
expect(parseEkklesiaAppearance({})).toBe("system");
expect(parseEkklesiaMotionPreference("allow")).toBe("allow");
expect(parseEkklesiaMotionPreference("off")).toBe("system");
});
it("resolve to what is on screen", () => {
expect(resolveEkklesiaColorScheme("system", false)).toBe("light");
expect(resolveEkklesiaColorScheme("system", true)).toBe("dark");
expect(resolveEkklesiaColorScheme("light", true)).toBe("light");
expect(resolveEkklesiaColorScheme("dark", false)).toBe("dark");
expect(resolveEkklesiaReducedMotion("system", true)).toBe(true);
expect(resolveEkklesiaReducedMotion("system", false)).toBe(false);
expect(resolveEkklesiaReducedMotion("reduce", false)).toBe(true);
expect(resolveEkklesiaReducedMotion("allow", true)).toBe(false);
});
});
describe("the theme controller", () => {
it("defaults to System and applies its attributes at once, before anything renders", () => {
const env = environment();
const controller = createEkklesiaThemeController({
matchMedia: env.matchMedia,
target: env.target,
});
expect(controller.appearance()).toBe("system");
expect(controller.motion()).toBe("system");
expect(env.attributes.get(DESIGN_TOKEN_APPEARANCE_ATTRIBUTE)).toBe("system");
expect(env.attributes.get(DESIGN_TOKEN_MOTION_ATTRIBUTE)).toBe("system");
});
it("resolves System to Light or Dark from the system, and follows it live", () => {
const env = environment({ dark: false });
const controller = createEkklesiaThemeController({
matchMedia: env.matchMedia,
target: env.target,
});
const listener = vi.fn();
controller.subscribe(listener);
expect(controller.colorScheme()).toBe("light");
env.dark.query.set(true);
expect(controller.colorScheme()).toBe("dark");
expect(listener).toHaveBeenCalledTimes(1);
});
it("lets an explicit Light or Dark ignore the system", () => {
for (const appearance of ["light", "dark"] as const) {
const env = environment({ dark: appearance === "light" });
const controller = createEkklesiaThemeController({
appearance,
matchMedia: env.matchMedia,
target: env.target,
});
expect(controller.colorScheme(), appearance).toBe(appearance);
env.dark.query.set(appearance !== "light");
expect(controller.colorScheme(), appearance).toBe(appearance);
expect(env.attributes.get(DESIGN_TOKEN_APPEARANCE_ATTRIBUTE)).toBe(appearance);
}
});
it("switches mode in place, without a reload, and only notifies on a real change", () => {
const env = environment({ dark: true });
const controller = createEkklesiaThemeController({
matchMedia: env.matchMedia,
target: env.target,
});
const listener = vi.fn();
controller.subscribe(listener);
controller.setAppearance("light");
expect(env.attributes.get(DESIGN_TOKEN_APPEARANCE_ATTRIBUTE)).toBe("light");
expect(controller.colorScheme()).toBe("light");
controller.setAppearance("light");
controller.setAppearance("dark");
controller.setAppearance("system");
expect(controller.colorScheme()).toBe("dark");
expect(listener).toHaveBeenCalledTimes(3);
});
it("follows the system's reduced-motion setting, and supports an explicit Reduce or Allow", () => {
const env = environment({ reduced: false });
const controller = createEkklesiaThemeController({
matchMedia: env.matchMedia,
target: env.target,
});
expect(controller.reducedMotion()).toBe(false);
env.reduced.query.set(true);
expect(controller.reducedMotion()).toBe(true);
controller.setMotion("allow");
expect(env.attributes.get(DESIGN_TOKEN_MOTION_ATTRIBUTE)).toBe("allow");
expect(controller.reducedMotion()).toBe(false);
controller.setMotion("reduce");
env.reduced.query.set(false);
expect(controller.reducedMotion()).toBe(true);
});
it("takes an untrusted stored preference straight in", () => {
const env = environment();
const controller = createEkklesiaThemeController({
appearance: "purple" as "dark",
matchMedia: env.matchMedia,
motion: 7 as unknown as "reduce",
target: env.target,
});
expect(controller.appearance()).toBe("system");
expect(controller.motion()).toBe("system");
});
it("listens to the system only while someone is subscribed", () => {
const env = environment();
const controller = createEkklesiaThemeController({
matchMedia: env.matchMedia,
target: env.target,
});
const unsubscribe = controller.subscribe(() => undefined);
expect(env.dark.listeners.size).toBe(1);
expect(env.reduced.listeners.size).toBe(1);
unsubscribe();
expect(env.dark.listeners.size).toBe(0);
expect(env.reduced.listeners.size).toBe(0);
});
it("works with no media queries at all, as light with full motion", () => {
const env = environment();
const controller = createEkklesiaThemeController({ target: env.target });
expect(controller.colorScheme()).toBe("light");
expect(controller.reducedMotion()).toBe(false);
});
});