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

themePalette.test.ts

1,083 lines36.8 KB

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