/** * 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-` → CSS value. */ tokens: Record; } /** 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; if (typeof id !== "string" || typeof dark !== "boolean") { return null; } const clean: Record = {}; 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(); /** The last theme's value of every token, to restore when an override ends. */ const themeTokens = new Map(); /** * 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 `