Lutra/ui/tests/theme/ThemePicker.test.ts
danny 086bc8a925 T1: four more themes, theme picker, theme file import, editor font settings
Plum Night, River, Paper and Reed (designed by Amy, approved by Daniel)
join the brand pair. theme.list/current/select/import, a picker with
live preview (view.selectTheme) and "Import Theme…" (view.importTheme);
imported themes are validated and stored in <data_dir>/themes. Editor
font family and line height settings apply live. Docs: docs/themes.md.

Gate: fmt, clippy and the rest pass up to cargo test, where only the
unrelated lutra-terminal PTY test a_full_buffer_stops_the_shell timed
out under load; to be re-run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:31:34 +01:00

279 lines
10 KiB
TypeScript

/**
* Tests of the theme picker and theme import (C9 T1): "Select Theme…"
* lists the six built-in themes, imported ones and "Same as system" with
* the current one selected; moving previews the tokens live; Escape puts
* the theme back; Enter switches through `theme.select`; "Import Theme…"
* runs `theme.import` with the picked file and reports success or the
* engine's reason. The engine is a fake behind the mocked Tauri `invoke`
* and `listen`, answering from the `themes.json` snapshot.
*/
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { createPinia, setActivePinia, type Pinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import themes from "./themes.json";
const invoke = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
vi.mock("@tauri-apps/api/event", () => ({ listen: () => Promise.resolve(() => undefined) }));
import { useCommandsStore } from "../../src/commands/store";
import { useModalsStore } from "../../src/commands/modals";
import ThemePicker from "../../src/components/theme/ThemePicker.vue";
import { SYSTEM, toThemeInfo, toThemeList, useThemesStore } from "../../src/components/theme/themes";
import { useNotificationsStore } from "../../src/stores/notifications";
/** An imported theme as `theme.list` lists it. */
const IMPORTED = {
id: "dusk",
label: null,
name: "My Dusk",
dark: true,
builtin: false,
tokens: { ...(themes[3]?.tokens ?? {}), "--lt-bg": "#102030" },
};
/** The fake engine's `appearance.theme`. */
let setting: string;
/** Every `engine_execute` call, in order. */
let calls: { command: string; params: Record<string, unknown> }[];
/** What `pick_file` returns. */
let picked: string | null;
/** Commands that fail, with their message. */
let failing: Map<string, string>;
/** Pinia of the current test. */
let pinia: Pinia;
/** Mounted components, unmounted after each test. */
let mounted: VueWrapper[];
const root = document.documentElement;
/**
* A theme of the fake engine by id.
*
* @param id - the theme id.
*/
function themeOf(id: string): { id: string; dark: boolean; tokens: Record<string, string> } {
if (id === IMPORTED.id) {
return IMPORTED;
}
const found = themes.find((t) => t.id === id) ?? themes[0];
if (!found) {
throw new Error("no themes");
}
return found;
}
/**
* The fake engine's answer to a command.
*
* @param command - the command id.
* @param params - its params.
*/
function answer(command: string, params: Record<string, unknown>): unknown {
switch (command) {
case "theme.list":
return [
...themes.map((t) => ({ id: t.id, label: t.labelKey, name: null, dark: t.dark, builtin: true, tokens: t.tokens })),
IMPORTED,
];
case "settings.get":
return { values: { "appearance.theme": setting } };
case "theme.current":
return themeOf(setting === SYSTEM ? "lutra-dark" : setting);
case "theme.select":
setting = params.id as string;
return themeOf(setting === SYSTEM ? "lutra-dark" : setting);
case "theme.import":
return { id: "dusk", name: "My Dusk", dark: true, replaced: false };
default:
return null;
}
}
/** Mounts the picker and starts the command store. */
async function mountPicker(): Promise<VueWrapper> {
const wrapper = mount(ThemePicker, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(wrapper);
await useCommandsStore(pinia).start();
await flushPromises();
return wrapper;
}
/**
* Presses a key on the picker's list.
*
* @param wrapper - the picker.
* @param key - the key.
*/
async function press(wrapper: VueWrapper, key: string): Promise<void> {
await wrapper.find("[data-test=theme-picker-list]").trigger("keydown", { key });
await flushPromises();
}
/**
* The ids of the listed themes.
*
* @param wrapper - the picker.
*/
function ids(wrapper: VueWrapper): string[] {
return wrapper.findAll("[data-test=theme-picker-row]").map((row) => row.attributes("data-id") ?? "");
}
beforeEach(() => {
pinia = createPinia();
setActivePinia(pinia);
setting = "lutra-river";
calls = [];
picked = null;
failing = new Map();
mounted = [];
root.removeAttribute("style");
invoke.mockReset();
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (cmd === "engine_list_commands") {
return Promise.resolve([]);
}
if (cmd === "pick_file") {
return Promise.resolve(picked);
}
if (cmd === "engine_execute" && args) {
calls.push({ command: args.command, params: args.params });
const message = failing.get(args.command);
if (message !== undefined) {
return Promise.reject(Object.assign(new Error(message), { code: "failed", message }));
}
return Promise.resolve(answer(args.command, args.params));
}
return Promise.resolve(null);
});
});
afterEach(() => {
useCommandsStore(pinia).stop();
for (const wrapper of mounted) {
wrapper.unmount();
}
});
describe("theme list helpers", () => {
it("reads theme.list defensively and names themes", () => {
expect(toThemeList("nope")).toBeNull();
const list = toThemeList([null, { id: 1 }, ...themes.map((t) => ({ ...t, label: t.labelKey })), IMPORTED]);
expect(list?.map((t) => t.name)).toEqual([
"Lutra Dark",
"Lutra Light",
"Plum Night",
"River",
"Paper",
"Reed",
"My Dusk",
"Same as system",
]);
expect(list?.at(-1)).toMatchObject({ id: SYSTEM, dark: null, theme: null });
expect(toThemeInfo({ id: "x", dark: false, name: " " })?.name).toBe("x");
});
});
describe("theme picker", () => {
it("opens from view.selectTheme with every theme and the current one selected", async () => {
const wrapper = await mountPicker();
await useCommandsStore(pinia).execute("view.selectTheme");
await flushPromises();
expect(ids(wrapper)).toEqual([
"lutra-dark",
"lutra-light",
"lutra-plum-night",
"lutra-river",
"lutra-paper",
"lutra-reed",
"dusk",
SYSTEM,
]);
const selected = wrapper.find(".theme-picker__row--selected");
expect(selected.attributes("data-id")).toBe("lutra-river");
expect(selected.text()).toContain("River");
expect(selected.text()).toContain("current");
expect(wrapper.find('[data-id="dusk"]').text()).toContain("Dark, imported");
expect(useModalsStore(pinia).current).toBe("themes");
expect(document.activeElement?.getAttribute("data-test")).toBe("theme-picker-list");
});
it("previews while moving and puts the theme back on Escape", async () => {
const wrapper = await mountPicker();
await useThemesStore(pinia).show();
await flushPromises();
await press(wrapper, "ArrowDown");
expect(root.style.getPropertyValue("--lt-bg")).toBe(themeOf("lutra-paper").tokens["--lt-bg"]);
expect(root.style.colorScheme).toBe("light");
await press(wrapper, "End");
expect(root.style.getPropertyValue("--lt-bg")).toBe(themeOf("lutra-river").tokens["--lt-bg"]);
await press(wrapper, "ArrowUp");
expect(root.style.getPropertyValue("--lt-bg")).toBe("#102030");
await press(wrapper, "Escape");
expect(wrapper.find("[data-test=theme-picker]").exists()).toBe(false);
expect(root.style.getPropertyValue("--lt-bg")).toBe(themeOf("lutra-river").tokens["--lt-bg"]);
expect(calls.some((c) => c.command === "theme.select")).toBe(false);
expect(useModalsStore(pinia).current).toBeNull();
});
it("switches with Enter and with a click", async () => {
const wrapper = await mountPicker();
await useThemesStore(pinia).show();
await flushPromises();
await press(wrapper, "Home");
await press(wrapper, "ArrowDown");
await press(wrapper, "ArrowDown");
await press(wrapper, "Enter");
expect(calls.filter((c) => c.command === "theme.select").map((c) => c.params)).toEqual([{ id: "lutra-plum-night" }]);
expect(wrapper.find("[data-test=theme-picker]").exists()).toBe(false);
expect(root.dataset.theme).toBe("lutra-plum-night");
await useThemesStore(pinia).show();
await flushPromises();
await wrapper.find('[data-id="lutra-reed"]').trigger("click");
await flushPromises();
expect(setting).toBe("lutra-reed");
expect(root.style.getPropertyValue("--lt-bg")).toBe(themeOf("lutra-reed").tokens["--lt-bg"]);
});
it("puts the theme back and raises a toast when switching fails", async () => {
const wrapper = await mountPicker();
failing.set("theme.select", "settings cannot be saved");
await useThemesStore(pinia).show();
await flushPromises();
await press(wrapper, "ArrowDown");
await press(wrapper, "Enter");
expect(root.style.getPropertyValue("--lt-bg")).toBe(themeOf("lutra-river").tokens["--lt-bg"]);
expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toContain("settings cannot be saved");
});
});
describe("theme import", () => {
it("imports the picked file and confirms it", async () => {
await mountPicker();
picked = "C:/themes/dusk.json";
await useCommandsStore(pinia).execute("view.importTheme");
await flushPromises();
expect(calls.find((c) => c.command === "theme.import")?.params).toEqual({ path: "C:/themes/dusk.json" });
expect(useNotificationsStore(pinia).toasts.at(-1)).toMatchObject({ level: "info", text: "Imported the theme My Dusk." });
});
it("does nothing when the file dialog is cancelled", async () => {
await mountPicker();
await useThemesStore(pinia).importFile();
await flushPromises();
expect(calls.filter((c) => c.command.startsWith("theme."))).toEqual([]);
expect(useNotificationsStore(pinia).toasts).toEqual([]);
});
it("shows the reason of a broken file", async () => {
await mountPicker();
picked = "C:/themes/bad.json";
failing.set("theme.import", 'cannot import the theme C:/themes/bad.json: 59 tokens are missing: bg, editor-bg');
await useThemesStore(pinia).importFile();
await flushPromises();
const toast = useNotificationsStore(pinia).toasts.at(-1);
expect(toast?.level).toBe("error");
expect(toast?.text).toContain("59 tokens are missing");
});
});