Open History to see the last commit
1import { describe, expect, it, vi } from "vite-plus/test";
2import { converter } from "culori/fn";
3import { BUILT_IN_THEMES } from "@t3tools/shared/themePalettes";
4
5import {
6 getThemeColorsForMode,
7 getThemeModes,
8 getCustomThemes,
9 getStandardThemeColors,
10 getStoredCustomThemeCollection,
11 invalidateCustomThemes,
12 installCustomTheme,
13 parseThemeFile,
14 removeCustomTheme,
15 replaceCustomThemeCollection,
16 resolveDesktopTheme,
17 resolveThemeAppearance,
18 serializeThemeFile,
19 T3_CHAT_THEME,
20 GROVE_THEME,
21 updateCustomTheme,
22 updateThemeColorFamily,
23 CUSTOM_THEMES_STORAGE_KEY,
24 createVividThemeColors,
25 getDefaultThemeColors,
26 themeColorToHex,
27 toCanonicalThemeColor,
28 THEME_FILE_VERSION,
29} from "./themePalette";
30
31function asHex(value: string): string {
32 const hex = themeColorToHex(value);
33 if (!hex) throw new Error(`Expected a theme color, received ${value}`);
34 return hex.slice(0, 7);
35}
36
37function canonical(value: string): string {
38 const color = toCanonicalThemeColor(value);
39 if (!color) throw new Error(`Expected a theme color, received ${value}`);
40 return color;
41}
42
43function contrastRatio(first: string, second: string): number {
44 const toRgb = (value: string) => {
45 const hex = asHex(value).slice(1);
46 return [0, 1, 2].map(
47 (channel) => Number.parseInt(hex.slice(channel * 2, channel * 2 + 2), 16) / 255,
48 );
49 };
50 const luminance = (value: string) =>
51 toRgb(value)
52 .map((channel) => (channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4))
53 .reduce((sum, channel, index) => sum + channel * [0.2126, 0.7152, 0.0722][index]!, 0);
54 const lighter = Math.max(luminance(first), luminance(second));
55 const darker = Math.min(luminance(first), luminance(second));
56 return (lighter + 0.05) / (darker + 0.05);
57}
58
59describe("theme files", () => {
60 it("keeps built-in and standard search pairs readable and distinct from inline code", () => {
61 const toOklab = converter("oklab");
62 const distance = (first: string, second: string) => {
63 const a = toOklab(first)!;
64 const b = toOklab(second)!;
65 return Math.hypot(a.l - b.l, a.a - b.a, a.b - b.b);
66 };
67 const palettes = [
68 getStandardThemeColors("light"),
69 getStandardThemeColors("dark"),
70 ...BUILT_IN_THEMES.flatMap((theme) => [theme.colors, ...Object.values(theme.variants ?? {})]),
71 ];
72 for (const colors of palettes) {
73 expect(
74 contrastRatio(colors.searchMatchForeground, colors.searchMatchBackground),
75 ).toBeGreaterThanOrEqual(4.5);
76 expect(
77 contrastRatio(colors.searchMatchActiveForeground, colors.searchMatchActiveBackground),
78 ).toBeGreaterThanOrEqual(4.5);
79 expect(
80 distance(colors.searchMatchBackground, colors.searchMatchActiveBackground),
81 ).toBeGreaterThan(0.14);
82 for (const background of [colors.muted, colors.messageSurface, colors.codeBackground]) {
83 expect(distance(colors.searchMatchBackground, background)).toBeGreaterThan(0.08);
84 expect(distance(colors.searchMatchActiveBackground, background)).toBeGreaterThan(0.08);
85 }
86 }
87 });
88
89 it("round-trips custom search colours and fills them in for older theme files", () => {
90 const legacy = parseThemeFile({
91 version: THEME_FILE_VERSION,
92 name: "Legacy",
93 appearance: "dark",
94 colors: { canvas: "#101010" },
95 });
96 expect(legacy.colors.searchMatchBackground).toBe(
97 getDefaultThemeColors("dark").searchMatchBackground,
98 );
99 const theme = parseThemeFile({
100 version: THEME_FILE_VERSION,
101 name: "Search",
102 appearance: "dark",
103 colors: {
104 searchMatchBackground: "#224466",
105 searchMatchForeground: "#ffffff",
106 searchMatchActiveBackground: "#aaddff",
107 searchMatchActiveForeground: "#112233",
108 },
109 variants: { light: { searchMatchBackground: "#ddeeff", searchMatchForeground: "#112233" } },
110 });
111 const restored = parseThemeFile(JSON.parse(serializeThemeFile(theme)));
112 expect(restored.colors).toEqual(theme.colors);
113 expect(restored.variants).toEqual(theme.variants);
114 });
115
116 it.each(["searchMatchBackground", "searchMatchActiveBackground"] as const)(
117 "editing %s derives readable text without changing the other match or warning colours",
118 (role) => {
119 const original = getDefaultThemeColors("dark");
120 const foreground =
121 role === "searchMatchBackground" ? "searchMatchForeground" : "searchMatchActiveForeground";
122 for (const value of ["#ffffff", "#000000", "#33669980"]) {
123 const updated = updateThemeColorFamily("dark", original, role, value);
124 expect(contrastRatio(updated[foreground], updated[role])).toBeGreaterThanOrEqual(4.5);
125 for (const key of Object.keys(original) as Array<keyof typeof original>) {
126 if (key !== role && key !== foreground) expect(updated[key]).toBe(original[key]);
127 }
128 }
129 },
130 );
131
132 it("derives readable, distinctive vivid palettes from exact seeds", () => {
133 const seeds: ReadonlyArray<["light" | "dark", string, string]> = [
134 ["light", "#f4f9f2", "#1d8a4e"],
135 ["dark", "#101a2c", "#4f8fe8"],
136 ["dark", "#211a23", "#df5398"],
137 ["light", "#fdf6ec", "#c2571b"],
138 ["light", "#111827", "#8ab4f8"],
139 ["dark", "#f5ecf5", "#a84370"],
140 ];
141 const channels = (value: string) =>
142 [1, 3, 5].map((index) => Number.parseInt(asHex(value).slice(index, index + 2), 16)) as [
143 number,
144 number,
145 number,
146 ];
147 for (const [appearance, canvas, accent] of seeds) {
148 const colors = createVividThemeColors(appearance, canvas, accent);
149 expect(colors.canvas).toMatch(/^oklch\(/);
150 expect(colors.accent).toMatch(/^oklch\(/);
151 expect(asHex(colors.canvas)).toBe(canvas);
152 expect(asHex(colors.accent)).toBe(accent);
153 expect(contrastRatio(colors.text, colors.canvas)).toBeGreaterThanOrEqual(7);
154 expect(contrastRatio(colors.textMuted, colors.canvas)).toBeGreaterThanOrEqual(4.5);
155 expect(contrastRatio(colors.textMuted, colors.canvas)).toBeLessThan(5.5);
156 expect(contrastRatio(colors.mutedForeground, colors.muted)).toBeGreaterThanOrEqual(4.5);
157 expect(contrastRatio(colors.mutedForeground, colors.muted)).toBeLessThan(
158 contrastRatio(colors.text, colors.muted),
159 );
160 expect(contrastRatio(colors.placeholder, colors.surfaceRaised)).toBeGreaterThanOrEqual(4.5);
161 expect(contrastRatio(colors.placeholder, colors.surfaceRaised)).toBeLessThan(
162 contrastRatio(colors.text, colors.surfaceRaised),
163 );
164 expect(colors.secondaryLabel).toBe(colors.textMuted);
165 expect(contrastRatio(colors.accentForeground, colors.accent)).toBeGreaterThanOrEqual(4.5);
166 expect(
167 contrastRatio(colors.searchMatchForeground, colors.searchMatchBackground),
168 ).toBeGreaterThanOrEqual(4.5);
169 expect(
170 contrastRatio(colors.searchMatchActiveForeground, colors.searchMatchActiveBackground),
171 ).toBeGreaterThanOrEqual(4.5);
172 expect(
173 contrastRatio(colors.messageActionForeground, colors.messageAction),
174 ).toBeGreaterThanOrEqual(4.5);
175 expect(contrastRatio(colors.messageForeground, colors.messageSurface)).toBeGreaterThanOrEqual(
176 4.5,
177 );
178 expect(contrastRatio(colors.secondaryForeground, colors.secondary)).toBeGreaterThanOrEqual(
179 4.5,
180 );
181 expect(contrastRatio(colors.sidebarForeground, colors.sidebar)).toBeGreaterThanOrEqual(4.5);
182 expect(colors.messageAction).not.toBe(colors.accent);
183 expect(asHex(colors.update)).toBe(accent);
184 const [errorRed, errorGreen, errorBlue] = channels(colors.error);
185 expect(errorRed).toBeGreaterThan(errorGreen * 2);
186 expect(errorRed).toBeGreaterThan(errorBlue * 2);
187 expect(contrastRatio(colors.error, "#ffffff")).toBeGreaterThanOrEqual(2.5);
188 expect(contrastRatio(colors.errorForeground, colors.errorSurface)).toBeGreaterThanOrEqual(
189 4.5,
190 );
191 const [warnRed, warnGreen, warnBlue] = channels(colors.warning);
192 expect(warnRed).toBeGreaterThan(warnBlue);
193 expect(warnGreen).toBeGreaterThan(warnBlue);
194 }
195 });
196
197 it("decodes literal CSS color formats into OKLCH without dropping alpha", () => {
198 const theme = parseThemeFile({
199 version: THEME_FILE_VERSION,
200 name: "Translucent",
201 appearance: "light",
202 colors: {
203 canvas: "oklch(62% 0.2 280deg / 50%)",
204 accent: "#abcd",
205 focus: "rgb(10 20 30 / 50%)",
206 error: "hsl(350 80% 50%)",
207 warning: "hwb(45 10% 20%)",
208 update: "lab(60% 40 30)",
209 messageAction: "lch(60% 50 120)",
210 sidebar: "oklab(0.6 0.1 -0.1)",
211 terminalCursor: "color(display-p3 0.8 0.2 0.3)",
212 terminalSelection: "rebeccapurple",
213 terminalScrollbar: "transparent",
214 terminalScrollbarHover: "rgb(10 20 30 / none)",
215 },
216 });
217
218 expect(theme.colors.canvas).toBe("oklch(0.62 0.2 280 / 0.5)");
219 expect(theme.colors.accent).toBe(canonical("#abcd"));
220 expect(themeColorToHex(theme.colors.accent)).toBe("#aabbccdd");
221 expect(themeColorToHex(theme.colors.focus)).toBe("#0a141e80");
222 expect(themeColorToHex(theme.colors.terminalSelection)).toBe("#663399");
223 expect(theme.colors.terminalScrollbar).toBe("oklch(0 0 0 / 0)");
224 expect(themeColorToHex(theme.colors.terminalScrollbarHover)).toBe("#0a141e00");
225 for (const role of [
226 "error",
227 "warning",
228 "update",
229 "messageAction",
230 "sidebar",
231 "terminalCursor",
232 ] as const) {
233 expect(theme.colors[role]).toMatch(/^oklch\(/);
234 }
235 });
236
237 it("gamut maps extreme finite OKLCH chroma from theme files", () => {
238 const theme = parseThemeFile({
239 version: THEME_FILE_VERSION,
240 name: "Extreme chroma",
241 appearance: "light",
242 colors: { accent: "oklch(0.5 1e303 0)" },
243 });
244
245 expect(theme.colors.accent).toBe("oklch(0.5 1e+303 0)");
246 expect(themeColorToHex(theme.colors.accent)).toBe("#b5005e");
247 });
248
249 it("keeps optional light and dark palettes under one theme id", () => {
250 const theme = parseThemeFile({
251 version: THEME_FILE_VERSION,
252 id: "aurora",
253 name: "Aurora",
254 appearance: "light",
255 colors: { canvas: "#f8fbff", text: "#10243d" },
256 variants: {
257 dark: { canvas: "#101827", text: "#eef5ff" },
258 },
259 });
260
261 expect(getThemeModes(theme)).toEqual(["light", "dark"]);
262 expect(getThemeColorsForMode(theme, "dark")).toMatchObject({
263 canvas: canonical("#101827"),
264 text: canonical("#eef5ff"),
265 });
266 expect(getThemeModes(T3_CHAT_THEME)).toEqual(["light", "dark"]);
267 expect(resolveThemeAppearance(T3_CHAT_THEME.id, true, true)).toBe("dark");
268 expect(resolveDesktopTheme(T3_CHAT_THEME.id, true)).toBe("system");
269 expect(resolveThemeAppearance(T3_CHAT_THEME.id, false, false, "dark")).toBe("dark");
270 expect(resolveDesktopTheme(T3_CHAT_THEME.id, false, "dark")).toBe("dark");
271 expect(JSON.parse(serializeThemeFile(theme)).variants.dark).toMatchObject({
272 canvas: canonical("#101827"),
273 text: canonical("#eef5ff"),
274 });
275 });
276
277 it("preserves valid imported-theme collections and drops malformed metadata", () => {
278 vi.stubGlobal("window", {
279 localStorage: {
280 getItem: (key: string) =>
281 key === CUSTOM_THEMES_STORAGE_KEY
282 ? JSON.stringify([
283 {
284 id: "github-dark",
285 label: "GitHub Dark",
286 appearance: "dark",
287 colors: { canvas: "#0d1117" },
288 collection: { id: "open-vsx:github.github-vscode-theme", label: "GitHub Theme" },
289 },
290 {
291 id: "github-light",
292 label: "GitHub Light",
293 appearance: "light",
294 colors: { canvas: "#ffffff" },
295 collection: { id: "bad collection id", label: "GitHub Theme" },
296 },
297 ])
298 : null,
299 },
300 });
301
302 invalidateCustomThemes();
303 expect(getCustomThemes()).toMatchObject([
304 { collection: { id: "open-vsx:github.github-vscode-theme", label: "GitHub Theme" } },
305 { id: "github-light" },
306 ]);
307 expect(getCustomThemes()[1]).not.toHaveProperty("collection");
308
309 vi.unstubAllGlobals();
310 invalidateCustomThemes();
311 });
312
313 it("atomically replaces an imported collection and removes stale variants", () => {
314 const collection = { id: "open-vsx:demo.theme", label: "Demo Theme" };
315 const personalTheme = {
316 id: "personal",
317 label: "Personal",
318 appearance: "dark",
319 colors: { canvas: "#111111", futureRole: "hsl(10 20% 30%)" },
320 futureMetadata: { version: 2 },
321 };
322 const stored = new Map<string, string>([
323 [
324 CUSTOM_THEMES_STORAGE_KEY,
325 JSON.stringify([
326 personalTheme,
327 {
328 id: "old-light",
329 label: "Old Light",
330 appearance: "light",
331 colors: { canvas: "#ffffff" },
332 collection,
333 },
334 {
335 id: "removed-dark",
336 label: "Removed Dark",
337 appearance: "dark",
338 colors: { canvas: "#000000" },
339 collection,
340 },
341 ]),
342 ],
343 ]);
344 const setItem = vi.fn((key: string, value: string) => stored.set(key, value));
345 vi.stubGlobal("window", {
346 localStorage: {
347 getItem: (key: string) => stored.get(key) ?? null,
348 setItem,
349 },
350 });
351
352 invalidateCustomThemes();
353 const expectedCollection = getStoredCustomThemeCollection(collection.id);
354 getCustomThemes();
355 const concurrentlyAddedTheme = {
356 id: "other-tab",
357 label: "Other Tab",
358 appearance: "dark",
359 colors: { canvas: "#222222" },
360 };
361 stored.set(
362 CUSTOM_THEMES_STORAGE_KEY,
363 JSON.stringify([
364 ...JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]"),
365 concurrentlyAddedTheme,
366 ]),
367 );
368 const replacement = [
369 {
370 ...parseThemeFile({
371 version: THEME_FILE_VERSION,
372 id: "old-light",
373 name: "New Light",
374 appearance: "light",
375 colors: { canvas: "#fafafa" },
376 }),
377 collection,
378 },
379 {
380 ...parseThemeFile({
381 version: THEME_FILE_VERSION,
382 id: "new-dark",
383 name: "New Dark",
384 appearance: "dark",
385 colors: { canvas: "#101010" },
386 }),
387 collection,
388 },
389 ];
390
391 expect(
392 replaceCustomThemeCollection(collection.id, replacement, { expectedCollection }),
393 ).toEqual(replacement);
394 expect(getCustomThemes().map((theme) => theme.id)).toEqual([
395 "personal",
396 "old-light",
397 "new-dark",
398 "other-tab",
399 ]);
400 expect(setItem).toHaveBeenCalledTimes(1);
401 expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")[0]).toEqual(personalTheme);
402
403 vi.unstubAllGlobals();
404 invalidateCustomThemes();
405 });
406
407 it("canonicalizes explicit writes without migrating untouched themes", () => {
408 const stored = new Map<string, string>();
409 const untouchedTheme = {
410 id: "legacy",
411 label: "Legacy",
412 appearance: "dark",
413 colors: { accent: "#5b6cff", futureRole: "hsl(10 20% 30%)" },
414 futureMetadata: { version: 2 },
415 };
416 stored.set(CUSTOM_THEMES_STORAGE_KEY, JSON.stringify([untouchedTheme]));
417 vi.stubGlobal("window", {
418 localStorage: {
419 getItem: (key: string) => stored.get(key) ?? null,
420 setItem: (key: string, value: string) => stored.set(key, value),
421 },
422 });
423
424 invalidateCustomThemes();
425 const createdTheme = installCustomTheme(
426 parseThemeFile({
427 version: THEME_FILE_VERSION,
428 id: "aurora",
429 name: "Aurora",
430 appearance: "light",
431 colors: { canvas: "#f8fbff", accent: "#5b6cff" },
432 sidebarArtwork: true,
433 }),
434 );
435 const updatedTheme = updateCustomTheme({
436 ...createdTheme,
437 label: "Aurora Night",
438 colors: { ...createdTheme.colors, accent: "hsl(263 70% 58%)" },
439 });
440
441 expect(updatedTheme).toMatchObject({
442 id: "aurora",
443 label: "Aurora Night",
444 colors: { accent: canonical("hsl(263 70% 58%)") },
445 });
446 expect(updatedTheme).not.toHaveProperty("sidebarArtwork");
447 const storedThemes = JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]");
448 expect(storedThemes[0]).toEqual(untouchedTheme);
449 expect(storedThemes[1]).toMatchObject({
450 id: "aurora",
451 label: "Aurora Night",
452 colors: { accent: canonical("hsl(263 70% 58%)") },
453 });
454 expect(storedThemes[1]).not.toHaveProperty("sidebarArtwork");
455 invalidateCustomThemes();
456 expect(getCustomThemes().find((theme) => theme.id === "aurora")).toMatchObject({
457 id: "aurora",
458 colors: { accent: canonical("hsl(263 70% 58%)") },
459 });
460 removeCustomTheme("aurora");
461 expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")).toEqual([untouchedTheme]);
462
463 vi.unstubAllGlobals();
464 invalidateCustomThemes();
465 });
466
467 it("writes from the cached raw snapshot without risking a destructive reread", () => {
468 const legacyTheme = {
469 id: "legacy",
470 label: "Legacy",
471 appearance: "dark",
472 colors: { accent: "#5b6cff" },
473 futureMetadata: true,
474 };
475 let storedThemes = JSON.stringify([legacyTheme]);
476 let readCount = 0;
477 const setItem = vi.fn((_key: string, value: string) => {
478 storedThemes = value;
479 });
480 vi.stubGlobal("window", {
481 localStorage: {
482 getItem: () => {
483 readCount += 1;
484 if (readCount > 1) throw new Error("transient read failure");
485 return storedThemes;
486 },
487 setItem,
488 },
489 });
490
491 invalidateCustomThemes();
492 expect(getCustomThemes()).toHaveLength(1);
493 installCustomTheme(
494 parseThemeFile({
495 version: THEME_FILE_VERSION,
496 id: "aurora",
497 name: "Aurora",
498 appearance: "light",
499 colors: { accent: "hsl(263 70% 58%)" },
500 }),
501 );
502
503 expect(readCount).toBe(1);
504 expect(setItem).toHaveBeenCalledOnce();
505 expect(JSON.parse(storedThemes)[0]).toEqual(legacyTheme);
506
507 vi.unstubAllGlobals();
508 invalidateCustomThemes();
509 });
510
511 it("refuses to overwrite a theme library that could not be read", () => {
512 const setItem = vi.fn();
513 vi.stubGlobal("window", {
514 localStorage: {
515 getItem: () => {
516 throw new Error("storage unavailable");
517 },
518 setItem,
519 },
520 });
521
522 invalidateCustomThemes();
523 expect(getCustomThemes()).toEqual([]);
524 expect(() =>
525 installCustomTheme(
526 parseThemeFile({
527 version: THEME_FILE_VERSION,
528 id: "aurora",
529 name: "Aurora",
530 appearance: "light",
531 colors: { accent: "#5b6cff" },
532 }),
533 ),
534 ).toThrow(`Failed to read the theme library from ${CUSTOM_THEMES_STORAGE_KEY}.`);
535 expect(setItem).not.toHaveBeenCalled();
536
537 vi.unstubAllGlobals();
538 invalidateCustomThemes();
539 });
540});
541
542describe("stored theme preferences", () => {
543 it("lets a configured half unlock an appearance the base theme lacks", () => {
544 const lightOnly = parseThemeFile({
545 version: THEME_FILE_VERSION,
546 id: "paper",
547 name: "Paper",
548 appearance: "light",
549 colors: { canvas: "#f8fbff" },
550 });
551 vi.stubGlobal("window", {
552 localStorage: {
553 getItem: (key: string) =>
554 key === CUSTOM_THEMES_STORAGE_KEY ? JSON.stringify([lightOnly]) : null,
555 },
556 });
557 invalidateCustomThemes();
558 try {
559 expect(resolveThemeAppearance("paper", true, true)).toBe("light");
560 const halves = { dark: GROVE_THEME.id };
561 expect(resolveThemeAppearance("paper", true, true, undefined, halves)).toBe("dark");
562 expect(resolveThemeAppearance("paper", false, false, "dark", halves)).toBe("dark");
563 expect(resolveDesktopTheme("paper", true, undefined, halves)).toBe("system");
564 } finally {
565 vi.unstubAllGlobals();
566 invalidateCustomThemes();
567 }
568 });
569
570 it("decodes stored colors in memory without writing during reads", () => {
571 const storedThemes = JSON.stringify([
572 {
573 id: "aurora",
574 label: "Aurora",
575 appearance: "light",
576 colors: { canvas: "#f8fbff", futureRole: "#123456", accent: "not-a-color" },
577 variants: { dark: { canvas: "rgb(16 24 39)" } },
578 },
579 { id: "light", label: "Reserved", appearance: "light", colors: {} },
580 { id: "aurora", label: "Duplicate", appearance: "dark", colors: {} },
581 ]);
582 const setItem = vi.fn();
583 vi.stubGlobal("window", {
584 localStorage: {
585 getItem: (key: string) => (key === CUSTOM_THEMES_STORAGE_KEY ? storedThemes : null),
586 setItem,
587 },
588 });
589 invalidateCustomThemes();
590
591 const themes = getCustomThemes();
592 expect(themes).toHaveLength(1);
593 expect(themes[0]).toMatchObject({
594 id: "aurora",
595 colors: { canvas: canonical("#f8fbff"), accent: getDefaultThemeColors("light").accent },
596 });
597 expect(getThemeModes(themes[0]!)).toEqual(["light", "dark"]);
598 expect(getThemeColorsForMode(themes[0]!, "dark")?.canvas).toBe(canonical("rgb(16 24 39)"));
599 expect(setItem).not.toHaveBeenCalled();
600 expect(JSON.parse(storedThemes)[0].colors).toEqual({
601 canvas: "#f8fbff",
602 futureRole: "#123456",
603 accent: "not-a-color",
604 });
605
606 vi.unstubAllGlobals();
607 invalidateCustomThemes();
608 });
609});