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;