/** * 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:** the editor font settings drive theme tokens above the * theme's value (see `setTokenOverride`), live: `editor.fontSize` → * `--lt-font-size-editor`, `editor.fontFamily` → `--lt-font-mono` (with * {@link MONO_FALLBACK} behind it), `editor.lineHeight` → * `--lt-line-height-editor`. `appearance.theme` needs nothing here: the * engine answers with `themeChanged`; a change of it reloads the list, * since an import adds a value (C9 T1). * - **Text:** labels, descriptions, section names and enum value names are * catalog keys (`settings..label`, `settings..description`, * `settings.section.`, `settings..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, userMessage, type EngineError, 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" | "string"; /** 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[]; /** Display names of enum values without a catalog key (imported themes), by value. */ valueNames: Record; /** 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.`. */ section: string; /** Whether a string setting holds a file path (the engine's `path` flag). */ path: boolean; } /** A section of the dialog with its settings, in engine order. */ export interface SettingSection { /** Section id. */ id: string; /** Catalog text of `settings.section.`, 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"; /** Key of the editor font family setting. */ export const FONT_FAMILY_KEY = "editor.fontFamily"; /** Theme token the editor font family drives. */ export const FONT_FAMILY_TOKEN = "--lt-font-mono"; /** Fonts behind a chosen family, as `font-mono` in `crates/engine/src/theme.rs`. */ export const MONO_FALLBACK = 'ui-monospace, "Cascadia Code", Menlo, Consolas, monospace'; /** Key of the editor line height setting, in percent of the font size. */ export const LINE_HEIGHT_KEY = "editor.lineHeight"; /** Theme token the editor line height drives. */ export const LINE_HEIGHT_TOKEN = "--lt-line-height-editor"; /** Key of the theme setting. */ export const THEME_KEY = "appearance.theme"; /** * The token value of an editor font setting, or null for the theme's. * * @param key - the setting. * @param value - its value; unchecked. * @returns the CSS value, or null when the value is the default or unusable. */ export function fontTokenValue(key: string, value: SettingValue | undefined): string | null { if (key === FONT_SIZE_KEY) { return typeof value === "number" && Number.isInteger(value) && value > 0 ? `${String(value)}px` : null; } if (key === LINE_HEIGHT_KEY) { return typeof value === "number" && Number.isInteger(value) && value >= 100 && value <= 300 ? String(value / 100) : null; } if (key === FONT_FAMILY_KEY) { const family = typeof value === "string" ? value.trim() : ""; return family === "" || /[;{}<>\\]/.test(family) ? null : `${family}, ${MONO_FALLBACK}`; } return null; } /** Each editor font setting and the token it drives. */ const FONT_TOKENS: Readonly> = { [FONT_SIZE_KEY]: FONT_SIZE_TOKEN, [FONT_FAMILY_KEY]: FONT_FAMILY_TOKEN, [LINE_HEIGHT_KEY]: LINE_HEIGHT_TOKEN, }; /** 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; const { key, type, labelKey, descriptionKey, section, enumValues, valueNames, min, max } = entry; if ( typeof key !== "string" || typeof labelKey !== "string" || typeof descriptionKey !== "string" || typeof section !== "string" || (type !== "enum" && type !== "int" && type !== "bool" && type !== "string") ) { 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; } const names: Record = {}; if (typeof valueNames === "object" && valueNames !== null) { for (const [value, name] of Object.entries(valueNames as Record)) { if (typeof name === "string" && values.includes(value)) { names[value] = clip(name); } } } return { key, type, default: toScalar(entry.default), enumValues: values, valueNames: names, min: typeof min === "number" && Number.isFinite(min) ? min : null, max: typeof max === "number" && Number.isFinite(max) ? max : null, labelKey, descriptionKey, section, path: type === "string" && entry.path === true, }; } /** * 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..value.` with the value * in camel case (`lutra-dark` → `lutraDark`), else the name the engine * sent (an imported theme), else 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}`, def.valueNames[value] ?? 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([]); /** Effective values by key. */ const values = reactive>({}); /** Error of the last refused change, by key. */ const errors = reactive>({}); /** Why loading failed, or null. */ const loadError = ref(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 * tokens. * * @param key - the changed key. */ function applyEffect(key: string): void { const token = FONT_TOKENS[key]; if (token !== undefined) { setTokenOverride(token, fontTokenValue(key, values[key])); } } /** * 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)) { 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 { 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 { 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`. A refusal is * kept as its reason, without the engine's command and key prefixes. * * @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: EngineError }, ): boolean { if (!result.ok) { const message = userMessage(result.error); errors[key] = clip(message.startsWith(`${key}: `) ? message.slice(key.length + 2) : 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 { 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 { 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, a string field with a refused text). * * @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); } if (keys.includes(THEME_KEY)) { void load(); return; } void fetchValues(keys); } /** Starts following `settingsChanged` and loads the settings. Starting twice is a no-op. */ async function start(): Promise { 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 }; });