M1.9b: settings dialog with search

settings.open (Mod+,) opens a dialog built from settings.list: sections,
controls by type (select, number with min/max, switch), catalog labels
and descriptions, search over label, description, key and section, Reset
to default, inline errors, live updates on settingsChanged. The theme
picker switches at once; editor.fontSize drives --lt-font-size-editor
through a token override that survives theme switches. Focus trap,
Escape closes. Finishes M1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-16 21:13:04 +02:00
parent db34e2ca52
commit 523d7f684f
17 changed files with 1751 additions and 36 deletions

View file

@ -40,7 +40,9 @@ const usedKeys = sourceFiles(SRC).flatMap((file) =>
/**
* Keys the source never passes to `t` literally because they arrive at
* runtime: theme labels from `theme.list`, the `messageKey` of
* runtime: theme labels from `theme.list`, the settings' `labelKey`,
* `descriptionKey`, section names and enum value names from
* `settings.list`, the `messageKey` of
* `notification` events (engine and desktop host), and the keys the
* notifications store passes through a constant.
*/
@ -57,6 +59,18 @@ const RUNTIME_KEYS = new Set([
"notification.settings.unavailable",
"notification.vfs.pumpFailed",
"notification.watch.failed",
"settings.appearance.theme.description",
"settings.appearance.theme.label",
"settings.appearance.theme.value.lutraDark",
"settings.appearance.theme.value.lutraLight",
"settings.appearance.theme.value.system",
"settings.editor.fontSize.description",
"settings.editor.fontSize.label",
"settings.section.appearance",
"settings.section.editor",
"settings.ui.language.description",
"settings.ui.language.label",
"settings.ui.language.value.en",
"theme.lutraDark",
"theme.lutraLight",
]);
@ -108,7 +122,7 @@ describe("en.json", () => {
it("uses flat dotted keys of known areas with string values", () => {
for (const [key, value] of Object.entries(en)) {
expect(key).toMatch(
/^(app|command|project|editor|common|palette|theme|recovery|notification)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
/^(app|command|project|editor|common|palette|theme|recovery|notification|settings)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
);
expect(typeof value).toBe("string");
expect(value.trim()).not.toBe("");

View file

@ -0,0 +1,453 @@
/**
* Tests of the settings store and dialog: opening through `settings.open`
* (`Mod+,`), rendering from a mocked `settings.list` (sections, controls by
* type, catalog labels), search, changes through `settings.set`, inline
* errors (refused here and by the engine), reset, live updates on
* `settingsChanged`, the editor font size token, focus trap and Escape.
* The engine is a fake behind the mocked Tauri `invoke` and `listen`.
*/
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 { defineComponent, h } from "vue";
const invoke = vi.hoisted(() => vi.fn());
const listen = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
vi.mock("@tauri-apps/api/event", () => ({ listen }));
import { useCommandsStore } from "../../src/commands/store";
import SettingsDialog from "../../src/components/settings/SettingsDialog.vue";
import {
FONT_SIZE_TOKEN,
matchesQuery,
toSettingDefs,
useSettingsStore,
valueLabel,
type SettingDef,
} from "../../src/stores/settings";
import { applyTheme, setTokenOverride } from "../../src/theme";
/** What the fake engine's `settings.list` returns. */
const LIST = [
{
key: "appearance.theme",
type: "enum",
default: "system",
enumValues: ["lutra-dark", "lutra-light", "system"],
labelKey: "settings.appearance.theme.label",
descriptionKey: "settings.appearance.theme.description",
section: "appearance",
},
{
key: "editor.fontSize",
type: "int",
default: 14,
min: 8,
max: 48,
labelKey: "settings.editor.fontSize.label",
descriptionKey: "settings.editor.fontSize.description",
section: "editor",
},
{
key: "ui.language",
type: "enum",
default: "en",
enumValues: ["en"],
labelKey: "settings.ui.language.label",
descriptionKey: "settings.ui.language.description",
section: "appearance",
},
{
key: "editor.softWrap",
type: "bool",
default: false,
labelKey: "settings.editor.softWrap.label",
descriptionKey: "settings.editor.softWrap.description",
section: "editor",
},
];
/** The fake engine's values. */
let values: Record<string, unknown>;
/** Every `engine_execute` call, in order. */
let calls: { command: string; params: unknown }[];
/** Commands that fail, with their error. */
let failing: Map<string, { code: string; message: string }>;
/** The engine event callbacks, one per subscription. */
let listeners: ((payload: unknown) => void)[];
/** Pinia of the current test. */
let pinia: Pinia;
/** Mounted components, unmounted after each test. */
let mounted: VueWrapper[];
/**
* Sends an engine event to every subscriber.
*
* @param payload - the event.
*/
async function emit(payload: unknown): Promise<void> {
for (const listener of listeners) {
listener(payload);
}
await flushPromises();
}
/**
* An error as the shell rejects with: an `Error` carrying `code` and `message`.
*
* @param code - the error code.
* @param message - the message.
*/
function engineError(code: string, message: string): Error {
return Object.assign(new Error(message), { code, message });
}
/**
* 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 {
const def = LIST.find((d) => d.key === params.key);
switch (command) {
case "settings.list":
return LIST;
case "settings.get": {
const keys = Array.isArray(params.keys) ? (params.keys as string[]) : Object.keys(values);
return { values: Object.fromEntries(keys.map((k) => [k, values[k]])) };
}
case "settings.set":
if (def?.type === "int" && (typeof params.value !== "number" || params.value < 8 || params.value > 48)) {
throw engineError("invalid_params", "editor.fontSize: expected an integer from 8 to 48");
}
values[params.key as string] = params.value;
return { value: params.value };
case "settings.reset":
values[params.key as string] = def?.default;
return { value: def?.default };
default:
return null;
}
}
/** A focusable button standing in for the editor. */
const Host = defineComponent({
setup: () => () => h("button", { id: "host-button" }, "host"),
});
/** Mounts the dialog next to a focusable button and starts the stores. */
async function mountDialog(): Promise<VueWrapper> {
const host = mount(Host, { attachTo: document.body });
const wrapper = mount(SettingsDialog, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(host, wrapper);
await useCommandsStore(pinia).start();
await useSettingsStore(pinia).start();
await flushPromises();
return wrapper;
}
/**
* Presses a key on the focused element (or the body).
*
* @param init - key event properties.
*/
async function press(init: KeyboardEventInit): Promise<void> {
const target = document.activeElement ?? document.body;
target.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...init }));
await flushPromises();
}
/**
* Opens the dialog with `Ctrl+,`.
*
* @param wrapper - the dialog.
*/
async function open(wrapper: VueWrapper): Promise<void> {
document.getElementById("host-button")?.focus();
await press({ key: ",", code: "Comma", ctrlKey: true });
await wrapper.vm.$nextTick();
}
/**
* The keys of the shown settings, in order.
*
* @param wrapper - the dialog.
*/
function rows(wrapper: VueWrapper): string[] {
return wrapper.findAll("[data-test=settings-row]").map((row) => row.attributes("data-key") ?? "");
}
/**
* A setting's row.
*
* @param wrapper - the dialog.
* @param key - the setting.
*/
function row(wrapper: VueWrapper, key: string) {
return wrapper.find(`[data-test=settings-row][data-key="${key}"]`);
}
beforeEach(() => {
pinia = createPinia();
setActivePinia(pinia);
values = { "appearance.theme": "system", "editor.fontSize": 14, "ui.language": "en", "editor.softWrap": false };
calls = [];
failing = new Map();
listeners = [];
mounted = [];
document.documentElement.removeAttribute("style");
listen.mockReset();
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
listeners.push((payload) => {
callback({ payload });
});
return Promise.resolve(() => undefined);
});
invoke.mockReset();
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (cmd === "engine_list_commands") {
return Promise.resolve([]);
}
if (cmd === "engine_execute" && args) {
calls.push({ command: args.command, params: args.params });
const error = failing.get(args.command);
if (error) {
return Promise.reject(engineError(error.code, error.message));
}
try {
return Promise.resolve(answer(args.command, args.params));
} catch (reason: unknown) {
return Promise.reject(reason instanceof Error ? reason : new Error(String(reason)));
}
}
return Promise.resolve(null);
});
});
afterEach(() => {
useCommandsStore(pinia).stop();
useSettingsStore(pinia).stop();
for (const wrapper of mounted) {
wrapper.unmount();
}
setTokenOverride(FONT_SIZE_TOKEN, null);
});
describe("settings helpers", () => {
it("reads settings.list defensively", () => {
expect(toSettingDefs("nope")).toBeNull();
const defs = toSettingDefs([...LIST, null, { key: 1 }, { ...LIST[0], type: "color" }, { ...LIST[0], enumValues: [] }]);
expect(defs?.map((d) => d.key)).toEqual(["appearance.theme", "editor.fontSize", "ui.language", "editor.softWrap"]);
expect(defs?.[1]).toMatchObject({ min: 8, max: 48, enumValues: [] });
});
it("matches label, description, key and section, every word", () => {
const [theme, size] = toSettingDefs(LIST) as SettingDef[];
expect(matchesQuery(size as SettingDef, "font")).toBe(true);
expect(matchesQuery(size as SettingDef, "PIXELS")).toBe(true);
expect(matchesQuery(size as SettingDef, "editor.fontsize")).toBe(true);
expect(matchesQuery(theme as SettingDef, "appearance")).toBe(true);
expect(matchesQuery(theme as SettingDef, "colours system")).toBe(true);
expect(matchesQuery(theme as SettingDef, "colours font")).toBe(false);
});
it("names enum values from the catalog, else the value", () => {
const [theme] = toSettingDefs(LIST) as SettingDef[];
expect(valueLabel(theme as SettingDef, "lutra-dark")).toBe("Lutra Dark");
expect(valueLabel(theme as SettingDef, "system")).toBe("Same as system");
expect(valueLabel(theme as SettingDef, "solarized")).toBe("solarized");
});
});
describe("settings dialog", () => {
it("is disabled until mounted and opens with Mod+, built from settings.list", async () => {
expect(useCommandsStore(pinia).isEnabled("settings.open")).toBe(false);
const wrapper = await mountDialog();
expect(useCommandsStore(pinia).isEnabled("settings.open")).toBe(true);
expect(wrapper.find("[data-test=settings]").exists()).toBe(false);
await open(wrapper);
expect(wrapper.find("[role=dialog]").attributes("aria-modal")).toBe("true");
expect(document.activeElement).toBe(wrapper.find("[data-test=settings-search]").element);
expect(wrapper.findAll("[data-test=settings-section]").map((s) => s.text())).toEqual(["Appearance", "Editor"]);
expect(rows(wrapper)).toEqual(["appearance.theme", "ui.language"]);
const theme = row(wrapper, "appearance.theme");
expect(theme.find("label").text()).toBe("Theme");
expect(theme.find("select").findAll("option").map((o) => o.text())).toEqual([
"Lutra Dark",
"Lutra Light",
"Same as system",
]);
expect((theme.find("select").element as HTMLSelectElement).value).toBe("system");
expect(theme.find("[data-test=settings-reset]").attributes("disabled")).toBeDefined();
await wrapper.find("[data-section=editor]").trigger("click");
expect(rows(wrapper)).toEqual(["editor.fontSize", "editor.softWrap"]);
const size = row(wrapper, "editor.fontSize").find("input");
expect(size.attributes()).toMatchObject({ type: "number", min: "8", max: "48" });
expect((size.element as HTMLInputElement).value).toBe("14");
const wrap = row(wrapper, "editor.softWrap").find("[role=switch]");
expect(wrap.attributes("aria-checked")).toBe("false");
expect(row(wrapper, "editor.softWrap").find("label").text()).toBe("editor.softWrap");
});
it("filters by search across sections and says when nothing matches", async () => {
const wrapper = await mountDialog();
await open(wrapper);
await wrapper.find("[data-test=settings-search]").setValue("font");
expect(rows(wrapper)).toEqual(["editor.fontSize"]);
expect(wrapper.find("[data-section=appearance]").classes()).toContain("settings__section--dim");
await wrapper.find("[data-test=settings-search]").setValue("language interface");
expect(rows(wrapper)).toEqual(["ui.language"]);
await wrapper.find("[data-test=settings-search]").setValue("e");
expect(rows(wrapper)).toEqual(["appearance.theme", "ui.language", "editor.fontSize", "editor.softWrap"]);
await wrapper.find("[data-test=settings-search]").setValue("zebra");
expect(rows(wrapper)).toEqual([]);
expect(wrapper.find("[data-test=settings-empty]").text()).toBe("No settings match your search");
});
it("switches the theme at once through settings.set", async () => {
const wrapper = await mountDialog();
await open(wrapper);
await row(wrapper, "appearance.theme").find("select").setValue("lutra-light");
await flushPromises();
expect(calls.at(-1)).toEqual({ command: "settings.set", params: { key: "appearance.theme", value: "lutra-light" } });
expect(useSettingsStore(pinia).values["appearance.theme"]).toBe("lutra-light");
expect(row(wrapper, "appearance.theme").find("[data-test=settings-reset]").attributes("disabled")).toBeUndefined();
});
it("applies the font size to the editor token, above the theme", async () => {
const wrapper = await mountDialog();
const root = document.documentElement;
expect(root.style.getPropertyValue(FONT_SIZE_TOKEN)).toBe("14px");
await open(wrapper);
await wrapper.find("[data-section=editor]").trigger("click");
await row(wrapper, "editor.fontSize").find("input").setValue("18");
await flushPromises();
expect(calls.at(-1)).toEqual({ command: "settings.set", params: { key: "editor.fontSize", value: 18 } });
expect(root.style.getPropertyValue(FONT_SIZE_TOKEN)).toBe("18px");
applyTheme({ id: "lutra-light", dark: false, tokens: { [FONT_SIZE_TOKEN]: "14px", "--lt-bg": "#fff" } });
expect(root.style.getPropertyValue(FONT_SIZE_TOKEN)).toBe("18px");
expect(root.style.getPropertyValue("--lt-bg")).toBe("#fff");
setTokenOverride(FONT_SIZE_TOKEN, null);
expect(root.style.getPropertyValue(FONT_SIZE_TOKEN)).toBe("14px");
});
it("shows refused values inline and keeps the typed text", async () => {
const wrapper = await mountDialog();
await open(wrapper);
await wrapper.find("[data-section=editor]").trigger("click");
const input = () => row(wrapper, "editor.fontSize").find("input");
await input().setValue("99");
await flushPromises();
expect(calls.some((c) => c.command === "settings.set")).toBe(false);
expect(row(wrapper, "editor.fontSize").find("[data-test=settings-error]").text()).toBe(
"Enter a whole number from 8 to 48",
);
expect(input().attributes("aria-invalid")).toBe("true");
expect((input().element as HTMLInputElement).value).toBe("99");
failing.set("settings.set", { code: "failed", message: "disk full" });
await input().setValue("20");
await flushPromises();
expect(row(wrapper, "editor.fontSize").find("[data-test=settings-error]").text()).toBe("disk full");
expect(useSettingsStore(pinia).values["editor.fontSize"]).toBe(14);
failing.clear();
await input().setValue("20");
await flushPromises();
expect(row(wrapper, "editor.fontSize").find("[data-test=settings-error]").exists()).toBe(false);
expect((input().element as HTMLInputElement).value).toBe("20");
});
it("shows the engine's error for a value it refuses", async () => {
const wrapper = await mountDialog();
await open(wrapper);
await useSettingsStore(pinia).set("editor.fontSize", 2);
await wrapper.find("[data-section=editor]").trigger("click");
expect(row(wrapper, "editor.fontSize").find("[data-test=settings-error]").text()).toBe(
"editor.fontSize: expected an integer from 8 to 48",
);
});
it("resets a setting to its default", async () => {
values["editor.fontSize"] = 20;
const wrapper = await mountDialog();
await open(wrapper);
await wrapper.find("[data-section=editor]").trigger("click");
const reset = row(wrapper, "editor.fontSize").find("[data-test=settings-reset]");
expect(reset.attributes("aria-label")).toBe("Reset Editor font size to default");
await reset.trigger("click");
await flushPromises();
expect(calls.at(-1)).toEqual({ command: "settings.reset", params: { key: "editor.fontSize" } });
expect((row(wrapper, "editor.fontSize").find("input").element as HTMLInputElement).value).toBe("14");
expect(document.documentElement.style.getPropertyValue(FONT_SIZE_TOKEN)).toBe("14px");
});
it("follows settingsChanged from elsewhere while open", async () => {
const wrapper = await mountDialog();
await open(wrapper);
await wrapper.find("[data-section=editor]").trigger("click");
await row(wrapper, "editor.fontSize").find("input").setValue("99");
await flushPromises();
values["editor.fontSize"] = 22;
values["editor.softWrap"] = true;
await emit({ kind: "settingsChanged", keys: ["editor.fontSize", "editor.softWrap", 7] });
expect(calls.at(-1)).toEqual({ command: "settings.get", params: { keys: ["editor.fontSize", "editor.softWrap"] } });
expect((row(wrapper, "editor.fontSize").find("input").element as HTMLInputElement).value).toBe("22");
expect(row(wrapper, "editor.fontSize").find("[data-test=settings-error]").exists()).toBe(false);
expect(row(wrapper, "editor.softWrap").find("[role=switch]").attributes("aria-checked")).toBe("true");
expect(document.documentElement.style.getPropertyValue(FONT_SIZE_TOKEN)).toBe("22px");
await emit({ kind: "settingsChanged", keys: "nope" });
});
it("flips a switch", async () => {
const wrapper = await mountDialog();
await open(wrapper);
await wrapper.find("[data-section=editor]").trigger("click");
await row(wrapper, "editor.softWrap").find("[role=switch]").trigger("click");
await flushPromises();
expect(calls.at(-1)).toEqual({ command: "settings.set", params: { key: "editor.softWrap", value: true } });
expect(row(wrapper, "editor.softWrap").find("[role=switch]").attributes("aria-checked")).toBe("true");
});
it("traps the focus, closes with Escape and gives the focus back", async () => {
const wrapper = await mountDialog();
await open(wrapper);
const dialog = wrapper.find("[data-test=settings-dialog]").element as HTMLElement;
const reachable = [
...dialog.querySelectorAll<HTMLElement>("button:not([disabled]), input, select"),
];
const last = reachable.at(-1) as HTMLElement;
last.focus();
await press({ key: "Tab" });
expect(document.activeElement).toBe(reachable[0]);
await press({ key: "Tab", shiftKey: true });
expect(document.activeElement).toBe(last);
document.getElementById("host-button")?.focus();
expect(document.activeElement).toBe(wrapper.find("[data-test=settings-search]").element);
const above = document.createElement("div");
above.setAttribute("aria-modal", "true");
const field = document.createElement("input");
above.append(field);
document.body.append(above);
field.focus();
expect(document.activeElement).toBe(field);
above.remove();
(wrapper.find("[data-test=settings-search]").element as HTMLElement).focus();
await press({ key: "Escape" });
expect(wrapper.find("[data-test=settings]").exists()).toBe(false);
expect(document.activeElement?.id).toBe("host-button");
});
it("opens from a uiCommand event and shows a load failure", async () => {
const wrapper = await mountDialog();
failing.set("settings.list", { code: "internal", message: "boom" });
await emit({ kind: "uiCommand", id: "settings.open", params: {} });
expect(wrapper.find("[data-test=settings]").exists()).toBe(true);
expect(wrapper.find("[data-test=settings-load-error]").text()).toBe("Settings could not be loaded: boom");
await wrapper.find("[data-test=settings-close]").trigger("click");
expect(wrapper.find("[data-test=settings]").exists()).toBe(false);
});
});

View file

@ -2,7 +2,7 @@
* WCAG 2.1 contrast check of the built-in themes
* (https://www.w3.org/TR/WCAG21/#contrast-minimum). Every token pair the
* UI draws text with reaches AA: 4.5:1 for body text, 3:1 for non-text
* marks (cursor, modified dot; WCAG 1.4.11). The themes come from
* marks (cursor, modified dot, settings switch knob; WCAG 1.4.11). The themes come from
* `themes.json`, a snapshot that the Rust test `ui_snapshot_is_current`
* keeps equal to `lutra_engine::theme`.
*/
@ -35,6 +35,8 @@ const PAIRS: [string, string, number][] = [
["editor-gutter-fg", "editor-gutter-bg", TEXT],
["editor-gutter-fg", "editor-active-line-bg", TEXT],
["editor-cursor", "editor-bg", LARGE],
["bg", "accent", LARGE],
["fg", "editor-bg", LARGE],
["editor-cursor", "editor-active-line-bg", LARGE],
["tab-modified", "bg", LARGE],
["tab-modified", "tab-active-bg", LARGE],