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

themePalette.test.ts

1,063 lines36.0 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("gamut maps extreme finite OKLCH chroma from theme files", () => {
250 const theme = parseThemeFile({
251 version: THEME_FILE_VERSION,
252 name: "Extreme chroma",
253 appearance: "light",
254 colors: { accent: "oklch(0.5 1e303 0)" },
255 });
256​
257 expect(theme.colors.accent).toBe("oklch(0.5 1e+303 0)");
258 expect(themeColorToHex(theme.colors.accent)).toBe("#b5005e");
259 });
260​
261 it("rejects unknown roles and invalid color values", () => {
262 expect(() =>
263 parseThemeFile({
264 version: THEME_FILE_VERSION,
265 name: "Broken",
266 appearance: "light",
267 colors: { background: "#ffffff" },
268 }),
269 ).toThrow('"background" is not a supported theme color role.');
270​
271 expect(() =>
272 parseThemeFile({
273 version: THEME_FILE_VERSION,
274 name: "Broken",
275 appearance: "light",
276 colors: { accent: "var(--danger)" },
277 }),
278 ).toThrow('The color for "accent" must be a literal CSS color');
279 });
280​
281 it("canonicalizes the explicitly exported theme", () => {
282 const serialized = serializeThemeFile({
283 ...T3_CHAT_THEME,
284 colors: { ...T3_CHAT_THEME.colors, accent: "hsl(263 70% 58%)" },
285 });
286 expect(JSON.parse(serialized)).toMatchObject({
287 version: THEME_FILE_VERSION,
288 id: T3_CHAT_THEME.id,
289 name: T3_CHAT_THEME.label,
290 appearance: "light",
291 colors: { accent: canonical("hsl(263 70% 58%)") },
292 });
293 });
294​
295 it("serializes a theme back into the importable file shape", () => {
296 const theme = {
297 ...parseThemeFile({
298 version: THEME_FILE_VERSION,
299 id: "community-demo",
300 name: "Community Demo",
301 appearance: "dark",
302 colors: { canvas: "#111111" },
303 }),
304 collection: { id: "open-vsx:demo.theme", label: "Demo Theme" },
305 };
306 const serialized = serializeThemeFile(theme);
307 expect(JSON.parse(serialized)).toMatchObject({
308 version: THEME_FILE_VERSION,
309 id: theme.id,
310 name: theme.label,
311 appearance: "dark",
312 collection: theme.collection,
313 });
314 expect(parseThemeFile(JSON.parse(serialized)).collection).toEqual(theme.collection);
315 });
316​
317 it("keeps sidebar artwork disabled for custom theme files", () => {
318 const theme = parseThemeFile({
319 version: THEME_FILE_VERSION,
320 name: "Art sidebar",
321 appearance: "light",
322 colors: { accent: "#5b6cff" },
323 sidebarArtwork: true,
324 });
325​
326 expect(theme.sidebarArtwork).toBeUndefined();
327 expect(JSON.parse(serializeThemeFile(theme))).not.toHaveProperty("sidebarArtwork");
328 });
329​
330 it("suppresses sidebar artwork during a live custom-theme preview", () => {
331 const listener = vi.fn();
332 const unsubscribe = subscribeToThemePreview(listener);
333 vi.stubGlobal("document", {
334 documentElement: {
335 classList: { toggle: vi.fn() },
336 dataset: {},
337 style: { removeProperty: vi.fn(), setProperty: vi.fn() },
338 },
339 });
340​
341 applyThemeColorPreview(T3_CHAT_THEME.colors, "light");
342 expect(getThemePreviewSidebarArtwork()).toBe(false);
343 expect(listener).toHaveBeenCalledTimes(1);
344​
345 applyThemePalette("system");
346 expect(getThemePreviewSidebarArtwork()).toBeNull();
347 expect(listener).toHaveBeenCalledTimes(2);
348​
349 unsubscribe();
350 vi.unstubAllGlobals();
351 });
352​
353 it("keeps optional light and dark palettes under one theme id", () => {
354 const theme = parseThemeFile({
355 version: THEME_FILE_VERSION,
356 id: "aurora",
357 name: "Aurora",
358 appearance: "light",
359 colors: { canvas: "#f8fbff", text: "#10243d" },
360 variants: {
361 dark: { canvas: "#101827", text: "#eef5ff" },
362 },
363 });
364​
365 expect(getThemeModes(theme)).toEqual(["light", "dark"]);
366 expect(getThemeColorsForMode(theme, "dark")).toMatchObject({
367 canvas: canonical("#101827"),
368 text: canonical("#eef5ff"),
369 });
370 expect(getThemeModes(T3_CHAT_THEME)).toEqual(["light", "dark"]);
371 expect(resolveThemeAppearance(T3_CHAT_THEME.id, true, true)).toBe("dark");
372 expect(resolveDesktopTheme(T3_CHAT_THEME.id, true)).toBe("system");
373 expect(resolveThemeAppearance(T3_CHAT_THEME.id, false, false, "dark")).toBe("dark");
374 expect(resolveDesktopTheme(T3_CHAT_THEME.id, false, "dark")).toBe("dark");
375 expect(JSON.parse(serializeThemeFile(theme)).variants.dark).toMatchObject({
376 canvas: canonical("#101827"),
377 text: canonical("#eef5ff"),
378 });
379 });
380​
381 it("keeps the T3 Chat palette faithful and readable", () => {
382 expectThemeColors(T3_CHAT_THEME.colors, {
383 canvas: "#fdf7fd",
384 chrome: "#fdf7fd",
385 toolbarBorder: "#efbdeb",
386 toolbarControl: "#f3e6f5",
387 toolbarControlHover: "#eccfe3",
388 surfaceRaised: "#fdfafd",
389 input: "#e7c1dc",
390 focus: "#db2777",
391 messageSurface: "#f7def2",
392 codeBackground: "#f5ecf9",
393 codeForeground: "#673c8b",
394 accentSurface: "#f3e6f5",
395 sidebar: "#f2e1f4",
396 });
397 expectThemeColors(T3_CHAT_THEME.variants!.dark!, {
398 canvas: "#1f1a24",
399 chrome: "#1f1a24",
400 surface: "#29232d",
401 surfaceRaised: "#2c2631",
402 input: "#302029",
403 focus: "#db2777",
404 messageSurface: "#2b2431",
405 codeBackground: "#1f1a24",
406 sidebar: "#171018",
407 sidebarBorder: "#322028",
408 });
409​
410 for (const mode of ["light", "dark"] as const) {
411 const colors = getThemeColorsForMode(T3_CHAT_THEME, mode)!;
412 expect(contrastRatio(colors.text, colors.canvas)).toBeGreaterThanOrEqual(7);
413 expect(contrastRatio(colors.textMuted, colors.canvas)).toBeGreaterThanOrEqual(4.5);
414 expect(contrastRatio(colors.messageForeground, colors.messageSurface)).toBeGreaterThanOrEqual(
415 4.5,
416 );
417 expect(contrastRatio(colors.secondaryForeground, colors.secondary)).toBeGreaterThanOrEqual(
418 4.5,
419 );
420 expect(contrastRatio(colors.sidebarForeground, colors.sidebar)).toBeGreaterThanOrEqual(4.5);
421 expect(contrastRatio(colors.accentForeground, colors.accent)).toBeGreaterThanOrEqual(4.5);
422 }
423 });
424​
425 it("includes the dual-mode maintainer themes", () => {
426 for (const theme of [T3_CHAT_THEME, GROVE_THEME, OCEAN_THEME, EMBER_THEME, IRIS_THEME]) {
427 expect(getThemeDefinition(theme.id)).toBe(theme);
428 expect(getThemeModes(theme)).toEqual(["light", "dark"]);
429 expect(theme.sidebarArtwork).toBe(true);
430 expect(themeAllowsSidebarArtwork(theme.id)).toBe(true);
431 expect(theme.colors.accent).toMatch(/^oklch\(/);
432 expect(theme.variants?.dark?.accent).toMatch(/^oklch\(/);
433​
434 for (const mode of ["light", "dark"] as const) {
435 const colors = getThemeColorsForMode(theme, mode);
436 expect(colors).not.toBeNull();
437 expect(contrastRatio(colors!.text, colors!.canvas)).toBeGreaterThanOrEqual(4.5);
438 expect(contrastRatio(colors!.textMuted, colors!.canvas)).toBeGreaterThanOrEqual(4.5);
439 if (theme !== T3_CHAT_THEME) {
440 expect(contrastRatio(colors!.textMuted, colors!.canvas)).toBeLessThan(5.5);
441 expect(contrastRatio(colors!.textMuted, colors!.canvas)).toBeCloseTo(
442 mode === "dark" ? 5.082 : 4.705,
443 1,
444 );
445 }
446 expect(contrastRatio(colors!.accentForeground, colors!.accent)).toBeGreaterThanOrEqual(4.5);
447 expect(
448 contrastRatio(colors!.toolbarControlForeground, colors!.toolbarControl),
449 ).toBeGreaterThanOrEqual(4.5);
450 expect(
451 contrastRatio(colors!.messageForeground, colors!.messageSurface),
452 ).toBeGreaterThanOrEqual(4.5);
453 expect(
454 contrastRatio(colors!.messageActionForeground, colors!.messageAction),
455 ).toBeGreaterThanOrEqual(4.5);
456 expect(
457 contrastRatio(colors!.messageActionForeground, colors!.messageActionHover),
458 ).toBeGreaterThanOrEqual(4.5);
459 expect(contrastRatio(colors!.mutedForeground, colors!.muted)).toBeGreaterThanOrEqual(4.5);
460 expect(contrastRatio(colors!.placeholder, colors!.surfaceRaised)).toBeGreaterThanOrEqual(
461 4.5,
462 );
463 }
464 }
465 expect(themeAllowsSidebarArtwork("my-custom-theme")).toBe(false);
466 });
467​
468 it("rejects a variant that repeats the base appearance", () => {
469 expect(() =>
470 parseThemeFile({
471 version: THEME_FILE_VERSION,
472 name: "Duplicate light",
473 appearance: "light",
474 colors: { canvas: "#f8fbff" },
475 variants: { light: { canvas: "#101827" } },
476 }),
477 ).toThrow('Theme variants must not repeat the base appearance "light".');
478 });
479​
480 it("keeps a single-mode theme on its only palette", () => {
481 const theme = parseThemeFile({
482 version: THEME_FILE_VERSION,
483 id: "midnight-slate",
484 name: "Midnight Slate",
485 appearance: "dark",
486 colors: { canvas: "#111827", messageAction: "#2563eb" },
487 });
488​
489 expect(getThemeModes(theme)).toEqual(["dark"]);
490 expect(getThemeColorsForMode(theme, "dark")).toMatchObject({
491 canvas: canonical("#111827"),
492 });
493 expect(getThemeColorsForMode(theme, "light")).toBeNull();
494 });
495​
496 it("invalidates cached themes when another tab clears localStorage", () => {
497 let storedThemes: string | null = JSON.stringify([
498 {
499 id: "ocean-dusk",
500 label: "Ocean dusk",
501 appearance: "dark",
502 colors: { canvas: "#07152f" },
503 },
504 ]);
505 let storageHandler: ((event: StorageEvent) => void) | undefined;
506 vi.stubGlobal("window", {
507 addEventListener: (type: string, listener: (event: StorageEvent) => void) => {
508 if (type === "storage") storageHandler = listener;
509 },
510 removeEventListener: vi.fn(),
511 localStorage: {
512 getItem: (key: string) => (key === CUSTOM_THEMES_STORAGE_KEY ? storedThemes : null),
513 },
514 });
515​
516 invalidateCustomThemes();
517 expect(getCustomThemes()).toHaveLength(1);
518 const listener = vi.fn();
519 const unsubscribe = subscribeToCustomThemes(listener);
520​
521 storedThemes = null;
522 storageHandler?.({ key: null } as StorageEvent);
523​
524 expect(listener).toHaveBeenCalledTimes(1);
525 expect(getCustomThemes()).toEqual([]);
526 unsubscribe();
527 invalidateCustomThemes();
528 vi.unstubAllGlobals();
529 });
530​
531 it("preserves valid imported-theme collections and drops malformed metadata", () => {
532 vi.stubGlobal("window", {
533 localStorage: {
534 getItem: (key: string) =>
535 key === CUSTOM_THEMES_STORAGE_KEY
536 ? JSON.stringify([
537 {
538 id: "github-dark",
539 label: "GitHub Dark",
540 appearance: "dark",
541 colors: { canvas: "#0d1117" },
542 collection: { id: "open-vsx:github.github-vscode-theme", label: "GitHub Theme" },
543 },
544 {
545 id: "github-light",
546 label: "GitHub Light",
547 appearance: "light",
548 colors: { canvas: "#ffffff" },
549 collection: { id: "bad collection id", label: "GitHub Theme" },
550 },
551 ])
552 : null,
553 },
554 });
555​
556 invalidateCustomThemes();
557 expect(getCustomThemes()).toMatchObject([
558 { collection: { id: "open-vsx:github.github-vscode-theme", label: "GitHub Theme" } },
559 { id: "github-light" },
560 ]);
561 expect(getCustomThemes()[1]).not.toHaveProperty("collection");
562​
563 vi.unstubAllGlobals();
564 invalidateCustomThemes();
565 });
566​
567 it("atomically replaces an imported collection and removes stale variants", () => {
568 const collection = { id: "open-vsx:demo.theme", label: "Demo Theme" };
569 const personalTheme = {
570 id: "personal",
571 label: "Personal",
572 appearance: "dark",
573 colors: { canvas: "#111111", futureRole: "hsl(10 20% 30%)" },
574 futureMetadata: { version: 2 },
575 };
576 const stored = new Map<string, string>([
577 [
578 CUSTOM_THEMES_STORAGE_KEY,
579 JSON.stringify([
580 personalTheme,
581 {
582 id: "old-light",
583 label: "Old Light",
584 appearance: "light",
585 colors: { canvas: "#ffffff" },
586 collection,
587 },
588 {
589 id: "removed-dark",
590 label: "Removed Dark",
591 appearance: "dark",
592 colors: { canvas: "#000000" },
593 collection,
594 },
595 ]),
596 ],
597 ]);
598 const setItem = vi.fn((key: string, value: string) => stored.set(key, value));
599 vi.stubGlobal("window", {
600 localStorage: {
601 getItem: (key: string) => stored.get(key) ?? null,
602 setItem,
603 },
604 });
605​
606 invalidateCustomThemes();
607 const expectedCollection = getStoredCustomThemeCollection(collection.id);
608 getCustomThemes();
609 const concurrentlyAddedTheme = {
610 id: "other-tab",
611 label: "Other Tab",
612 appearance: "dark",
613 colors: { canvas: "#222222" },
614 };
615 stored.set(
616 CUSTOM_THEMES_STORAGE_KEY,
617 JSON.stringify([
618 ...JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]"),
619 concurrentlyAddedTheme,
620 ]),
621 );
622 const replacement = [
623 {
624 ...parseThemeFile({
625 version: THEME_FILE_VERSION,
626 id: "old-light",
627 name: "New Light",
628 appearance: "light",
629 colors: { canvas: "#fafafa" },
630 }),
631 collection,
632 },
633 {
634 ...parseThemeFile({
635 version: THEME_FILE_VERSION,
636 id: "new-dark",
637 name: "New Dark",
638 appearance: "dark",
639 colors: { canvas: "#101010" },
640 }),
641 collection,
642 },
643 ];
644​
645 expect(
646 replaceCustomThemeCollection(collection.id, replacement, { expectedCollection }),
647 ).toEqual(replacement);
648 expect(getCustomThemes().map((theme) => theme.id)).toEqual([
649 "personal",
650 "old-light",
651 "new-dark",
652 "other-tab",
653 ]);
654 expect(setItem).toHaveBeenCalledTimes(1);
655 expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")[0]).toEqual(personalTheme);
656​
657 vi.unstubAllGlobals();
658 invalidateCustomThemes();
659 });
660​
661 it("replaces collection entries even when their stored collection label is malformed", () => {
662 const collection = { id: "open-vsx:demo.theme", label: "Demo Theme" };
663 const stored = new Map<string, string>([
664 [
665 CUSTOM_THEMES_STORAGE_KEY,
666 JSON.stringify([
667 {
668 id: "old-light",
669 label: "Old Light",
670 appearance: "light",
671 colors: { canvas: "#ffffff" },
672 collection: { id: collection.id, label: 42 },
673 },
674 ]),
675 ],
676 ]);
677 vi.stubGlobal("window", {
678 localStorage: {
679 getItem: (key: string) => stored.get(key) ?? null,
680 setItem: (key: string, value: string) => stored.set(key, value),
681 },
682 });
683​
684 invalidateCustomThemes();
685 const replacement = {
686 ...parseThemeFile({
687 version: THEME_FILE_VERSION,
688 id: "old-light",
689 name: "New Light",
690 appearance: "light",
691 colors: { canvas: "#fafafa" },
692 }),
693 collection,
694 };
695​
696 expect(replaceCustomThemeCollection(collection.id, [replacement])).toEqual([replacement]);
697 expect(getCustomThemes()).toEqual([replacement]);
698​
699 vi.unstubAllGlobals();
700 invalidateCustomThemes();
701 });
702​
703 it("canonicalizes explicit writes without migrating untouched themes", () => {
704 const stored = new Map<string, string>();
705 const untouchedTheme = {
706 id: "legacy",
707 label: "Legacy",
708 appearance: "dark",
709 colors: { accent: "#5b6cff", futureRole: "hsl(10 20% 30%)" },
710 futureMetadata: { version: 2 },
711 };
712 stored.set(CUSTOM_THEMES_STORAGE_KEY, JSON.stringify([untouchedTheme]));
713 vi.stubGlobal("window", {
714 localStorage: {
715 getItem: (key: string) => stored.get(key) ?? null,
716 setItem: (key: string, value: string) => stored.set(key, value),
717 },
718 });
719​
720 invalidateCustomThemes();
721 const createdTheme = installCustomTheme(
722 parseThemeFile({
723 version: THEME_FILE_VERSION,
724 id: "aurora",
725 name: "Aurora",
726 appearance: "light",
727 colors: { canvas: "#f8fbff", accent: "#5b6cff" },
728 sidebarArtwork: true,
729 }),
730 );
731 const updatedTheme = updateCustomTheme({
732 ...createdTheme,
733 label: "Aurora Night",
734 colors: { ...createdTheme.colors, accent: "hsl(263 70% 58%)" },
735 });
736​
737 expect(updatedTheme).toMatchObject({
738 id: "aurora",
739 label: "Aurora Night",
740 colors: { accent: canonical("hsl(263 70% 58%)") },
741 });
742 expect(updatedTheme).not.toHaveProperty("sidebarArtwork");
743 const storedThemes = JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]");
744 expect(storedThemes[0]).toEqual(untouchedTheme);
745 expect(storedThemes[1]).toMatchObject({
746 id: "aurora",
747 label: "Aurora Night",
748 colors: { accent: canonical("hsl(263 70% 58%)") },
749 });
750 expect(storedThemes[1]).not.toHaveProperty("sidebarArtwork");
751 invalidateCustomThemes();
752 expect(getCustomThemes().find((theme) => theme.id === "aurora")).toMatchObject({
753 id: "aurora",
754 colors: { accent: canonical("hsl(263 70% 58%)") },
755 });
756 removeCustomTheme("aurora");
757 expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")).toEqual([untouchedTheme]);
758​
759 vi.unstubAllGlobals();
760 invalidateCustomThemes();
761 });
762​
763 it("removes multiple custom themes atomically while preserving unrelated entries", () => {
764 const collection = { id: "open-vsx:demo.theme", label: "Demo Theme" };
765 const personalTheme = {
766 id: "personal",
767 label: "Personal",
768 appearance: "dark",
769 colors: { canvas: "#111111", futureRole: "hsl(10 20% 30%)" },
770 futureMetadata: { version: 2 },
771 };
772 const stored = new Map<string, string>([
773 [
774 CUSTOM_THEMES_STORAGE_KEY,
775 JSON.stringify([
776 personalTheme,
777 {
778 id: "demo-light",
779 label: "Demo Light",
780 appearance: "light",
781 colors: { canvas: "#ffffff" },
782 collection,
783 },
784 {
785 id: "demo-dark",
786 label: "Demo Dark",
787 appearance: "dark",
788 colors: { canvas: "#000000" },
789 collection,
790 },
791 ]),
792 ],
793 ]);
794 const setItem = vi.fn((key: string, value: string) => stored.set(key, value));
795 vi.stubGlobal("window", {
796 localStorage: {
797 getItem: (key: string) => stored.get(key) ?? null,
798 setItem,
799 },
800 });
801​
802 invalidateCustomThemes();
803 removeCustomThemes(["demo-light", "demo-dark"]);
804​
805 expect(setItem).toHaveBeenCalledOnce();
806 expect(getCustomThemes()).toEqual([expect.objectContaining({ id: "personal" })]);
807 expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")).toEqual([personalTheme]);
808​
809 vi.unstubAllGlobals();
810 invalidateCustomThemes();
811 });
812​
813 it("writes from the cached raw snapshot without risking a destructive reread", () => {
814 const legacyTheme = {
815 id: "legacy",
816 label: "Legacy",
817 appearance: "dark",
818 colors: { accent: "#5b6cff" },
819 futureMetadata: true,
820 };
821 let storedThemes = JSON.stringify([legacyTheme]);
822 let readCount = 0;
823 const setItem = vi.fn((_key: string, value: string) => {
824 storedThemes = value;
825 });
826 vi.stubGlobal("window", {
827 localStorage: {
828 getItem: () => {
829 readCount += 1;
830 if (readCount > 1) throw new Error("transient read failure");
831 return storedThemes;
832 },
833 setItem,
834 },
835 });
836​
837 invalidateCustomThemes();
838 expect(getCustomThemes()).toHaveLength(1);
839 installCustomTheme(
840 parseThemeFile({
841 version: THEME_FILE_VERSION,
842 id: "aurora",
843 name: "Aurora",
844 appearance: "light",
845 colors: { accent: "hsl(263 70% 58%)" },
846 }),
847 );
848​
849 expect(readCount).toBe(1);
850 expect(setItem).toHaveBeenCalledOnce();
851 expect(JSON.parse(storedThemes)[0]).toEqual(legacyTheme);
852​
853 vi.unstubAllGlobals();
854 invalidateCustomThemes();
855 });
856​
857 it("refuses to overwrite a theme library that could not be read", () => {
858 const setItem = vi.fn();
859 vi.stubGlobal("window", {
860 localStorage: {
861 getItem: () => {
862 throw new Error("storage unavailable");
863 },
864 setItem,
865 },
866 });
867​
868 invalidateCustomThemes();
869 expect(getCustomThemes()).toEqual([]);
870 expect(() =>
871 installCustomTheme(
872 parseThemeFile({
873 version: THEME_FILE_VERSION,
874 id: "aurora",
875 name: "Aurora",
876 appearance: "light",
877 colors: { accent: "#5b6cff" },
878 }),
879 ),
880 ).toThrow(`Failed to read the theme library from ${CUSTOM_THEMES_STORAGE_KEY}.`);
881 expect(setItem).not.toHaveBeenCalled();
882​
883 vi.unstubAllGlobals();
884 invalidateCustomThemes();
885 });
886​
887 it("rejects malformed stored entries that reuse an installed theme id", () => {
888 const storedThemes = JSON.stringify([{ id: "aurora", malformed: true }]);
889 const setItem = vi.fn();
890 vi.stubGlobal("window", {
891 localStorage: {
892 getItem: () => storedThemes,
893 setItem,
894 },
895 });
896​
897 invalidateCustomThemes();
898 expect(() =>
899 installCustomTheme(
900 parseThemeFile({
901 version: THEME_FILE_VERSION,
902 id: "aurora",
903 name: "Aurora",
904 appearance: "light",
905 colors: { accent: "#5b6cff" },
906 }),
907 ),
908 ).toThrow('A theme named "Aurora" is already installed.');
909 expect(setItem).not.toHaveBeenCalled();
910​
911 vi.unstubAllGlobals();
912 invalidateCustomThemes();
913 });
914​
915 it("collapses duplicate raw entries when their theme is explicitly updated", () => {
916 const stored = new Map<string, string>();
917 const theme = {
918 id: "aurora",
919 label: "Aurora",
920 appearance: "light",
921 colors: { accent: "#5b6cff" },
922 };
923 const untouchedTheme = { id: "future", malformed: true, metadata: { version: 2 } };
924 stored.set(
925 CUSTOM_THEMES_STORAGE_KEY,
926 JSON.stringify([theme, { id: "aurora", malformed: true }, untouchedTheme]),
927 );
928 vi.stubGlobal("window", {
929 localStorage: {
930 getItem: (key: string) => stored.get(key) ?? null,
931 setItem: (key: string, value: string) => stored.set(key, value),
932 },
933 });
934​
935 invalidateCustomThemes();
936 const installedTheme = getCustomThemes()[0]!;
937 updateCustomTheme({
938 ...installedTheme,
939 label: "Aurora Night",
940 colors: { ...installedTheme.colors, accent: "hsl(263 70% 58%)" },
941 });
942​
943 const updatedLibrary = JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]");
944 expect(updatedLibrary.filter((entry: { id?: string }) => entry.id === "aurora")).toHaveLength(
945 1,
946 );
947 expect(updatedLibrary[0]).toMatchObject({
948 id: "aurora",
949 label: "Aurora Night",
950 colors: { accent: canonical("hsl(263 70% 58%)") },
951 });
952 expect(updatedLibrary[1]).toEqual(untouchedTheme);
953​
954 vi.unstubAllGlobals();
955 invalidateCustomThemes();
956 });
957});
958​
959describe("stored theme preferences", () => {
960 it("lets a configured half unlock an appearance the base theme lacks", () => {
961 // Light-only base: without halves, dark requests fall back to light.
962 const lightOnly = parseThemeFile({
963 version: THEME_FILE_VERSION,
964 id: "paper",
965 name: "Paper",
966 appearance: "light",
967 colors: { canvas: "#f8fbff" },
968 });
969 vi.stubGlobal("window", {
970 localStorage: {
971 getItem: (key: string) =>
972 key === CUSTOM_THEMES_STORAGE_KEY ? JSON.stringify([lightOnly]) : null,
973 },
974 });
975 invalidateCustomThemes();
976 try {
977 expect(resolveThemeAppearance("paper", true, true)).toBe("light");
978 const halves = { dark: GROVE_THEME.id };
979 expect(resolveThemeAppearance("paper", true, true, undefined, halves)).toBe("dark");
980 expect(resolveThemeAppearance("paper", false, false, "dark", halves)).toBe("dark");
981 expect(resolveDesktopTheme("paper", true, undefined, halves)).toBe("system");
982 } finally {
983 vi.unstubAllGlobals();
984 invalidateCustomThemes();
985 }
986 });
987​
988 it("resolves the legacy t3-chat-dark preference to dark T3 Chat", () => {
989 expect(getThemeDefinition("t3-chat-dark")).toBe(T3_CHAT_THEME);
990 expect(getThemePreferenceMode("t3-chat-dark")).toBe("dark");
991 expect(resolveThemeAppearance("t3-chat-dark", true, false)).toBe("dark");
992 expect(resolveDesktopTheme("t3-chat-dark", false)).toBe("dark");
993 expect(isKnownThemePreference("t3-chat-dark")).toBe(true);
994 });
995​
996 it("resolves legacy t3-prefixed ids onto the renamed themes", () => {
997 for (const [legacy, theme] of [
998 ["t3-grove", GROVE_THEME],
999 ["t3-ocean", OCEAN_THEME],
1000 ["t3-ember", EMBER_THEME],
1001 ["t3-iris", IRIS_THEME],
1002 ] as const) {
1003 expect(getThemeDefinition(legacy)).toBe(theme);
1004 expect(isKnownThemePreference(legacy)).toBe(true);
1005 expect(canonicalThemePreference(legacy)).toBe(theme.id);
1007 // The dark-variant alias keeps its raw form: it still carries a mode hint.
1008 expect(canonicalThemePreference("t3-chat-dark")).toBe("t3-chat-dark");
1009 // A stored mix that predates the rename resolves to the new ids.
1010 expect(parseThemeHalves(JSON.stringify({ light: "t3-ocean", dark: "t3-grove" }))).toEqual({
1011 light: OCEAN_THEME.id,
1012 dark: GROVE_THEME.id,
1013 });
1014 });
1015​
1016 it("recognizes only preferences the runtime can render", () => {
1017 for (const preference of ["light", "dark", "system", T3_CHAT_THEME.id, GROVE_THEME.id]) {
1018 expect(isKnownThemePreference(preference)).toBe(true);
1020 expect(isKnownThemePreference(`${GROVE_THEME.id}:dark`)).toBe(false);
1021 expect(isKnownThemePreference("missing-theme")).toBe(false);
1022 });
1023​
1024 it("decodes stored colors in memory without writing during reads", () => {
1025 const storedThemes = JSON.stringify([
1027 id: "aurora",
1028 label: "Aurora",
1029 appearance: "light",
1030 colors: { canvas: "#f8fbff", futureRole: "#123456", accent: "not-a-color" },
1031 variants: { dark: { canvas: "rgb(16 24 39)" } },
1032 },
1033 { id: "light", label: "Reserved", appearance: "light", colors: {} },
1034 { id: "aurora", label: "Duplicate", appearance: "dark", colors: {} },
1035 ]);
1036 const setItem = vi.fn();
1037 vi.stubGlobal("window", {
1038 localStorage: {
1039 getItem: (key: string) => (key === CUSTOM_THEMES_STORAGE_KEY ? storedThemes : null),
1040 setItem,
1041 },
1042 });
1043 invalidateCustomThemes();
1044​
1045 const themes = getCustomThemes();
1046 expect(themes).toHaveLength(1);
1047 expect(themes[0]).toMatchObject({
1048 id: "aurora",
1049 colors: { canvas: canonical("#f8fbff"), accent: getDefaultThemeColors("light").accent },
1050 });
1051 expect(getThemeModes(themes[0]!)).toEqual(["light", "dark"]);
1052 expect(getThemeColorsForMode(themes[0]!, "dark")?.canvas).toBe(canonical("rgb(16 24 39)"));
1053 expect(setItem).not.toHaveBeenCalled();
1054 expect(JSON.parse(storedThemes)[0].colors).toEqual({
1055 canvas: "#f8fbff",
1056 futureRole: "#123456",
1057 accent: "not-a-color",
1058 });
1059​
1060 vi.unstubAllGlobals();
1061 invalidateCustomThemes();
1062 });
1063});