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