Lutra/ui/src/stores/settings.ts
danny 523d7f684f 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>
2026-10-16 21:13:04 +02:00

425 lines
12 KiB
TypeScript

/**
* 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 };
});