Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: theme presets applied before paint

ogsamrat5ff533be29e4
diff --git a/apps/app/index.html b/apps/app/index.html
index 490628da..ae7df0af 100644
--- a/apps/app/index.html
+++ b/apps/app/index.html
@@ -18,9 +18,34 @@
<script>
(function () {
try {
- var mode = localStorage.getItem("omnirush.themePref") || "system";
+ var mode =
+ localStorage.getItem("omnirush.react.settings.theme-mode") ||
+ localStorage.getItem("omnirush.themePref") ||
+ "system";
var prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
var resolved = mode === "dark" || (mode === "system" && prefersDark) ? "dark" : "light";
+ // Theme colours saved by app/theme.ts, painted before the bundle loads (no flash).
+ var boot = null;
+ try {
+ boot = JSON.parse(localStorage.getItem("omnirush.react.settings.theme-boot") || "null");
+ } catch (e) {
+ boot = null;
+ }
+ if (boot && (boot.only === "dark" || boot.only === "light")) resolved = boot.only;
+ var vars = boot && boot[resolved];
+ if (vars && typeof vars === "object") {
+ for (var name in vars) {
+ var value = vars[name];
+ if (
+ Object.prototype.hasOwnProperty.call(vars, name) &&
+ /^--[a-z0-9-]+$/.test(name) &&
+ typeof value === "string" &&
+ /^(#[0-9a-f]{6}([0-9a-f]{2})?|\d{1,3} \d{1,3} \d{1,3}|\d+(\.\d+)?(px)?)$/.test(value)
+ ) {
+ document.documentElement.style.setProperty(name, value);
+ }
+ }
+ }
document.documentElement.dataset.theme = resolved;
document.documentElement.style.colorScheme = resolved;
} catch (e) {
diff --git a/apps/app/src/app/index.css b/apps/app/src/app/index.css
index f6f9f9df..1ef4dd35 100644
--- a/apps/app/src/app/index.css
+++ b/apps/app/src/app/index.css
@@ -182,7 +182,8 @@ body {
}
html {
- font-size: var(--omnirush-font-size, 16px);
+ /* --omnirush-theme-font-scale: custom theme text size (app/themes/palette.ts). */
+ font-size: calc(var(--omnirush-font-size, 16px) * var(--omnirush-theme-font-scale, 1));
}
body {
@@ -232,6 +233,50 @@ body {
color: var(--shiki-dark) !important;
}
+/* Theme presets and custom themes (html[data-omnirush-palette], set by app/theme.ts):
+ chat code blocks use the theme's code background and syntax colours. Shiki
+ writes GitHub colours inline; each one maps to its syntax role. */
+html[data-omnirush-palette] .markdown-content [data-omnirush-code-block] {
+ background-color: var(--omnirush-code-bg);
+ color: var(--omnirush-code-fg);
+}
+
+html[data-omnirush-palette] :is(.markdown-content [data-omnirush-code-block] .shiki, [data-shell-command-highlighted]) span[style*="color:#6A737D;" i] {
+ color: var(--omnirush-syntax-comment) !important;
+}
+
+html[data-omnirush-palette] :is(.markdown-content [data-omnirush-code-block] .shiki, [data-shell-command-highlighted]) span[style*="color:#D73A49;" i] {
+ color: var(--omnirush-syntax-keyword) !important;
+}
+
+html[data-omnirush-palette] :is(.markdown-content [data-omnirush-code-block] .shiki, [data-shell-command-highlighted]) span[style*="color:#032F62;" i] {
+ color: var(--omnirush-syntax-string) !important;
+}
+
+html[data-omnirush-palette] :is(.markdown-content [data-omnirush-code-block] .shiki, [data-shell-command-highlighted]) span[style*="color:#005CC5;" i] {
+ color: var(--omnirush-syntax-number) !important;
+}
+
+html[data-omnirush-palette] :is(.markdown-content [data-omnirush-code-block] .shiki, [data-shell-command-highlighted]) span[style*="color:#6F42C1;" i] {
+ color: var(--omnirush-syntax-function) !important;
+}
+
+html[data-omnirush-palette] :is(.markdown-content [data-omnirush-code-block] .shiki, [data-shell-command-highlighted]) span[style*="color:#22863A;" i] {
+ color: var(--omnirush-syntax-type) !important;
+}
+
+html[data-omnirush-palette] :is(.markdown-content [data-omnirush-code-block] .shiki, [data-shell-command-highlighted]) span[style*="color:#E36209;" i] {
+ color: var(--omnirush-syntax-variable) !important;
+}
+
+html[data-omnirush-palette] :is(.markdown-content [data-omnirush-code-block] .shiki, [data-shell-command-highlighted]) span[style*="color:#24292E;" i] {
+ color: var(--omnirush-code-fg) !important;
+}
+
+html[data-omnirush-palette] :is(.markdown-content [data-omnirush-code-block] .shiki, [data-shell-command-highlighted]) span[style*="color:#B31D28;" i] {
+ color: var(--destructive) !important;
+}
+
/* KaTeX sets its own absolute font-size; keep formulas at the surrounding text size
so inline math does not tower over the sentence it sits in. */
.markdown-content .katex {
@@ -782,6 +827,12 @@ select:disabled {
--color-card: var(--card);
--color-foreground: var(--foreground);
--color-background: var(--background);
+ /* Theme tokens for colours that used to be fixed hex values. */
+ --color-highlight: var(--omnirush-highlight, #b9f45a);
+ --color-link: var(--omnirush-link, var(--primary));
+ --color-terminal: var(--omnirush-terminal-bg, #0b0d12);
+ --color-terminal-foreground: var(--omnirush-terminal-fg, #ffffff);
+ --color-gate: var(--omnirush-gate-bg, #05070c);
--radius-sm: calc(var(--radius) * 0.6);
--radius-md: calc(var(--radius) * 0.8);
--radius-lg: var(--radius);
diff --git a/apps/app/src/app/theme.ts b/apps/app/src/app/theme.ts
index 2b4e022e..96ef8213 100644
--- a/apps/app/src/app/theme.ts
+++ b/apps/app/src/app/theme.ts
@@ -1,12 +1,35 @@
+import {
+ CUSTOM_THEME_ID,
+ DEFAULT_PRESET_ID,
+ applyPaletteVars,
+ findPreset,
+ isSafeVar,
+ paletteVars,
+ resolveActiveTheme,
+ type ActiveTheme,
+ type ThemeSelection,
+} from "./themes/palette";
+import { parseThemeJson, serializeTheme } from "./themes/share";
+import type { CustomTheme, ThemeVariantMode } from "./themes/types";
+
export type ThemeMode = "light" | "dark" | "system";
export type ResolvedThemeMode = "light" | "dark";
+export type { ActiveTheme, ThemeSelection } from "./themes/palette";
const THEME_PREF_KEY = "omnirush.react.settings.theme-mode";
const LEGACY_THEME_PREF_KEYS = ["omnirush.themePref"];
+export const THEME_PRESET_KEY = "omnirush.react.settings.theme-preset";
+export const THEME_CUSTOM_KEY = "omnirush.react.settings.theme-custom";
+/** Variables for both modes, read by the inline script in index.html before the bundle loads. */
+export const THEME_BOOT_KEY = "omnirush.react.settings.theme-boot";
const mediaQuery = "(prefers-color-scheme: dark)";
const listeners = new Set<() => void>();
let currentMode: ThemeMode | null = null;
+let currentSelection: ThemeSelection | null = null;
+let customTheme: CustomTheme | null | undefined;
+let previewTheme: CustomTheme | null = null;
+let activeTheme: ActiveTheme | null = null;
let systemThemeCleanup: (() => void) | null = null;
const getMediaQueryList = () =>
@@ -17,18 +40,27 @@ const getMediaQueryList = () =>
const isThemeMode = (value: string | null): value is ThemeMode =>
value === "light" || value === "dark" || value === "system";
+const storage = (): Storage | null => {
+ try {
+ return typeof window === "undefined" ? null : window.localStorage;
+ } catch {
+ return null;
+ }
+};
+
const readStoredMode = (): ThemeMode => {
- if (typeof window === "undefined") return "system";
+ const store = storage();
+ if (!store) return "system";
try {
- const stored = window.localStorage.getItem(THEME_PREF_KEY);
+ const stored = store.getItem(THEME_PREF_KEY);
if (isThemeMode(stored)) {
return stored;
}
for (const key of LEGACY_THEME_PREF_KEYS) {
- const legacyStored = window.localStorage.getItem(key);
+ const legacyStored = store.getItem(key);
if (isThemeMode(legacyStored)) {
- window.localStorage.setItem(THEME_PREF_KEY, legacyStored);
+ store.setItem(THEME_PREF_KEY, legacyStored);
return legacyStored;
}
}
@@ -38,16 +70,91 @@ const readStoredMode = (): ThemeMode => {
return "system";
};
+const readStoredSelection = (): ThemeSelection => {
+ try {
+ const stored = storage()?.getItem(THEME_PRESET_KEY);
+ if (stored === CUSTOM_THEME_ID) return { kind: "custom" };
+ if (stored && findPreset(stored)) return { kind: "preset", id: stored };
+ } catch {
+ // ignore
+ }
+ return { kind: "preset", id: DEFAULT_PRESET_ID };
+};
+
+const readStoredCustomTheme = (): CustomTheme | null => {
+ try {
+ const stored = storage()?.getItem(THEME_CUSTOM_KEY);
+ if (!stored) return null;
+ const parsed = parseThemeJson(stored);
+ return parsed.ok ? parsed.theme : null;
+ } catch {
+ return null;
+ }
+};
+
const resolveMode = (mode: ThemeMode): ResolvedThemeMode => {
if (mode !== "system") return mode;
return getMediaQueryList()?.matches ? "dark" : "light";
};
+const getCurrentMode = () => {
+ if (currentMode === null) {
+ currentMode = readStoredMode();
+ }
+ return currentMode;
+};
+
+const getCurrentSelection = () => {
+ if (currentSelection === null) currentSelection = readStoredSelection();
+ return currentSelection;
+};
+
+export const getCustomTheme = (): CustomTheme | null => {
+ if (customTheme === undefined) customTheme = readStoredCustomTheme();
+ return customTheme;
+};
+
+/** The theme to show: the preview being edited/imported, else the saved choice. */
+const computeActiveTheme = (wanted: ResolvedThemeMode): ActiveTheme => {
+ if (previewTheme) return resolveActiveTheme({ kind: "custom" }, wanted, previewTheme);
+ return resolveActiveTheme(getCurrentSelection(), wanted, getCustomTheme());
+};
+
+const darkVariantOf = (active: ActiveTheme) => {
+ if (active.selection.kind === "custom") return (previewTheme ?? getCustomTheme())?.dark ?? null;
+ return findPreset(active.selection.id)?.variants.dark ?? null;
+};
+
+/** Saves both modes' variables so the next start can paint them before the bundle runs. */
+const persistBootVars = () => {
+ if (previewTheme) return;
+ const store = storage();
+ if (!store) return;
+ try {
+ const light = computeActiveTheme("light");
+ const dark = computeActiveTheme("dark");
+ const only = light.mode === dark.mode ? light.mode : null;
+ const boot = {
+ only,
+ light: paletteVars(light, darkVariantOf(light)),
+ dark: paletteVars(dark, darkVariantOf(dark)),
+ };
+ store.setItem(THEME_BOOT_KEY, JSON.stringify(boot));
+ } catch {
+ // ignore
+ }
+};
+
const applyTheme = (mode: ThemeMode) => {
+ const active = computeActiveTheme(resolveMode(mode));
+ activeTheme = active;
if (typeof document === "undefined") return;
- const resolved = resolveMode(mode);
- document.documentElement.dataset.theme = resolved;
- document.documentElement.style.colorScheme = resolved;
+ const root = document.documentElement;
+ root.dataset.theme = active.mode;
+ root.style.colorScheme = active.mode;
+ if (active.legacy) delete root.dataset.omnirushPalette;
+ else root.dataset.omnirushPalette = active.selection.kind === "custom" ? CUSTOM_THEME_ID : active.selection.id;
+ applyPaletteVars(root.style, paletteVars(active, darkVariantOf(active)));
};
const emitThemeChange = () => {
@@ -58,14 +165,10 @@ const emitThemeChange = () => {
const syncNativeTheme = (mode: ThemeMode) => {
if (typeof window === "undefined") return;
- void window.__OMNIRUSH_ELECTRON__?.invokeDesktop?.("__setNativeTheme", mode);
-};
-
-const getCurrentMode = () => {
- if (currentMode === null) {
- currentMode = readStoredMode();
- }
- return currentMode;
+ // A dark-only theme (Midnight) keeps native chrome dark even when the mode says light.
+ const active = activeTheme;
+ const native: ThemeMode = active && active.mode !== resolveMode(mode) ? active.mode : mode;
+ void window.__OMNIRUSH_ELECTRON__?.invokeDesktop?.("__setNativeTheme", native);
};
const handleSystemThemeChange = () => {
@@ -85,6 +188,13 @@ const ensureSystemThemeSubscription = () => {
systemThemeCleanup = () => list.removeEventListener("change", handleSystemThemeChange);
};
+const reapply = () => {
+ const mode = getCurrentMode();
+ applyTheme(mode);
+ syncNativeTheme(mode);
+ emitThemeChange();
+};
+
export const bootstrapTheme = () => {
const mode = getCurrentMode();
applyTheme(mode);
@@ -94,12 +204,21 @@ export const bootstrapTheme = () => {
export const getInitialThemeMode = () => getCurrentMode();
-export const getResolvedThemeMode = () => resolveMode(getCurrentMode());
+/** The light/dark the window shows (a dark-only theme reports dark). */
+export const getResolvedThemeMode = (): ResolvedThemeMode => getActiveTheme().mode;
+
+export const getActiveTheme = (): ActiveTheme => {
+ if (!activeTheme) activeTheme = computeActiveTheme(resolveMode(getCurrentMode()));
+ return activeTheme;
+};
+
+export const getThemeSelection = (): ThemeSelection => getCurrentSelection();
+
+export const isThemePreviewActive = () => previewTheme !== null;
const persistThemeMode = (mode: ThemeMode) => {
- if (typeof window === "undefined") return;
try {
- window.localStorage.setItem(THEME_PREF_KEY, mode);
+ storage()?.setItem(THEME_PREF_KEY, mode);
} catch {
// ignore
}
@@ -116,8 +235,83 @@ export const subscribeToTheme = (onChange: () => void) => {
export const setThemeMode = (mode: ThemeMode) => {
currentMode = mode;
persistThemeMode(mode);
- applyTheme(mode);
- syncNativeTheme(mode);
ensureSystemThemeSubscription();
- emitThemeChange();
+ reapply();
+ persistBootVars();
+};
+
+/** Picks a preset or the saved custom theme. */
+export const setThemeSelection = (selection: ThemeSelection) => {
+ const next: ThemeSelection =
+ selection.kind === "preset" && !findPreset(selection.id) ? { kind: "preset", id: DEFAULT_PRESET_ID } : selection;
+ currentSelection = next;
+ try {
+ storage()?.setItem(THEME_PRESET_KEY, next.kind === "custom" ? CUSTOM_THEME_ID : next.id);
+ } catch {
+ // ignore
+ }
+ reapply();
+ persistBootVars();
+};
+
+/** Stores the custom theme ("My theme"). Callers select it with setThemeSelection. */
+export const saveCustomTheme = (theme: CustomTheme) => {
+ const checked = parseThemeJson(serializeTheme(theme));
+ if (!checked.ok) throw new Error(checked.error);
+ customTheme = checked.theme;
+ try {
+ storage()?.setItem(THEME_CUSTOM_KEY, serializeTheme(checked.theme));
+ } catch {
+ // ignore
+ }
+ reapply();
+ persistBootVars();
+};
+
+/** Shows a theme in the whole window without saving it (editor and import preview). Null ends it. */
+export const setThemePreview = (theme: CustomTheme | null) => {
+ previewTheme = theme;
+ reapply();
+};
+
+/**
+ * A preset or custom theme that only has a dark (or light) version cannot
+ * follow the chosen mode; picking it switches the mode instead of silently
+ * falling back. Returns the mode to switch to, or null.
+ */
+export const modeSwitchFor = (
+ available: readonly ThemeVariantMode[],
+ mode: ThemeMode,
+): ResolvedThemeMode | null => {
+ if (available.length !== 1) return null;
+ const only = available[0]!;
+ if (mode === "system") return null;
+ return mode === only ? null : only;
+};
+
+/** Values for the early inline script; exported for tests. */
+export const readBootVars = (raw: string | null, resolved: ResolvedThemeMode) => {
+ if (!raw) return null;
+ try {
+ const boot = JSON.parse(raw) as { only?: unknown; light?: unknown; dark?: unknown };
+ const mode: ResolvedThemeMode = boot.only === "dark" || boot.only === "light" ? boot.only : resolved;
+ const vars = boot[mode];
+ if (!vars || typeof vars !== "object") return { mode, vars: {} };
+ const safe: Record<string, string> = {};
+ for (const [name, value] of Object.entries(vars as Record<string, unknown>)) {
+ if (typeof value === "string" && isSafeVar(name, value)) safe[name] = value;
+ }
+ return { mode, vars: safe };
+ } catch {
+ return null;
+ }
+};
+
+export const resetThemeStateForTests = () => {
+ currentMode = null;
+ currentSelection = null;
+ customTheme = undefined;
+ previewTheme = null;
+ activeTheme = null;
+ listeners.clear();
};
diff --git a/apps/app/src/app/themes/contrast.ts b/apps/app/src/app/themes/contrast.ts
new file mode 100644
index 00000000..f1f61609
--- /dev/null
+++ b/apps/app/src/app/themes/contrast.ts
@@ -0,0 +1,254 @@
+/**
+ * WCAG contrast maths for theme colours, and the "use this colour instead"
+ * suggestion shown by the theme editor (same hue and saturation, lightness
+ * moved away from the background until the pair passes).
+ */
+import { ANSI_KEYS, SYNTAX_KEYS, type ThemeVariant } from "./types";
+
+export const TEXT_TARGET = 4.5;
+export const UI_TARGET = 3;
+export const AAA_TEXT_TARGET = 7;
+
+type Rgb = [number, number, number];
+
+export function hexToRgb(hex: string): Rgb {
+ const h = hex.replace(/^#/, "");
+ return [0, 2, 4].map((i) => Number.parseInt(h.slice(i, i + 2), 16) / 255) as Rgb;
+}
+
+export function rgbToHex(r: number, g: number, b: number): string {
+ const part = (c: number) => Math.max(0, Math.min(255, Math.round(c * 255))).toString(16).padStart(2, "0");
+ return `#${part(r)}${part(g)}${part(b)}`;
+}
+
+export function luminance(hex: string): number {
+ const ch = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
+ const [r, g, b] = hexToRgb(hex).map(ch) as Rgb;
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
+}
+
+export function contrastRatio(a: string, b: string): number {
+ const la = luminance(a);
+ const lb = luminance(b);
+ const hi = Math.max(la, lb);
+ const lo = Math.min(la, lb);
+ return (hi + 0.05) / (lo + 0.05);
+}
+
+/** A background is "dark" below this luminance (same threshold as the preset generator). */
+export function isDarkColour(hex: string): boolean {
+ return luminance(hex) < 0.18;
+}
+
+// HLS conversions matching Python's colorsys, so suggestions equal the generator's.
+function rgbToHls(r: number, g: number, b: number): [number, number, number] {
+ const maxc = Math.max(r, g, b);
+ const minc = Math.min(r, g, b);
+ const sumc = maxc + minc;
+ const rangec = maxc - minc;
+ const l = sumc / 2;
+ if (minc === maxc) return [0, l, 0];
+ const s = l <= 0.5 ? rangec / sumc : rangec / (2 - maxc - minc);
+ const rc = (maxc - r) / rangec;
+ const gc = (maxc - g) / rangec;
+ const bc = (maxc - b) / rangec;
+ let h: number;
+ if (r === maxc) h = bc - gc;
+ else if (g === maxc) h = 2 + rc - bc;
+ else h = 4 + gc - rc;
+ h = (((h / 6) % 1) + 1) % 1;
+ return [h, l, s];
+}
+
+function hlsToRgb(h: number, l: number, s: number): Rgb {
+ if (s === 0) return [l, l, l];
+ const m2 = l <= 0.5 ? l * (1 + s) : l + s - l * s;
+ const m1 = 2 * l - m2;
+ const v = (hue: number) => {
+ const x = ((hue % 1) + 1) % 1;
+ if (x < 1 / 6) return m1 + (m2 - m1) * x * 6;
+ if (x < 0.5) return m2;
+ if (x < 2 / 3) return m1 + (m2 - m1) * (2 / 3 - x) * 6;
+ return m1;
+ };
+ return [v(h + 1 / 3), v(h), v(h - 1 / 3)];
+}
+
+/** Moves fg's lightness away from bg (hue and saturation kept) until the pair reaches target. */
+export function fixContrast(fg: string, bg: string, target: number): string {
+ if (contrastRatio(fg, bg) >= target) return fg;
+ const [r, g, b] = hexToRgb(fg);
+ const [h, l0, s] = rgbToHls(r, g, b);
+ const step = luminance(bg) > 0.18 ? -0.005 : 0.005;
+ let l = l0;
+ while (l >= 0 && l <= 1) {
+ l += step;
+ const c = rgbToHex(...hlsToRgb(h, Math.max(0, Math.min(1, l)), s));
+ if (contrastRatio(c, bg) >= target) return c;
+ }
+ return step < 0 ? "#000000" : "#ffffff";
+}
+
+/** A colour close to fg that passes target on every background given (or the best effort). */
+export function suggestColour(fg: string, backgrounds: readonly string[], target: number): string {
+ let current = fg;
+ for (let pass = 0; pass < 6; pass += 1) {
+ let changed = false;
+ for (const bg of backgrounds) {
+ if (contrastRatio(current, bg) < target) {
+ current = fixContrast(current, bg, target);
+ changed = true;
+ }
+ }
+ if (!changed) break;
+ }
+ return current;
+}
+
+export function worstRatio(fg: string, backgrounds: readonly string[]): number {
+ return Math.min(...backgrounds.map((bg) => contrastRatio(fg, bg)));
+}
+
+/** The four backgrounds body text is drawn on. */
+export function textBackgrounds(v: ThemeVariant): string[] {
+ return [v.background, v.surface, v.surfaceRaised, v.code.bg];
+}
+
+/**
+ * Accent colour safe to use as text (links, counts): the accent itself when it
+ * reaches 4.5:1 on all four backgrounds, otherwise the nearest colour that does.
+ */
+export function textSafeAccent(v: ThemeVariant): string {
+ return suggestColour(v.accent, textBackgrounds(v), TEXT_TARGET);
+}
+
+export type ContrastCheck = {
+ label: string;
+ fg: string;
+ bg: string;
+ target: number;
+};
+
+export type ContrastRow = ContrastCheck & {
+ fgColour: string;
+ bgColour: string;
+ ratio: number;
+ pass: boolean;
+};
+
+export function readPath(v: ThemeVariant, path: string): string {
+ const [head, tail] = path.split(".") as [string, string | undefined];
+ const value = tail ? (v as unknown as Record<string, Record<string, string>>)[head]?.[tail] : (v as unknown as Record<string, string>)[head];
+ return typeof value === "string" ? value : "#000000";
+}
+
+/** The pairs every variant must pass (port of the preset generator's list). */
+export function contrastChecks(v: ThemeVariant, aaa = false): ContrastCheck[] {
+ const body = aaa ? AAA_TEXT_TARGET : TEXT_TARGET;
+ const dark = isDarkColour(v.background);
+ const out: ContrastCheck[] = [
+ { label: "text / background", fg: "text", bg: "background", target: body },
+ { label: "text / surface", fg: "text", bg: "surface", target: body },
+ { label: "text / surface-raised", fg: "text", bg: "surfaceRaised", target: body },
+ { label: "text-muted / background", fg: "textMuted", bg: "background", target: TEXT_TARGET },
+ { label: "text-muted / surface", fg: "textMuted", bg: "surface", target: TEXT_TARGET },
+ { label: "text-muted / surface-raised", fg: "textMuted", bg: "surfaceRaised", target: TEXT_TARGET },
+ { label: "text-muted / code bg", fg: "textMuted", bg: "code.bg", target: TEXT_TARGET },
+ { label: "text / code bg", fg: "text", bg: "code.bg", target: body },
+ { label: "accent-text / accent", fg: "accentText", bg: "accent", target: TEXT_TARGET },
+ { label: "accent / background (UI)", fg: "accent", bg: "background", target: UI_TARGET },
+ { label: "accent / surface-raised (UI)", fg: "accent", bg: "surfaceRaised", target: UI_TARGET },
+ { label: "accent / code bg (UI)", fg: "accent", bg: "code.bg", target: UI_TARGET },
+ ];
+ for (const key of ["success", "warn", "danger"] as const) {
+ for (const [name, bg] of [
+ ["background", "background"],
+ ["surface", "surface"],
+ ["surface-raised", "surfaceRaised"],
+ ["code bg", "code.bg"],
+ ] as const) {
+ out.push({ label: `${key} / ${name}`, fg: key, bg, target: TEXT_TARGET });
+ }
+ }
+ out.push(
+ { label: "code fg / code bg", fg: "code.fg", bg: "code.bg", target: body },
+ { label: "terminal fg / terminal bg", fg: "terminal.fg", bg: "terminal.bg", target: body },
+ { label: "terminal cursor / terminal bg (UI)", fg: "terminal.cursor", bg: "terminal.bg", target: UI_TARGET },
+ );
+ for (const key of SYNTAX_KEYS) {
+ out.push({ label: `syntax ${key} / code bg`, fg: `code.${key}`, bg: "code.bg", target: TEXT_TARGET });
+ }
+ // The ANSI colour meant to sit on the background side is exempt (black on dark, white on light).
+ const exempt = new Set<string>(dark ? ["black"] : ["white", "brightWhite"]);
+ for (const key of ANSI_KEYS) {
+ if (exempt.has(key)) continue;
+ out.push({ label: `ansi ${key} / terminal bg`, fg: `terminal.${key}`, bg: "terminal.bg", target: TEXT_TARGET });
+ }
+ return out;
+}
+
+export function contrastRows(v: ThemeVariant, aaa = false): ContrastRow[] {
+ return contrastChecks(v, aaa).map((check) => {
+ const fgColour = readPath(v, check.fg);
+ const bgColour = readPath(v, check.bg);
+ const ratio = contrastRatio(fgColour, bgColour);
+ return { ...check, fgColour, bgColour, ratio, pass: ratio >= check.target };
+ });
+}
+
+export type ContrastWarning = {
+ /** Token the suggestion changes (the accent fill for the text-on-accent pair). */
+ token: string;
+ current: string;
+ suggestion: string;
+ worst: number;
+ target: number;
+ rows: ContrastRow[];
+};
+
+/**
+ * Failing pairs grouped by the token to change, each with one suggested colour
+ * that passes on every background that token is checked against.
+ */
+export function contrastWarnings(v: ThemeVariant, aaa = false): ContrastWarning[] {
+ const rows = contrastRows(v, aaa);
+ const failing = rows.filter((row) => !row.pass);
+ const byToken = new Map<string, ContrastRow[]>();
+ for (const row of failing) {
+ const token = row.fg === "accentText" ? "accent" : row.fg;
+ byToken.set(token, [...(byToken.get(token) ?? []), row]);
+ }
+ const warnings: ContrastWarning[] = [];
+ for (const [token, tokenRows] of byToken) {
+ const current = readPath(v, token);
+ const target = Math.max(...tokenRows.map((row) => row.target));
+ let backgrounds: string[];
+ if (token === "accent") {
+ // Fix the accent fill against its text colour first, then keep it visible as a UI colour.
+ const accentTextRow = tokenRows.find((row) => row.fg === "accentText");
+ const allAccentRows = rows.filter((row) => row.fg === "accent");
+ let suggestion = accentTextRow ? fixContrast(current, v.accentText, TEXT_TARGET) : current;
+ suggestion = suggestColour(suggestion, allAccentRows.map((row) => row.bgColour), UI_TARGET);
+ warnings.push({
+ token,
+ current,
+ suggestion,
+ worst: Math.min(...tokenRows.map((row) => row.ratio)),
+ target,
+ rows: tokenRows,
+ });
+ continue;
+ }
+ backgrounds = rows.filter((row) => row.fg === token).map((row) => row.bgColour);
+ const suggestion = suggestColour(current, backgrounds, target);
+ warnings.push({
+ token,
+ current,
+ suggestion,
+ worst: Math.min(...tokenRows.map((row) => row.ratio)),
+ target,
+ rows: tokenRows,
+ });
+ }
+ return warnings;
+}
diff --git a/apps/app/src/app/themes/editor-themes.ts b/apps/app/src/app/themes/editor-themes.ts
new file mode 100644
index 00000000..4986d22e
--- /dev/null
+++ b/apps/app/src/app/themes/editor-themes.ts
@@ -0,0 +1,145 @@
+/**
+ * Code editor (Monaco) and terminal (xterm) colours for the active theme.
+ * Pure: monaco.ts and terminal-runtime.ts apply the results.
+ */
+import { hexToRgb, rgbToHex } from "./contrast";
+import type { ActiveTheme } from "./palette";
+import { ANSI_KEYS, type AnsiKey } from "./types";
+
+function mix(a: string, b: string, t: number): string {
+ const [ar, ag, ab] = hexToRgb(a);
+ const [br, bg, bb] = hexToRgb(b);
+ return rgbToHex(ar + (br - ar) * t, ag + (bg - ag) * t, ab + (bb - ab) * t);
+}
+
+const alpha = (hex: string, a: string) => `${hex}${a}`;
+const bare = (hex: string) => hex.replace(/^#/, "");
+
+export type MonacoThemeData = {
+ base: "vs" | "vs-dark";
+ inherit: boolean;
+ rules: Array<{ token: string; foreground?: string; fontStyle?: string }>;
+ colors: Record<string, string>;
+};
+
+/** Today's editor look (Default preset): background/foreground from the app stylesheet. */
+export function legacyMonacoTheme(dark: boolean, background: string, foreground: string): MonacoThemeData {
+ return {
+ base: dark ? "vs-dark" : "vs",
+ inherit: true,
+ rules: [],
+ colors: {
+ "editor.background": background,
+ "editor.foreground": foreground,
+ "editorLineNumber.foreground": dark ? "#5a6169" : "#a0a5ad",
+ "editorLineNumber.activeForeground": dark ? "#b0b4ba" : "#60646c",
+ "editor.lineHighlightBackground": dark ? "#18191b" : "#f5f5f7",
+ "editor.lineHighlightBorder": "#00000000",
+ "editorGutter.background": background,
+ "editorWidget.background": dark ? "#18191b" : "#ffffff",
+ "editorWidget.border": dark ? "#2e3135" : "#e0e1e6",
+ "diffEditor.insertedLineBackground": dark ? "#3dd68c1f" : "#30a46c1c",
+ "diffEditor.removedLineBackground": dark ? "#ff95921f" : "#e5484d1a",
+ "diffEditor.insertedTextBackground": dark ? "#3dd68c33" : "#30a46c33",
+ "diffEditor.removedTextBackground": dark ? "#ff959233" : "#e5484d33",
+ "scrollbarSlider.background": dark ? "#ffffff1a" : "#0000001a",
+ "scrollbarSlider.hoverBackground": dark ? "#ffffff29" : "#00000029",
+ },
+ };
+}
+
+/** Editor theme from a preset or custom theme's code, border and status colours. */
+export function monacoThemeFor(active: Pick<ActiveTheme, "variant" | "mode">): MonacoThemeData {
+ const v = active.variant;
+ const c = v.code;
+ const dark = active.mode === "dark";
+ const rule = (token: string, colour: string, fontStyle?: string) => ({
+ token,
+ foreground: bare(colour),
+ ...(fontStyle ? { fontStyle } : {}),
+ });
+ return {
+ base: dark ? "vs-dark" : "vs",
+ inherit: true,
+ rules: [
+ rule("", c.fg),
+ rule("comment", c.comment, "italic"),
+ rule("comment.doc", c.comment, "italic"),
+ rule("keyword", c.keyword),
+ rule("keyword.flow", c.keyword),
+ rule("storage", c.keyword),
+ rule("string", c.string),
+ rule("string.escape", c.number),
+ rule("regexp", c.string),
+ rule("number", c.number),
+ rule("number.hex", c.number),
+ rule("constant", c.number),
+ rule("type", c.type),
+ rule("type.identifier", c.type),
+ rule("tag", c.type),
+ rule("attribute.name", c.function),
+ rule("attribute.value", c.string),
+ rule("predefined", c.function),
+ rule("function", c.function),
+ rule("identifier", c.variable),
+ rule("variable", c.variable),
+ rule("variable.predefined", c.function),
+ rule("delimiter", c.punctuation),
+ rule("delimiter.bracket", c.punctuation),
+ rule("operator", c.punctuation),
+ rule("metatag", c.keyword),
+ rule("annotation", c.function),
+ ],
+ colors: {
+ "editor.background": c.bg,
+ "editor.foreground": c.fg,
+ "editorCursor.foreground": v.accent,
+ "editorLineNumber.foreground": mix(c.bg, v.textMuted, 0.75),
+ "editorLineNumber.activeForeground": c.fg,
+ "editor.lineHighlightBackground": mix(c.bg, c.fg, 0.06),
+ "editor.lineHighlightBorder": "#00000000",
+ "editor.selectionBackground": alpha(v.accent, "40"),
+ "editor.inactiveSelectionBackground": alpha(v.accent, "26"),
+ "editorGutter.background": c.bg,
+ "editorWidget.background": v.surfaceRaised,
+ "editorWidget.border": v.border,
+ "editorIndentGuide.background1": alpha(c.fg, "1a"),
+ "diffEditor.insertedLineBackground": alpha(v.success, "1f"),
+ "diffEditor.removedLineBackground": alpha(v.danger, "1f"),
+ "diffEditor.insertedTextBackground": alpha(v.success, "33"),
+ "diffEditor.removedTextBackground": alpha(v.danger, "33"),
+ "scrollbarSlider.background": alpha(c.fg, "1a"),
+ "scrollbarSlider.hoverBackground": alpha(c.fg, "29"),
+ },
+ };
+}
+
+export type XtermTheme = {
+ background: string;
+ foreground: string;
+ cursor: string;
+ cursorAccent?: string;
+ selectionBackground: string;
+} & Partial<Record<AnsiKey, string>>;
+
+/** Today's terminal look (Default preset). */
+export const LEGACY_XTERM_THEME: XtermTheme = {
+ background: "#0b0d12",
+ foreground: "#d7dde8",
+ cursor: "#ffffff",
+ selectionBackground: "#334155",
+};
+
+export function xtermThemeFor(active: Pick<ActiveTheme, "variant" | "legacy">): XtermTheme {
+ if (active.legacy) return LEGACY_XTERM_THEME;
+ const t = active.variant.terminal;
+ const theme: XtermTheme = {
+ background: t.bg,
+ foreground: t.fg,
+ cursor: t.cursor,
+ cursorAccent: t.bg,
+ selectionBackground: mix(t.bg, t.fg, 0.25),
+ };
+ for (const key of ANSI_KEYS) theme[key] = t[key];
+ return theme;
+}
diff --git a/apps/app/src/app/themes/palette.ts b/apps/app/src/app/themes/palette.ts
new file mode 100644
index 00000000..43372c16
--- /dev/null
+++ b/apps/app/src/app/themes/palette.ts
@@ -0,0 +1,237 @@
+/**
+ * Turns a theme variant into values for the CSS custom properties the app
+ * already uses (index.css, colors.css), and applies them on <html> with
+ * style.setProperty. Only names from this module and only validated values
+ * (#rrggbb, #rrggbbaa, "r g b", px and plain numbers) are ever written.
+ */
+import { hexToRgb, isDarkColour, rgbToHex, textSafeAccent } from "./contrast";
+import { THEME_PRESETS } from "./presets";
+import {
+ DEFAULT_FONT_SIZE_PX,
+ DEFAULT_RADIUS_PX,
+ FONT_SIZE_RANGE,
+ RADIUS_RANGE,
+ SYNTAX_KEYS,
+ type CustomTheme,
+ type ThemePreset,
+ type ThemeVariant,
+ type ThemeVariantMode,
+} from "./types";
+
+export const DEFAULT_PRESET_ID = "default";
+export const CUSTOM_THEME_ID = "custom";
+
+export type ThemeSelection = { kind: "preset"; id: string } | { kind: "custom" };
+
+export type ActiveTheme = {
+ selection: ThemeSelection;
+ /** The light/dark the window actually shows (Midnight is always dark). */
+ mode: ThemeVariantMode;
+ variant: ThemeVariant;
+ /**
+ * Default preset: the app keeps its stylesheet colours (today's look); only
+ * the contrast fixes are applied, and the editor/terminal keep their own look.
+ */
+ legacy: boolean;
+ radiusPx: number;
+ fontSizePx: number;
+};
+
+export function findPreset(id: string): ThemePreset | undefined {
+ return THEME_PRESETS.find((preset) => preset.id === id);
+}
+
+export function presetModes(preset: Pick<ThemePreset, "variants">): ThemeVariantMode[] {
+ return (["light", "dark"] as const).filter((mode) => Boolean(preset.variants[mode]));
+}
+
+/** The variant a preset or custom theme shows for the wanted mode (its only one when it has one). */
+export function pickVariant(
+ variants: Partial<Record<ThemeVariantMode, ThemeVariant>>,
+ wanted: ThemeVariantMode,
+): { mode: ThemeVariantMode; variant: ThemeVariant } | null {
+ const exact = variants[wanted];
+ if (exact) return { mode: wanted, variant: exact };
+ const other: ThemeVariantMode = wanted === "light" ? "dark" : "light";
+ const fallback = variants[other];
+ return fallback ? { mode: other, variant: fallback } : null;
+}
+
+/** Preset x mode (x system, already resolved by the caller) -> the theme the window shows. */
+export function resolveActiveTheme(
+ selection: ThemeSelection,
+ wanted: ThemeVariantMode,
+ custom: CustomTheme | null,
+): ActiveTheme {
+ if (selection.kind === "custom" && custom) {
+ const picked = pickVariant(custom, wanted);
+ if (picked) {
+ return {
+ selection,
+ ...picked,
+ legacy: false,
+ radiusPx: custom.radiusPx,
+ fontSizePx: custom.fontSizePx,
+ };
+ }
+ }
+ const preset = (selection.kind === "preset" ? findPreset(selection.id) : undefined) ?? findPreset(DEFAULT_PRESET_ID)!;
+ const picked = pickVariant(preset.variants, wanted)!;
+ const effectiveSelection: ThemeSelection = { kind: "preset", id: preset.id };
+ return {
+ selection: effectiveSelection,
+ ...picked,
+ legacy: preset.id === DEFAULT_PRESET_ID,
+ radiusPx: DEFAULT_RADIUS_PX,
+ fontSizePx: DEFAULT_FONT_SIZE_PX,
+ };
+}
+
+function mix(a: string, b: string, t: number): string {
+ const [ar, ag, ab] = hexToRgb(a);
+ const [br, bg, bb] = hexToRgb(b);
+ return rgbToHex(ar + (br - ar) * t, ag + (bg - ag) * t, ab + (bb - ab) * t);
+}
+
+function withAlpha(hex: string, alpha: number): string {
+ const a = Math.max(0, Math.min(255, Math.round(alpha * 255)));
+ return `${hex}${a.toString(16).padStart(2, "0")}`;
+}
+
+function rgbTriplet(hex: string): string {
+ return hexToRgb(hex)
+ .map((c) => Math.round(c * 255))
+ .join(" ");
+}
+
+// Steps of the neutral (gray/slate) scale as a blend from background (1) to text (12),
+// close to Radix slate's spacing; 2 = surface, 5 = border and 11 = muted text are exact.
+const NEUTRAL_MIX = [0, 0, 0.055, 0.085, 0, 0.15, 0.2, 0.28, 0.45, 0.5, 0, 1];
+const NEUTRAL_ALPHA = [0.012, 0.027, 0.06, 0.09, 0.12, 0.15, 0.2, 0.28, 0.45, 0.5, 0.62, 0.9];
+
+function neutralScale(v: ThemeVariant): string[] {
+ return NEUTRAL_MIX.map((t, index) => {
+ if (index === 0) return v.background;
+ if (index === 1) return v.surface;
+ if (index === 4) return v.border;
+ if (index === 10) return v.textMuted;
+ if (index === 11) return v.text;
+ return mix(v.background, v.text, t);
+ });
+}
+
+/** Contrast fixes applied on top of today's stylesheet for the Default preset. */
+const DEFAULT_PRESET_FIXES: Record<ThemeVariantMode, Record<string, string>> = {
+ light: {},
+ // Muted text in dark mode was 4.2:1 (slate-10); the design's fix is #858991 (4.5:1+).
+ dark: { "--muted-foreground": "#858991" },
+};
+
+/** CSS custom property name -> value for an active theme. */
+export function paletteVars(active: Pick<ActiveTheme, "variant" | "mode" | "legacy" | "radiusPx" | "fontSizePx">, darkVariant?: ThemeVariant | null): Record<string, string> {
+ if (active.legacy) return { ...DEFAULT_PRESET_FIXES[active.mode] };
+ const v = active.variant;
+ const dark = isDarkColour(v.background);
+ const scale = neutralScale(v);
+ const vars: Record<string, string> = {};
+ const set = (names: string[], value: string) => {
+ for (const name of names) vars[name] = value;
+ };
+ set(["--background", "--dls-background", "--dls-app-bg"], v.background);
+ set(["--card", "--dls-surface", "--sidebar", "--dls-sidebar", "--secondary", "--muted", "--dls-canvas"], v.surface);
+ set(["--popover", "--dls-surface-muted"], v.surfaceRaised);
+ set(["--border", "--dls-border", "--sidebar-border", "--popover-border"], v.border);
+ set(["--input"], mix(v.border, v.textMuted, 0.25));
+ set(
+ [
+ "--foreground",
+ "--dls-text-primary",
+ "--card-foreground",
+ "--popover-foreground",
+ "--secondary-foreground",
+ "--accent-foreground",
+ "--sidebar-foreground",
+ "--sidebar-accent-foreground",
+ ],
+ v.text,
+ );
+ set(["--muted-foreground", "--dls-text-secondary"], v.textMuted);
+ set(["--primary", "--dls-accent", "--sidebar-primary", "--ring", "--sidebar-ring"], v.accent);
+ set(["--primary-foreground", "--dls-accent-fg", "--sidebar-primary-foreground"], v.accentText);
+ set(["--dls-accent-hover"], mix(v.accent, dark ? "#ffffff" : "#000000", 0.12));
+ set(["--dls-accent-rgb"], rgbTriplet(v.accent));
+ set(["--dls-secondary-rgb"], rgbTriplet(v.textMuted));
+ set(["--accent", "--sidebar-accent", "--dls-hover"], scale[2]!);
+ set(["--dls-active"], scale[4]!);
+ set(["--destructive"], v.danger);
+ set(["--warning"], v.warn);
+ set(["--omnirush-success"], v.success);
+ set(["--omnirush-highlight"], v.highlight ?? v.accent);
+ set(["--omnirush-link"], textSafeAccent(v));
+ set(["--omnirush-terminal-bg"], v.terminal.bg);
+ set(["--omnirush-terminal-fg"], v.terminal.fg);
+ set(["--omnirush-terminal-header"], mix(v.terminal.bg, v.terminal.fg, 0.06));
+ set(["--omnirush-terminal-input"], v.terminal.bg);
+ set(["--omnirush-code-bg"], v.code.bg);
+ set(["--omnirush-code-fg"], v.code.fg);
+ for (const key of SYNTAX_KEYS) set([`--omnirush-syntax-${key}`], v.code[key]);
+ if (darkVariant) set(["--omnirush-gate-bg"], darkVariant.background);
+ scale.forEach((value, index) => set([`--gray-${index + 1}`, `--slate-${index + 1}`], value));
+ NEUTRAL_ALPHA.forEach((alpha, index) => set([`--gray-a${index + 1}`, `--slate-a${index + 1}`], withAlpha(v.text, alpha)));
+ const radius = Math.min(RADIUS_RANGE.max, Math.max(RADIUS_RANGE.min, active.radiusPx));
+ if (radius !== DEFAULT_RADIUS_PX) vars["--radius"] = `${radius}px`;
+ const fontSize = Math.min(FONT_SIZE_RANGE.max, Math.max(FONT_SIZE_RANGE.min, active.fontSizePx));
+ if (fontSize !== DEFAULT_FONT_SIZE_PX) vars["--omnirush-theme-font-scale"] = String(Math.round((fontSize / DEFAULT_FONT_SIZE_PX) * 10000) / 10000);
+ return vars;
+}
+
+const VAR_NAME = /^--[a-z0-9-]+$/;
+const VAR_VALUE = /^(#[0-9a-f]{6}([0-9a-f]{2})?|\d{1,3} \d{1,3} \d{1,3}|\d+(\.\d+)?(px)?)$/;
+
+/** True for values this module produces; anything else is never written to CSS. */
+export function isSafeVar(name: string, value: string): boolean {
+ return VAR_NAME.test(name) && VAR_VALUE.test(value);
+}
+
+let appliedNames: string[] = [];
+
+/** Writes the variables on <html>, removing ones a previous theme set. */
+export function applyPaletteVars(
+ style: Pick<CSSStyleDeclaration, "setProperty" | "removeProperty" | "getPropertyValue">,
+ vars: Record<string, string>,
+): void {
+ seedFromStyle(style);
+ const next = Object.entries(vars).filter(([name, value]) => isSafeVar(name, value));
+ const nextNames = new Set(next.map(([name]) => name));
+ for (const name of appliedNames) {
+ if (!nextNames.has(name)) style.removeProperty(name);
+ }
+ for (const [name, value] of next) style.setProperty(name, value);
+ appliedNames = [...nextNames];
+}
+
+/** Every variable name a theme can set (the early inline script may have set any of them). */
+export function allPaletteVarNames(): string[] {
+ const preset = findPreset("fjord")!;
+ const names = Object.keys(
+ paletteVars(
+ { variant: preset.variants.light!, mode: "light", legacy: false, radiusPx: 0, fontSizePx: FONT_SIZE_RANGE.max },
+ preset.variants.dark,
+ ),
+ );
+ return [...new Set([...names, ...Object.keys(DEFAULT_PRESET_FIXES.dark)])];
+}
+
+let seeded = false;
+
+/** Adopts variables the early inline script set, so a changed theme removes them. */
+function seedFromStyle(style: Pick<CSSStyleDeclaration, "getPropertyValue">): void {
+ if (seeded) return;
+ seeded = true;
+ appliedNames = allPaletteVarNames().filter((name) => style.getPropertyValue(name) !== "");
+}
+
+export function resetAppliedPaletteForTests(): void {
+ seeded = false;
+ appliedNames = [];
+}
diff --git a/apps/app/src/app/themes/presets.ts b/apps/app/src/app/themes/presets.ts
new file mode 100644
index 00000000..33699267
--- /dev/null
+++ b/apps/app/src/app/themes/presets.ts
@@ -0,0 +1,298 @@
+// Theme presets. Values come from the approved design (WCAG AA checked for every pair).
+import type { ThemePreset } from "./types";
+
+export const THEME_PRESETS: readonly ThemePreset[] = [
+ {
+ id: "default",
+ name: "Default",
+ description: "The current OmniRush look (slate). Shown for reference and as the base of a custom theme.",
+ target: "AA",
+ variants: {
+ light: {
+ background: "#fcfcfd",
+ surface: "#f9f9fb",
+ surfaceRaised: "#ffffff",
+ border: "#e0e1e6",
+ text: "#1c2024",
+ textMuted: "#60646c",
+ accent: "#1c2024",
+ accentText: "#fcfcfd",
+ success: "#208157",
+ warn: "#a56100",
+ danger: "#ce2c31",
+ code: { bg: "#f9f9fb", fg: "#1c2024", keyword: "#cf222e", string: "#0a3069", number: "#0550ae", function: "#8250df", type: "#953800", variable: "#1c2024", comment: "#6c747e", punctuation: "#57606a" },
+ terminal: { bg: "#fcfcfd", fg: "#1c2024", cursor: "#1c2024", black: "#1c2024", red: "#ce2c31", green: "#218358", yellow: "#a86300", blue: "#0d74ce", magenta: "#8145b5", cyan: "#107d98", white: "#8b8d98", brightBlack: "#60646c", brightRed: "#da353a", brightGreen: "#258457", brightYellow: "#a86300", brightBlue: "#0076d1", brightMagenta: "#8e4ec6", brightCyan: "#007f9c", brightWhite: "#cdced6" },
+ highlight: "#bdee63",
+ },
+ dark: {
+ background: "#111113",
+ surface: "#18191b",
+ surfaceRaised: "#212225",
+ border: "#2e3135",
+ text: "#edeef0",
+ textMuted: "#858991",
+ accent: "#edeef0",
+ accentText: "#111113",
+ success: "#3dd68c",
+ warn: "#ffca16",
+ danger: "#ff9592",
+ code: { bg: "#18191b", fg: "#edeef0", keyword: "#ff7b72", string: "#a5d6ff", number: "#79c0ff", function: "#d2a8ff", type: "#ffa657", variable: "#edeef0", comment: "#8b949e", punctuation: "#b0b4ba" },
+ terminal: { bg: "#111113", fg: "#edeef0", cursor: "#edeef0", black: "#2e3135", red: "#ff9592", green: "#3dd68c", yellow: "#ffca16", blue: "#70b8ff", magenta: "#d19dff", cyan: "#4ccce6", white: "#b0b4ba", brightBlack: "#747d87", brightRed: "#ffb3b0", brightGreen: "#71e8a8", brightYellow: "#ffe08a", brightBlue: "#9dcdff", brightMagenta: "#e2bdff", brightCyan: "#8be0f0", brightWhite: "#edeef0" },
+ highlight: "#bdee63",
+ },
+ },
+ },
+ {
+ id: "midnight",
+ name: "Midnight",
+ description: "Deep navy for late sessions. Dark only.",
+ target: "AA",
+ variants: {
+ dark: {
+ background: "#0b1020",
+ surface: "#111830",
+ surfaceRaised: "#18213d",
+ border: "#263252",
+ text: "#e6e9f2",
+ textMuted: "#9aa3b8",
+ accent: "#7aa2ff",
+ accentText: "#0b1020",
+ success: "#5fdc96",
+ warn: "#f5c26b",
+ danger: "#ff7a85",
+ code: { bg: "#0e1428", fg: "#d6dbe8", keyword: "#c792ea", string: "#a8e0a0", number: "#f7a46b", function: "#82aaff", type: "#ffcb6b", variable: "#d6dbe8", comment: "#7f8bab", punctuation: "#a6b0c8" },
+ terminal: { bg: "#0b1020", fg: "#d6dbe8", cursor: "#7aa2ff", black: "#1b2236", red: "#ff7a85", green: "#7ee2a8", yellow: "#f5c26b", blue: "#7aa2ff", magenta: "#c792ea", cyan: "#6fd3e6", white: "#c8cfdd", brightBlack: "#6d7ba1", brightRed: "#ff9aa2", brightGreen: "#9ff0bf", brightYellow: "#ffd88f", brightBlue: "#9fbcff", brightMagenta: "#dcb2f5", brightCyan: "#93e3f0", brightWhite: "#f2f4f8" },
+ },
+ },
+ },
+ {
+ id: "fjord",
+ name: "Fjord",
+ description: "Cool arctic greys and frost blues.",
+ target: "AA",
+ variants: {
+ light: {
+ background: "#eceff4",
+ surface: "#e5e9f0",
+ surfaceRaised: "#f6f8fb",
+ border: "#d3d9e4",
+ text: "#2e3440",
+ textMuted: "#4c566a",
+ accent: "#4c6e98",
+ accentText: "#ffffff",
+ success: "#3f6b2c",
+ warn: "#8a5f00",
+ danger: "#a83a45",
+ code: { bg: "#e5e9f0", fg: "#2e3440", keyword: "#496a93", string: "#3f6b2c", number: "#8a4d78", function: "#2f6b80", type: "#6a4f94", variable: "#2e3440", comment: "#5b6680", punctuation: "#434c5e" },
+ terminal: { bg: "#eceff4", fg: "#2e3440", cursor: "#4c6e98", black: "#2e3440", red: "#a83a45", green: "#3f6b2c", yellow: "#8a5f00", blue: "#4c6e98", magenta: "#8a4d78", cyan: "#2f6b80", white: "#7b8394", brightBlack: "#4c566a", brightRed: "#b64752", brightGreen: "#4c7836", brightYellow: "#8d6400", brightBlue: "#4e6f97", brightMagenta: "#945982", brightCyan: "#377387", brightWhite: "#a0a8b8" },
+ },
+ dark: {
+ background: "#2e3440",
+ surface: "#353c4a",
+ surfaceRaised: "#3b4252",
+ border: "#4c566a",
+ text: "#eceff4",
+ textMuted: "#bfc7d5",
+ accent: "#88c0d0",
+ accentText: "#2e3440",
+ success: "#a3be8c",
+ warn: "#ebcb8b",
+ danger: "#e59aa1",
+ code: { bg: "#333a48", fg: "#e5e9f0", keyword: "#88a6c4", string: "#a3be8c", number: "#bb99b5", function: "#88c0d0", type: "#8fbcbb", variable: "#d8dee9", comment: "#9aa5ba", punctuation: "#c8d0dc" },
+ terminal: { bg: "#2e3440", fg: "#e5e9f0", cursor: "#d8dee9", black: "#3b4252", red: "#e08a92", green: "#a3be8c", yellow: "#ebcb8b", blue: "#81a1c1", magenta: "#b691af", cyan: "#88c0d0", white: "#e5e9f0", brightBlack: "#949caf", brightRed: "#ee9aa2", brightGreen: "#b6d0a0", brightYellow: "#f2d9a2", brightBlue: "#9bb6d4", brightMagenta: "#c6a2c0", brightCyan: "#8fbcbb", brightWhite: "#eceff4" },
+ },
+ },
+ },
+ {
+ id: "sol",
+ name: "Sol",
+ description: "Warm low-glare paper. Blue accent in light, amber accent in dark.",
+ target: "AA",
+ variants: {
+ light: {
+ background: "#fdf6e3",
+ surface: "#f3ecd6",
+ surfaceRaised: "#fffbef",
+ border: "#e2d9bd",
+ text: "#26363c",
+ textMuted: "#52646b",
+ accent: "#1f6fa8",
+ accentText: "#ffffff",
+ success: "#5a6e00",
+ warn: "#8a6200",
+ danger: "#b8282a",
+ code: { bg: "#f3ecd6", fg: "#26363c", keyword: "#5a6e00", string: "#1c766e", number: "#b02a6c", function: "#1f6fa8", type: "#8a6200", variable: "#26363c", comment: "#5c6e74", punctuation: "#4a5b61" },
+ terminal: { bg: "#fdf6e3", fg: "#26363c", cursor: "#1f6fa8", black: "#073642", red: "#b8282a", green: "#5a6e00", yellow: "#8a6200", blue: "#1f6fa8", magenta: "#b02a6c", cyan: "#1d7a72", white: "#93a1a1", brightBlack: "#586e75", brightRed: "#c4421f", brightGreen: "#5f747c", brightYellow: "#7a6c00", brightBlue: "#4e5a9e", brightMagenta: "#8a52a8", brightCyan: "#297d76", brightWhite: "#eee8d5" },
+ },
+ dark: {
+ background: "#002b36",
+ surface: "#073642",
+ surfaceRaised: "#0b4150",
+ border: "#1d5563",
+ text: "#e4e2d6",
+ textMuted: "#9fb0b0",
+ accent: "#d4a82a",
+ accentText: "#002b36",
+ success: "#a4b830",
+ warn: "#e2a33a",
+ danger: "#f48581",
+ code: { bg: "#073642", fg: "#d8d9cf", keyword: "#a4b830", string: "#2fb5aa", number: "#e870a8", function: "#4ea5e8", type: "#d4a82a", variable: "#d8d9cf", comment: "#8a9e9e", punctuation: "#b3bfbf" },
+ terminal: { bg: "#002b36", fg: "#d8d9cf", cursor: "#d4a82a", black: "#073642", red: "#f2706c", green: "#a4b830", yellow: "#d4a82a", blue: "#4ea5e8", magenta: "#e870a8", cyan: "#2fb5aa", white: "#eee8d5", brightBlack: "#5d95a7", brightRed: "#f58a5a", brightGreen: "#9fb0b0", brightYellow: "#c8b860", brightBlue: "#9a9ee8", brightMagenta: "#c58ad8", brightCyan: "#6fc8c0", brightWhite: "#fdf6e3" },
+ },
+ },
+ },
+ {
+ id: "rose",
+ name: "Rose",
+ description: "Soft blush neutrals with a raspberry accent.",
+ target: "AA",
+ variants: {
+ light: {
+ background: "#fffafb",
+ surface: "#fcf1f4",
+ surfaceRaised: "#ffffff",
+ border: "#efd6dd",
+ text: "#2a1a1f",
+ textMuted: "#74525c",
+ accent: "#b3195a",
+ accentText: "#ffffff",
+ success: "#2b7449",
+ warn: "#8f5400",
+ danger: "#b42318",
+ code: { bg: "#fbeef1", fg: "#2a1a1f", keyword: "#a8215f", string: "#2b7449", number: "#a34a00", function: "#7438a0", type: "#8f2c55", variable: "#2a1a1f", comment: "#82646d", punctuation: "#5e4148" },
+ terminal: { bg: "#fffafb", fg: "#2a1a1f", cursor: "#b3195a", black: "#2a1a1f", red: "#b42318", green: "#2b7449", yellow: "#8f5400", blue: "#3a55a8", magenta: "#a8215f", cyan: "#1f6f78", white: "#a08890", brightBlack: "#74525c", brightRed: "#c43a2f", brightGreen: "#388156", brightYellow: "#a06400", brightBlue: "#4a66b8", brightMagenta: "#b8336f", brightCyan: "#2f7f88", brightWhite: "#e8d4da" },
+ },
+ dark: {
+ background: "#1a1215",
+ surface: "#22181c",
+ surfaceRaised: "#2c1f25",
+ border: "#41303a",
+ text: "#f5e6ea",
+ textMuted: "#c9aab3",
+ accent: "#f48fb1",
+ accentText: "#2a0f19",
+ success: "#7fd6a0",
+ warn: "#f0c27a",
+ danger: "#ff8a80",
+ code: { bg: "#22181c", fg: "#f0dfe4", keyword: "#f48fb1", string: "#9de0b4", number: "#ffb27a", function: "#c9a0f0", type: "#ffa0c0", variable: "#f0dfe4", comment: "#a88a93", punctuation: "#d4bcc3" },
+ terminal: { bg: "#1a1215", fg: "#f0dfe4", cursor: "#f48fb1", black: "#3a2a30", red: "#ff8a80", green: "#7fd6a0", yellow: "#f0c27a", blue: "#90b0f8", magenta: "#f48fb1", cyan: "#7ad0d8", white: "#e0ccd2", brightBlack: "#957683", brightRed: "#ffa89f", brightGreen: "#a0e4b8", brightYellow: "#f6d49a", brightBlue: "#b0c6ff", brightMagenta: "#f8aac8", brightCyan: "#9ce0e6", brightWhite: "#fff5f7" },
+ },
+ },
+ },
+ {
+ id: "forest",
+ name: "Forest",
+ description: "Moss and bark greens, calm and earthy.",
+ target: "AA",
+ variants: {
+ light: {
+ background: "#f6f8f3",
+ surface: "#edf1e7",
+ surfaceRaised: "#fbfcf9",
+ border: "#d4ddc9",
+ text: "#1c261c",
+ textMuted: "#4d5d4a",
+ accent: "#2f6b3a",
+ accentText: "#ffffff",
+ success: "#2f6b3a",
+ warn: "#875700",
+ danger: "#b3261e",
+ code: { bg: "#edf1e7", fg: "#1c261c", keyword: "#2f6b3a", string: "#7a5a00", number: "#a8481e", function: "#245f86", type: "#6d4a96", variable: "#1c261c", comment: "#5c6b58", punctuation: "#3f4b3d" },
+ terminal: { bg: "#f6f8f3", fg: "#1c261c", cursor: "#2f6b3a", black: "#1c261c", red: "#b3261e", green: "#2f6b3a", yellow: "#875700", blue: "#245f86", magenta: "#7a4a8c", cyan: "#1d6b66", white: "#8a9686", brightBlack: "#4d5d4a", brightRed: "#c23a2e", brightGreen: "#3c7d46", brightYellow: "#966600", brightBlue: "#3470a0", brightMagenta: "#8a5aa0", brightCyan: "#2a7a74", brightWhite: "#dfe6d8" },
+ },
+ dark: {
+ background: "#121a14",
+ surface: "#18221a",
+ surfaceRaised: "#1f2b21",
+ border: "#2e3d30",
+ text: "#e3ece0",
+ textMuted: "#a8b8a4",
+ accent: "#8fcf7a",
+ accentText: "#0f1a10",
+ success: "#8fcf7a",
+ warn: "#e6c26a",
+ danger: "#f08a7a",
+ code: { bg: "#18221a", fg: "#dde8da", keyword: "#8fcf7a", string: "#e6c26a", number: "#f0a070", function: "#7ab8e0", type: "#c6a0e0", variable: "#dde8da", comment: "#8a9c86", punctuation: "#b8c6b4" },
+ terminal: { bg: "#121a14", fg: "#dde8da", cursor: "#8fcf7a", black: "#26322a", red: "#f08a7a", green: "#8fcf7a", yellow: "#e6c26a", blue: "#7ab8e0", magenta: "#c6a0e0", cyan: "#70c8b8", white: "#d0dccc", brightBlack: "#6f8775", brightRed: "#f6a69a", brightGreen: "#aee09c", brightYellow: "#f0d48c", brightBlue: "#9ccaf0", brightMagenta: "#d8bcec", brightCyan: "#94dccc", brightWhite: "#f3f8f1" },
+ },
+ },
+ },
+ {
+ id: "high-contrast",
+ name: "High contrast",
+ description: "Maximum legibility: pure black/white, strong borders, AAA (7:1) text.",
+ target: "AAA",
+ variants: {
+ light: {
+ background: "#ffffff",
+ surface: "#ffffff",
+ surfaceRaised: "#ffffff",
+ border: "#1a1a1a",
+ text: "#000000",
+ textMuted: "#2b2b2b",
+ accent: "#0038b8",
+ accentText: "#ffffff",
+ success: "#00632a",
+ warn: "#6b4000",
+ danger: "#a3001b",
+ code: { bg: "#ffffff", fg: "#000000", keyword: "#0038b8", string: "#00632a", number: "#8a1a00", function: "#6a0dad", type: "#7a3a00", variable: "#000000", comment: "#454545", punctuation: "#1f1f1f" },
+ terminal: { bg: "#ffffff", fg: "#000000", cursor: "#000000", black: "#000000", red: "#a3001b", green: "#00632a", yellow: "#6b4000", blue: "#0038b8", magenta: "#6a0dad", cyan: "#005a6b", white: "#595959", brightBlack: "#3a3a3a", brightRed: "#b8001f", brightGreen: "#006b2e", brightYellow: "#7a4a00", brightBlue: "#003fcc", brightMagenta: "#7a12c0", brightCyan: "#006478", brightWhite: "#d0d0d0" },
+ },
+ dark: {
+ background: "#000000",
+ surface: "#0a0a0a",
+ surfaceRaised: "#141414",
+ border: "#ffffff",
+ text: "#ffffff",
+ textMuted: "#e0e0e0",
+ accent: "#ffe14d",
+ accentText: "#000000",
+ success: "#4dff9a",
+ warn: "#ffe14d",
+ danger: "#ff8080",
+ code: { bg: "#000000", fg: "#ffffff", keyword: "#ff9ee6", string: "#9dff9d", number: "#ffc266", function: "#8fd0ff", type: "#ffe14d", variable: "#ffffff", comment: "#c8c8c8", punctuation: "#e8e8e8" },
+ terminal: { bg: "#000000", fg: "#ffffff", cursor: "#ffe14d", black: "#3a3a3a", red: "#ff8080", green: "#4dff9a", yellow: "#ffe14d", blue: "#8fd0ff", magenta: "#ff9ee6", cyan: "#66f0ff", white: "#e8e8e8", brightBlack: "#8c8c8c", brightRed: "#ffa3a3", brightGreen: "#8affbd", brightYellow: "#fff08a", brightBlue: "#b3e0ff", brightMagenta: "#ffbff0", brightCyan: "#a3f7ff", brightWhite: "#ffffff" },
+ },
+ },
+ },
+ {
+ id: "omnirush",
+ name: "OmniRush",
+ description: "The brand: violet accent in both modes, lime only as a highlight (usage bar, status dot).",
+ target: "AA",
+ variants: {
+ light: {
+ background: "#fbfaff",
+ surface: "#f5f3fd",
+ surfaceRaised: "#ffffff",
+ border: "#e2dcf6",
+ text: "#1b1530",
+ textMuted: "#5b5475",
+ accent: "#6e56cf",
+ accentText: "#ffffff",
+ success: "#3f6b12",
+ warn: "#8a5a00",
+ danger: "#c0262d",
+ code: { bg: "#f4f1fc", fg: "#1b1530", keyword: "#6550b9", string: "#3f6b12", number: "#b4441f", function: "#2a5fb0", type: "#8a3fa0", variable: "#1b1530", comment: "#6c6585", punctuation: "#4a4462" },
+ terminal: { bg: "#fbfaff", fg: "#1b1530", cursor: "#6e56cf", black: "#1b1530", red: "#c0262d", green: "#3f6b12", yellow: "#8a5a00", blue: "#2a5fb0", magenta: "#6e56cf", cyan: "#1d6f7a", white: "#8a84a0", brightBlack: "#5b5475", brightRed: "#d0353c", brightGreen: "#4d7d1c", brightYellow: "#9a6800", brightBlue: "#3a70c4", brightMagenta: "#7860da", brightCyan: "#297e88", brightWhite: "#e2dcf6" },
+ highlight: "#bdee63",
+ },
+ dark: {
+ background: "#0f0c1a",
+ surface: "#161226",
+ surfaceRaised: "#1e1933",
+ border: "#2e2748",
+ text: "#efeafc",
+ textMuted: "#aaa2c4",
+ accent: "#a48fff",
+ accentText: "#0f0c1a",
+ success: "#9fe870",
+ warn: "#ffca16",
+ danger: "#ff8a8a",
+ code: { bg: "#141022", fg: "#e6e0f6", keyword: "#baa7ff", string: "#b9f45a", number: "#ffb07a", function: "#7cc4ff", type: "#f0a6ff", variable: "#e6e0f6", comment: "#8e86aa", punctuation: "#c4bcdc" },
+ terminal: { bg: "#0f0c1a", fg: "#e6e0f6", cursor: "#a48fff", black: "#2a2440", red: "#ff8a8a", green: "#b9f45a", yellow: "#ffca16", blue: "#7cc4ff", magenta: "#baa7ff", cyan: "#6fe0e0", white: "#d8d2ea", brightBlack: "#7f769f", brightRed: "#ffa8a8", brightGreen: "#d0ff8a", brightYellow: "#ffe070", brightBlue: "#a4d6ff", brightMagenta: "#d4c6ff", brightCyan: "#9cf0f0", brightWhite: "#ffffff" },
+ highlight: "#b9f45a",
+ },
+ },
+ },
+];
diff --git a/apps/app/src/app/themes/share.ts b/apps/app/src/app/themes/share.ts
new file mode 100644
index 00000000..d2f56b77
--- /dev/null
+++ b/apps/app/src/app/themes/share.ts
@@ -0,0 +1,329 @@
+/**
+ * Custom theme files and share codes.
+ *
+ * Share code: `omnirush-theme:1:<base64url(deflate-raw(json))>` (plain
+ * base64url JSON when the runtime has no CompressionStream). The theme JSON
+ * goes through validateThemeData before anything uses it: only known keys,
+ * only #rrggbb colours, a short printable name, clamped numbers, and an 8 KB
+ * cap before and after decompression.
+ */
+import {
+ BASE_COLOUR_KEYS,
+ CODE_KEYS,
+ DEFAULT_FONT_SIZE_PX,
+ DEFAULT_RADIUS_PX,
+ FONT_SIZE_RANGE,
+ RADIUS_RANGE,
+ TERMINAL_KEYS,
+ type CustomTheme,
+ type ThemeVariant,
+ type ThemeVariantMode,
+} from "./types";
+
+export const SHARE_CODE_PREFIX = "omnirush-theme:";
+export const SHARE_CODE_VERSION = 1;
+export const THEME_FILE_SUFFIX = ".omnirush-theme.json";
+/** Upper bound for theme JSON, compressed payloads and decompressed output. */
+export const MAX_THEME_BYTES = 8 * 1024;
+export const MAX_NAME_LENGTH = 40;
+
+export type ThemeImportResult = { ok: true; theme: CustomTheme } | { ok: false; error: string };
+
+const TOP_KEYS = ["v", "name", "modes", "light", "dark", "radiusPx", "fontSizePx"] as const;
+const VARIANT_KEYS = [...BASE_COLOUR_KEYS, "code", "terminal", "highlight"] as const;
+const COLOUR = /^#[0-9a-fA-F]{6}$/;
+// No control, format (bidi overrides, zero-width), surrogate, private-use or unassigned characters.
+const PRINTABLE = /^[^\p{C}]+$/u;
+const BASE64URL = /^[A-Za-z0-9_-]+$/;
+
+const fail = (error: string): ThemeImportResult => ({ ok: false, error });
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
+ const proto = Object.getPrototypeOf(value);
+ return proto === Object.prototype || proto === null;
+}
+
+function unknownKey(obj: Record<string, unknown>, allowed: readonly string[], where: string): string | null {
+ for (const key of Object.keys(obj)) {
+ if (!allowed.includes(key)) return `unknown key "${key.slice(0, 40)}"${where ? ` in ${where}` : ""}`;
+ }
+ return null;
+}
+
+function clamp(value: number, min: number, max: number): number {
+ return Math.min(max, Math.max(min, value));
+}
+
+function readColour(value: unknown, path: string): { colour: string } | { error: string } {
+ if (typeof value !== "string" || !COLOUR.test(value)) return { error: `"${path}" must be a colour like #1a2b3c` };
+ return { colour: value.toLowerCase() };
+}
+
+function validateGroup(
+ value: unknown,
+ keys: readonly string[],
+ path: string,
+): { group: Record<string, string> } | { error: string } {
+ if (!isPlainObject(value)) return { error: `"${path}" must be an object` };
+ const unknown = unknownKey(value, keys, path);
+ if (unknown) return { error: unknown };
+ const group: Record<string, string> = {};
+ for (const key of keys) {
+ if (!(key in value)) return { error: `missing colour "${path}.${key}"` };
+ const read = readColour(value[key], `${path}.${key}`);
+ if ("error" in read) return read;
+ group[key] = read.colour;
+ }
+ return { group };
+}
+
+function validateVariant(value: unknown, mode: ThemeVariantMode): { variant: ThemeVariant } | { error: string } {
+ if (!isPlainObject(value)) return { error: `"${mode}" must be an object` };
+ const unknown = unknownKey(value, VARIANT_KEYS, mode);
+ if (unknown) return { error: unknown };
+ const out: Record<string, unknown> = {};
+ for (const key of BASE_COLOUR_KEYS) {
+ if (!(key in value)) return { error: `missing colour "${mode}.${key}"` };
+ const read = readColour(value[key], `${mode}.${key}`);
+ if ("error" in read) return read;
+ out[key] = read.colour;
+ }
+ const code = validateGroup(value.code, CODE_KEYS, `${mode}.code`);
+ if ("error" in code) return code;
+ out.code = code.group;
+ const terminal = validateGroup(value.terminal, TERMINAL_KEYS, `${mode}.terminal`);
+ if ("error" in terminal) return terminal;
+ out.terminal = terminal.group;
+ if ("highlight" in value) {
+ const read = readColour(value.highlight, `${mode}.highlight`);
+ if ("error" in read) return read;
+ out.highlight = read.colour;
+ }
+ return { variant: out as ThemeVariant };
+}
+
+function readNumber(value: unknown, name: string, range: { min: number; max: number }, fallback: number) {
+ if (value === undefined) return { value: fallback };
+ if (typeof value !== "number" || !Number.isFinite(value)) return { error: `"${name}" must be a number` };
+ return { value: Math.round(clamp(value, range.min, range.max) * 10) / 10 };
+}
+
+/**
+ * The only way theme data from outside (file, share code, storage) becomes a
+ * CustomTheme. Pure: no I/O, no DOM.
+ */
+export function validateThemeData(input: unknown): ThemeImportResult {
+ if (!isPlainObject(input)) return fail("a theme must be a JSON object");
+ const unknown = unknownKey(input, TOP_KEYS, "");
+ if (unknown) return fail(unknown);
+ if (input.v !== 1) return fail("unsupported theme version (expected 1)");
+
+ if (typeof input.name !== "string") return fail('"name" must be text');
+ const name = input.name.trim();
+ if (name.length === 0) return fail('"name" is empty');
+ if ([...name].length > MAX_NAME_LENGTH) return fail(`"name" is longer than ${MAX_NAME_LENGTH} characters`);
+ if (!PRINTABLE.test(name)) return fail('"name" contains characters that cannot be shown');
+
+ if (!Array.isArray(input.modes) || input.modes.length === 0 || input.modes.length > 2) {
+ return fail('"modes" must list "light", "dark" or both');
+ }
+ const modes: ThemeVariantMode[] = [];
+ for (const mode of input.modes) {
+ if (mode !== "light" && mode !== "dark") return fail('"modes" may only contain "light" and "dark"');
+ if (modes.includes(mode)) return fail(`"modes" lists "${mode}" twice`);
+ modes.push(mode);
+ }
+
+ const theme: CustomTheme = { v: 1, name, modes: [], radiusPx: DEFAULT_RADIUS_PX, fontSizePx: DEFAULT_FONT_SIZE_PX };
+ for (const mode of ["light", "dark"] as const) {
+ const listed = modes.includes(mode);
+ const present = mode in input;
+ if (listed && !present) return fail(`"modes" lists "${mode}" but there is no ${mode} version`);
+ if (!listed && present) return fail(`there is a ${mode} version but "modes" does not list it`);
+ if (!listed) continue;
+ const result = validateVariant(input[mode], mode);
+ if ("error" in result) return fail(result.error);
+ theme[mode] = result.variant;
+ theme.modes.push(mode);
+ }
+
+ const radius = readNumber(input.radiusPx, "radiusPx", RADIUS_RANGE, DEFAULT_RADIUS_PX);
+ if ("error" in radius) return fail(radius.error ?? "bad radiusPx");
+ const fontSize = readNumber(input.fontSizePx, "fontSizePx", FONT_SIZE_RANGE, DEFAULT_FONT_SIZE_PX);
+ if ("error" in fontSize) return fail(fontSize.error ?? "bad fontSizePx");
+ theme.radiusPx = radius.value;
+ theme.fontSizePx = fontSize.value;
+ return { ok: true, theme };
+}
+
+function byteLength(text: string): number {
+ return new TextEncoder().encode(text).length;
+}
+
+/** Parses theme JSON text (a file, or a decoded share code) with the size cap. */
+export function parseThemeJson(text: string): ThemeImportResult {
+ if (byteLength(text) > MAX_THEME_BYTES) return fail("the theme is larger than 8 KB");
+ let data: unknown;
+ try {
+ data = JSON.parse(text);
+ } catch {
+ return fail("this is not valid theme JSON");
+ }
+ return validateThemeData(data);
+}
+
+/** Stable JSON for a theme (fixed key order), used for files and share codes. */
+export function serializeTheme(theme: CustomTheme, pretty = false): string {
+ const variant = (v: ThemeVariant) => {
+ const out: Record<string, unknown> = {};
+ for (const key of BASE_COLOUR_KEYS) out[key] = v[key];
+ out.code = Object.fromEntries(CODE_KEYS.map((key) => [key, v.code[key]]));
+ out.terminal = Object.fromEntries(TERMINAL_KEYS.map((key) => [key, v.terminal[key]]));
+ if (v.highlight) out.highlight = v.highlight;
+ return out;
+ };
+ const doc: Record<string, unknown> = { v: 1, name: theme.name, modes: theme.modes };
+ for (const mode of theme.modes) {
+ const v = theme[mode];
+ if (v) doc[mode] = variant(v);
+ }
+ doc.radiusPx = theme.radiusPx;
+ doc.fontSizePx = theme.fontSizePx;
+ return pretty ? `${JSON.stringify(doc, null, 2)}\n` : JSON.stringify(doc);
+}
+
+export function themeFileName(theme: Pick<CustomTheme, "name">): string {
+ const slug = theme.name
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 40);
+ return `${slug || "theme"}${THEME_FILE_SUFFIX}`;
+}
+
+export function bytesToBase64Url(bytes: Uint8Array): string {
+ let binary = "";
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+}
+
+export function base64UrlToBytes(text: string): Uint8Array | null {
+ if (!BASE64URL.test(text) || text.length % 4 === 1) return null;
+ const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text.length + 3) % 4);
+ try {
+ const binary = atob(padded);
+ const bytes = new Uint8Array(binary.length);
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
+ return bytes;
+ } catch {
+ return null;
+ }
+}
+
+export type Codec = {
+ compress: ((bytes: Uint8Array) => Promise<Uint8Array>) | null;
+ /** Inflates, stopping (and returning null) once the output would pass `limit` bytes. */
+ decompress: ((bytes: Uint8Array, limit: number) => Promise<Uint8Array | null>) | null;
+};
+
+async function readCapped(stream: ReadableStream<Uint8Array>, limit: number): Promise<Uint8Array | null> {
+ const reader = stream.getReader();
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > limit) {
+ await reader.cancel().catch(() => undefined);
+ return null;
+ }
+ chunks.push(value);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ const out = new Uint8Array(total);
+ let offset = 0;
+ for (const chunk of chunks) {
+ out.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return out;
+}
+
+function streamOf(bytes: Uint8Array): ReadableStream<Uint8Array> {
+ return new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(bytes);
+ controller.close();
+ },
+ });
+}
+
+/** deflate-raw via the platform's CompressionStream when it has one. */
+export function platformCodec(): Codec {
+ const hasCompression = typeof CompressionStream === "function" && typeof DecompressionStream === "function";
+ if (!hasCompression) return { compress: null, decompress: null };
+ return {
+ compress: async (bytes) => {
+ const out = await readCapped(
+ streamOf(bytes).pipeThrough(new CompressionStream("deflate-raw") as unknown as TransformStream<Uint8Array, Uint8Array>),
+ Number.MAX_SAFE_INTEGER,
+ );
+ return out ?? new Uint8Array();
+ },
+ decompress: async (bytes, limit) => {
+ try {
+ return await readCapped(
+ streamOf(bytes).pipeThrough(new DecompressionStream("deflate-raw") as unknown as TransformStream<Uint8Array, Uint8Array>),
+ limit,
+ );
+ } catch {
+ return new Uint8Array(0);
+ }
+ },
+ };
+}
+
+export async function encodeShareCode(theme: CustomTheme, codec: Codec = platformCodec()): Promise<string> {
+ const json = new TextEncoder().encode(serializeTheme(theme));
+ const payload = codec.compress ? await codec.compress(json) : json;
+ return `${SHARE_CODE_PREFIX}${SHARE_CODE_VERSION}:${bytesToBase64Url(payload)}`;
+}
+
+export async function decodeShareCode(code: string, codec: Codec = platformCodec()): Promise<ThemeImportResult> {
+ const text = code.trim();
+ // base64url grows data by 4/3; anything longer cannot hold an allowed payload.
+ if (text.length > SHARE_CODE_PREFIX.length + 4 + Math.ceil((MAX_THEME_BYTES * 4) / 3)) {
+ return fail("the code is larger than 8 KB");
+ }
+ if (!text.startsWith(SHARE_CODE_PREFIX)) return fail('a theme code starts with "omnirush-theme:1:"');
+ const rest = text.slice(SHARE_CODE_PREFIX.length);
+ const colon = rest.indexOf(":");
+ if (colon < 0) return fail('a theme code starts with "omnirush-theme:1:"');
+ if (rest.slice(0, colon) !== String(SHARE_CODE_VERSION)) return fail("unsupported theme code version (expected 1)");
+ const bytes = base64UrlToBytes(rest.slice(colon + 1));
+ if (!bytes || bytes.length === 0) return fail("the code is damaged (not base64url)");
+ if (bytes.length > MAX_THEME_BYTES) return fail("the code is larger than 8 KB");
+
+ // Plain JSON payload (written where compression is unavailable) starts with "{".
+ if (bytes[0] === 0x7b) {
+ const plain = new TextDecoder("utf-8", { fatal: false }).decode(bytes);
+ const parsed = parseThemeJson(plain);
+ if (parsed.ok || !codec.decompress) return parsed;
+ }
+ if (!codec.decompress) return fail("the code is compressed and this app cannot read it");
+ const inflated = await codec.decompress(bytes, MAX_THEME_BYTES);
+ if (inflated === null) return fail("the theme is larger than 8 KB once decoded");
+ if (inflated.length === 0) return fail("the code is damaged (cannot be decompressed)");
+ let json: string;
+ try {
+ json = new TextDecoder("utf-8", { fatal: true }).decode(inflated);
+ } catch {
+ return fail("the code is damaged (not text)");
+ }
+ return parseThemeJson(json);
+}
diff --git a/apps/app/src/app/themes/types.ts b/apps/app/src/app/themes/types.ts
new file mode 100644
index 00000000..3fccb689
--- /dev/null
+++ b/apps/app/src/app/themes/types.ts
@@ -0,0 +1,87 @@
+export type ThemeVariantMode = "light" | "dark";
+
+export const SYNTAX_KEYS = [
+ "keyword",
+ "string",
+ "number",
+ "function",
+ "type",
+ "variable",
+ "comment",
+ "punctuation",
+] as const;
+export type SyntaxKey = (typeof SYNTAX_KEYS)[number];
+
+export const ANSI_KEYS = [
+ "black",
+ "red",
+ "green",
+ "yellow",
+ "blue",
+ "magenta",
+ "cyan",
+ "white",
+ "brightBlack",
+ "brightRed",
+ "brightGreen",
+ "brightYellow",
+ "brightBlue",
+ "brightMagenta",
+ "brightCyan",
+ "brightWhite",
+] as const;
+export type AnsiKey = (typeof ANSI_KEYS)[number];
+
+export const BASE_COLOUR_KEYS = [
+ "background",
+ "surface",
+ "surfaceRaised",
+ "border",
+ "text",
+ "textMuted",
+ "accent",
+ "accentText",
+ "success",
+ "warn",
+ "danger",
+] as const;
+export type BaseColourKey = (typeof BASE_COLOUR_KEYS)[number];
+
+export const CODE_KEYS = ["bg", "fg", ...SYNTAX_KEYS] as const;
+export type CodeKey = (typeof CODE_KEYS)[number];
+
+export const TERMINAL_KEYS = ["bg", "fg", "cursor", ...ANSI_KEYS] as const;
+export type TerminalKey = (typeof TERMINAL_KEYS)[number];
+
+/** One full colour set (light or dark) of a theme. Every colour is #rrggbb. */
+export type ThemeVariant = Record<BaseColourKey, string> & {
+ code: Record<CodeKey, string>;
+ terminal: Record<TerminalKey, string>;
+ /** Decorative highlight (usage bar, connected dot). Optional. */
+ highlight?: string;
+};
+
+export type ThemePreset = {
+ id: string;
+ name: string;
+ description: string;
+ target: "AA" | "AAA";
+ variants: Partial<Record<ThemeVariantMode, ThemeVariant>>;
+};
+
+/** A custom theme as stored and shared (schema 1). */
+export type CustomTheme = {
+ v: 1;
+ name: string;
+ modes: ThemeVariantMode[];
+ light?: ThemeVariant;
+ dark?: ThemeVariant;
+ radiusPx: number;
+ fontSizePx: number;
+};
+
+export const RADIUS_RANGE = { min: 0, max: 16 } as const;
+export const FONT_SIZE_RANGE = { min: 12, max: 16 } as const;
+/** Today's corner radius (0.45rem) and body text size. */
+export const DEFAULT_RADIUS_PX = 7.2;
+export const DEFAULT_FONT_SIZE_PX = 13;