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

themePalette.test.ts

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