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