Open History to see the last commit
1import { describe, expect, it, vi } from "vite-plus/test";
2import { BUILT_IN_THEMES } from "@t3tools/shared/themePalettes";
3
4import {
5 applyThemeColorPreview,
6 applyThemePalette,
7 getThemeColorsForMode,
8 getThemeDefinition,
9 getThemeModes,
10 getThemePreviewSidebarArtwork,
11 getThemePreferenceMode,
12 isKnownThemePreference,
13 getCustomThemes,
14 getStandardThemeColors,
15 getStoredCustomThemeCollection,
16 invalidateCustomThemes,
17 installCustomTheme,
18 canonicalThemePreference,
19 parseThemeFile,
20 parseThemeHalves,
21 removeCustomTheme,
22 removeCustomThemes,
23 replaceCustomThemeCollection,
24 resolveDesktopTheme,
25 resolveThemeAppearance,
26 serializeThemeFile,
27 subscribeToThemePreview,
28 subscribeToCustomThemes,
29 themeAllowsSidebarArtwork,
30 T3_CHAT_THEME,
31 EMBER_THEME,
32 GROVE_THEME,
33 IRIS_THEME,
34 OCEAN_THEME,
35 updateCustomTheme,
36 CUSTOM_THEMES_STORAGE_KEY,
37 createManagedThemeColors,
38 createVividThemeColors,
39 getDefaultThemeColors,
40 themeColorToHex,
41 toCanonicalThemeColor,
42 THEME_FILE_VERSION,
43 singleAppearanceOf,
44} from "./themePalette";
45
46function asHex(value: string): string {
47 const hex = themeColorToHex(value);
48 if (!hex) throw new Error(`Expected a theme color, received ${value}`);
49 return hex.slice(0, 7);
50}
51
52function canonical(value: string): string {
53 const color = toCanonicalThemeColor(value);
54 if (!color) throw new Error(`Expected a theme color, received ${value}`);
55 return color;
56}
57
58function expectThemeColors(
59 colors: Readonly<Record<string, string>>,
60 expected: Readonly<Record<string, string>>,
61): void {
62 for (const [role, value] of Object.entries(expected)) {
63 expect(asHex(colors[role]!)).toBe(value);
64 }
65}
66
67function contrastRatio(first: string, second: string): number {
68 const toRgb = (value: string) => {
69 const hex = asHex(value).slice(1);
70 return [0, 1, 2].map(
71 (channel) => Number.parseInt(hex.slice(channel * 2, channel * 2 + 2), 16) / 255,
72 );
73 };
74 const luminance = (value: string) =>
75 toRgb(value)
76 .map((channel) => (channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4))
77 .reduce((sum, channel, index) => sum + channel * [0.2126, 0.7152, 0.0722][index]!, 0);
78 const lighter = Math.max(luminance(first), luminance(second));
79 const darker = Math.min(luminance(first), luminance(second));
80 return (lighter + 0.05) / (darker + 0.05);
81}
82
83describe("theme files", () => {
84 it("keeps every built-in palette value in canonical OKLCH form", () => {
85 for (const theme of BUILT_IN_THEMES) {
86 for (const colors of [theme.colors, ...Object.values(theme.variants ?? {})]) {
87 for (const value of Object.values(colors)) {
88 expect(toCanonicalThemeColor(value)).toBe(value);
89 }
90 }
91 }
92 });
93
94 it("derives a readable palette from extreme simple-editor colors", () => {
95 const light = createManagedThemeColors("light", "#111827", "#ffff00");
96 const dark = createManagedThemeColors("dark", "#ffffff", "#ffff00");
97 const darkDefaults = getDefaultThemeColors("dark");
98
99 expect(asHex(light.canvas)).not.toBe("#111827");
100 expect(asHex(dark.canvas)).not.toBe("#ffffff");
101 expect(contrastRatio(light.accent, light.canvas)).toBeGreaterThanOrEqual(4.5);
102 expect(contrastRatio(dark.accent, dark.canvas)).toBeGreaterThanOrEqual(4.5);
103 expect(contrastRatio(light.textMuted, light.canvas)).toBeGreaterThanOrEqual(4.5);
104 expect(contrastRatio(dark.textMuted, dark.canvas)).toBeGreaterThanOrEqual(4.5);
105 expect(contrastRatio(light.textMuted, light.canvas)).toBeLessThan(5.5);
106 expect(contrastRatio(dark.textMuted, dark.canvas)).toBeLessThan(5.5);
107 expect(contrastRatio(light.textMuted, light.canvas)).toBeCloseTo(4.705, 1);
108 expect(contrastRatio(dark.textMuted, dark.canvas)).toBeCloseTo(5.082, 1);
109 expect(light.secondaryLabel).toBe(light.textMuted);
110 expect(dark.secondaryLabel).toBe(dark.textMuted);
111 expect(contrastRatio(light.accentForeground, light.accent)).toBeGreaterThanOrEqual(4.5);
112 expect(contrastRatio(dark.accentForeground, dark.accent)).toBeGreaterThanOrEqual(4.5);
113 // Status colors fall back to T3 Code's standard red and amber rather than
114 // the flagship palette's, so no generated theme inherits a brand tint.
115 const channels = (value: string) =>
116 [1, 3, 5].map((index) => Number.parseInt(asHex(value).slice(index, index + 2), 16)) as [
117 number,
118 number,
119 number,
120 ];
121 for (const colors of [light, dark]) {
122 const [errorRed, errorGreen, errorBlue] = channels(colors.error);
123 // Red leads by a wide margin; the old default was a pink whose blue sat
124 // close behind its red.
125 expect(errorRed).toBeGreaterThan(errorGreen * 2);
126 expect(errorRed).toBeGreaterThan(errorBlue * 2);
127 expect(contrastRatio(colors.error, "#ffffff")).toBeGreaterThanOrEqual(2.5);
128 expect(contrastRatio(colors.errorForeground, colors.errorSurface)).toBeGreaterThanOrEqual(
129 4.5,
130 );
131 const [warnRed, warnGreen, warnBlue] = channels(colors.warning);
132 expect(warnRed).toBeGreaterThan(warnBlue);
133 expect(warnGreen).toBeGreaterThan(warnBlue);
134 }
135 expect(asHex(dark.error)).not.toBe(asHex(darkDefaults.error));
136 });
137
138 it("keeps stock dark controls in the neutral-black surface hierarchy", () => {
139 expectThemeColors(getStandardThemeColors("dark"), {
140 canvas: "#0a0a0a",
141 surface: "#111111",
142 surfaceRaised: "#111111",
143 surfaceOverlay: "#111111",
144 toolbarControl: "#111111",
145 secondary: "#111111",
146 muted: "#111111",
147 accentSurface: "#141414",
148 });
149 });
150
151 it("derives readable, distinctive vivid palettes from exact seeds", () => {
152 const seeds: ReadonlyArray<["light" | "dark", string, string]> = [
153 ["light", "#f4f9f2", "#1d8a4e"],
154 ["dark", "#101a2c", "#4f8fe8"],
155 ["dark", "#211a23", "#df5398"],
156 ["light", "#fdf6ec", "#c2571b"],
157 // Inverted canvases: the palette follows the picked color, not the slot.
158 ["light", "#111827", "#8ab4f8"],
159 ["dark", "#f5ecf5", "#a84370"],
160 ];
161 for (const [appearance, canvas, accent] of seeds) {
162 const colors = createVividThemeColors(appearance, canvas, accent);
163 // Exact seeds are honored.
164 expect(colors.canvas).toMatch(/^oklch\(/);
165 expect(colors.accent).toMatch(/^oklch\(/);
166 expect(asHex(colors.canvas)).toBe(canvas);
167 expect(asHex(colors.accent)).toBe(accent);
168 // Readability is solved per surface.
169 expect(contrastRatio(colors.text, colors.canvas)).toBeGreaterThanOrEqual(7);
170 expect(contrastRatio(colors.textMuted, colors.canvas)).toBeGreaterThanOrEqual(4.5);
171 expect(contrastRatio(colors.textMuted, colors.canvas)).toBeLessThan(5.5);
172 expect(contrastRatio(colors.mutedForeground, colors.muted)).toBeGreaterThanOrEqual(4.5);
173 expect(contrastRatio(colors.mutedForeground, colors.muted)).toBeLessThan(
174 contrastRatio(colors.text, colors.muted),
175 );
176 expect(contrastRatio(colors.placeholder, colors.surfaceRaised)).toBeGreaterThanOrEqual(4.5);
177 expect(contrastRatio(colors.placeholder, colors.surfaceRaised)).toBeLessThan(
178 contrastRatio(colors.text, colors.surfaceRaised),
179 );
180 expect(colors.secondaryLabel).toBe(colors.textMuted);
181 expect(contrastRatio(colors.accentForeground, colors.accent)).toBeGreaterThanOrEqual(4.5);
182 expect(
183 contrastRatio(colors.messageActionForeground, colors.messageAction),
184 ).toBeGreaterThanOrEqual(4.5);
185 expect(contrastRatio(colors.messageForeground, colors.messageSurface)).toBeGreaterThanOrEqual(
186 4.5,
187 );
188 expect(contrastRatio(colors.secondaryForeground, colors.secondary)).toBeGreaterThanOrEqual(
189 4.5,
190 );
191 expect(contrastRatio(colors.sidebarForeground, colors.sidebar)).toBeGreaterThanOrEqual(4.5);
192 // The companion action is a distinct voice, not the accent again.
193 expect(colors.messageAction).not.toBe(colors.accent);
194 // Update family follows the theme, not the default palette.
195 expect(asHex(colors.update)).toBe(accent);
196 }
197 });
198
199 it("keys status colors off the canvas, not the appearance slot", () => {
200 // Inverted seeds: a dark canvas in the light slot must still get the dark
201 // status pair, or the alert foreground lands on a dark surface unreadable.
202 const inverted = [
203 createVividThemeColors("light", "#111827", "#8ab4f8"),
204 createVividThemeColors("dark", "#f5ecf5", "#a84370"),
205 createManagedThemeColors("light", "#0d1117", "#69b1ff", { exactSeeds: true }),
206 createManagedThemeColors("dark", "#fdfdfd", "#c2571b", { exactSeeds: true }),
207 ];
208 for (const colors of inverted) {
209 expect(contrastRatio(colors.errorForeground, colors.errorSurface)).toBeGreaterThanOrEqual(
210 4.5,
211 );
212 expect(contrastRatio(colors.warningForeground, colors.warningSurface)).toBeGreaterThanOrEqual(
213 4.5,
214 );
215 }
216 });
217
218 it("merges a small user file onto the matching contrast-safe base palette", () => {
219 const theme = parseThemeFile({
220 version: THEME_FILE_VERSION,
221 name: "Ocean dusk",
222 appearance: "dark",
223 colors: {
224 canvas: "#07152f",
225 accent: "#67c2ff",
226 },
227 });
228
229 expect(theme).toMatchObject({
230 id: "ocean-dusk",
231 label: "Ocean dusk",
232 appearance: "dark",
233 colors: {
234 canvas: canonical("#07152f"),
235 accent: canonical("#67c2ff"),
236 placeholder: canonical("#968d9f"),
237 },
238 });
239 });
240
241 it("decodes literal CSS color formats into OKLCH without dropping alpha", () => {
242 const theme = parseThemeFile({
243 version: THEME_FILE_VERSION,
244 name: "Translucent",
245 appearance: "light",
246 colors: {
247 canvas: "oklch(62% 0.2 280deg / 50%)",
248 accent: "#abcd",
249 focus: "rgb(10 20 30 / 50%)",
250 error: "hsl(350 80% 50%)",
251 warning: "hwb(45 10% 20%)",
252 update: "lab(60% 40 30)",
253 messageAction: "lch(60% 50 120)",
254 sidebar: "oklab(0.6 0.1 -0.1)",
255 terminalCursor: "color(display-p3 0.8 0.2 0.3)",
256 terminalSelection: "rebeccapurple",
257 terminalScrollbar: "transparent",
258 terminalScrollbarHover: "rgb(10 20 30 / none)",
259 },
260 });
261
262 expect(theme.colors.canvas).toBe("oklch(0.62 0.2 280 / 0.5)");
263 expect(theme.colors.accent).toBe(canonical("#abcd"));
264 expect(themeColorToHex(theme.colors.accent)).toBe("#aabbccdd");
265 expect(themeColorToHex(theme.colors.focus)).toBe("#0a141e80");
266 expect(themeColorToHex(theme.colors.terminalSelection)).toBe("#663399");
267 expect(theme.colors.terminalScrollbar).toBe("oklch(0 0 0 / 0)");
268 expect(themeColorToHex(theme.colors.terminalScrollbarHover)).toBe("#0a141e00");
269 for (const role of [
270 "error",
271 "warning",
272 "update",
273 "messageAction",
274 "sidebar",
275 "terminalCursor",
276 ] as const) {
277 expect(theme.colors[role]).toMatch(/^oklch\(/);
278 }
279 });
280
281 it("gamut maps extreme finite OKLCH chroma from theme files", () => {
282 const theme = parseThemeFile({
283 version: THEME_FILE_VERSION,
284 name: "Extreme chroma",
285 appearance: "light",
286 colors: { accent: "oklch(0.5 1e303 0)" },
287 });
288
289 expect(theme.colors.accent).toBe("oklch(0.5 1e+303 0)");
290 expect(themeColorToHex(theme.colors.accent)).toBe("#b5005e");
291 });
292
293 it("rejects unknown roles and invalid color values", () => {
294 expect(() =>
295 parseThemeFile({
296 version: THEME_FILE_VERSION,
297 name: "Broken",
298 appearance: "light",
299 colors: { background: "#ffffff" },
300 }),
301 ).toThrow('"background" is not a supported theme color role.');
302
303 expect(() =>
304 parseThemeFile({
305 version: THEME_FILE_VERSION,
306 name: "Broken",
307 appearance: "light",
308 colors: { accent: "var(--danger)" },
309 }),
310 ).toThrow('The color for "accent" must be a literal CSS color');
311 });
312
313 it("canonicalizes the explicitly exported theme", () => {
314 const serialized = serializeThemeFile({
315 ...T3_CHAT_THEME,
316 colors: { ...T3_CHAT_THEME.colors, accent: "hsl(263 70% 58%)" },
317 });
318 expect(JSON.parse(serialized)).toMatchObject({
319 version: THEME_FILE_VERSION,
320 id: T3_CHAT_THEME.id,
321 name: T3_CHAT_THEME.label,
322 appearance: "light",
323 colors: { accent: canonical("hsl(263 70% 58%)") },
324 });
325 });
326
327 it("serializes a theme back into the importable file shape", () => {
328 const theme = {
329 ...parseThemeFile({
330 version: THEME_FILE_VERSION,
331 id: "community-demo",
332 name: "Community Demo",
333 appearance: "dark",
334 colors: { canvas: "#111111" },
335 }),
336 collection: { id: "open-vsx:demo.theme", label: "Demo Theme" },
337 };
338 const serialized = serializeThemeFile(theme);
339 expect(JSON.parse(serialized)).toMatchObject({
340 version: THEME_FILE_VERSION,
341 id: theme.id,
342 name: theme.label,
343 appearance: "dark",
344 collection: theme.collection,
345 });
346 expect(parseThemeFile(JSON.parse(serialized)).collection).toEqual(theme.collection);
347 });
348
349 it("keeps sidebar artwork disabled for custom theme files", () => {
350 const theme = parseThemeFile({
351 version: THEME_FILE_VERSION,
352 name: "Art sidebar",
353 appearance: "light",
354 colors: { accent: "#5b6cff" },
355 sidebarArtwork: true,
356 });
357
358 expect(theme.sidebarArtwork).toBeUndefined();
359 expect(JSON.parse(serializeThemeFile(theme))).not.toHaveProperty("sidebarArtwork");
360 });
361
362 it("suppresses sidebar artwork during a live custom-theme preview", () => {
363 const listener = vi.fn();
364 const unsubscribe = subscribeToThemePreview(listener);
365 vi.stubGlobal("document", {
366 documentElement: {
367 classList: { toggle: vi.fn() },
368 dataset: {},
369 style: { removeProperty: vi.fn(), setProperty: vi.fn() },
370 },
371 });
372
373 applyThemeColorPreview(T3_CHAT_THEME.colors, "light");
374 expect(getThemePreviewSidebarArtwork()).toBe(false);
375 expect(listener).toHaveBeenCalledTimes(1);
376
377 applyThemePalette("system");
378 expect(getThemePreviewSidebarArtwork()).toBeNull();
379 expect(listener).toHaveBeenCalledTimes(2);
380
381 unsubscribe();
382 vi.unstubAllGlobals();
383 });
384
385 it("keeps optional light and dark palettes under one theme id", () => {
386 const theme = parseThemeFile({
387 version: THEME_FILE_VERSION,
388 id: "aurora",
389 name: "Aurora",
390 appearance: "light",
391 colors: { canvas: "#f8fbff", text: "#10243d" },
392 variants: {
393 dark: { canvas: "#101827", text: "#eef5ff" },
394 },
395 });
396
397 expect(getThemeModes(theme)).toEqual(["light", "dark"]);
398 expect(getThemeColorsForMode(theme, "dark")).toMatchObject({
399 canvas: canonical("#101827"),
400 text: canonical("#eef5ff"),
401 });
402 expect(getThemeModes(T3_CHAT_THEME)).toEqual(["light", "dark"]);
403 expect(resolveThemeAppearance(T3_CHAT_THEME.id, true, true)).toBe("dark");
404 expect(resolveDesktopTheme(T3_CHAT_THEME.id, true)).toBe("system");
405 expect(resolveThemeAppearance(T3_CHAT_THEME.id, false, false, "dark")).toBe("dark");
406 expect(resolveDesktopTheme(T3_CHAT_THEME.id, false, "dark")).toBe("dark");
407 expect(JSON.parse(serializeThemeFile(theme)).variants.dark).toMatchObject({
408 canvas: canonical("#101827"),
409 text: canonical("#eef5ff"),
410 });
411 });
412
413 it("keeps the T3 Chat palette faithful and readable", () => {
414 expectThemeColors(T3_CHAT_THEME.colors, {
415 canvas: "#fdf7fd",
416 chrome: "#fdf7fd",
417 toolbarBorder: "#efbdeb",
418 toolbarControl: "#f3e6f5",
419 toolbarControlHover: "#eccfe3",
420 surfaceRaised: "#fdfafd",
421 input: "#e7c1dc",
422 focus: "#db2777",
423 messageSurface: "#f7def2",
424 codeBackground: "#f5ecf9",
425 codeForeground: "#673c8b",
426 accentSurface: "#f3e6f5",
427 sidebar: "#f2e1f4",
428 });
429 expectThemeColors(T3_CHAT_THEME.variants!.dark!, {
430 canvas: "#1f1a24",
431 chrome: "#1f1a24",
432 surface: "#29232d",
433 surfaceRaised: "#2c2631",
434 input: "#302029",
435 focus: "#db2777",
436 messageSurface: "#2b2431",
437 codeBackground: "#1f1a24",
438 sidebar: "#171018",
439 sidebarBorder: "#322028",
440 });
441
442 for (const mode of ["light", "dark"] as const) {
443 const colors = getThemeColorsForMode(T3_CHAT_THEME, mode)!;
444 expect(contrastRatio(colors.text, colors.canvas)).toBeGreaterThanOrEqual(7);
445 expect(contrastRatio(colors.textMuted, colors.canvas)).toBeGreaterThanOrEqual(4.5);
446 expect(contrastRatio(colors.messageForeground, colors.messageSurface)).toBeGreaterThanOrEqual(
447 4.5,
448 );
449 expect(contrastRatio(colors.secondaryForeground, colors.secondary)).toBeGreaterThanOrEqual(
450 4.5,
451 );
452 expect(contrastRatio(colors.sidebarForeground, colors.sidebar)).toBeGreaterThanOrEqual(4.5);
453 expect(contrastRatio(colors.accentForeground, colors.accent)).toBeGreaterThanOrEqual(4.5);
454 }
455 });
456
457 it("includes the dual-mode maintainer themes", () => {
458 for (const theme of [T3_CHAT_THEME, GROVE_THEME, OCEAN_THEME, EMBER_THEME, IRIS_THEME]) {
459 expect(getThemeDefinition(theme.id)).toBe(theme);
460 expect(getThemeModes(theme)).toEqual(["light", "dark"]);
461 expect(theme.sidebarArtwork).toBe(true);
462 expect(themeAllowsSidebarArtwork(theme.id)).toBe(true);
463 expect(theme.colors.accent).toMatch(/^oklch\(/);
464 expect(theme.variants?.dark?.accent).toMatch(/^oklch\(/);
465
466 for (const mode of ["light", "dark"] as const) {
467 const colors = getThemeColorsForMode(theme, mode);
468 expect(colors).not.toBeNull();
469 expect(contrastRatio(colors!.text, colors!.canvas)).toBeGreaterThanOrEqual(4.5);
470 expect(contrastRatio(colors!.textMuted, colors!.canvas)).toBeGreaterThanOrEqual(4.5);
471 if (theme !== T3_CHAT_THEME) {
472 expect(contrastRatio(colors!.textMuted, colors!.canvas)).toBeLessThan(5.5);
473 expect(contrastRatio(colors!.textMuted, colors!.canvas)).toBeCloseTo(
474 mode === "dark" ? 5.082 : 4.705,
475 1,
476 );
477 }
478 expect(contrastRatio(colors!.accentForeground, colors!.accent)).toBeGreaterThanOrEqual(4.5);
479 expect(
480 contrastRatio(colors!.toolbarControlForeground, colors!.toolbarControl),
481 ).toBeGreaterThanOrEqual(4.5);
482 expect(
483 contrastRatio(colors!.messageForeground, colors!.messageSurface),
484 ).toBeGreaterThanOrEqual(4.5);
485 expect(
486 contrastRatio(colors!.messageActionForeground, colors!.messageAction),
487 ).toBeGreaterThanOrEqual(4.5);
488 expect(
489 contrastRatio(colors!.messageActionForeground, colors!.messageActionHover),
490 ).toBeGreaterThanOrEqual(4.5);
491 expect(contrastRatio(colors!.mutedForeground, colors!.muted)).toBeGreaterThanOrEqual(4.5);
492 expect(contrastRatio(colors!.placeholder, colors!.surfaceRaised)).toBeGreaterThanOrEqual(
493 4.5,
494 );
495 }
496 }
497 expect(themeAllowsSidebarArtwork("my-custom-theme")).toBe(false);
498 });
499
500 it("rejects a variant that repeats the base appearance", () => {
501 expect(() =>
502 parseThemeFile({
503 version: THEME_FILE_VERSION,
504 name: "Duplicate light",
505 appearance: "light",
506 colors: { canvas: "#f8fbff" },
507 variants: { light: { canvas: "#101827" } },
508 }),
509 ).toThrow('Theme variants must not repeat the base appearance "light".');
510 });
511
512 it("keeps a single-mode theme on its only palette", () => {
513 const theme = parseThemeFile({
514 version: THEME_FILE_VERSION,
515 id: "midnight-slate",
516 name: "Midnight Slate",
517 appearance: "dark",
518 colors: { canvas: "#111827", messageAction: "#2563eb" },
519 });
520
521 expect(getThemeModes(theme)).toEqual(["dark"]);
522 expect(getThemeColorsForMode(theme, "dark")).toMatchObject({
523 canvas: canonical("#111827"),
524 });
525 expect(getThemeColorsForMode(theme, "light")).toBeNull();
526 });
527
528 it("invalidates cached themes when another tab clears localStorage", () => {
529 let storedThemes: string | null = JSON.stringify([
530 {
531 id: "ocean-dusk",
532 label: "Ocean dusk",
533 appearance: "dark",
534 colors: { canvas: "#07152f" },
535 },
536 ]);
537 let storageHandler: ((event: StorageEvent) => void) | undefined;
538 vi.stubGlobal("window", {
539 addEventListener: (type: string, listener: (event: StorageEvent) => void) => {
540 if (type === "storage") storageHandler = listener;
541 },
542 removeEventListener: vi.fn(),
543 localStorage: {
544 getItem: (key: string) => (key === CUSTOM_THEMES_STORAGE_KEY ? storedThemes : null),
545 },
546 });
547
548 invalidateCustomThemes();
549 expect(getCustomThemes()).toHaveLength(1);
550 const listener = vi.fn();
551 const unsubscribe = subscribeToCustomThemes(listener);
552
553 storedThemes = null;
554 storageHandler?.({ key: null } as StorageEvent);
555
556 expect(listener).toHaveBeenCalledTimes(1);
557 expect(getCustomThemes()).toEqual([]);
558 unsubscribe();
559 invalidateCustomThemes();
560 vi.unstubAllGlobals();
561 });
562
563 it("preserves valid imported-theme collections and drops malformed metadata", () => {
564 vi.stubGlobal("window", {
565 localStorage: {
566 getItem: (key: string) =>
567 key === CUSTOM_THEMES_STORAGE_KEY
568 ? JSON.stringify([
569 {
570 id: "github-dark",
571 label: "GitHub Dark",
572 appearance: "dark",
573 colors: { canvas: "#0d1117" },
574 collection: { id: "open-vsx:github.github-vscode-theme", label: "GitHub Theme" },
575 },
576 {
577 id: "github-light",
578 label: "GitHub Light",
579 appearance: "light",
580 colors: { canvas: "#ffffff" },
581 collection: { id: "bad collection id", label: "GitHub Theme" },
582 },
583 ])
584 : null,
585 },
586 });
587
588 invalidateCustomThemes();
589 expect(getCustomThemes()).toMatchObject([
590 { collection: { id: "open-vsx:github.github-vscode-theme", label: "GitHub Theme" } },
591 { id: "github-light" },
592 ]);
593 expect(getCustomThemes()[1]).not.toHaveProperty("collection");
594
595 vi.unstubAllGlobals();
596 invalidateCustomThemes();
597 });
598
599 it("atomically replaces an imported collection and removes stale variants", () => {
600 const collection = { id: "open-vsx:demo.theme", label: "Demo Theme" };
601 const personalTheme = {
602 id: "personal",
603 label: "Personal",
604 appearance: "dark",
605 colors: { canvas: "#111111", futureRole: "hsl(10 20% 30%)" },
606 futureMetadata: { version: 2 },
607 };
608 const stored = new Map<string, string>([
609 [
610 CUSTOM_THEMES_STORAGE_KEY,
611 JSON.stringify([
612 personalTheme,
613 {
614 id: "old-light",
615 label: "Old Light",
616 appearance: "light",
617 colors: { canvas: "#ffffff" },
618 collection,
619 },
620 {
621 id: "removed-dark",
622 label: "Removed Dark",
623 appearance: "dark",
624 colors: { canvas: "#000000" },
625 collection,
626 },
627 ]),
628 ],
629 ]);
630 const setItem = vi.fn((key: string, value: string) => stored.set(key, value));
631 vi.stubGlobal("window", {
632 localStorage: {
633 getItem: (key: string) => stored.get(key) ?? null,
634 setItem,
635 },
636 });
637
638 invalidateCustomThemes();
639 const expectedCollection = getStoredCustomThemeCollection(collection.id);
640 getCustomThemes();
641 const concurrentlyAddedTheme = {
642 id: "other-tab",
643 label: "Other Tab",
644 appearance: "dark",
645 colors: { canvas: "#222222" },
646 };
647 stored.set(
648 CUSTOM_THEMES_STORAGE_KEY,
649 JSON.stringify([
650 ...JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]"),
651 concurrentlyAddedTheme,
652 ]),
653 );
654 const replacement = [
655 {
656 ...parseThemeFile({
657 version: THEME_FILE_VERSION,
658 id: "old-light",
659 name: "New Light",
660 appearance: "light",
661 colors: { canvas: "#fafafa" },
662 }),
663 collection,
664 },
665 {
666 ...parseThemeFile({
667 version: THEME_FILE_VERSION,
668 id: "new-dark",
669 name: "New Dark",
670 appearance: "dark",
671 colors: { canvas: "#101010" },
672 }),
673 collection,
674 },
675 ];
676
677 expect(
678 replaceCustomThemeCollection(collection.id, replacement, { expectedCollection }),
679 ).toEqual(replacement);
680 expect(getCustomThemes().map((theme) => theme.id)).toEqual([
681 "personal",
682 "old-light",
683 "new-dark",
684 "other-tab",
685 ]);
686 expect(setItem).toHaveBeenCalledTimes(1);
687 expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")[0]).toEqual(personalTheme);
688
689 vi.unstubAllGlobals();
690 invalidateCustomThemes();
691 });
692
693 it("replaces collection entries even when their stored collection label is malformed", () => {
694 const collection = { id: "open-vsx:demo.theme", label: "Demo Theme" };
695 const stored = new Map<string, string>([
696 [
697 CUSTOM_THEMES_STORAGE_KEY,
698 JSON.stringify([
699 {
700 id: "old-light",
701 label: "Old Light",
702 appearance: "light",
703 colors: { canvas: "#ffffff" },
704 collection: { id: collection.id, label: 42 },
705 },
706 ]),
707 ],
708 ]);
709 vi.stubGlobal("window", {
710 localStorage: {
711 getItem: (key: string) => stored.get(key) ?? null,
712 setItem: (key: string, value: string) => stored.set(key, value),
713 },
714 });
715
716 invalidateCustomThemes();
717 const replacement = {
718 ...parseThemeFile({
719 version: THEME_FILE_VERSION,
720 id: "old-light",
721 name: "New Light",
722 appearance: "light",
723 colors: { canvas: "#fafafa" },
724 }),
725 collection,
726 };
727
728 expect(replaceCustomThemeCollection(collection.id, [replacement])).toEqual([replacement]);
729 expect(getCustomThemes()).toEqual([replacement]);
730
731 vi.unstubAllGlobals();
732 invalidateCustomThemes();
733 });
734
735 it("canonicalizes explicit writes without migrating untouched themes", () => {
736 const stored = new Map<string, string>();
737 const untouchedTheme = {
738 id: "legacy",
739 label: "Legacy",
740 appearance: "dark",
741 colors: { accent: "#5b6cff", futureRole: "hsl(10 20% 30%)" },
742 futureMetadata: { version: 2 },
743 };
744 stored.set(CUSTOM_THEMES_STORAGE_KEY, JSON.stringify([untouchedTheme]));
745 vi.stubGlobal("window", {
746 localStorage: {
747 getItem: (key: string) => stored.get(key) ?? null,
748 setItem: (key: string, value: string) => stored.set(key, value),
749 },
750 });
751
752 invalidateCustomThemes();
753 const createdTheme = installCustomTheme(
754 parseThemeFile({
755 version: THEME_FILE_VERSION,
756 id: "aurora",
757 name: "Aurora",
758 appearance: "light",
759 colors: { canvas: "#f8fbff", accent: "#5b6cff" },
760 sidebarArtwork: true,
761 }),
762 );
763 const updatedTheme = updateCustomTheme({
764 ...createdTheme,
765 label: "Aurora Night",
766 colors: { ...createdTheme.colors, accent: "hsl(263 70% 58%)" },
767 });
768
769 expect(updatedTheme).toMatchObject({
770 id: "aurora",
771 label: "Aurora Night",
772 colors: { accent: canonical("hsl(263 70% 58%)") },
773 });
774 expect(updatedTheme).not.toHaveProperty("sidebarArtwork");
775 const storedThemes = JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]");
776 expect(storedThemes[0]).toEqual(untouchedTheme);
777 expect(storedThemes[1]).toMatchObject({
778 id: "aurora",
779 label: "Aurora Night",
780 colors: { accent: canonical("hsl(263 70% 58%)") },
781 });
782 expect(storedThemes[1]).not.toHaveProperty("sidebarArtwork");
783 invalidateCustomThemes();
784 expect(getCustomThemes().find((theme) => theme.id === "aurora")).toMatchObject({
785 id: "aurora",
786 colors: { accent: canonical("hsl(263 70% 58%)") },
787 });
788 removeCustomTheme("aurora");
789 expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")).toEqual([untouchedTheme]);
790
791 vi.unstubAllGlobals();
792 invalidateCustomThemes();
793 });
794
795 it("removes multiple custom themes atomically while preserving unrelated entries", () => {
796 const collection = { id: "open-vsx:demo.theme", label: "Demo Theme" };
797 const personalTheme = {
798 id: "personal",
799 label: "Personal",
800 appearance: "dark",
801 colors: { canvas: "#111111", futureRole: "hsl(10 20% 30%)" },
802 futureMetadata: { version: 2 },
803 };
804 const stored = new Map<string, string>([
805 [
806 CUSTOM_THEMES_STORAGE_KEY,
807 JSON.stringify([
808 personalTheme,
809 {
810 id: "demo-light",
811 label: "Demo Light",
812 appearance: "light",
813 colors: { canvas: "#ffffff" },
814 collection,
815 },
816 {
817 id: "demo-dark",
818 label: "Demo Dark",
819 appearance: "dark",
820 colors: { canvas: "#000000" },
821 collection,
822 },
823 ]),
824 ],
825 ]);
826 const setItem = vi.fn((key: string, value: string) => stored.set(key, value));
827 vi.stubGlobal("window", {
828 localStorage: {
829 getItem: (key: string) => stored.get(key) ?? null,
830 setItem,
831 },
832 });
833
834 invalidateCustomThemes();
835 removeCustomThemes(["demo-light", "demo-dark"]);
836
837 expect(setItem).toHaveBeenCalledOnce();
838 expect(getCustomThemes()).toEqual([expect.objectContaining({ id: "personal" })]);
839 expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")).toEqual([personalTheme]);
840
841 vi.unstubAllGlobals();
842 invalidateCustomThemes();
843 });
844
845 it("writes from the cached raw snapshot without risking a destructive reread", () => {
846 const legacyTheme = {
847 id: "legacy",
848 label: "Legacy",
849 appearance: "dark",
850 colors: { accent: "#5b6cff" },
851 futureMetadata: true,
852 };
853 let storedThemes = JSON.stringify([legacyTheme]);
854 let readCount = 0;
855 const setItem = vi.fn((_key: string, value: string) => {
856 storedThemes = value;
857 });
858 vi.stubGlobal("window", {
859 localStorage: {
860 getItem: () => {
861 readCount += 1;
862 if (readCount > 1) throw new Error("transient read failure");
863 return storedThemes;
864 },
865 setItem,
866 },
867 });
868
869 invalidateCustomThemes();
870 expect(getCustomThemes()).toHaveLength(1);
871 installCustomTheme(
872 parseThemeFile({
873 version: THEME_FILE_VERSION,
874 id: "aurora",
875 name: "Aurora",
876 appearance: "light",
877 colors: { accent: "hsl(263 70% 58%)" },
878 }),
879 );
880
881 expect(readCount).toBe(1);
882 expect(setItem).toHaveBeenCalledOnce();
883 expect(JSON.parse(storedThemes)[0]).toEqual(legacyTheme);
884
885 vi.unstubAllGlobals();
886 invalidateCustomThemes();
887 });
888
889 it("refuses to overwrite a theme library that could not be read", () => {
890 const setItem = vi.fn();
891 vi.stubGlobal("window", {
892 localStorage: {
893 getItem: () => {
894 throw new Error("storage unavailable");
895 },
896 setItem,
897 },
898 });
899
900 invalidateCustomThemes();
901 expect(getCustomThemes()).toEqual([]);
902 expect(() =>
903 installCustomTheme(
904 parseThemeFile({
905 version: THEME_FILE_VERSION,
906 id: "aurora",
907 name: "Aurora",
908 appearance: "light",
909 colors: { accent: "#5b6cff" },
910 }),
911 ),
912 ).toThrow(`Failed to read the theme library from ${CUSTOM_THEMES_STORAGE_KEY}.`);
913 expect(setItem).not.toHaveBeenCalled();
914
915 vi.unstubAllGlobals();
916 invalidateCustomThemes();
917 });
918
919 it("rejects malformed stored entries that reuse an installed theme id", () => {
920 const storedThemes = JSON.stringify([{ id: "aurora", malformed: true }]);
921 const setItem = vi.fn();
922 vi.stubGlobal("window", {
923 localStorage: {
924 getItem: () => storedThemes,
925 setItem,
926 },
927 });
928
929 invalidateCustomThemes();
930 expect(() =>
931 installCustomTheme(
932 parseThemeFile({
933 version: THEME_FILE_VERSION,
934 id: "aurora",
935 name: "Aurora",
936 appearance: "light",
937 colors: { accent: "#5b6cff" },
938 }),
939 ),
940 ).toThrow('A theme named "Aurora" is already installed.');
941 expect(setItem).not.toHaveBeenCalled();
942
943 vi.unstubAllGlobals();
944 invalidateCustomThemes();
945 });
946
947 it("collapses duplicate raw entries when their theme is explicitly updated", () => {
948 const stored = new Map<string, string>();
949 const theme = {
950 id: "aurora",
951 label: "Aurora",
952 appearance: "light",
953 colors: { accent: "#5b6cff" },
954 };
955 const untouchedTheme = { id: "future", malformed: true, metadata: { version: 2 } };
956 stored.set(
957 CUSTOM_THEMES_STORAGE_KEY,
958 JSON.stringify([theme, { id: "aurora", malformed: true }, untouchedTheme]),
959 );
960 vi.stubGlobal("window", {
961 localStorage: {
962 getItem: (key: string) => stored.get(key) ?? null,
963 setItem: (key: string, value: string) => stored.set(key, value),
964 },
965 });
966
967 invalidateCustomThemes();
968 const installedTheme = getCustomThemes()[0]!;
969 updateCustomTheme({
970 ...installedTheme,
971 label: "Aurora Night",
972 colors: { ...installedTheme.colors, accent: "hsl(263 70% 58%)" },
973 });
974
975 const updatedLibrary = JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]");
976 expect(updatedLibrary.filter((entry: { id?: string }) => entry.id === "aurora")).toHaveLength(
977 1,
978 );
979 expect(updatedLibrary[0]).toMatchObject({
980 id: "aurora",
981 label: "Aurora Night",
982 colors: { accent: canonical("hsl(263 70% 58%)") },
983 });
984 expect(updatedLibrary[1]).toEqual(untouchedTheme);
985
986 vi.unstubAllGlobals();
987 invalidateCustomThemes();
988 });
989});
990
991describe("stored theme preferences", () => {
992 it("lets a configured half unlock an appearance the base theme lacks", () => {
993 // Light-only base: without halves, dark requests fall back to light.
994 const lightOnly = parseThemeFile({
995 version: THEME_FILE_VERSION,
996 id: "paper",
997 name: "Paper",
998 appearance: "light",
999 colors: { canvas: "#f8fbff" },
1000 });
1001 vi.stubGlobal("window", {
1002 localStorage: {
1003 getItem: (key: string) =>
1004 key === CUSTOM_THEMES_STORAGE_KEY ? JSON.stringify([lightOnly]) : null,
1005 },
1006 });
1007 invalidateCustomThemes();
1008 try {
1009 expect(resolveThemeAppearance("paper", true, true)).toBe("light");
1010 const halves = { dark: GROVE_THEME.id };
1011 expect(resolveThemeAppearance("paper", true, true, undefined, halves)).toBe("dark");
1012 expect(resolveThemeAppearance("paper", false, false, "dark", halves)).toBe("dark");
1013 expect(resolveDesktopTheme("paper", true, undefined, halves)).toBe("system");
1014 } finally {
1015 vi.unstubAllGlobals();
1016 invalidateCustomThemes();
1017 }
1018 });
1019
1020 it("resolves the legacy t3-chat-dark preference to dark T3 Chat", () => {
1021 expect(getThemeDefinition("t3-chat-dark")).toBe(T3_CHAT_THEME);
1022 expect(getThemePreferenceMode("t3-chat-dark")).toBe("dark");
1023 expect(resolveThemeAppearance("t3-chat-dark", true, false)).toBe("dark");
1024 expect(resolveDesktopTheme("t3-chat-dark", false)).toBe("dark");
1025 expect(isKnownThemePreference("t3-chat-dark")).toBe(true);
1026 });
1027
1028 it("resolves legacy t3-prefixed ids onto the renamed themes", () => {
1029 for (const [legacy, theme] of [
1030 ["t3-grove", GROVE_THEME],
1031 ["t3-ocean", OCEAN_THEME],
1032 ["t3-ember", EMBER_THEME],
1033 ["t3-iris", IRIS_THEME],
1034 ] as const) {
1035 expect(getThemeDefinition(legacy)).toBe(theme);
1036 expect(isKnownThemePreference(legacy)).toBe(true);
1037 expect(canonicalThemePreference(legacy)).toBe(theme.id);
1038 }
1039 // The dark-variant alias keeps its raw form: it still carries a mode hint.
1040 expect(canonicalThemePreference("t3-chat-dark")).toBe("t3-chat-dark");
1041 // A stored mix that predates the rename resolves to the new ids.
1042 expect(parseThemeHalves(JSON.stringify({ light: "t3-ocean", dark: "t3-grove" }))).toEqual({
1043 light: OCEAN_THEME.id,
1044 dark: GROVE_THEME.id,
1045 });
1046 });
1047
1048 it("recognizes only preferences the runtime can render", () => {
1049 for (const preference of ["light", "dark", "system", T3_CHAT_THEME.id, GROVE_THEME.id]) {
1050 expect(isKnownThemePreference(preference)).toBe(true);
1051 }
1052 expect(isKnownThemePreference(`${GROVE_THEME.id}:dark`)).toBe(false);
1053 expect(isKnownThemePreference("missing-theme")).toBe(false);
1054 });
1055
1056 it("decodes stored colors in memory without writing during reads", () => {
1057 const storedThemes = JSON.stringify([
1058 {
1059 id: "aurora",
1060 label: "Aurora",
1061 appearance: "light",
1062 colors: { canvas: "#f8fbff", futureRole: "#123456", accent: "not-a-color" },
1063 variants: { dark: { canvas: "rgb(16 24 39)" } },
1064 },
1065 { id: "light", label: "Reserved", appearance: "light", colors: {} },
1066 { id: "aurora", label: "Duplicate", appearance: "dark", colors: {} },
1067 ]);
1068 const setItem = vi.fn();
1069 vi.stubGlobal("window", {
1070 localStorage: {
1071 getItem: (key: string) => (key === CUSTOM_THEMES_STORAGE_KEY ? storedThemes : null),
1072 setItem,
1073 },
1074 });
1075 invalidateCustomThemes();
1076
1077 const themes = getCustomThemes();
1078 expect(themes).toHaveLength(1);
1079 expect(themes[0]).toMatchObject({
1080 id: "aurora",
1081 colors: { canvas: canonical("#f8fbff"), accent: getDefaultThemeColors("light").accent },
1082 });
1083 expect(getThemeModes(themes[0]!)).toEqual(["light", "dark"]);
1084 expect(getThemeColorsForMode(themes[0]!, "dark")?.canvas).toBe(canonical("rgb(16 24 39)"));
1085 expect(setItem).not.toHaveBeenCalled();
1086 expect(JSON.parse(storedThemes)[0].colors).toEqual({
1087 canvas: "#f8fbff",
1088 futureRole: "#123456",
1089 accent: "not-a-color",
1090 });
1091
1092 vi.unstubAllGlobals();
1093 invalidateCustomThemes();
1094 });
1095});
1096
1097describe("singleAppearanceOf", () => {
1098 it("reports the only half a theme can claim, and null for a pair", () => {
1099 const { variants: _pair, ...base } = T3_CHAT_THEME;
1100 expect(singleAppearanceOf({ ...base, id: "x", appearance: "dark" })).toBe("dark");
1101 expect(singleAppearanceOf(T3_CHAT_THEME)).toBe(null);
1102 });
1103});