Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

themePalette.test.ts

1,051 lines35.6 KB

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