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