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

@ -2,11 +2,12 @@
/**
* Root component: mounts the main window layout with the editor area; the
* slogan shows while no tab is open, and the restore dialog for unsaved
* texts from the recovery journal, the toast stack and the command
* palette. Loads product information from the engine on mount, starts
* showing notifications, following the theme (see `theme.ts`; a failed
* theme report raises an error toast) and the global keymap with the UI
* commands (see `commands/store.ts`).
* texts from the recovery journal, the toast stack, the command palette
* and the settings dialog. Loads product information from the engine on
* mount, starts showing notifications, following the theme (see
* `theme.ts`; a failed theme report raises an error toast) and the global
* keymap with the UI commands (see `commands/store.ts`), and loads the settings so the
* editor font size applies from the start (see `stores/settings.ts`).
*/
import { onMounted, onUnmounted } from "vue";
import { useCommandsStore } from "./commands/store";
@ -15,13 +16,16 @@ import EditorArea from "./components/editor/EditorArea.vue";
import MainLayout from "./components/layout/MainLayout.vue";
import NotificationStack from "./components/notifications/NotificationStack.vue";
import RecoveryDialog from "./components/recovery/RecoveryDialog.vue";
import SettingsDialog from "./components/settings/SettingsDialog.vue";
import { useAppStore } from "./stores/app";
import { useNotificationsStore } from "./stores/notifications";
import { useSettingsStore } from "./stores/settings";
import { startTheme } from "./theme";
const app = useAppStore();
const notifications = useNotificationsStore();
const commands = useCommandsStore();
const settings = useSettingsStore();
/** Stops following the theme; set while mounted. */
let stopTheme: (() => void) | null = null;
@ -30,6 +34,7 @@ onMounted(() => {
notifications.start();
stopTheme = startTheme((error) => notifications.notifyError("theme.systemPreference", error));
void commands.start();
void settings.start();
void app.loadAbout();
});
@ -37,6 +42,7 @@ onUnmounted(() => {
stopTheme?.();
stopTheme = null;
commands.stop();
settings.stop();
notifications.stop();
});
</script>
@ -51,6 +57,7 @@ onUnmounted(() => {
</MainLayout>
<RecoveryDialog />
<CommandPalette />
<SettingsDialog />
<NotificationStack />
</template>

View file

@ -0,0 +1,730 @@
<script setup lang="ts">
/**
* The settings dialog (`settings.open`, `Mod+,`), built from the engine's
* `settings.list`: sections on the left, the settings of the chosen
* section on the right, each with its control by type (enum → select,
* int → number field with min/max, bool → switch), label and description
* from the catalog, and "Reset to default" when it differs from the
* default.
*
* - **Search:** the field filters by label, description, key and section
* name; while it has text, every match shows, grouped by section.
* - **Changes** apply at once through `settings.set` (a number when the
* field is committed: Enter, the spinner or leaving it). A refused value
* shows its error under the control and keeps the typed text.
* - **Live:** values follow `settingsChanged` through the settings store,
* so a change over the control channel shows while the dialog is open.
* - **Keyboard:** Escape closes, Tab and Shift+Tab stay inside the dialog,
* and the focus returns to where it was.
*/
import { X } from "@lucide/vue";
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from "vue";
import { useCommandsStore } from "../../commands/store";
import { t } from "../../i18n";
import {
descriptionOf,
groupSections,
labelOf,
matchesQuery,
useSettingsStore,
valueLabel,
type SettingDef,
type SettingSection,
} from "../../stores/settings";
const commands = useCommandsStore();
const settings = useSettingsStore();
/** Whether the dialog is shown. */
const open = ref(false);
/** What the user typed into the search field. */
const query = ref("");
/** Id of the chosen section. */
const current = ref<string | null>(null);
/** Text typed into number fields, by key; shown while their value is refused. */
const drafts = reactive<Record<string, string>>({});
/** The dialog element. */
const dialog = ref<HTMLElement | null>(null);
/** The search field. */
const search = ref<HTMLInputElement | null>(null);
/** The element that had the focus before the dialog opened. */
let returnFocus: HTMLElement | null = null;
/** Withdraws the `settings.open` handler; set while mounted. */
let withdraw: (() => void) | null = null;
/** Every section. */
const sections = computed<SettingSection[]>(() => groupSections(settings.defs));
/** Whether the search field has text. */
const searching = computed(() => query.value.trim() !== "");
/** The sections shown on the right: the chosen one, or every match while searching. */
const shown = computed<SettingSection[]>(() => {
if (searching.value) {
return sections.value
.map((section) => ({ ...section, settings: section.settings.filter((def) => matchesQuery(def, query.value)) }))
.filter((section) => section.settings.length > 0);
}
const chosen = sections.value.find((section) => section.id === current.value) ?? sections.value[0];
return chosen ? [chosen] : [];
});
/** Ids of the sections that have matches. */
const matching = computed(() => new Set(shown.value.map((section) => section.id)));
/** The id of the section highlighted on the left. */
const activeSection = computed(() =>
searching.value ? (shown.value[0]?.id ?? null) : (current.value ?? sections.value[0]?.id ?? null),
);
/**
* DOM id of a setting's control.
*
* @param def - the setting.
*/
function controlId(def: SettingDef): string {
return `lt-setting-${def.key.replace(/[^A-Za-z0-9]/g, "-")}`;
}
/**
* The text of a number field: the refused draft while there is an error,
* else the value.
*
* @param def - the setting.
*/
function numberText(def: SettingDef): string {
const draft = drafts[def.key];
if (draft !== undefined && settings.errors[def.key] !== undefined) {
return draft;
}
const value = settings.values[def.key];
return typeof value === "number" ? String(value) : "";
}
/**
* The value of a select.
*
* @param def - the setting.
*/
function enumValue(def: SettingDef): string {
const value = settings.values[def.key];
return typeof value === "string" ? value : "";
}
/**
* Whether a switch is on.
*
* @param def - the setting.
*/
function boolValue(def: SettingDef): boolean {
return settings.values[def.key] === true;
}
/**
* Applies a select's choice.
*
* @param def - the setting.
* @param event - the change event.
*/
async function onSelect(def: SettingDef, event: Event): Promise<void> {
const target = event.target;
if (target instanceof HTMLSelectElement) {
await settings.set(def.key, target.value);
}
}
/**
* Applies a committed number field. Text that is no whole number in range
* is refused here with the catalog's message; the engine validates
* everything else.
*
* @param def - the setting.
* @param event - the change event.
*/
async function onNumber(def: SettingDef, event: Event): Promise<void> {
const target = event.target;
if (!(target instanceof HTMLInputElement)) {
return;
}
const text = target.value.trim();
drafts[def.key] = target.value;
const value = Number(text);
const inRange =
text !== "" &&
Number.isInteger(value) &&
(def.min === null || value >= def.min) &&
(def.max === null || value <= def.max);
if (!inRange) {
settings.setError(
def.key,
def.min !== null && def.max !== null
? t("settings.error.intRange", { min: def.min, max: def.max })
: t("settings.error.int"),
);
return;
}
if (await settings.set(def.key, value)) {
Reflect.deleteProperty(drafts, def.key);
}
}
/**
* Flips a switch.
*
* @param def - the setting.
*/
async function onToggle(def: SettingDef): Promise<void> {
await settings.set(def.key, !boolValue(def));
}
/**
* Resets a setting and drops its draft.
*
* @param def - the setting.
*/
async function onReset(def: SettingDef): Promise<void> {
if (await settings.reset(def.key)) {
Reflect.deleteProperty(drafts, def.key);
}
}
/**
* Chooses a section; clears the search so the section shows whole.
*
* @param id - the section id.
*/
function choose(id: string): void {
current.value = id;
query.value = "";
}
/** Opens the dialog (or focuses its search field) and reloads the settings. */
async function show(): Promise<void> {
if (!open.value) {
const active = document.activeElement;
returnFocus = active instanceof HTMLElement ? active : null;
query.value = "";
open.value = true;
}
await nextTick();
search.value?.focus();
await settings.load();
}
/** Closes the dialog and gives the focus back. */
function close(): void {
if (!open.value) {
return;
}
open.value = false;
for (const key of Object.keys(drafts)) {
Reflect.deleteProperty(drafts, key);
}
returnFocus?.focus();
returnFocus = null;
}
/** The elements Tab reaches inside the dialog, in order. */
function focusables(): HTMLElement[] {
const root = dialog.value;
if (!root) {
return [];
}
return [
...root.querySelectorAll<HTMLElement>(
"button:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex='-1'])",
),
];
}
/**
* Keyboard handling of the dialog: Escape closes, Tab wraps around.
*
* @param event - the key press.
*/
function onKeydown(event: KeyboardEvent): void {
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
close();
return;
}
if (event.key !== "Tab") {
return;
}
const list = focusables();
const first = list[0];
const last = list.at(-1);
if (!first || !last) {
event.preventDefault();
return;
}
const active = document.activeElement;
const inside = active instanceof HTMLElement && list.includes(active);
if (event.shiftKey && (active === first || !inside)) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && (active === last || !inside)) {
event.preventDefault();
first.focus();
}
}
/**
* Keeps the focus inside the dialog when something outside would get it,
* except for another modal dialog opened above it (the palette).
*
* @param event - a focus change anywhere in the document.
*/
function onFocusIn(event: FocusEvent): void {
const root = dialog.value;
const target = event.target;
if (!open.value || !root || !(target instanceof Element) || root.contains(target)) {
return;
}
if (target.closest("[aria-modal='true']")) {
return;
}
search.value?.focus();
}
onMounted(() => {
withdraw = commands.provide("settings.open", { run: show });
document.addEventListener("focusin", onFocusIn);
});
onBeforeUnmount(() => {
withdraw?.();
withdraw = null;
document.removeEventListener("focusin", onFocusIn);
});
defineExpose({ show, close });
</script>
<template>
<div
v-if="open"
class="settings"
data-test="settings"
@mousedown.self.prevent="close()"
>
<div
ref="dialog"
class="settings__dialog"
role="dialog"
aria-modal="true"
aria-labelledby="lt-settings-title"
data-test="settings-dialog"
@keydown="onKeydown"
>
<header class="settings__header">
<h2
id="lt-settings-title"
class="settings__title"
>
{{ t("settings.dialog.title") }}
</h2>
<input
ref="search"
v-model="query"
class="settings__search"
type="search"
:aria-label="t('settings.dialog.search')"
:placeholder="t('settings.dialog.search')"
spellcheck="false"
autocomplete="off"
data-test="settings-search"
>
<button
type="button"
class="settings__close"
:aria-label="t('common.close')"
:title="t('common.close')"
data-test="settings-close"
@click="close()"
>
<X
:size="16"
aria-hidden="true"
/>
</button>
</header>
<div class="settings__body">
<nav
class="settings__nav"
:aria-label="t('settings.dialog.sections')"
>
<ul class="settings__sections">
<li
v-for="section in sections"
:key="section.id"
>
<button
type="button"
class="settings__section"
:class="{
'settings__section--active': section.id === activeSection,
'settings__section--dim': searching && !matching.has(section.id),
}"
:aria-current="section.id === activeSection ? 'true' : undefined"
:data-section="section.id"
data-test="settings-section"
@click="choose(section.id)"
>
{{ section.label }}
</button>
</li>
</ul>
</nav>
<div
class="settings__pane"
data-test="settings-pane"
>
<p
v-if="settings.loadError"
class="settings__error"
role="alert"
data-test="settings-load-error"
>
{{ t("settings.dialog.loadFailed", { message: settings.loadError }) }}
</p>
<p
v-if="searching && shown.length === 0"
class="settings__empty"
role="status"
data-test="settings-empty"
>
{{ t("settings.dialog.noMatches") }}
</p>
<section
v-for="section in shown"
:key="section.id"
class="settings__group"
:aria-labelledby="`lt-settings-group-${section.id}`"
>
<h3
:id="`lt-settings-group-${section.id}`"
class="settings__group-title"
>
{{ section.label }}
</h3>
<div
v-for="def in section.settings"
:key="def.key"
class="settings__row"
:data-key="def.key"
data-test="settings-row"
>
<div class="settings__text">
<label
:for="controlId(def)"
class="settings__label"
>{{ labelOf(def) }}</label>
<p
:id="`${controlId(def)}-description`"
class="settings__description"
>
{{ descriptionOf(def) }}
</p>
<p
v-if="settings.errors[def.key]"
:id="`${controlId(def)}-error`"
class="settings__error"
role="alert"
data-test="settings-error"
>
{{ settings.errors[def.key] }}
</p>
</div>
<div class="settings__control">
<select
v-if="def.type === 'enum'"
:id="controlId(def)"
class="settings__input"
:value="enumValue(def)"
:aria-describedby="`${controlId(def)}-description`"
:aria-invalid="settings.errors[def.key] ? 'true' : undefined"
:aria-errormessage="settings.errors[def.key] ? `${controlId(def)}-error` : undefined"
data-test="settings-control"
@change="onSelect(def, $event)"
>
<option
v-for="option in def.enumValues"
:key="option"
:value="option"
>
{{ valueLabel(def, option) }}
</option>
</select>
<input
v-else-if="def.type === 'int'"
:id="controlId(def)"
class="settings__input settings__input--number"
type="number"
step="1"
:min="def.min ?? undefined"
:max="def.max ?? undefined"
:value="numberText(def)"
:aria-describedby="`${controlId(def)}-description`"
:aria-invalid="settings.errors[def.key] ? 'true' : undefined"
:aria-errormessage="settings.errors[def.key] ? `${controlId(def)}-error` : undefined"
data-test="settings-control"
@change="onNumber(def, $event)"
>
<button
v-else
:id="controlId(def)"
type="button"
role="switch"
class="settings__switch"
:class="{ 'settings__switch--on': boolValue(def) }"
:aria-checked="boolValue(def)"
:aria-describedby="`${controlId(def)}-description`"
data-test="settings-control"
@click="onToggle(def)"
>
<span class="settings__knob" />
</button>
<button
type="button"
class="settings__reset"
:disabled="settings.isDefault(def)"
:aria-label="t('settings.dialog.resetLabel', { name: labelOf(def) })"
data-test="settings-reset"
@click="onReset(def)"
>
{{ t("settings.dialog.reset") }}
</button>
</div>
</div>
</section>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.settings {
position: fixed;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background: color-mix(in srgb, var(--lt-bg) 40%, transparent);
z-index: 30;
}
.settings__dialog {
width: min(760px, 92vw);
height: min(520px, 84vh);
display: flex;
flex-direction: column;
background: var(--lt-bg);
color: var(--lt-fg);
border: 1px solid var(--lt-border);
border-radius: 6px;
overflow: hidden;
}
.settings__header {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 12px;
border-bottom: 1px solid var(--lt-border);
}
.settings__title {
margin: 0;
font-size: var(--lt-font-size-ui);
font-weight: 600;
}
.settings__search {
flex: 1;
min-width: 0;
padding: 4px 8px;
font: inherit;
color: var(--lt-fg);
background: var(--lt-editor-bg);
border: 1px solid var(--lt-border);
border-radius: 4px;
}
.settings__close {
display: flex;
padding: 4px;
color: var(--lt-fg);
background: none;
border: none;
border-radius: 4px;
cursor: pointer;
}
.settings__body {
flex: 1;
min-height: 0;
display: flex;
}
.settings__nav {
width: 180px;
flex-shrink: 0;
overflow-y: auto;
border-right: 1px solid var(--lt-border);
}
.settings__sections {
margin: 0;
padding: 4px 0;
list-style: none;
}
.settings__section {
width: 100%;
padding: 4px 12px;
font: inherit;
text-align: left;
color: var(--lt-fg);
background: none;
border: none;
cursor: pointer;
}
.settings__section--active {
background: var(--lt-editor-selection-bg);
color: var(--lt-fg);
}
.settings__section--dim {
opacity: 0.55;
}
.settings__pane {
flex: 1;
min-width: 0;
overflow-y: auto;
padding: 8px 16px 16px;
}
.settings__group-title {
margin: 8px 0;
font-size: var(--lt-font-size-ui);
font-weight: 600;
}
.settings__row {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
padding: 8px 0;
border-bottom: 1px solid var(--lt-border);
}
.settings__text {
min-width: 0;
}
.settings__label {
display: block;
}
.settings__description {
margin: 2px 0 0;
font-size: var(--lt-font-size-small);
color: var(--lt-fg-muted);
}
.settings__error {
margin: 4px 0 0;
font-size: var(--lt-font-size-small);
color: var(--lt-error);
}
.settings__empty {
color: var(--lt-fg-muted);
}
.settings__control {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.settings__input {
padding: 3px 6px;
font: inherit;
color: var(--lt-fg);
background: var(--lt-editor-bg);
border: 1px solid var(--lt-border);
border-radius: 4px;
}
.settings__input--number {
width: 6em;
}
.settings__input[aria-invalid="true"] {
border-color: var(--lt-error);
}
.settings__switch {
position: relative;
width: 32px;
height: 18px;
padding: 0;
background: var(--lt-editor-bg);
border: 1px solid var(--lt-border);
border-radius: 9px;
cursor: pointer;
}
.settings__switch--on {
background: var(--lt-accent);
}
.settings__knob {
position: absolute;
top: 2px;
left: 2px;
width: 12px;
height: 12px;
background: var(--lt-fg);
border-radius: 50%;
}
.settings__switch--on .settings__knob {
left: 16px;
background: var(--lt-bg);
}
.settings__reset {
padding: 3px 8px;
font: inherit;
font-size: var(--lt-font-size-small);
color: var(--lt-fg);
background: none;
border: 1px solid var(--lt-border);
border-radius: 4px;
cursor: pointer;
}
.settings__reset:disabled {
color: var(--lt-fg-muted);
cursor: default;
}
.settings__close:focus-visible,
.settings__section:focus-visible,
.settings__search:focus-visible,
.settings__input:focus-visible,
.settings__switch:focus-visible,
.settings__reset:focus-visible {
outline: 2px solid var(--lt-accent);
outline-offset: 1px;
}
</style>

View file

@ -56,6 +56,27 @@
"recovery.dialog.restoreSelected": "Restore Selected",
"recovery.dialog.savedAt": "Saved {time}",
"recovery.dialog.title": "Unsaved changes found",
"settings.appearance.theme.description": "Colours of the whole window. System follows the light or dark preference of your operating system.",
"settings.appearance.theme.label": "Theme",
"settings.appearance.theme.value.lutraDark": "Lutra Dark",
"settings.appearance.theme.value.lutraLight": "Lutra Light",
"settings.appearance.theme.value.system": "Same as system",
"settings.dialog.loadFailed": "Settings could not be loaded: {message}",
"settings.dialog.noMatches": "No settings match your search",
"settings.dialog.reset": "Reset to default",
"settings.dialog.resetLabel": "Reset {name} to default",
"settings.dialog.search": "Search settings",
"settings.dialog.sections": "Settings sections",
"settings.dialog.title": "Settings",
"settings.editor.fontSize.description": "Size of the text in the editor, in pixels.",
"settings.editor.fontSize.label": "Editor font size",
"settings.error.int": "Enter a whole number",
"settings.error.intRange": "Enter a whole number from {min} to {max}",
"settings.section.appearance": "Appearance",
"settings.section.editor": "Editor",
"settings.ui.language.description": "Language of the interface. More languages follow.",
"settings.ui.language.label": "Language",
"settings.ui.language.value.en": "English",
"theme.lutraDark": "Lutra Dark",
"theme.lutraLight": "Lutra Light"
}

