Lutra/ui/tests/theme/theme.test.ts
danny cde6e119c6 M1.10: light theme, live theme switching, editor tokens
- theme::LIGHT next to DARK with the 10 new tokens (editor selection,
  active line, cursor, gutter, match, font size, tab active/modified,
  notice); light fg-muted, accent and error darkened for WCAG AA
- theme.list, theme.systemPreference, themeChanged event when the
  resolved theme changes (settings.set/reset appearance.theme, or the
  OS preference in system mode)
- desktop init script and window background from the stored setting;
  system mode uses a prefers-color-scheme media query for the first frame
- ui/src/theme.ts applies tokens to :root and color-scheme live; editor,
  tabs and notice drop their var() fallbacks
- Vitest WCAG AA contrast check against a Rust-maintained snapshot,
  DOM tests, headless control-channel test
- docs: architecture Themes, parity rows, ui-parity, gaps, roadmaps

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 15:49:23 +02:00

194 lines
6.5 KiB
TypeScript

/**
* Tests of live theme switching (`ui/src/theme.ts`): tokens and
* `color-scheme` land on `:root`, `themeChanged` events and the OS
* preference drive it, and the components read only tokens both themes
* define (no `var(--lt-x, fallback)` left for theme tokens).
*/
import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { flushPromises } from "@vue/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import themes from "./themes.json";
const invoke = vi.hoisted(() => vi.fn());
const listeners = vi.hoisted(() => new Map<string, (event: { payload: unknown }) => void>());
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
vi.mock("@tauri-apps/api/event", () => ({
listen: (name: string, handler: (event: { payload: unknown }) => void) => {
listeners.set(name, handler);
return Promise.resolve(() => listeners.delete(name));
},
}));
import { ENGINE_EVENT } from "../../src/ipc";
import { applyTheme, startTheme, toResolvedTheme, type ResolvedTheme } from "../../src/theme";
/** The snapshot themes by id. */
const byId = (id: string): ResolvedTheme => {
const theme = themes.find((t) => t.id === id);
if (!theme) {
throw new Error(`no theme ${id}`);
}
return theme;
};
/** A controllable `matchMedia` stand-in. */
function fakeMedia(dark: boolean) {
const handlers = new Set<(event: MediaQueryListEvent) => void>();
const query = {
matches: dark,
addEventListener: (_: string, h: (event: MediaQueryListEvent) => void) => handlers.add(h),
removeEventListener: (_: string, h: (event: MediaQueryListEvent) => void) =>
handlers.delete(h),
};
return {
query,
handlers,
change(next: boolean) {
query.matches = next;
for (const h of handlers) {
h({ matches: next } as MediaQueryListEvent);
}
},
};
}
const root = document.documentElement;
beforeEach(() => {
invoke.mockReset();
listeners.clear();
root.removeAttribute("style");
delete root.dataset.theme;
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe("applyTheme", () => {
it("writes every token and the colour scheme onto :root", () => {
const light = byId("lutra-light");
applyTheme(light);
for (const [name, value] of Object.entries(light.tokens)) {
expect(root.style.getPropertyValue(name)).toBe(value);
}
expect(root.style.colorScheme).toBe("light");
expect(root.dataset.theme).toBe("lutra-light");
applyTheme(byId("lutra-dark"));
expect(root.style.getPropertyValue("--lt-bg")).toBe("#1f1d1b");
expect(root.style.getPropertyValue("--lt-editor-selection-bg")).toBe("#513f2c");
expect(root.style.colorScheme).toBe("dark");
});
});
describe("toResolvedTheme", () => {
it("rejects malformed data and drops foreign tokens", () => {
expect(toResolvedTheme(null)).toBeNull();
expect(toResolvedTheme({ id: "x" })).toBeNull();
expect(
toResolvedTheme({
kind: "themeChanged",
id: "x",
dark: true,
tokens: { "--lt-bg": "#000000", color: "red", "--lt-fg": 3 },
}),
).toEqual({ id: "x", dark: true, tokens: { "--lt-bg": "#000000" } });
});
});
describe("startTheme", () => {
it("reports the OS preference, applies the result and follows changes", async () => {
const media = fakeMedia(false);
vi.stubGlobal("matchMedia", () => media.query);
invoke.mockImplementation((_: string, args: { command: string; params: { dark: boolean } }) =>
Promise.resolve(
args.command === "theme.systemPreference"
? byId(args.params.dark ? "lutra-dark" : "lutra-light")
: null,
),
);
const stop = startTheme();
await flushPromises();
expect(invoke).toHaveBeenCalledWith("engine_execute", {
command: "theme.systemPreference",
params: { dark: false },
});
expect(root.dataset.theme).toBe("lutra-light");
expect(root.style.colorScheme).toBe("light");
media.change(true);
await flushPromises();
expect(root.dataset.theme).toBe("lutra-dark");
expect(root.style.getPropertyValue("--lt-bg")).toBe("#1f1d1b");
stop();
expect(media.handlers.size).toBe(0);
});
it("applies themeChanged events without a reload", async () => {
invoke.mockResolvedValue(null);
const stop = startTheme();
await flushPromises();
const emit = listeners.get(ENGINE_EVENT);
expect(emit).toBeDefined();
emit?.({ payload: { kind: "themeChanged", ...byId("lutra-light") } });
expect(root.dataset.theme).toBe("lutra-light");
expect(root.style.getPropertyValue("--lt-notice-bg")).toBe("#e9dfd4");
emit?.({ payload: { kind: "treeChanged", dir: "" } });
expect(root.dataset.theme).toBe("lutra-light");
stop();
});
it("keeps the current theme when the engine call fails", async () => {
invoke.mockRejectedValue({ code: "internal", message: "down" });
const stop = startTheme();
await flushPromises();
expect(root.dataset.theme).toBeUndefined();
stop();
});
});
describe("components", () => {
const SRC = join(import.meta.dirname, "..", "..", "src");
const files = (dir: string): string[] =>
readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
const path = join(dir, entry.name);
if (entry.isDirectory()) {
return files(path);
}
return /\.(ts|vue|css)$/.test(entry.name) ? [path] : [];
});
const source = files(SRC).map((file) => readFileSync(file, "utf8"));
const defined = (name: string) => themes.every((t) => name in t.tokens);
it("use only theme tokens that both themes define, without fallbacks", () => {
const used = source.flatMap((text) =>
[...text.matchAll(/var\((--lt-[a-z0-9-]+)\s*(,)?/g)].map((m) => ({
name: m[1] ?? "",
fallback: m[2] !== undefined,
})),
);
expect(used.length).toBeGreaterThan(0);
const missing = used.filter((u) => !u.fallback && !defined(u.name)).map((u) => u.name);
expect([...new Set(missing)]).toEqual([]);
const needless = used.filter((u) => u.fallback && defined(u.name)).map((u) => u.name);
expect([...new Set(needless)]).toEqual([]);
});
it("give the editor every editor token", () => {
const editor = readFileSync(join(SRC, "components", "editor", "extensions.ts"), "utf8");
for (const name of [
"--lt-editor-selection-bg",
"--lt-editor-active-line-bg",
"--lt-editor-cursor",
"--lt-editor-gutter-bg",
"--lt-editor-gutter-fg",
"--lt-editor-match-bg",
"--lt-font-size-editor",
]) {
expect(editor).toContain(`var(${name})`);
}
});
});