The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,858 lines 68 KB
Raw
1 import { pipe } from "effect/Function";
2 import { THEME_CSS_MAX_LENGTH, type EnvironmentTheme } from "@t3tools/contracts";
3 import * as Equal from "effect/Equal";
4 import * as Option from "effect/Option";
5 import * as Schema from "effect/Schema";
6 import { Atom } from "effect/reactivity";
7 import { msg } from "gt-react";
8 import "culori/css";
9 import { converter, parse } from "culori/fn";
10 import {
11 BUILT_IN_THEMES,
12 EMBER_THEME,
13 GROVE_THEME,
14 IRIS_THEME,
15 OCEAN_THEME,
16 T3_CHAT_THEME,
17 T3_CODE_LIGHT_THEME_COLORS,
18 T3_CODE_DARK_THEME_COLORS,
19 RESERVED_THEME_IDS,
20 THEME_COLOR_ROLES,
21 type ThemeAppearance,
22 type ThemeColorRole,
23 type ThemeColors,
24 type ThemeDefinition,
25 type ThemeVariants,
26 } from "@t3tools/shared/themePalettes";
27 import {
28 CONTEXT_CHIP_ACCENTS,
29 contextChipColorVariable,
30 type ContextChipAccentKind,
31 } from "./lib/contextChipAccents";
32
33 import { m } from "./i18n/messages";
34 import { appAtomRegistry, subscribeAtomChanges } from "./rpc/atomRegistry";
35 import { applyThemeBackground } from "./themeBackground";
36 import { applyThemeCss } from "./themeCss";
37 import { themeServerEnvironmentThemesAtom } from "./state/server";
38
39 export { EMBER_THEME, GROVE_THEME, IRIS_THEME, OCEAN_THEME, T3_CHAT_THEME, THEME_COLOR_ROLES };
40 export type { ThemeAppearance, ThemeColorRole, ThemeColors, ThemeDefinition, ThemeVariants };
41
42 const T3_CHAT_THEME_ID = "t3-chat" as const;
43 const GROVE_THEME_ID = "grove" as const;
44 const OCEAN_THEME_ID = "ocean" as const;
45 const EMBER_THEME_ID = "ember" as const;
46 const IRIS_THEME_ID = "iris" as const;
47 export const THEME_FILE_VERSION = 1 as const;
48 export const CUSTOM_THEMES_STORAGE_KEY = "t3code:themes:v1";
49 export const THEME_FOLLOW_SYSTEM_STORAGE_KEY = "t3code:theme-follow-system";
50 export const THEME_APPEARANCE_MODE_STORAGE_KEY = "t3code:theme-appearance-mode";
51 export const THEME_HALVES_STORAGE_KEY = "t3code:theme-halves:v1";
52 export const ENVIRONMENT_THEMES_STORAGE_KEY = "t3code:environment-themes:v1";
53
54 const LEGACY_T3_CHAT_DARK_THEME_ID = "t3-chat-dark";
55
56 export const ThemePreference = Schema.String;
57 export type ThemePreference = typeof ThemePreference.Type;
58
59 const THEME_COLOR_ROLE_SET: ReadonlySet<string> = new Set(THEME_COLOR_ROLES);
60 export type ThemeColorOverrides = Readonly<Partial<Record<ThemeColorRole, string>>>;
61 export type ThemeVariantOverrides = Readonly<Partial<Record<ThemeAppearance, ThemeColorOverrides>>>;
62 export type ThemePreferenceMode = ThemeAppearance | "system";
63 export type ThemeCollection = Readonly<{ id: string; label: string }>;
64 export type ThemeFile = Readonly<{
65 version: typeof THEME_FILE_VERSION;
66 id: string;
67 name: string;
68 appearance: ThemeAppearance;
69 colors: ThemeColorOverrides;
70 variants?: ThemeVariantOverrides;
71 collection?: ThemeCollection;
72 managed?: boolean;
73 css?: string;
74 }>;
75
76 const customThemeListeners = new Set<() => void>();
77 type CustomThemeLibrarySnapshot =
78 | Readonly<{
79 status: "ready";
80 storedThemes: ReadonlyArray<unknown>;
81 themes: ReadonlyArray<ThemeDefinition>;
82 }>
83 | Readonly<{ status: "unavailable"; reason: "malformed" }>
84 | Readonly<{ status: "unavailable"; reason: "storage-unavailable"; cause: unknown }>;
85
86 let customThemeLibrarySnapshot: CustomThemeLibrarySnapshot | null = null;
87 const themePreviewListeners = new Set<() => void>();
88 let themePreviewAppearance: ThemeAppearance | null = null;
89
90 export function getThemePreviewAppearance(): ThemeAppearance | null {
91 return themePreviewAppearance;
92 }
93
94 export function getThemePreviewSidebarArtwork(): boolean | null {
95 return themePreviewAppearance === null ? null : false;
96 }
97
98 export function subscribeToThemePreview(listener: () => void): () => void {
99 themePreviewListeners.add(listener);
100 return () => themePreviewListeners.delete(listener);
101 }
102
103 function setThemePreviewAppearance(appearance: ThemeAppearance | null): void {
104 if (themePreviewAppearance === appearance) return;
105 themePreviewAppearance = appearance;
106 for (const listener of themePreviewListeners) listener();
107 }
108
109 function isRecord(value: unknown): value is Record<string, unknown> {
110 return typeof value === "object" && value !== null && !Array.isArray(value);
111 }
112
113 function isThemeAppearance(value: unknown): value is ThemeAppearance {
114 return value === "light" || value === "dark";
115 }
116
117 export function isThemeColor(value: unknown): value is string {
118 return typeof value === "string" && toCanonicalThemeColor(value) !== null;
119 }
120
121 function isThemeId(value: unknown): value is string {
122 return typeof value === "string" && /^[a-z0-9](?:[a-z0-9-]{0,47})$/.test(value);
123 }
124
125 function isThemeLabel(value: unknown): value is string {
126 return typeof value === "string" && value.trim().length > 0 && value.trim().length <= 48;
127 }
128
129 function isThemeCss(value: unknown): value is string {
130 return typeof value === "string" && value.length <= THEME_CSS_MAX_LENGTH;
131 }
132
133 function parseThemeCollection(value: unknown): ThemeCollection | undefined {
134 return isRecord(value) &&
135 typeof value.id === "string" &&
136 /^[a-z0-9][a-z0-9.:-]{0,127}$/i.test(value.id) &&
137 isThemeLabel(value.label)
138 ? { id: value.id, label: value.label.trim() }
139 : undefined;
140 }
141
142 function lenientThemeColorOverrides(
143 value: Readonly<Record<string, unknown>>,
144 ): Partial<Record<ThemeColorRole, string>> {
145 const overrides: Partial<Record<ThemeColorRole, string>> = {};
146 for (const [role, color] of Object.entries(value)) {
147 const normalized = toCanonicalThemeColor(color);
148 if (THEME_COLOR_ROLE_SET.has(role) && normalized) {
149 overrides[role as ThemeColorRole] = normalized;
150 }
151 }
152 return overrides;
153 }
154
155 function parseStoredThemeColors(value: unknown, appearance: ThemeAppearance): ThemeColors | null {
156 if (!isRecord(value)) return null;
157 return { ...getDefaultThemeColors(appearance), ...lenientThemeColorOverrides(value) };
158 }
159
160 function parseStoredThemeVariants(
161 value: unknown,
162 baseAppearance: ThemeAppearance,
163 ): ThemeVariants | null | undefined {
164 if (value === undefined) return undefined;
165 if (!isRecord(value)) return null;
166
167 const variants: Partial<Record<ThemeAppearance, ThemeColors>> = {};
168 for (const [appearance, colors] of Object.entries(value)) {
169 if (!isThemeAppearance(appearance)) return null;
170 // Base colors shadow a matching variant; drop it for parseThemeFile round-trips.
171 if (appearance === baseAppearance) continue;
172 const parsedColors = parseStoredThemeColors(colors, appearance);
173 if (!parsedColors) return null;
174 variants[appearance] = parsedColors;
175 }
176 return Object.keys(variants).length > 0 ? variants : undefined;
177 }
178
179 function parseStoredTheme(value: unknown): ThemeDefinition | null {
180 if (!isRecord(value)) return null;
181 if (!isThemeId(value.id) || RESERVED_THEME_IDS.has(value.id)) return null;
182 if (!isThemeLabel(value.label) || !isThemeAppearance(value.appearance)) return null;
183 const colors = parseStoredThemeColors(value.colors, value.appearance);
184 if (!colors) return null;
185 const variants = parseStoredThemeVariants(value.variants, value.appearance);
186 if (value.variants !== undefined && variants === null) return null;
187 const collection = parseThemeCollection(value.collection);
188
189 return {
190 id: value.id,
191 label: value.label.trim(),
192 appearance: value.appearance,
193 colors,
194 ...(variants ? { variants } : {}),
195 ...(collection ? { collection } : {}),
196 ...(value.managed === true ? { managed: true } : {}),
197 ...(isThemeCss(value.css) && value.css.length > 0 ? { css: value.css } : {}),
198 };
199 }
200
201 function parseStoredThemes(storedThemes: ReadonlyArray<unknown>): ReadonlyArray<ThemeDefinition> {
202 const themes: ThemeDefinition[] = [];
203 for (const value of storedThemes) {
204 const theme = parseStoredTheme(value);
205 if (theme && !themes.some((existing) => existing.id === theme.id)) {
206 themes.push(theme);
207 }
208 }
209 return themes;
210 }
211
212 function readCustomThemeLibrarySnapshot(): CustomThemeLibrarySnapshot {
213 if (typeof window === "undefined") {
214 return { status: "ready", storedThemes: [], themes: [] };
215 }
216
217 let raw: string | null;
218 try {
219 raw = window.localStorage.getItem(CUSTOM_THEMES_STORAGE_KEY);
220 } catch (cause) {
221 return { status: "unavailable", reason: "storage-unavailable", cause };
222 }
223 if (!raw) return { status: "ready", storedThemes: [], themes: [] };
224
225 let parsed: unknown;
226 try {
227 parsed = JSON.parse(raw);
228 } catch {
229 return { status: "unavailable", reason: "malformed" };
230 }
231 if (!Array.isArray(parsed)) return { status: "unavailable", reason: "malformed" };
232
233 return { status: "ready", storedThemes: parsed, themes: parseStoredThemes(parsed) };
234 }
235
236 function getCustomThemeLibrarySnapshot(): CustomThemeLibrarySnapshot {
237 if (customThemeLibrarySnapshot === null) {
238 customThemeLibrarySnapshot = readCustomThemeLibrarySnapshot();
239 }
240 return customThemeLibrarySnapshot;
241 }
242
243 function notifyCustomThemeListeners() {
244 for (const listener of customThemeListeners) listener();
245 }
246
247 export function invalidateCustomThemes() {
248 customThemeLibrarySnapshot = null;
249 notifyCustomThemeListeners();
250 }
251
252 const EMPTY_CUSTOM_THEMES: ReadonlyArray<ThemeDefinition> = [];
253
254 export function getCustomThemes(): ReadonlyArray<ThemeDefinition> {
255 const snapshot = getCustomThemeLibrarySnapshot();
256 return snapshot.status === "ready" ? snapshot.themes : EMPTY_CUSTOM_THEMES;
257 }
258
259 function publishedThemeColors(
260 theme: EnvironmentTheme,
261 appearance: ThemeAppearance,
262 colors: Readonly<Record<string, string>> | undefined,
263 ): ThemeColors {
264 // A variant builds on that appearance's stock defaults: the generator follows
265 // the seed canvas's luminance, so dark seeds would give a light variant
266 // unreadable colors.
267 const base =
268 appearance === theme.appearance && theme.canvas !== undefined && theme.accent !== undefined
269 ? createVividThemeColors(appearance, theme.canvas, theme.accent)
270 : getDefaultThemeColors(appearance);
271 return { ...base, ...lenientThemeColorOverrides(colors ?? {}) };
272 }
273
274 function environmentThemeDefinition(theme: EnvironmentTheme): ThemeDefinition {
275 const variants: Partial<Record<ThemeAppearance, ThemeColors>> = {};
276 for (const [variantAppearance, variantColors] of Object.entries(theme.variants ?? {})) {
277 if (variantAppearance === theme.appearance) continue;
278 variants[variantAppearance as ThemeAppearance] = publishedThemeColors(
279 theme,
280 variantAppearance as ThemeAppearance,
281 variantColors,
282 );
283 }
284
285 return {
286 id: theme.id,
287 label: theme.name,
288 appearance: theme.appearance,
289 colors: publishedThemeColors(theme, theme.appearance, theme.colors),
290 ...(Object.keys(variants).length > 0 ? { variants } : {}),
291 // Only the pure seeded form is guided-generator output. An exported file,
292 // or seeds carrying explicit role overrides, must open Duplicate in the
293 // advanced editor -- the guided one regenerates from canvas and accent and
294 // would discard whatever the machine hand-tuned.
295 ...(theme.canvas !== undefined &&
296 theme.accent !== undefined &&
297 theme.colors === undefined &&
298 theme.variants === undefined
299 ? { managed: true }
300 : {}),
301 ...(theme.css ? { css: theme.css } : {}),
302 };
303 }
304
305 /**
306 * Published palettes this client can render. Reserved ids are dropped here rather
307 * than rendered: a published `t3-iris.json` would show this palette on its
308 * card while "Use" resolved the built-in, and a published `dark.json` would
309 * capture everyone whose stored preference is the stock `"dark"`.
310 */
311 export function publishedThemeDefinitions(
312 themes: ReadonlyArray<EnvironmentTheme>,
313 ): ReadonlyArray<ThemeDefinition> {
314 return themes
315 .filter((theme) => {
316 if (isReservedThemeId(theme.id)) return false;
317 if (theme.canvas !== undefined && theme.accent !== undefined) return true;
318 const otherAppearance = theme.appearance === "dark" ? "light" : "dark";
319 return [theme.colors, theme.variants?.[otherAppearance]].some(
320 (colors) =>
321 colors !== undefined && Object.keys(lenientThemeColorOverrides(colors)).length > 0,
322 );
323 })
324 .map(environmentThemeDefinition);
325 }
326
327 // Every reconnect snapshot delivers a fresh but usually identical array; keeping the
328 // previous one skips regenerating palettes and repainting the document for it.
329 const publishedThemesAtom = Atom.make((get): ReadonlyArray<EnvironmentTheme> | null => {
330 const next = get(themeServerEnvironmentThemesAtom);
331 const previous = Option.getOrNull(get.self<ReadonlyArray<EnvironmentTheme> | null>());
332 return previous !== null && Equal.equals(previous, next) ? previous : next;
333 }).pipe(Atom.withLabel("web-published-environment-themes"));
334
335 function readStoredEnvironmentThemes(): ReadonlyArray<ThemeDefinition> {
336 try {
337 const parsed: unknown = JSON.parse(
338 window.localStorage.getItem(ENVIRONMENT_THEMES_STORAGE_KEY) ?? "null",
339 );
340 return Array.isArray(parsed) ? parseStoredThemes(parsed) : [];
341 } catch {
342 return [];
343 }
344 }
345
346 /**
347 * Falls back to the last published set while the server connects, so boot and the
348 * first render paint the selected palette. Kept alive because theme lookups read it
349 * outside React on every repaint.
350 */
351 export const environmentThemeDefinitionsAtom = Atom.make((get) => {
352 const published = get(publishedThemesAtom);
353 const definitions =
354 published === null ? readStoredEnvironmentThemes() : publishedThemeDefinitions(published);
355 const previous = Option.getOrNull(get.self<ReadonlyArray<ThemeDefinition>>());
356 return previous !== null && Equal.equals(previous, definitions) ? previous : definitions;
357 }).pipe(Atom.keepAlive, Atom.withLabel("web-environment-theme-definitions"));
358
359 export function storePublishedEnvironmentThemes(definitions: ReadonlyArray<ThemeDefinition>) {
360 if (appAtomRegistry.get(publishedThemesAtom) === null) return;
361 try {
362 window.localStorage.setItem(ENVIRONMENT_THEMES_STORAGE_KEY, JSON.stringify(definitions));
363 } catch {
364 // Without the stored copy the next launch paints stock colors until connect.
365 }
366 }
367
368 function getEnvironmentThemes(): ReadonlyArray<ThemeDefinition> {
369 return appAtomRegistry.get(environmentThemeDefinitionsAtom);
370 }
371
372 export function isReservedThemeId(themeId: string): boolean {
373 return RESERVED_THEME_IDS.has(themeId);
374 }
375
376 export function getStoredCustomThemeCollection(
377 collectionId: string,
378 ): ReadonlyArray<ThemeDefinition> {
379 return readWritableCustomThemeLibrary().themes.filter(
380 (theme) => theme.collection?.id === collectionId,
381 );
382 }
383
384 export function subscribeToCustomThemes(listener: () => void): () => void {
385 customThemeListeners.add(listener);
386 const unsubscribeEnvironment = subscribeAtomChanges(environmentThemeDefinitionsAtom, () =>
387 listener(),
388 );
389 if (typeof window === "undefined") {
390 return () => {
391 customThemeListeners.delete(listener);
392 unsubscribeEnvironment();
393 };
394 }
395 const handleStorage = (event: StorageEvent) => {
396 if (event.key === CUSTOM_THEMES_STORAGE_KEY || event.key === null) {
397 invalidateCustomThemes();
398 }
399 };
400 window.addEventListener("storage", handleStorage);
401
402 return () => {
403 customThemeListeners.delete(listener);
404 unsubscribeEnvironment();
405 window.removeEventListener("storage", handleStorage);
406 };
407 }
408
409 const LEGACY_THEME_ID_ALIASES: Readonly<Record<string, string>> = {
410 [LEGACY_T3_CHAT_DARK_THEME_ID]: T3_CHAT_THEME_ID,
411 "t3-grove": GROVE_THEME_ID,
412 "t3-ocean": OCEAN_THEME_ID,
413 "t3-ember": EMBER_THEME_ID,
414 "t3-iris": IRIS_THEME_ID,
415 };
416
417 function normalizeThemeId(themeId: string): string {
418 return Object.hasOwn(LEGACY_THEME_ID_ALIASES, themeId)
419 ? (LEGACY_THEME_ID_ALIASES[themeId] ?? themeId)
420 : themeId;
421 }
422
423 export function canonicalThemePreference(theme: string): string {
424 return theme === LEGACY_T3_CHAT_DARK_THEME_ID ? theme : normalizeThemeId(theme);
425 }
426
427 function themeIdFromPreference(theme: ThemePreference): string {
428 return normalizeThemeId(theme);
429 }
430
431 function legacyThemeMode(theme: ThemePreference): ThemeAppearance | null {
432 return theme === LEGACY_T3_CHAT_DARK_THEME_ID ? "dark" : null;
433 }
434
435 export function getStandardThemeColors(appearance: ThemeAppearance): ThemeColors {
436 if (appearance === "dark") {
437 return (standardDarkThemeColors ??= decodeThemeColors({
438 ...T3_CODE_DARK_THEME_COLORS,
439 canvas: "#000000",
440 }));
441 }
442 return (standardLightThemeColors ??= decodeThemeColors(T3_CODE_LIGHT_THEME_COLORS));
443 }
444
445 // index.css paints the light bubble a step darker than the shared palette mobile uses.
446 const STANDARD_WEB_PAINTED_COLORS: Record<ThemeAppearance, Partial<ThemeColors>> = {
447 light: { messageSurface: "#ebebed" },
448 dark: { canvas: "#000000", messageSurface: "#1e1e1e" },
449 };
450
451 /** The standard theme as index.css paints it, for solves that measure the page. */
452 export function getStandardPaintedThemeColors(appearance: ThemeAppearance): ThemeColors {
453 return { ...getStandardThemeColors(appearance), ...STANDARD_WEB_PAINTED_COLORS[appearance] };
454 }
455
456 type ThemeRgbColor = {
457 r: number;
458 g: number;
459 b: number;
460 };
461
462 type ThemeOklch = { L: number; C: number; h: number };
463 type ParsedThemeColor = { color: ThemeOklch; alpha: number };
464
465 let standardLightThemeColors: ThemeColors | undefined;
466 let standardDarkThemeColors: ThemeColors | undefined;
467
468 const THEME_LIGHT_FOREGROUND: ThemeRgbColor = { r: 255, g: 250, b: 255 };
469 const THEME_DARK_FOREGROUND: ThemeRgbColor = { r: 36, g: 21, b: 35 };
470 const THEME_WHITE_FOREGROUND: ThemeRgbColor = { r: 255, g: 255, b: 255 };
471 const THEME_BLACK_FOREGROUND: ThemeRgbColor = { r: 0, g: 0, b: 0 };
472
473 const convertToOklch = converter("oklch");
474
475 function parseThemeColor(value: unknown): ParsedThemeColor | null {
476 if (typeof value !== "string") return null;
477 const input = value.trim();
478 const parsed = parse(input);
479 if (!parsed) return null;
480 const color = convertToOklch(parsed);
481 const lightness = color.l ?? 0;
482 const chroma = color.c ?? 0;
483 const hue = color.h ?? 0;
484 // Missing CSS components are zero; Culori omits none alpha, so distinguish it from absent alpha.
485 const alpha = /\/\s*none\s*\)$/i.test(input) ? 0 : (color.alpha ?? 1);
486 if (![lightness, chroma, hue, alpha].every(Number.isFinite)) return null;
487 return {
488 color: {
489 L: Math.min(1, Math.max(0, lightness)),
490 C: Math.max(0, chroma),
491 h: hue,
492 },
493 alpha: Math.min(1, Math.max(0, alpha)),
494 };
495 }
496
497 function formatThemeColorNumber(value: number, precision: number): string {
498 const rounded = Math.abs(value) < 10 ** -precision / 2 ? 0 : value;
499 return rounded.toFixed(precision).replace(/(?:\.0+|(?:(\.[0-9]*?)0+))$/, "$1");
500 }
501
502 function formatOklchThemeColor(color: ThemeOklch, alpha = 1): string {
503 const normalizedHue = color.C < 0.0000005 ? 0 : ((color.h % 360) + 360) % 360;
504 const body = `${formatThemeColorNumber(color.L, 6)} ${formatThemeColorNumber(color.C, 6)} ${formatThemeColorNumber(normalizedHue, 3)}`;
505 return alpha < 1 ? `oklch(${body} / ${formatThemeColorNumber(alpha, 4)})` : `oklch(${body})`;
506 }
507
508 export function toCanonicalThemeColor(value: unknown): string | null {
509 const parsed = parseThemeColor(value);
510 return parsed ? formatOklchThemeColor(parsed.color, parsed.alpha) : null;
511 }
512
513 export function themeColorToHex(value: string): string | null {
514 const color = parseThemeColor(value);
515 const parsed = color ? { rgb: themeOklchToRgb(color.color), alpha: color.alpha } : null;
516 if (!parsed) return null;
517
518 const opaque = themeRgbToHexColor(parsed.rgb);
519 if (parsed.alpha >= 1) return opaque;
520 const alpha = Math.round(parsed.alpha * 255)
521 .toString(16)
522 .padStart(2, "0");
523 return `${opaque}${alpha}`;
524 }
525
526 function parseThemeRgbColor(value: string, fallback: ThemeRgbColor): ThemeRgbColor {
527 const parsed = parseThemeColor(value);
528 return parsed ? themeOklchToRgb(parsed.color) : fallback;
529 }
530
531 function themeRgbToHexColor(color: ThemeRgbColor): string {
532 return `#${[color.r, color.g, color.b]
533 .map((channel) =>
534 Math.round(Math.min(255, Math.max(0, channel)))
535 .toString(16)
536 .padStart(2, "0"),
537 )
538 .join("")}`;
539 }
540
541 function themeRgbToThemeColor(color: ThemeRgbColor): string {
542 return formatOklchThemeColor(themeRgbToOklch(color));
543 }
544
545 function decodeThemeColors(colors: ThemeColors): ThemeColors {
546 return Object.fromEntries(
547 THEME_COLOR_ROLES.map((role) => {
548 const color = toCanonicalThemeColor(colors[role]);
549 if (!color) {
550 throw new Error(
551 m(
552 msg('The color for "{role}" must be a literal CSS color such as oklch(0.62 0.2 280).', {
553 role,
554 }),
555 ),
556 );
557 }
558 return [role, color];
559 }),
560 ) as Record<ThemeColorRole, string>;
561 }
562
563 function canonicalizeThemeDefinition(theme: ThemeDefinition): ThemeDefinition {
564 return {
565 ...theme,
566 colors: decodeThemeColors(theme.colors),
567 ...(theme.variants
568 ? {
569 variants: Object.fromEntries(
570 Object.entries(theme.variants).map(([appearance, colors]) => [
571 appearance,
572 decodeThemeColors(colors),
573 ]),
574 ) as ThemeVariants,
575 }
576 : {}),
577 };
578 }
579
580 function mixThemeRgbColors(
581 base: ThemeRgbColor,
582 overlay: ThemeRgbColor,
583 amount: number,
584 ): ThemeRgbColor {
585 return {
586 r: base.r + (overlay.r - base.r) * amount,
587 g: base.g + (overlay.g - base.g) * amount,
588 b: base.b + (overlay.b - base.b) * amount,
589 };
590 }
591
592 function themeRelativeLuminance(color: ThemeRgbColor): number {
593 const linearize = (channel: number) => {
594 const normalized = channel / 255;
595 return normalized <= 0.03928 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4;
596 };
597
598 return 0.2126 * linearize(color.r) + 0.7152 * linearize(color.g) + 0.0722 * linearize(color.b);
599 }
600
601 function srgbChannelToLinear(channel: number): number {
602 const c = channel / 255;
603 return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
604 }
605
606 function linearChannelToSrgb(channel: number, round = true): number {
607 const c = channel <= 0.0031308 ? channel * 12.92 : 1.055 * channel ** (1 / 2.4) - 0.055;
608 const srgb = Math.min(1, Math.max(0, c)) * 255;
609 return round ? Math.round(srgb) : srgb;
610 }
611
612 function themeRgbToOklch(color: ThemeRgbColor): ThemeOklch {
613 const r = srgbChannelToLinear(color.r);
614 const g = srgbChannelToLinear(color.g);
615 const b = srgbChannelToLinear(color.b);
616 const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
617 const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
618 const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
619 const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s;
620 const a = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;
621 const bb = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;
622 return { L, C: Math.hypot(a, bb), h: (Math.atan2(bb, a) * 180) / Math.PI };
623 }
624
625 function oklchToRgbUnclamped({ L, C, h }: ThemeOklch): { r: number; g: number; b: number } {
626 const hr = (h * Math.PI) / 180;
627 const a = C * Math.cos(hr);
628 const bb = C * Math.sin(hr);
629 const l = (L + 0.3963377774 * a + 0.2158037573 * bb) ** 3;
630 const m = (L - 0.1055613458 * a - 0.0638541728 * bb) ** 3;
631 const s = (L - 0.0894841775 * a - 1.291485548 * bb) ** 3;
632 return {
633 r: 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
634 g: -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
635 b: -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
636 };
637 }
638
639 function mapThemeOklchToSrgbGamut(color: ThemeOklch): ThemeOklch {
640 const isInGamut = (C: number) => {
641 const linear = oklchToRgbUnclamped({ ...color, C });
642 return [linear.r, linear.g, linear.b].every(
643 (channel) => channel >= -0.0001 && channel <= 1.0001,
644 );
645 };
646 if (isInGamut(color.C)) return color;
647
648 let low = 0;
649 let high = color.C;
650 const chromaResolution = 0.000001;
651 const steps = Math.max(
652 1,
653 Math.ceil(Math.log2(Math.max(color.C, chromaResolution)) - Math.log2(chromaResolution)),
654 );
655 for (let step = 0; step < steps; step += 1) {
656 const mid = (low + high) / 2;
657 if (isInGamut(mid)) low = mid;
658 else high = mid;
659 }
660 return { ...color, C: low };
661 }
662
663 function themeOklchToRgb(color: ThemeOklch, round = true): ThemeRgbColor {
664 const linear = oklchToRgbUnclamped(mapThemeOklchToSrgbGamut(color));
665 return {
666 r: linearChannelToSrgb(linear.r, round),
667 g: linearChannelToSrgb(linear.g, round),
668 b: linearChannelToSrgb(linear.b, round),
669 };
670 }
671
672 function themeOklchToThemeColor(color: ThemeOklch): string {
673 return formatOklchThemeColor(mapThemeOklchToSrgbGamut(color));
674 }
675
676 function solveOklchLightness(
677 base: ThemeOklch,
678 against: ReadonlyArray<ThemeRgbColor>,
679 minContrast: number,
680 direction: "lighter" | "darker",
681 ): ThemeOklch {
682 const contrastOf = (color: ThemeOklch) =>
683 Math.min(...against.map((surface) => themeContrastRatio(themeOklchToRgb(color), surface)));
684 let low = direction === "lighter" ? base.L : 0;
685 let high = direction === "lighter" ? 1 : base.L;
686 let candidate = { ...base };
687 if (contrastOf(candidate) >= minContrast) return candidate;
688 for (let step = 0; step < 18; step += 1) {
689 const mid = (low + high) / 2;
690 candidate = { ...base, L: mid };
691 if (contrastOf(candidate) >= minContrast) {
692 if (direction === "lighter") high = mid;
693 else low = mid;
694 } else {
695 if (direction === "lighter") low = mid;
696 else high = mid;
697 }
698 }
699 return { ...base, L: direction === "lighter" ? high : low };
700 }
701
702 /**
703 * Moves only the lightness, so a color that is too dim on `surface` keeps its
704 * hue instead of collapsing to black or white.
705 */
706 export function readableThemeColorOn(color: string, surface: string, minContrast: number): string {
707 const parsedColor = parseThemeColor(color);
708 const parsedSurface = parseThemeColor(surface);
709 if (!parsedColor || !parsedSurface) return color;
710 const surfaceRgb = themeOklchToRgb(parsedSurface.color);
711 if (themeContrastRatio(themeOklchToRgb(parsedColor.color), surfaceRgb) >= minContrast) {
712 return color;
713 }
714 const direction = themeRelativeLuminance(surfaceRgb) < 0.179 ? "lighter" : "darker";
715 const solved = solveOklchLightness(parsedColor.color, [surfaceRgb], minContrast, direction);
716 // Return the 8-bit color the solver measured: the unrounded OKLCH can round
717 // to a neighbor just under the target once it is stored and read back.
718 return themeRgbToHexColor(themeOklchToRgb(solved));
719 }
720
721 /** A chip kind's per-theme contrast-solved lightness with `color`'s hue and chroma. */
722 export function contextChipAccentWithHueOf(
723 kind: ContextChipAccentKind,
724 color: string,
725 ): string | null {
726 const parsed = parseThemeColor(color);
727 if (!parsed) return null;
728 const { C, h } = parsed.color;
729 return `oklch(from var(${contextChipColorVariable(kind)}) l ${formatThemeColorNumber(C, 4)} ${formatThemeColorNumber(h, 2)})`;
730 }
731
732 const CONTEXT_CHIP_CONTRAST = 5;
733 const CONTEXT_CHIP_MESSAGE_VARIABLE = "--context-chip-message";
734 const CONTEXT_CHIP_INVALID_VARIABLE = "--context-chip-invalid";
735
736 export function contextChipVariables(colors: ThemeColors): Readonly<Record<string, string>> {
737 // CSS paints surfaces from their unrounded OKLCH, so measure them unrounded.
738 const parsedCanvas = parseThemeColor(colors.canvas);
739 const canvas = parsedCanvas ? themeOklchToRgb(parsedCanvas.color, false) : THEME_WHITE_FOREGROUND;
740 const onCanvas = (value: string) => {
741 const parsed = parseThemeColor(value);
742 return parsed
743 ? mixThemeRgbColors(canvas, themeOklchToRgb(parsed.color, false), parsed.alpha)
744 : canvas;
745 };
746 const isDark = (color: ThemeRgbColor) => themeRelativeLuminance(color) < 0.179;
747 const messageMatchesCanvas = isDark(onCanvas(colors.messageSurface)) === isDark(canvas);
748 const surfaces = [canvas, onCanvas(colors.surface), onCanvas(colors.surfaceRaised)];
749 if (messageMatchesCanvas) surfaces.push(onCanvas(colors.messageSurface));
750 const contrastOnSurfaces = (color: ThemeRgbColor) =>
751 Math.min(...surfaces.map((surface) => themeContrastRatio(color, surface)));
752 const blackContrast = contrastOnSurfaces(THEME_BLACK_FOREGROUND);
753 const whiteContrast = contrastOnSurfaces(THEME_WHITE_FOREGROUND);
754 const direction = blackContrast >= whiteContrast ? "darker" : "lighter";
755 const minContrast = Math.min(CONTEXT_CHIP_CONTRAST, Math.max(blackContrast, whiteContrast));
756 const accents: Array<[string, string]> = [
757 ...(Object.entries(CONTEXT_CHIP_ACCENTS) as Array<[ContextChipAccentKind, string]>).map(
758 ([kind, accent]): [string, string] => [contextChipColorVariable(kind), accent],
759 ),
760 [CONTEXT_CHIP_INVALID_VARIABLE, colors.errorForeground],
761 ];
762 const variables: Record<string, string> = Object.fromEntries(
763 accents.flatMap(([variable, accent]) => {
764 const parsed = parseThemeColor(accent);
765 if (!parsed) return [];
766 const solved = solveOklchLightness(parsed.color, surfaces, minContrast, direction);
767 return [[variable, themeRgbToHexColor(themeOklchToRgb(solved))]];
768 }),
769 );
770 if (!messageMatchesCanvas) variables[CONTEXT_CHIP_MESSAGE_VARIABLE] = colors.messageForeground;
771 return variables;
772 }
773
774 function applyContextChipVariables(root: HTMLElement, colors: ThemeColors): void {
775 const variables = contextChipVariables(colors);
776 root.style.removeProperty(CONTEXT_CHIP_MESSAGE_VARIABLE);
777 root.style.removeProperty(CONTEXT_CHIP_INVALID_VARIABLE);
778 for (const [variable, value] of Object.entries(variables)) {
779 root.style.setProperty(variable, value);
780 }
781 }
782
783 const STANDARD_STATUS_COLORS = {
784 light: {
785 error: "#fb2c36",
786 errorForeground: "#c10007",
787 warning: "#fe9a00",
788 warningForeground: "#bb4d00",
789 },
790 dark: {
791 error: "#fb414a",
792 errorForeground: "#ff6467",
793 warning: "#fe9a00",
794 warningForeground: "#ffb900",
795 },
796 } as const;
797
798 function standardStatusColors(canvas: ThemeRgbColor): {
799 error: string;
800 errorForeground: string;
801 errorSurface: string;
802 warning: string;
803 warningForeground: string;
804 warningSurface: string;
805 } {
806 const appearance: ThemeAppearance = themeRelativeLuminance(canvas) < 0.179 ? "dark" : "light";
807 const standard = STANDARD_STATUS_COLORS[appearance];
808 const surfaceMix = appearance === "dark" ? 0.16 : 0.08;
809 const surfaceOf = (value: string) =>
810 mixThemeRgbColors(canvas, parseThemeRgbColor(value, canvas), surfaceMix);
811 const readableOn = (foreground: string, surface: ThemeRgbColor) =>
812 pipe(
813 parseThemeRgbColor(foreground, canvas),
814 themeRgbToOklch,
815 (color) =>
816 solveOklchLightness(color, [surface], 4.6, appearance === "dark" ? "lighter" : "darker"),
817 themeOklchToThemeColor,
818 );
819 const errorSurface = surfaceOf(standard.error);
820 const warningSurface = surfaceOf(standard.warning);
821 return {
822 error: toCanonicalThemeColor(standard.error)!,
823 errorForeground: readableOn(standard.errorForeground, errorSurface),
824 errorSurface: themeRgbToThemeColor(errorSurface),
825 warning: toCanonicalThemeColor(standard.warning)!,
826 warningForeground: readableOn(standard.warningForeground, warningSurface),
827 warningSurface: themeRgbToThemeColor(warningSurface),
828 };
829 }
830
831 export function createVividThemeColors(
832 appearance: ThemeAppearance,
833 backgroundValue: string,
834 accentValue: string,
835 ): ThemeColors {
836 const defaults = getDefaultThemeColors(appearance);
837 const canvasRgb = parseThemeRgbColor(
838 backgroundValue,
839 appearance === "dark" ? { r: 24, g: 15, b: 27 } : { r: 250, g: 245, b: 250 },
840 );
841 const accentRgb = parseThemeRgbColor(accentValue, { r: 168, g: 67, b: 112 });
842 const canvas = themeRgbToOklch(canvasRgb);
843 const accent = themeRgbToOklch(accentRgb);
844 // At luminance 0.179, black and white text have equal contrast.
845 const dark = themeRelativeLuminance(canvasRgb) < 0.179;
846 const hue = accent.C < 0.02 ? canvas.h : accent.h;
847 const tintC = Math.min(0.045, Math.max(0.008, accent.C * 0.22));
848 const step = dark ? 1 : -1;
849
850 const surfaceAt = (deltaL: number, chroma = tintC): ThemeOklch => ({
851 L: Math.min(0.98, Math.max(0.05, canvas.L + step * deltaL)),
852 C: chroma,
853 h: hue,
854 });
855 const themeColor = (color: ThemeOklch) => themeOklchToThemeColor(color);
856
857 const textBase: ThemeOklch = {
858 L: dark ? 0.95 : 0.2,
859 C: Math.min(0.035, accent.C * 0.25),
860 h: hue,
861 };
862 const text = solveOklchLightness(textBase, [canvasRgb], 7, dark ? "lighter" : "darker");
863 const textRgb = themeOklchToRgb(text);
864 const textMutedRgb = standardMutedThemeText(canvasRgb, textRgb);
865
866 const action: ThemeOklch = {
867 L: Math.min(0.85, Math.max(0.35, accent.L + (dark ? 0.06 : -0.02))),
868 C: Math.max(accent.C * 0.9, 0.06),
869 h: (hue + 50) % 360,
870 };
871 const actionRgb = themeOklchToRgb(action);
872 const actionForeground = readableThemeForeground(actionRgb);
873 const accentForeground = readableThemeForeground(accentRgb);
874
875 const sidebar = surfaceAt(0.045, tintC * 1.4);
876 const sidebarRgb = themeOklchToRgb(sidebar);
877 const surface = surfaceAt(0.015);
878 const surfaceRaised = surfaceAt(0.05);
879 const surfaceRaisedRgb = themeOklchToRgb(surfaceRaised);
880 const surfaceOverlay = surfaceAt(0.075);
881 const border = surfaceAt(dark ? 0.16 : 0.12, Math.min(0.07, accent.C * 0.35));
882 const input = surfaceAt(dark ? 0.21 : 0.16, Math.min(0.08, accent.C * 0.4));
883 const secondary = surfaceAt(dark ? 0.1 : 0.06, Math.min(0.09, accent.C * 0.5));
884 const secondaryRgb = themeOklchToRgb(secondary);
885 const muted = surfaceAt(dark ? 0.06 : 0.04, Math.min(0.06, accent.C * 0.35));
886 const mutedRgb = themeOklchToRgb(muted);
887 const accentSurface = surfaceAt(dark ? 0.13 : 0.08, Math.min(0.11, accent.C * 0.55));
888 const accentSurfaceRgb = themeOklchToRgb(accentSurface);
889 const messageSurface = surfaceAt(dark ? 0.16 : 0.1, Math.min(0.13, accent.C * 0.6));
890 const messageSurfaceRgb = themeOklchToRgb(messageSurface);
891 const codeBackground = surfaceAt(0.035, tintC * 0.8);
892 const updateSurface = surfaceAt(dark ? 0.14 : 0.09, Math.min(0.12, accent.C * 0.55));
893
894 const foregroundOn = (surfaceRgb: ThemeRgbColor): string =>
895 themeOklchToThemeColor(
896 solveOklchLightness(textBase, [surfaceRgb], 4.6, dark ? "lighter" : "darker"),
897 );
898 const mutedForeground = themeRgbToThemeColor(readableThemeText(mutedRgb, textRgb, 1, 4.6));
899 const placeholder = themeRgbToThemeColor(readableThemeText(surfaceRaisedRgb, textRgb, 1, 4.6));
900
901 const searchMatch = themeOklchToRgb(surfaceAt(0.22, Math.min(0.12, accent.C)));
902 const searchMatchActive = themeOklchToRgb(surfaceAt(0.4, Math.min(0.18, accent.C)));
903
904 const actionHover: ThemeOklch = { ...action, L: action.L + (dark ? 0.06 : -0.06) };
905
906 return {
907 ...defaults,
908 ...standardStatusColors(canvasRgb),
909 canvas: themeRgbToThemeColor(canvasRgb),
910 chrome: themeRgbToThemeColor(canvasRgb),
911 toolbar: themeRgbToThemeColor(canvasRgb),
912 toolbarForeground: themeRgbToThemeColor(textRgb),
913 toolbarBorder: themeColor(surfaceAt(dark ? 0.14 : 0.1, Math.min(0.08, accent.C * 0.4))),
914 toolbarControl: themeColor(surfaceAt(dark ? 0.09 : 0.05, tintC * 1.3)),
915 toolbarControlForeground: themeRgbToThemeColor(textRgb),
916 toolbarControlHover: themeColor(surfaceAt(dark ? 0.14 : 0.09, tintC * 1.6)),
917 surface: themeColor(surface),
918 surfaceRaised: themeColor(surfaceRaised),
919 surfaceOverlay: themeColor(surfaceOverlay),
920 text: themeRgbToThemeColor(textRgb),
921 textMuted: themeRgbToThemeColor(textMutedRgb),
922 border: themeColor(border),
923 input: themeColor(input),
924 focus: themeRgbToThemeColor(accentRgb),
925 accent: themeRgbToThemeColor(accentRgb),
926 accentForeground: themeRgbToThemeColor(accentForeground),
927 secondary: themeColor(secondary),
928 secondaryForeground: foregroundOn(secondaryRgb),
929 muted: themeColor(muted),
930 mutedForeground,
931 placeholder,
932 secondaryLabel: themeRgbToThemeColor(textMutedRgb),
933 iconMuted: themeRgbToThemeColor(textMutedRgb),
934 update: themeRgbToThemeColor(accentRgb),
935 updateForeground: foregroundOn(themeOklchToRgb(updateSurface)),
936 updateSurface: themeColor(updateSurface),
937 accentSurface: themeColor(accentSurface),
938 accentSurfaceForeground: foregroundOn(accentSurfaceRgb),
939 messageSurface: themeColor(messageSurface),
940 messageForeground: foregroundOn(messageSurfaceRgb),
941 messageAction: themeRgbToThemeColor(actionRgb),
942 messageActionForeground: themeRgbToThemeColor(actionForeground),
943 messageActionHover: themeColor(actionHover),
944 codeBackground: themeColor(codeBackground),
945 codeForeground: themeRgbToThemeColor(textRgb),
946 searchMatchBackground: themeRgbToThemeColor(searchMatch),
947 searchMatchForeground: themeRgbToThemeColor(readableThemeForeground(searchMatch)),
948 searchMatchActiveBackground: themeRgbToThemeColor(searchMatchActive),
949 searchMatchActiveForeground: themeRgbToThemeColor(readableThemeForeground(searchMatchActive)),
950 sidebar: themeColor(sidebar),
951 sidebarForeground: foregroundOn(sidebarRgb),
952 sidebarMutedForeground: themeRgbToThemeColor(standardMutedThemeText(sidebarRgb, textRgb)),
953 sidebarControlSurface: themeColor(surfaceAt(dark ? 0.1 : 0.07, tintC * 1.5)),
954 sidebarRowHover: themeColor(surfaceAt(dark ? 0.08 : 0.06, Math.min(0.08, accent.C * 0.45))),
955 sidebarRowActive: themeColor(surfaceAt(dark ? 0.12 : 0.09, Math.min(0.1, accent.C * 0.55))),
956 sidebarRowSelected: themeColor(surfaceAt(dark ? 0.14 : 0.1, Math.min(0.11, accent.C * 0.6))),
957 sidebarBorder: themeColor(surfaceAt(dark ? 0.17 : 0.12, Math.min(0.08, accent.C * 0.4))),
958 terminalBackground: themeRgbToThemeColor(canvasRgb),
959 terminalForeground: themeRgbToThemeColor(textRgb),
960 terminalCursor: themeRgbToThemeColor(accentRgb),
961 terminalSelection: themeColor(surfaceAt(dark ? 0.18 : 0.12, Math.min(0.12, accent.C * 0.55))),
962 terminalScrollbar: themeColor(surfaceAt(dark ? 0.22 : 0.16, tintC)),
963 terminalScrollbarHover: themeColor(surfaceAt(dark ? 0.3 : 0.22, tintC)),
964 };
965 }
966
967 function themeContrastRatio(first: ThemeRgbColor, second: ThemeRgbColor): number {
968 const firstLuminance = themeRelativeLuminance(first);
969 const secondLuminance = themeRelativeLuminance(second);
970 const lighter = Math.max(firstLuminance, secondLuminance);
971 const darker = Math.min(firstLuminance, secondLuminance);
972 return (lighter + 0.05) / (darker + 0.05);
973 }
974
975 function readableThemeForeground(background: ThemeRgbColor): ThemeRgbColor {
976 const lightContrast = themeContrastRatio(background, THEME_LIGHT_FOREGROUND);
977 const darkContrast = themeContrastRatio(background, THEME_DARK_FOREGROUND);
978 if (Math.max(lightContrast, darkContrast) >= 4.5) {
979 return lightContrast >= darkContrast ? THEME_LIGHT_FOREGROUND : THEME_DARK_FOREGROUND;
980 }
981
982 return themeContrastRatio(background, THEME_WHITE_FOREGROUND) >=
983 themeContrastRatio(background, THEME_BLACK_FOREGROUND)
984 ? THEME_WHITE_FOREGROUND
985 : THEME_BLACK_FOREGROUND;
986 }
987
988 function readableThemeText(
989 background: ThemeRgbColor,
990 foreground: ThemeRgbColor,
991 amount: number,
992 minimumRatio: number,
993 ): ThemeRgbColor {
994 const softened = mixThemeRgbColors(foreground, background, amount);
995 if (themeContrastRatio(softened, background) >= minimumRatio) return softened;
996
997 let readable = foreground;
998 let lowerAmount = 0;
999 let upperAmount = amount;
1000 for (let index = 0; index < 12; index += 1) {
1001 const candidateAmount = (lowerAmount + upperAmount) / 2;
1002 const candidate = mixThemeRgbColors(foreground, background, candidateAmount);
1003 if (themeContrastRatio(candidate, background) >= minimumRatio) {
1004 readable = candidate;
1005 lowerAmount = candidateAmount;
1006 } else {
1007 upperAmount = candidateAmount;
1008 }
1009 }
1010 return readable;
1011 }
1012
1013 const STANDARD_LIGHT_MUTED_CONTRAST = 4.705;
1014 const STANDARD_DARK_MUTED_CONTRAST = 5.082;
1015
1016 function standardMutedThemeText(
1017 background: ThemeRgbColor,
1018 foreground: ThemeRgbColor,
1019 ): ThemeRgbColor {
1020 const target =
1021 themeRelativeLuminance(background) < 0.179
1022 ? STANDARD_DARK_MUTED_CONTRAST
1023 : STANDARD_LIGHT_MUTED_CONTRAST;
1024 return readableThemeText(background, foreground, 1, target);
1025 }
1026
1027 export function getDefaultThemeColors(appearance: ThemeAppearance): ThemeColors {
1028 return appearance === "dark" ? T3_CHAT_THEME.variants!.dark! : T3_CHAT_THEME.colors;
1029 }
1030
1031 export function updateThemeColorFamily(
1032 appearance: ThemeAppearance,
1033 colors: ThemeColors,
1034 role: ThemeColorRole,
1035 value: string,
1036 ): ThemeColors {
1037 const parsedSelected = parseThemeColor(value);
1038 if (!parsedSelected) return { ...colors, [role]: value };
1039 const normalized = formatOklchThemeColor(parsedSelected.color, parsedSelected.alpha);
1040
1041 const canvas = parseThemeRgbColor(
1042 colors.canvas,
1043 appearance === "dark" ? { r: 24, g: 15, b: 27 } : { r: 250, g: 245, b: 250 },
1044 );
1045 const selected = themeOklchToRgb(parsedSelected.color);
1046 const selectedOn = (background: ThemeRgbColor) =>
1047 mixThemeRgbColors(background, selected, parsedSelected.alpha);
1048 const selectedOnCanvas = selectedOn(canvas);
1049 const accent = parseThemeRgbColor(colors.accent, { r: 168, g: 67, b: 112 });
1050 const canvasIsDark = themeRelativeLuminance(canvas) < 0.179;
1051 const terminalIsDark = themeRelativeLuminance(selectedOnCanvas) < 0.179;
1052 const colorOf = (color: ThemeRgbColor) => themeRgbToThemeColor(color);
1053 const foregroundOn = (background: ThemeRgbColor) => colorOf(readableThemeForeground(background));
1054 const selectedToneOn = (background: ThemeRgbColor) =>
1055 themeOklchToThemeColor(
1056 solveOklchLightness(
1057 parsedSelected.color,
1058 [background],
1059 4.6,
1060 themeRelativeLuminance(background) < 0.179 ? "lighter" : "darker",
1061 ),
1062 );
1063 const statusColors = () => {
1064 const surface = mixThemeRgbColors(canvas, selectedOnCanvas, canvasIsDark ? 0.16 : 0.08);
1065 return {
1066 foreground: selectedToneOn(surface),
1067 surface: colorOf(surface),
1068 };
1069 };
1070
1071 switch (role) {
1072 case "canvas":
1073 return { ...colors, canvas: normalized, chrome: normalized, toolbar: normalized };
1074 case "surface":
1075 case "surfaceRaised":
1076 case "surfaceOverlay":
1077 case "input":
1078 case "sidebarControlSurface":
1079 return { ...colors, [role]: normalized };
1080 case "text":
1081 return {
1082 ...colors,
1083 text: normalized,
1084 toolbarForeground: normalized,
1085 toolbarControlForeground: normalized,
1086 };
1087 case "mutedForeground":
1088 return {
1089 ...colors,
1090 textMuted: normalized,
1091 mutedForeground: normalized,
1092 placeholder: normalized,
1093 secondaryLabel: normalized,
1094 iconMuted: normalized,
1095 sidebarMutedForeground: normalized,
1096 };
1097 case "border":
1098 return {
1099 ...colors,
1100 border: normalized,
1101 toolbarBorder: normalized,
1102 sidebarBorder: normalized,
1103 };
1104 case "secondary":
1105 return {
1106 ...colors,
1107 secondary: normalized,
1108 secondaryForeground: foregroundOn(selectedOnCanvas),
1109 muted: normalized,
1110 toolbarControl: normalized,
1111 };
1112 case "accentSurface":
1113 return {
1114 ...colors,
1115 accentSurface: normalized,
1116 accentSurfaceForeground: foregroundOn(selectedOnCanvas),
1117 toolbarControlHover: normalized,
1118 };
1119 case "accent": {
1120 const updateSurface = mixThemeRgbColors(canvas, selectedOnCanvas, canvasIsDark ? 0.32 : 0.16);
1121 return {
1122 ...colors,
1123 accent: normalized,
1124 accentForeground: foregroundOn(selectedOnCanvas),
1125 focus: normalized,
1126 update: normalized,
1127 updateForeground: selectedToneOn(updateSurface),
1128 updateSurface: colorOf(updateSurface),
1129 terminalCursor: normalized,
1130 };
1131 }
1132 case "messageAction": {
1133 const actionForeground = readableThemeForeground(selectedOnCanvas);
1134 const towardOpposite =
1135 actionForeground === THEME_LIGHT_FOREGROUND || actionForeground === THEME_WHITE_FOREGROUND
1136 ? THEME_BLACK_FOREGROUND
1137 : THEME_WHITE_FOREGROUND;
1138 const actionHover = mixThemeRgbColors(selected, towardOpposite, 0.12);
1139 return {
1140 ...colors,
1141 messageAction: normalized,
1142 messageActionForeground: colorOf(actionForeground),
1143 messageActionHover: formatOklchThemeColor(
1144 themeRgbToOklch(actionHover),
1145 parsedSelected.alpha,
1146 ),
1147 };
1148 }
1149 case "messageSurface":
1150 return {
1151 ...colors,
1152 messageSurface: normalized,
1153 messageForeground: foregroundOn(selectedOnCanvas),
1154 };
1155 case "searchMatchBackground":
1156 return {
1157 ...colors,
1158 searchMatchBackground: colorOf(selectedOnCanvas),
1159 searchMatchForeground: foregroundOn(selectedOnCanvas),
1160 };
1161 case "searchMatchActiveBackground":
1162 return {
1163 ...colors,
1164 searchMatchActiveBackground: colorOf(selectedOnCanvas),
1165 searchMatchActiveForeground: foregroundOn(selectedOnCanvas),
1166 };
1167 case "codeBackground":
1168 return {
1169 ...colors,
1170 codeBackground: normalized,
1171 codeForeground: foregroundOn(selectedOnCanvas),
1172 };
1173 case "sidebar":
1174 return {
1175 ...colors,
1176 sidebar: normalized,
1177 sidebarForeground: foregroundOn(selectedOnCanvas),
1178 };
1179 case "sidebarRowSelected": {
1180 const sidebar = parseThemeRgbColor(colors.sidebar, canvas);
1181 const selectedOnSidebar = selectedOn(sidebar);
1182 return {
1183 ...colors,
1184 sidebarRowHover: colorOf(mixThemeRgbColors(sidebar, selectedOnSidebar, 0.5)),
1185 sidebarRowActive: colorOf(mixThemeRgbColors(sidebar, selectedOnSidebar, 0.8)),
1186 sidebarRowSelected: normalized,
1187 };
1188 }
1189 case "terminalBackground": {
1190 const terminalForeground = readableThemeForeground(selectedOnCanvas);
1191 return {
1192 ...colors,
1193 terminalBackground: normalized,
1194 terminalForeground: colorOf(terminalForeground),
1195 terminalSelection: colorOf(
1196 mixThemeRgbColors(selectedOnCanvas, accent, terminalIsDark ? 0.35 : 0.18),
1197 ),
1198 terminalScrollbar: colorOf(
1199 mixThemeRgbColors(selectedOnCanvas, terminalForeground, terminalIsDark ? 0.42 : 0.22),
1200 ),
1201 terminalScrollbarHover: colorOf(
1202 mixThemeRgbColors(selectedOnCanvas, terminalForeground, terminalIsDark ? 0.55 : 0.32),
1203 ),
1204 };
1205 }
1206 case "error": {
1207 const status = statusColors();
1208 return {
1209 ...colors,
1210 error: normalized,
1211 errorForeground: status.foreground,
1212 errorSurface: status.surface,
1213 };
1214 }
1215 case "warning": {
1216 const status = statusColors();
1217 return {
1218 ...colors,
1219 warning: normalized,
1220 warningForeground: status.foreground,
1221 warningSurface: status.surface,
1222 };
1223 }
1224 default:
1225 return { ...colors, [role]: normalized };
1226 }
1227 }
1228
1229 const BUILT_IN_THEME_DEFINITIONS: ReadonlyArray<ThemeDefinition> = BUILT_IN_THEMES;
1230
1231 export function getThemeDefinition(theme: ThemePreference): ThemeDefinition | null {
1232 const themeId = themeIdFromPreference(theme);
1233 return (
1234 BUILT_IN_THEME_DEFINITIONS.find((definition) => definition.id === themeId) ??
1235 getCustomThemes().find((definition) => definition.id === themeId) ??
1236 getEnvironmentThemes().find((definition) => definition.id === themeId) ??
1237 null
1238 );
1239 }
1240
1241 export function themeAllowsSidebarArtwork(theme: ThemePreference): boolean {
1242 const themeId = themeIdFromPreference(theme);
1243 return (
1244 BUILT_IN_THEME_DEFINITIONS.find((definition) => definition.id === themeId)?.sidebarArtwork ===
1245 true
1246 );
1247 }
1248
1249 /** Every selection path must check single-appearance themes to keep mix and appearance tiles in sync. */
1250 export function singleAppearanceOf(theme: ThemeDefinition): ThemeAppearance | null {
1251 const modes = getThemeModes(theme);
1252 return modes.length === 1 ? modes[0]! : null;
1253 }
1254
1255 export function getThemeColorsForMode(
1256 theme: ThemeDefinition,
1257 mode: ThemeAppearance,
1258 ): ThemeColors | null {
1259 if (mode === theme.appearance) return theme.colors;
1260 return theme.variants?.[mode] ?? null;
1261 }
1262
1263 export function getThemeModes(theme: ThemeDefinition): ReadonlyArray<ThemeAppearance> {
1264 return (["light", "dark"] as const).filter((mode) => getThemeColorsForMode(theme, mode) !== null);
1265 }
1266
1267 export function getThemePreferenceMode(theme: ThemePreference): ThemeAppearance | null {
1268 if (theme === "system") return null;
1269 if (theme === "light" || theme === "dark") return theme;
1270 const legacyMode = legacyThemeMode(theme);
1271 if (legacyMode) return legacyMode;
1272 return getThemeDefinition(theme)?.appearance ?? null;
1273 }
1274
1275 export function themeIdFromName(name: string): string {
1276 const label = name.trim().toLowerCase();
1277 const normalized = label
1278 .replace(/[^a-z0-9]+/g, "-")
1279 .replace(/^-+|-+$/g, "")
1280 .slice(0, 48);
1281 if (normalized || !label) return normalized || "custom-theme";
1282
1283 // Names without ASCII letters or digits still need independent, stable ids.
1284 let hash = 2_166_136_261;
1285 for (let index = 0; index < label.length; index += 1) {
1286 hash ^= label.charCodeAt(index);
1287 hash = Math.imul(hash, 16_777_619);
1288 }
1289 return `theme-${(hash >>> 0).toString(36)}`;
1290 }
1291
1292 export class ThemeLibraryStorageError extends Schema.TaggedError<ThemeLibraryStorageError>()(
1293 "ThemeLibraryStorageError",
1294 {
1295 storageKey: Schema.String,
1296 operation: Schema.Literals(["read", "write"]),
1297 reason: Schema.Literals(["malformed", "storage-unavailable"]),
1298 cause: Schema.optional(Schema.Defect()),
1299 },
1300 ) {
1301 override get message(): string {
1302 return this.operation === "read"
1303 ? m(
1304 msg("Failed to read the theme library from {storageKey}.", {
1305 storageKey: this.storageKey,
1306 }),
1307 )
1308 : m(
1309 msg("Failed to write the theme library to {storageKey}.", {
1310 storageKey: this.storageKey,
1311 }),
1312 );
1313 }
1314 }
1315
1316 function saveCustomThemes(
1317 storedThemes: ReadonlyArray<unknown>,
1318 themes: ReadonlyArray<ThemeDefinition>,
1319 ): void {
1320 if (typeof window === "undefined") return;
1321 try {
1322 window.localStorage.setItem(CUSTOM_THEMES_STORAGE_KEY, JSON.stringify(storedThemes));
1323 customThemeLibrarySnapshot = { status: "ready", storedThemes, themes };
1324 } catch (cause) {
1325 throw new ThemeLibraryStorageError({
1326 storageKey: CUSTOM_THEMES_STORAGE_KEY,
1327 operation: "write",
1328 reason: "storage-unavailable",
1329 cause,
1330 });
1331 }
1332 notifyCustomThemeListeners();
1333 }
1334
1335 function requireWritableCustomThemeLibrary(
1336 snapshot: CustomThemeLibrarySnapshot,
1337 ): Extract<CustomThemeLibrarySnapshot, { status: "ready" }> {
1338 if (snapshot.status === "unavailable") {
1339 throw new ThemeLibraryStorageError({
1340 storageKey: CUSTOM_THEMES_STORAGE_KEY,
1341 operation: "read",
1342 reason: snapshot.reason,
1343 ...("cause" in snapshot ? { cause: snapshot.cause } : {}),
1344 });
1345 }
1346 return snapshot;
1347 }
1348
1349 function getWritableCustomThemeLibrary(): Extract<CustomThemeLibrarySnapshot, { status: "ready" }> {
1350 return requireWritableCustomThemeLibrary(getCustomThemeLibrarySnapshot());
1351 }
1352
1353 function readWritableCustomThemeLibrary(): Extract<
1354 CustomThemeLibrarySnapshot,
1355 { status: "ready" }
1356 > {
1357 return requireWritableCustomThemeLibrary(readCustomThemeLibrarySnapshot());
1358 }
1359
1360 function storedThemeHasId(storedTheme: unknown, themeId: string): boolean {
1361 return isRecord(storedTheme) && storedTheme.id === themeId;
1362 }
1363
1364 function storedThemeHasCollectionId(storedTheme: unknown, collectionId: string): boolean {
1365 return (
1366 isRecord(storedTheme) &&
1367 isRecord(storedTheme.collection) &&
1368 storedTheme.collection.id === collectionId
1369 );
1370 }
1371
1372 export function installCustomTheme(theme: ThemeDefinition): ThemeDefinition {
1373 if (RESERVED_THEME_IDS.has(theme.id)) {
1374 throw new Error(m(msg('The theme id "{id}" is reserved.', { id: theme.id })));
1375 }
1376 const library = getWritableCustomThemeLibrary();
1377 if (
1378 BUILT_IN_THEME_DEFINITIONS.some((existing) => existing.id === theme.id) ||
1379 library.storedThemes.some((storedTheme) => storedThemeHasId(storedTheme, theme.id))
1380 ) {
1381 throw new Error(
1382 m(msg('A theme named "{label}" is already installed.', { label: theme.label })),
1383 );
1384 }
1385 const canonicalTheme = canonicalizeThemeDefinition(theme);
1386 const themes = [...library.themes, canonicalTheme];
1387 saveCustomThemes([...library.storedThemes, canonicalTheme], themes);
1388 return canonicalTheme;
1389 }
1390
1391 export function updateCustomTheme(theme: ThemeDefinition): ThemeDefinition {
1392 if (RESERVED_THEME_IDS.has(theme.id)) {
1393 throw new Error(m(msg('The theme id "{id}" is reserved.', { id: theme.id })));
1394 }
1395
1396 const library = getWritableCustomThemeLibrary();
1397 const themes = library.themes;
1398 const themeIndex = themes.findIndex((existing) => existing.id === theme.id);
1399 if (themeIndex === -1) {
1400 throw new Error(m(msg('The theme "{label}" is not installed.', { label: theme.label })));
1401 }
1402
1403 const canonicalTheme = canonicalizeThemeDefinition(theme);
1404 const nextThemes = [...themes];
1405 nextThemes[themeIndex] = canonicalTheme;
1406
1407 const nextStoredThemes: unknown[] = [];
1408 let replaced = false;
1409 for (const storedTheme of library.storedThemes) {
1410 if (!storedThemeHasId(storedTheme, theme.id)) {
1411 nextStoredThemes.push(storedTheme);
1412 } else if (!replaced) {
1413 nextStoredThemes.push(canonicalTheme);
1414 replaced = true;
1415 }
1416 }
1417 saveCustomThemes(nextStoredThemes, nextThemes);
1418 return canonicalTheme;
1419 }
1420
1421 export function replaceCustomThemeCollection(
1422 collectionId: string,
1423 themes: ReadonlyArray<ThemeDefinition>,
1424 options?: { expectedCollection?: ReadonlyArray<ThemeDefinition> },
1425 ): ReadonlyArray<ThemeDefinition> {
1426 if (themes.length === 0) throw new Error(m(msg("A theme collection cannot be empty.")));
1427
1428 const validated = themes.map((theme) => parseStoredTheme(theme));
1429 if (
1430 validated.some((theme) => theme === null || theme.collection?.id !== collectionId) ||
1431 new Set(validated.map((theme) => theme?.id)).size !== validated.length
1432 ) {
1433 throw new Error(m(msg("That theme collection is invalid.")));
1434 }
1435 const replacement = validated as ThemeDefinition[];
1436 const library = readWritableCustomThemeLibrary();
1437 const current = library.themes;
1438 const currentCollection = current.filter((theme) => theme.collection?.id === collectionId);
1439 if (
1440 options?.expectedCollection &&
1441 JSON.stringify(currentCollection) !== JSON.stringify(options.expectedCollection)
1442 ) {
1443 throw new Error(
1444 m(msg("Your installed themes changed while this package was downloading. Try again.")),
1445 );
1446 }
1447 const occupiedIds = new Set(BUILT_IN_THEME_DEFINITIONS.map((theme) => theme.id));
1448 for (const storedTheme of library.storedThemes) {
1449 if (
1450 !storedThemeHasCollectionId(storedTheme, collectionId) &&
1451 isRecord(storedTheme) &&
1452 typeof storedTheme.id === "string"
1453 ) {
1454 occupiedIds.add(storedTheme.id);
1455 }
1456 }
1457 const conflictingTheme = replacement.find(
1458 (theme) => RESERVED_THEME_IDS.has(theme.id) || occupiedIds.has(theme.id),
1459 );
1460 if (conflictingTheme) {
1461 throw new Error(
1462 m(msg('A theme named "{label}" is already installed.', { label: conflictingTheme.label })),
1463 );
1464 }
1465
1466 const nextStoredThemes: unknown[] = [];
1467 let insertedReplacement = false;
1468 for (const storedTheme of library.storedThemes) {
1469 if (!storedThemeHasCollectionId(storedTheme, collectionId)) {
1470 nextStoredThemes.push(storedTheme);
1471 } else if (!insertedReplacement) {
1472 nextStoredThemes.push(...replacement);
1473 insertedReplacement = true;
1474 }
1475 }
1476 if (!insertedReplacement) nextStoredThemes.push(...replacement);
1477
1478 saveCustomThemes(nextStoredThemes, parseStoredThemes(nextStoredThemes));
1479 return replacement;
1480 }
1481
1482 export function removeCustomTheme(themeId: string): void {
1483 removeCustomThemes([themeId]);
1484 }
1485
1486 export function removeCustomThemes(themeIds: ReadonlyArray<string>): void {
1487 const removedIds = new Set(themeIds);
1488 if (removedIds.size === 0) return;
1489 const library = getWritableCustomThemeLibrary();
1490 const nextThemes = library.themes.filter((theme) => !removedIds.has(theme.id));
1491 if (nextThemes.length === library.themes.length) return;
1492 saveCustomThemes(
1493 library.storedThemes.filter(
1494 (storedTheme) =>
1495 !isRecord(storedTheme) ||
1496 typeof storedTheme.id !== "string" ||
1497 !removedIds.has(storedTheme.id),
1498 ),
1499 nextThemes,
1500 );
1501 }
1502
1503 function parseThemeColorOverrides(value: unknown): ThemeColorOverrides {
1504 if (!isRecord(value)) throw new Error(m(msg("Theme colors must be objects.")));
1505
1506 const overrides: Partial<Record<ThemeColorRole, string>> = {};
1507 for (const [role, color] of Object.entries(value)) {
1508 if (!THEME_COLOR_ROLE_SET.has(role)) {
1509 throw new Error(m(msg('"{role}" is not a supported theme color role.', { role })));
1510 }
1511 const normalized = toCanonicalThemeColor(color);
1512 if (!normalized) {
1513 throw new Error(
1514 m(
1515 msg('The color for "{role}" must be a literal CSS color such as oklch(0.62 0.2 280).', {
1516 role,
1517 }),
1518 ),
1519 );
1520 }
1521 overrides[role as ThemeColorRole] = normalized;
1522 }
1523 if (Object.keys(overrides).length === 0) {
1524 throw new Error(m(msg("Add at least one color role to the theme file.")));
1525 }
1526 return overrides;
1527 }
1528
1529 function parseThemeSeedColor(name: string, value: unknown): string {
1530 if (typeof value !== "string" || !toCanonicalThemeColor(value)) {
1531 throw new Error(m(msg("The theme''s \"{name}\" must be a literal CSS color.", { name })));
1532 }
1533 return value;
1534 }
1535
1536 export function parseThemeFile(value: unknown): ThemeDefinition {
1537 if (!isRecord(value)) {
1538 throw new Error(m(msg("Theme files must contain a JSON object.")));
1539 }
1540 if (value.version !== THEME_FILE_VERSION) {
1541 throw new Error(
1542 m(
1543 msg("This theme file uses an unsupported version. Expected {version}.", {
1544 version: THEME_FILE_VERSION,
1545 }),
1546 ),
1547 );
1548 }
1549
1550 const name = value.name;
1551 const appearance = value.appearance;
1552 const rawColors = value.colors;
1553 if (!isThemeLabel(name))
1554 throw new Error(m(msg("Theme files need a name (48 characters or fewer).")));
1555 if (!isThemeAppearance(appearance)) {
1556 throw new Error(m(msg('Theme files need an appearance of "light" or "dark".')));
1557 }
1558 if (!isRecord(rawColors)) throw new Error(m(msg("Theme files need a colors object.")));
1559
1560 const id = value.id === undefined ? themeIdFromName(name) : value.id;
1561 if (!isThemeId(id)) {
1562 throw new Error(m(msg("Theme ids may only contain lowercase letters, numbers, and hyphens.")));
1563 }
1564 if (RESERVED_THEME_IDS.has(id)) {
1565 throw new Error(m(msg('The theme id "{id}" is reserved.', { id })));
1566 }
1567
1568 const overrides = parseThemeColorOverrides(rawColors);
1569 const collection = parseThemeCollection(value.collection);
1570 if (value.collection !== undefined && !collection) {
1571 throw new Error(m(msg("Theme collections need a valid id and label.")));
1572 }
1573
1574 if (value.css !== undefined && !isThemeCss(value.css)) {
1575 throw new Error(
1576 m(msg("Theme CSS must be text of {max} characters or fewer.", { max: THEME_CSS_MAX_LENGTH })),
1577 );
1578 }
1579
1580 const fallback =
1581 value.canvas !== undefined && value.accent !== undefined
1582 ? createVividThemeColors(
1583 appearance,
1584 parseThemeSeedColor("canvas", value.canvas),
1585 parseThemeSeedColor("accent", value.accent),
1586 )
1587 : getDefaultThemeColors(appearance);
1588 const variants: Partial<Record<ThemeAppearance, ThemeColors>> = {};
1589 if (value.variants !== undefined) {
1590 if (!isRecord(value.variants)) throw new Error(m(msg("Theme variants must be an object.")));
1591 for (const [variantAppearance, variantColors] of Object.entries(value.variants)) {
1592 if (!isThemeAppearance(variantAppearance)) {
1593 throw new Error(m(msg('Theme variants may only be named "light" or "dark".')));
1594 }
1595 if (variantAppearance === appearance) {
1596 throw new Error(
1597 m(
1598 msg('Theme variants must not repeat the base appearance "{appearance}".', {
1599 appearance,
1600 }),
1601 ),
1602 );
1603 }
1604 const variantFallback = getDefaultThemeColors(variantAppearance);
1605 variants[variantAppearance] = {
1606 ...variantFallback,
1607 ...parseThemeColorOverrides(variantColors),
1608 };
1609 }
1610 }
1611
1612 return {
1613 id,
1614 label: name.trim(),
1615 appearance,
1616 colors: { ...fallback, ...overrides },
1617 ...(Object.keys(variants).length > 0 ? { variants } : {}),
1618 ...(collection ? { collection } : {}),
1619 ...(value.managed === true ? { managed: true } : {}),
1620 ...(value.css ? { css: value.css } : {}),
1621 };
1622 }
1623
1624 /** A copy of `theme` under `name` and the id it derives. The collection stays behind. */
1625 export function renameTheme(theme: ThemeDefinition, name: string): ThemeDefinition {
1626 return parseThemeFile({
1627 version: THEME_FILE_VERSION,
1628 name,
1629 appearance: theme.appearance,
1630 colors: theme.colors,
1631 ...(theme.variants ? { variants: theme.variants } : {}),
1632 ...(theme.managed ? { managed: true } : {}),
1633 ...(theme.css ? { css: theme.css } : {}),
1634 });
1635 }
1636
1637 export function serializeThemeFile(theme: ThemeDefinition): string {
1638 const canonicalTheme = canonicalizeThemeDefinition(theme);
1639 const file: ThemeFile = {
1640 version: THEME_FILE_VERSION,
1641 id: canonicalTheme.id,
1642 name: canonicalTheme.label,
1643 appearance: canonicalTheme.appearance,
1644 colors: canonicalTheme.colors,
1645 ...(canonicalTheme.variants ? { variants: canonicalTheme.variants } : {}),
1646 ...(canonicalTheme.collection ? { collection: canonicalTheme.collection } : {}),
1647 ...(canonicalTheme.managed ? { managed: true } : {}),
1648 ...(canonicalTheme.css ? { css: canonicalTheme.css } : {}),
1649 };
1650 return `${JSON.stringify(file, null, 2)}\n`;
1651 }
1652
1653 const APP_THEME_VARIABLES: Readonly<Record<ThemeColorRole, string>> = {
1654 canvas: "--app-theme-canvas",
1655 chrome: "--app-theme-chrome",
1656 toolbar: "--app-theme-toolbar",
1657 toolbarForeground: "--app-theme-toolbar-foreground",
1658 toolbarBorder: "--app-theme-toolbar-border",
1659 toolbarControl: "--app-theme-toolbar-control",
1660 toolbarControlForeground: "--app-theme-toolbar-control-foreground",
1661 toolbarControlHover: "--app-theme-toolbar-control-hover",
1662 surface: "--app-theme-surface",
1663 surfaceRaised: "--app-theme-surface-raised",
1664 surfaceOverlay: "--app-theme-surface-overlay",
1665 text: "--app-theme-text",
1666 textMuted: "--app-theme-text-muted",
1667 border: "--app-theme-border",
1668 input: "--app-theme-input",
1669 focus: "--app-theme-focus",
1670 accent: "--app-theme-accent",
1671 accentForeground: "--app-theme-accent-foreground",
1672 secondary: "--app-theme-secondary",
1673 secondaryForeground: "--app-theme-secondary-foreground",
1674 muted: "--app-theme-muted",
1675 mutedForeground: "--app-theme-muted-foreground",
1676 placeholder: "--app-theme-placeholder",
1677 secondaryLabel: "--app-theme-secondary-label",
1678 iconMuted: "--app-theme-icon-muted",
1679 error: "--app-theme-error",
1680 errorForeground: "--app-theme-error-foreground",
1681 errorSurface: "--app-theme-error-surface",
1682 warning: "--app-theme-warning",
1683 warningForeground: "--app-theme-warning-foreground",
1684 warningSurface: "--app-theme-warning-surface",
1685 update: "--app-theme-update",
1686 updateForeground: "--app-theme-update-foreground",
1687 updateSurface: "--app-theme-update-surface",
1688 accentSurface: "--app-theme-accent-surface",
1689 accentSurfaceForeground: "--app-theme-accent-surface-foreground",
1690 messageSurface: "--app-theme-message-surface",
1691 messageForeground: "--app-theme-message-foreground",
1692 messageAction: "--app-theme-message-action",
1693 messageActionForeground: "--app-theme-message-action-foreground",
1694 messageActionHover: "--app-theme-message-action-hover",
1695 codeBackground: "--app-theme-code-background",
1696 codeForeground: "--app-theme-code-foreground",
1697 searchMatchBackground: "--app-theme-search-match-background",
1698 searchMatchForeground: "--app-theme-search-match-foreground",
1699 searchMatchActiveBackground: "--app-theme-search-match-active-background",
1700 searchMatchActiveForeground: "--app-theme-search-match-active-foreground",
1701 sidebar: "--app-theme-sidebar",
1702 sidebarForeground: "--app-theme-sidebar-foreground",
1703 sidebarMutedForeground: "--app-theme-sidebar-muted-foreground",
1704 sidebarControlSurface: "--app-theme-sidebar-control-surface",
1705 sidebarRowHover: "--app-theme-sidebar-row-hover",
1706 sidebarRowActive: "--app-theme-sidebar-row-active",
1707 sidebarRowSelected: "--app-theme-sidebar-row-selected",
1708 sidebarBorder: "--app-theme-sidebar-border",
1709 terminalBackground: "--app-theme-terminal-background",
1710 terminalForeground: "--app-theme-terminal-foreground",
1711 terminalCursor: "--app-theme-terminal-cursor",
1712 terminalSelection: "--app-theme-terminal-selection-background",
1713 terminalScrollbar: "--app-theme-terminal-scrollbar",
1714 terminalScrollbarHover: "--app-theme-terminal-scrollbar-hover",
1715 };
1716
1717 export function getThemeColorVariable(role: ThemeColorRole): string {
1718 return APP_THEME_VARIABLES[role];
1719 }
1720
1721 export const THEME_PREVIEW_ID = "__preview";
1722
1723 /** Callers must restore the stored theme with refreshTheme when the draft closes. */
1724 export function applyThemeColorPreview(
1725 colors: ThemeColors,
1726 appearance: ThemeAppearance,
1727 css?: string,
1728 ): void {
1729 if (typeof document === "undefined") return;
1730 const root = document.documentElement;
1731 if (!root?.style) return;
1732
1733 root.dataset.themeId = THEME_PREVIEW_ID;
1734 root.classList.toggle("dark", appearance === "dark");
1735 for (const [role, value] of Object.entries(colors) as Array<[ThemeColorRole, string]>) {
1736 if (isThemeColor(value)) root.style.setProperty(APP_THEME_VARIABLES[role], value);
1737 }
1738 applyContextChipVariables(root, colors);
1739 applyThemeCss(css);
1740 setThemePreviewAppearance(appearance);
1741 }
1742
1743 export function applyThemePalette(theme: ThemePreference, appearance?: ThemeAppearance): void {
1744 if (typeof document === "undefined") return;
1745
1746 const root = document.documentElement;
1747 if (!root?.style) return;
1748
1749 setThemePreviewAppearance(null);
1750 const palette = getThemeDefinition(theme);
1751 applyThemeCss(palette?.css);
1752 applyThemeBackground(palette?.id);
1753
1754 if (palette) {
1755 root.dataset.themeId = palette.id;
1756 const mode = appearance ?? legacyThemeMode(theme) ?? palette.appearance;
1757 const colors = getThemeColorsForMode(palette, mode) ?? palette.colors;
1758 for (const [role, value] of Object.entries(colors) as Array<[ThemeColorRole, string]>) {
1759 root.style.setProperty(APP_THEME_VARIABLES[role], value);
1760 }
1761 applyContextChipVariables(root, colors);
1762 return;
1763 }
1764
1765 delete root.dataset.themeId;
1766 for (const variable of Object.values(APP_THEME_VARIABLES)) {
1767 root.style.removeProperty(variable);
1768 }
1769 applyContextChipVariables(root, getStandardPaintedThemeColors(appearance ?? "light"));
1770 }
1771
1772 export function resolveThemeAppearance(
1773 theme: ThemePreference,
1774 systemDark: boolean,
1775 followSystem?: boolean,
1776 appearanceMode?: ThemePreferenceMode,
1777 halves?: ThemeHalves | null,
1778 ): "light" | "dark" {
1779 const systemAppearance = systemDark ? "dark" : "light";
1780 const mode = appearanceMode ?? ((followSystem ?? theme === "system") ? "system" : null);
1781 if (mode === "system") {
1782 if (halves?.[systemAppearance]) return systemAppearance;
1783 const definition = getThemeDefinition(theme);
1784 return definition && getThemeColorsForMode(definition, systemAppearance) === null
1785 ? definition.appearance
1786 : systemAppearance;
1787 }
1788 if (mode === "light" || mode === "dark") {
1789 if (halves?.[mode]) return mode;
1790 const definition = getThemeDefinition(theme);
1791 return definition && getThemeColorsForMode(definition, mode) === null
1792 ? definition.appearance
1793 : mode;
1794 }
1795 return getThemePreferenceMode(theme) ?? "light";
1796 }
1797
1798 export function resolveDesktopTheme(
1799 theme: ThemePreference,
1800 followSystem?: boolean,
1801 appearanceMode?: ThemePreferenceMode,
1802 halves?: ThemeHalves | null,
1803 ): "light" | "dark" | "system" {
1804 const mode = appearanceMode ?? ((followSystem ?? theme === "system") ? "system" : null);
1805 if (mode === "system") {
1806 const definition = getThemeDefinition(theme);
1807 const hasLightMode =
1808 halves?.light !== undefined ||
1809 (definition !== null && getThemeColorsForMode(definition, "light") !== null);
1810 const hasDarkMode =
1811 halves?.dark !== undefined ||
1812 (definition !== null && getThemeColorsForMode(definition, "dark") !== null);
1813 return definition && (!hasLightMode || !hasDarkMode) ? definition.appearance : "system";
1814 }
1815 if (mode === "light" || mode === "dark") {
1816 if (halves?.[mode]) return mode;
1817 const definition = getThemeDefinition(theme);
1818 return definition && getThemeColorsForMode(definition, mode) === null
1819 ? definition.appearance
1820 : mode;
1821 }
1822 return getThemePreferenceMode(theme) ?? "system";
1823 }
1824
1825 export function isKnownThemePreference(theme: string): boolean {
1826 if (theme === "light" || theme === "dark" || theme === "system") return true;
1827 return getThemeDefinition(theme) !== null;
1828 }
1829
1830 export type ThemeHalves = Readonly<{ light?: string; dark?: string }>;
1831
1832 export function parseThemeHalves(raw: string | null): ThemeHalves | null {
1833 if (!raw) return null;
1834 try {
1835 const value: unknown = JSON.parse(raw);
1836 if (!isRecord(value)) return null;
1837 const halves: { light?: string; dark?: string } = {};
1838 for (const appearance of ["light", "dark"] as const) {
1839 const themeId = value[appearance];
1840 if (typeof themeId !== "string") continue;
1841 const definition = getThemeDefinition(themeId);
1842 if (definition && getThemeColorsForMode(definition, appearance) !== null) {
1843 halves[appearance] = definition.id;
1844 }
1845 }
1846 return halves.light !== undefined || halves.dark !== undefined ? halves : null;
1847 } catch {
1848 return null;
1849 }
1850 }
1851
1852 export function resolveThemeHalf(
1853 theme: ThemePreference,
1854 halves: ThemeHalves | null,
1855 appearance: ThemeAppearance,
1856 ): ThemePreference {
1857 return halves?.[appearance] ?? theme;
1858 }