Lutra/ui/tests/theme/theme.test.ts
danny f41df518b5 M1.12: notifications as toasts
The host publishes picker, command-line and pump errors as notification
events (Engine::notify, same id sequence) instead of stderr, keeps
notifications and watchFailed published before engine_ready and replays
them after the state replay, so startup warnings (corrupt settings,
journal entries) reach the UI. ipc.ts announces engine_ready once all
subscriptions started together are registered.

Frontend: notifications store and NotificationStack (bottom right, info
auto-dismissed after 5 s, warnings/errors stay, close button and Escape,
at most 5 visible with "+n more", role status/alert); watchFailed maps to
a warning toast; failed commands without their own UI raise an error
toast. Catalog keys notification.settings.*, project.*, vfs.*, watch.*,
command.* plus the runtime allow-list. Docs updated.

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

196 lines
6.6 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 and reports the error when the engine call fails", async () => {
invoke.mockRejectedValue({ code: "internal", message: "down" });
const onError = vi.fn();
const stop = startTheme(onError);
await flushPromises();
expect(root.dataset.theme).toBeUndefined();
expect(onError).toHaveBeenCalledWith({ code: "internal", message: "down" });
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})`);
}
});
});