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