View file

@ -28,6 +28,11 @@ export type EngineEventPayload =
| { kind: "fileChangedOnDisk"; path: string; id: number; removed: boolean }
| { kind: "watchFailed"; message: string }
| { kind: "themeChanged"; id: string; dark: boolean; tokens: Record<string, string> }
| {
kind: "settingsChanged";
/** Keys whose effective value changed; unchecked, it comes from the engine. */
keys: unknown;
}
| {
kind: "recoveryAvailable";
entries: { path: string; savedAt: number; diskChanged: boolean }[];

425
ui/src/stores/settings.ts Normal file
View file

@ -0,0 +1,425 @@
/**
* Settings as the engine defines them (`settings.list`) with their
* effective values (`settings.get`), changed through `settings.set` and
* `settings.reset`.
*
* - **Live:** `settingsChanged` (from the dialog, the control channel or
* an agent) reloads the changed values, so every view shows the current
* ones.
* - **Errors:** a refused change keeps the error per key until the value
* changes or another change succeeds; the dialog shows it inline.
* - **Effects:** `editor.fontSize` drives `--lt-font-size-editor` (above
* the theme's value, see `setTokenOverride`). `appearance.theme` needs
* nothing here: the engine answers with `themeChanged`.
* - **Text:** labels, descriptions, section names and enum value names are
* catalog keys (`settings.<key>.label`, `settings.<key>.description`,
* `settings.section.<id>`, `settings.<key>.value.<value>`); the engine
* sends no English for settings. A key the catalog lacks shows as is.
*/
import { defineStore } from "pinia";
import { reactive, ref } from "vue";
import { hasMessage, t } from "../i18n";
import { onEngineEvent, run, type EngineEventPayload } from "../ipc";
import { setTokenOverride } from "../theme";
/** A setting value: settings are scalars. Values from the engine are unchecked. */
export type SettingValue = string | number | boolean | null;
/** Types of settings the dialog has a control for. */
export type SettingType = "enum" | "int" | "bool";
/** A setting as `settings.list` describes it. */
export interface SettingDef {
/** Dotted key, e.g. `editor.fontSize`. */
key: string;
/** Type, which decides the control. */
type: SettingType;
/** Default value. */
default: SettingValue;
/** Accepted values of an enum; empty otherwise. */
enumValues: string[];
/** Smallest value of an int, or null. */
min: number | null;
/** Largest value of an int, or null. */
max: number | null;
/** Catalog key of the label. */
labelKey: string;
/** Catalog key of the description. */
descriptionKey: string;
/** Section id; shown with `settings.section.<id>`. */
section: string;
}
/** A section of the dialog with its settings, in engine order. */
export interface SettingSection {
/** Section id. */
id: string;
/** Catalog text of `settings.section.<id>`, or the id. */
label: string;
/** Its settings. */
settings: SettingDef[];
}
/** Key of the editor font size setting. */
export const FONT_SIZE_KEY = "editor.fontSize";
/** Theme token the editor font size drives. */
export const FONT_SIZE_TOKEN = "--lt-font-size-editor";
/** Most settings read from `settings.list`; the rest are dropped. */
export const MAX_SETTINGS = 1000;
/** Most characters of a setting value shown in an error or a draft. */
const MAX_TEXT = 256;
/**
* A scalar from untrusted data; anything else counts as null.
*
* @param value - the data.
*/
function toScalar(value: unknown): SettingValue {
return typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? value : null;
}
/**
* Reads one `settings.list` entry from untrusted data.
*
* @param raw - the entry.
* @returns the setting, or null if it is malformed or of an unknown type.
*/
function toSettingDef(raw: unknown): SettingDef | null {
if (typeof raw !== "object" || raw === null) {
return null;
}
const entry = raw as Record<string, unknown>;
const { key, type, labelKey, descriptionKey, section, enumValues, min, max } = entry;
if (
typeof key !== "string" ||
typeof labelKey !== "string" ||
typeof descriptionKey !== "string" ||
typeof section !== "string" ||
(type !== "enum" && type !== "int" && type !== "bool")
) {
return null;
}
const values = Array.isArray(enumValues)
? (enumValues as unknown[]).filter((v): v is string => typeof v === "string")
: [];
if (type === "enum" && values.length === 0) {
return null;
}
return {
key,
type,
default: toScalar(entry.default),
enumValues: values,
min: typeof min === "number" && Number.isFinite(min) ? min : null,
max: typeof max === "number" && Number.isFinite(max) ? max : null,
labelKey,
descriptionKey,
section,
};
}
/**
* Reads the `settings.list` result, keeping well-formed entries.
*
* @param raw - the result.
* @returns the settings, or null if the result is not a list.
*/
export function toSettingDefs(raw: unknown): SettingDef[] | null {
if (!Array.isArray(raw)) {
return null;
}
return (raw as unknown[])
.slice(0, MAX_SETTINGS)
.map(toSettingDef)
.filter((def): def is SettingDef => def !== null);
}
/**
* Catalog text of a key, or the fallback when the catalog lacks it.
*
* @param key - the catalog key.
* @param fallback - what to show instead.
*/
function textOr(key: string, fallback: string): string {
return hasMessage(key) ? t(key) : fallback;
}
/**
* The label of a setting.
*
* @param def - the setting.
*/
export function labelOf(def: SettingDef): string {
return textOr(def.labelKey, def.key);
}
/**
* The description of a setting; empty when the catalog lacks it.
*
* @param def - the setting.
*/
export function descriptionOf(def: SettingDef): string {
return textOr(def.descriptionKey, "");
}
/**
* The name of a section.
*
* @param id - the section id.
*/
export function sectionLabel(id: string): string {
return textOr(`settings.section.${id}`, id);
}
/**
* The name of an enum value: `settings.<key>.value.<value>` with the value
* in camel case (`lutra-dark` → `lutraDark`), or the value itself.
*
* @param def - the setting.
* @param value - one of its values.
*/
export function valueLabel(def: SettingDef, value: string): string {
const name = value.replace(/[-_.\s]+([A-Za-z0-9])/g, (_m, c: string) => c.toUpperCase());
return textOr(`settings.${def.key}.value.${name}`, value);
}
/**
* Whether a setting matches a search: every word of the query occurs in
* its label, description, key or section name (ignoring case).
*
* @param def - the setting.
* @param query - what the user typed.
*/
export function matchesQuery(def: SettingDef, query: string): boolean {
const words = query.toLowerCase().split(/\s+/).filter((w) => w !== "");
if (words.length === 0) {
return true;
}
const haystack = [labelOf(def), descriptionOf(def), def.key, sectionLabel(def.section)]
.join("\n")
.toLowerCase();
return words.every((word) => haystack.includes(word));
}
/**
* Groups settings into sections, in the order they first appear.
*
* @param defs - the settings.
*/
export function groupSections(defs: readonly SettingDef[]): SettingSection[] {
const sections: SettingSection[] = [];
for (const def of defs) {
let section = sections.find((s) => s.id === def.section);
if (!section) {
section = { id: def.section, label: sectionLabel(def.section), settings: [] };
sections.push(section);
}
section.settings.push(def);
}
return sections;
}
/**
* Whether two setting values are equal.
*
* @param a - one value.
* @param b - the other.
*/
function sameValue(a: SettingValue | undefined, b: SettingValue | undefined): boolean {
return a === b;
}
/**
* Shortens a text for display.
*
* @param text - the text.
*/
function clip(text: string): string {
return text.length > MAX_TEXT ? `${text.slice(0, MAX_TEXT)}…` : text;
}
/** Store of the settings, their values and refused changes. */
export const useSettingsStore = defineStore("settings", () => {
/** Settings as the engine lists them; empty until loaded. */
const defs = ref<SettingDef[]>([]);
/** Effective values by key. */
const values = reactive<Record<string, SettingValue>>({});
/** Error of the last refused change, by key. */
const errors = reactive<Record<string, string>>({});
/** Why loading failed, or null. */
const loadError = ref<string | null>(null);
/** Ends the engine event subscription; set while started. */
let unsubscribe: (() => void) | null = null;
/**
* Applies what a value change means outside the dialog: the editor font
* size token.
*
* @param key - the changed key.
*/
function applyEffect(key: string): void {
if (key !== FONT_SIZE_KEY) {
return;
}
const size = values[key];
setTokenOverride(
FONT_SIZE_TOKEN,
typeof size === "number" && Number.isInteger(size) && size > 0 ? `${String(size)}px` : null,
);
}
/**
* Stores values read from the engine and applies their effects.
*
* @param raw - `{values: {key: value}}` from `settings.get`; unchecked.
*/
function storeValues(raw: unknown): void {
if (typeof raw !== "object" || raw === null) {
return;
}
const read = (raw as { values?: unknown }).values;
if (typeof read !== "object" || read === null) {
return;
}
for (const [key, value] of Object.entries(read as Record<string, unknown>)) {
values[key] = toScalar(value);
applyEffect(key);
}
}
/**
* Reads values from the engine.
*
* @param keys - keys to read; every setting when absent.
* @returns whether it worked.
*/
async function fetchValues(keys?: string[]): Promise<boolean> {
const result = await run("settings.get", keys ? { keys } : {});
if (!result.ok) {
loadError.value = result.error.message;
return false;
}
storeValues(result.value);
return true;
}
/** Loads the settings and their values; a failure is kept in `loadError`. */
async function load(): Promise<void> {
const listed = await run("settings.list");
const list = listed.ok ? toSettingDefs(listed.value) : null;
if (!list) {
loadError.value = listed.ok ? t("common.error.unexpectedResult", { command: "settings.list" }) : listed.error.message;
return;
}
defs.value = list;
if (await fetchValues()) {
loadError.value = null;
}
}
/**
* Whether a setting has its default value.
*
* @param def - the setting.
*/
function isDefault(def: SettingDef): boolean {
return sameValue(values[def.key], def.default);
}
/**
* Stores the outcome of `settings.set` or `settings.reset`.
*
* @param key - the setting.
* @param result - the command's outcome.
* @returns whether the change was accepted.
*/
function settle(
key: string,
result: { ok: true; value: unknown } | { ok: false; error: { message: string } },
): boolean {
if (!result.ok) {
errors[key] = clip(result.error.message);
return false;
}
Reflect.deleteProperty(errors, key);
const value = (result.value as { value?: unknown } | null)?.value;
if (value !== undefined) {
values[key] = toScalar(value);
applyEffect(key);
}
return true;
}
/**
* Changes a setting through `settings.set`. A refused value keeps the
* engine's message as the key's error.
*
* @param key - the setting.
* @param value - the new value.
* @returns whether the engine accepted it.
*/
async function set(key: string, value: SettingValue): Promise<boolean> {
return settle(key, await run("settings.set", { key, value }));
}
/**
* Resets a setting to its default through `settings.reset`.
*
* @param key - the setting.
* @returns whether it worked.
*/
async function reset(key: string): Promise<boolean> {
return settle(key, await run("settings.reset", { key }));
}
/**
* Records an error found before asking the engine (a number field with
* text that is no whole number).
*
* @param key - the setting.
* @param message - the error text.
*/
function setError(key: string, message: string): void {
errors[key] = message;
}
/**
* Reloads the values a `settingsChanged` event names and drops their
* errors: the value changed after them.
*
* @param event - the engine event.
*/
function onEvent(event: EngineEventPayload): void {
if (event.kind !== "settingsChanged" || !Array.isArray(event.keys)) {
return;
}
const keys = (event.keys as unknown[]).filter((k): k is string => typeof k === "string");
if (keys.length === 0) {
return;
}
for (const key of keys) {
Reflect.deleteProperty(errors, key);
}
void fetchValues(keys);
}
/** Starts following `settingsChanged` and loads the settings. Starting twice is a no-op. */
async function start(): Promise<void> {
if (unsubscribe) {
return;
}
unsubscribe = onEngineEvent(onEvent);
await load();
}
/** Stops following `settingsChanged`. */
function stop(): void {
unsubscribe?.();
unsubscribe = null;
}
return { defs, values, errors, loadError, load, isDefault, set, reset, setError, start, stop };
});

View file

@ -47,9 +47,45 @@ export function toResolvedTheme(value: unknown): ResolvedTheme | null {
return { id, dark, tokens: clean };
}
/** Token values that settings put above the theme's (`--lt-font-size-editor`). */
const overrides = new Map<string, string>();
/** The last theme's value of every token, to restore when an override ends. */
const themeTokens = new Map<string, string>();
/**
* Puts a value above a theme token, now and for every theme applied later,
* so a setting such as `editor.fontSize` survives a theme switch. `null`
* ends the override and restores the theme's value, or the injected
* style's when no theme was applied yet.
*
* @param name - the token, `--lt-…`.
* @param value - the CSS value, or null.
* @param root - the element to theme; the document element by default.
*/
export function setTokenOverride(
name: string,
value: string | null,
root: HTMLElement = document.documentElement,
): void {
if (value === null) {
overrides.delete(name);
const base = themeTokens.get(name);
if (base === undefined) {
root.style.removeProperty(name);
} else {
root.style.setProperty(name, base);
}
return;
}
overrides.set(name, value);
root.style.setProperty(name, value);
}
/**
* Applies a theme: writes its tokens onto the root element's inline style
* (which wins over the injected `<style id="lt-theme">`), sets
* (which wins over the injected `<style id="lt-theme">`), keeping the
* values of {@link setTokenOverride}, sets
* `color-scheme` and records the id in `data-theme`.
*
* @param theme - the theme.
@ -57,7 +93,8 @@ export function toResolvedTheme(value: unknown): ResolvedTheme | null {
*/
export function applyTheme(theme: ResolvedTheme, root: HTMLElement = document.documentElement): void {
for (const [name, value] of Object.entries(theme.tokens)) {
root.style.setProperty(name, value);
themeTokens.set(name, value);
root.style.setProperty(name, overrides.get(name) ?? value);
}
root.style.colorScheme = theme.dark ? "dark" : "light";
root.dataset.theme = theme.id;

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],