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