Lutra/ui/src/theme.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

152 lines
5.1 KiB
TypeScript

/**
* Live theme switching. The desktop shell injects the stored theme's tokens
* before first paint; afterwards the engine sends `themeChanged` with every
* token, and {@link applyTheme} writes them onto `:root` and sets
* `color-scheme`, so a switch needs no reload. In "system" mode the engine
* resolves the theme from the OS preference that {@link startTheme} reports
* with `theme.systemPreference` whenever it changes.
*/
import { onEngineEvent, run, type EngineError } from "./ipc";
/** A resolved theme as the engine sends it. */
export interface ResolvedTheme {
/** Theme id, e.g. `lutra-light`. */
id: string;
/** Whether the theme is dark. */
dark: boolean;
/** Every token as `--lt-<name>` → CSS value. */
tokens: Record<string, string>;
}
/** Media query of the OS dark preference. */
export const DARK_QUERY = "(prefers-color-scheme: dark)";
/**
* Reads a resolved theme from untrusted data (an event or a command result).
* Tokens without the `--lt-` prefix or with a non-string value are dropped.
*
* @param value - the data.
* @returns the theme, or null if `id` or `dark` is missing.
*/
export function toResolvedTheme(value: unknown): ResolvedTheme | null {
if (typeof value !== "object" || value === null) {
return null;
}
const { id, dark, tokens } = value as Record<string, unknown>;
if (typeof id !== "string" || typeof dark !== "boolean") {
return null;
}
const clean: Record<string, string> = {};
if (typeof tokens === "object" && tokens !== null) {
for (const [name, token] of Object.entries(tokens)) {
if (name.startsWith("--lt-") && typeof token === "string") {
clean[name] = token;
}
}
}
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">`), keeping the
* values of {@link setTokenOverride}, sets
* `color-scheme` and records the id in `data-theme`.
*
* @param theme - the theme.
* @param root - the element to theme; the document element by default.
*/
export function applyTheme(theme: ResolvedTheme, root: HTMLElement = document.documentElement): void {
for (const [name, value] of Object.entries(theme.tokens)) {
themeTokens.set(name, value);
root.style.setProperty(name, overrides.get(name) ?? value);
}
root.style.colorScheme = theme.dark ? "dark" : "light";
root.dataset.theme = theme.id;
}
/**
* Reports the OS preference to the engine and applies the theme it
* resolves. A failed call keeps the current theme.
*
* @param dark - whether the OS prefers a dark theme.
* @param onError - called with the error of a failed call.
*/
export async function reportSystemPreference(
dark: boolean,
onError?: (error: EngineError) => void,
): Promise<void> {
const result = await run("theme.systemPreference", { dark });
if (!result.ok) {
onError?.(result.error);
return;
}
const theme = toResolvedTheme(result.value);
if (theme) {
applyTheme(theme);
}
}
/**
* Starts following the theme: applies every `themeChanged` event and
* reports the OS preference now and whenever it changes. Outside a browser
* with `matchMedia` the OS preference counts as dark.
*
* @param onError - called when reporting the OS preference fails.
* @returns a function that stops following.
*/
export function startTheme(onError?: (error: EngineError) => void): () => void {
const unsubscribe = onEngineEvent((event) => {
if (event.kind === "themeChanged") {
const theme = toResolvedTheme(event);
if (theme) {
applyTheme(theme);
}
}
});
const query = typeof window.matchMedia === "function" ? window.matchMedia(DARK_QUERY) : null;
const onChange = (event: MediaQueryListEvent): void => {
void reportSystemPreference(event.matches, onError);
};
query?.addEventListener("change", onChange);
void reportSystemPreference(query?.matches ?? true, onError);
return () => {
unsubscribe();
query?.removeEventListener("change", onChange);
};
}