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 resolveDesktopTheme,
19 resolveThemeAppearance,
20 serializeThemeFile,
21 subscribeToThemePreview,
22 subscribeToCustomThemes,
23 T3_CHAT_THEME,
24 EMBER_THEME,
25 GROVE_THEME,
26 IRIS_THEME,
27 OCEAN_THEME,
28 updateCustomTheme,
29 CUSTOM_THEMES_STORAGE_KEY,
30 createManagedThemeColors,
31 createVividThemeColors,
32 getDefaultThemeColors,
33 THEME_FILE_VERSION,
34} from "./themePalette";
35
36function contrastRatio(first: string, second: string): number {
37 const toRgb = (value: string) => {
38 const hex = value.slice(1);
39 return [0, 1, 2].map(
40 (channel) => Number.parseInt(hex.slice(channel * 2, channel * 2 + 2), 16) / 255,
41 );
42 };
43 const luminance = (value: string) =>
44 toRgb(value)
45 .map((channel) => (channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4))
46 .reduce((sum, channel, index) => sum + channel * [0.2126, 0.7152, 0.0722][index]!, 0);
47 const lighter = Math.max(luminance(first), luminance(second));
48 const darker = Math.min(luminance(first), luminance(second));
49 return (lighter + 0.05) / (darker + 0.05);
50}
51
52describe("theme files", () => {
53 it("derives a readable palette from extreme simple-editor colors", () => {
54 const light = createManagedThemeColors("light", "#111827", "#ffff00");
55 const dark = createManagedThemeColors("dark", "#ffffff", "#ffff00");
56 const darkDefaults = getDefaultThemeColors("dark");
57
58 expect(light.canvas).not.toBe("#111827");
59 expect(dark.canvas).not.toBe("#ffffff");
60 expect(contrastRatio(light.accent, light.canvas)).toBeGreaterThanOrEqual(4.5);
61 expect(contrastRatio(dark.accent, dark.canvas)).toBeGreaterThanOrEqual(4.5);
62 expect(contrastRatio(light.textMuted, light.canvas)).toBeGreaterThanOrEqual(4.5);
63 expect(contrastRatio(dark.textMuted, dark.canvas)).toBeGreaterThanOrEqual(4.5);
64 expect(contrastRatio(light.textMuted, light.canvas)).toBeLessThan(5.5);
65 expect(contrastRatio(dark.textMuted, dark.canvas)).toBeLessThan(5.5);
66 expect(contrastRatio(light.textMuted, light.canvas)).toBeCloseTo(4.705, 1);
67 expect(contrastRatio(dark.textMuted, dark.canvas)).toBeCloseTo(5.082, 1);
68 expect(light.secondaryLabel).toBe(light.textMuted);
69 expect(dark.secondaryLabel).toBe(dark.textMuted);
70 expect(contrastRatio(light.accentForeground, light.accent)).toBeGreaterThanOrEqual(4.5);
71 expect(contrastRatio(dark.accentForeground, dark.accent)).toBeGreaterThanOrEqual(4.5);
72 // Status colors fall back to T3 Code's standard red and amber rather than
73 // the flagship palette's, so no generated theme inherits a brand tint.
74 const channels = (value: string) =>
75 [1, 3, 5].map((index) => Number.parseInt(value.slice(index, index + 2), 16)) as [
76 number,
77 number,
78 number,
79 ];
80 for (const colors of [light, dark]) {
81 const [errorRed, errorGreen, errorBlue] = channels(colors.error);
82 // Red leads by a wide margin; the old default was a pink whose blue sat
83 // close behind its red.
84 expect(errorRed).toBeGreaterThan(errorGreen * 2);
85 expect(errorRed).toBeGreaterThan(errorBlue * 2);
86 expect(contrastRatio(colors.error, "#ffffff")).toBeGreaterThanOrEqual(2.5);
87 expect(contrastRatio(colors.errorForeground, colors.errorSurface)).toBeGreaterThanOrEqual(
88 4.5,
89 );
90 const [warnRed, warnGreen, warnBlue] = channels(colors.warning);
91 expect(warnRed).toBeGreaterThan(warnBlue);
92 expect(warnGreen).toBeGreaterThan(warnBlue);
93 }
94 expect(dark.error).not.toBe(darkDefaults.error);
95 });
96
97 it("derives readable, distinctive vivid palettes from exact seeds", () => {
98 const seeds: ReadonlyArray<["light" | "dark", string, string]> = [
99 ["light", "#f4f9f2", "#1d8a4e"],
100 ["dark", "#101a2c", "#4f8fe8"],
101 ["dark", "#211a23", "#df5398"],
102 ["light", "#fdf6ec", "#c2571b"],
103 // Inverted canvases: the palette follows the picked color, not the slot.
104 ["light", "#111827", "#8ab4f8"],
105 ["dark", "#f5ecf5", "#a84370"],
106 ];
107 for (const [appearance, canvas, accent] of seeds) {
108 const colors = createVividThemeColors(appearance, canvas, accent);
109 // Exact seeds are honored.
110 expect(colors.canvas).toBe(canvas);
111 expect(colors.accent).toBe(accent);
112 // Readability is solved per surface.
113 expect(contrastRatio(colors.text, colors.canvas)).toBeGreaterThanOrEqual(7);
114 expect(contrastRatio(colors.textMuted, colors.canvas)).toBeGreaterThanOrEqual(4.5);
115 expect(contrastRatio(colors.textMuted, colors.canvas)).toBeLessThan(5.5);
116 expect(colors.secondaryLabel).toBe(colors.textMuted);
117 expect(contrastRatio(colors.accentForeground, colors.accent)).toBeGreaterThanOrEqual(4.5);
118 expect(
119 contrastRatio(colors.messageActionForeground, colors.messageAction),
120 ).toBeGreaterThanOrEqual(4.5);
121 expect(contrastRatio(colors.messageForeground, colors.messageSurface)).toBeGreaterThanOrEqual(
122 4.5,
123 );
124 expect(contrastRatio(colors.secondaryForeground, colors.secondary)).toBeGreaterThanOrEqual(
125 4.5,
126 );
127 expect(contrastRatio(colors.sidebarForeground, colors.sidebar)).toBeGreaterThanOrEqual(4.5);
128 // The companion action is a distinct voice, not the accent again.
129 expect(colors.messageAction).not.toBe(colors.accent);
130 // Update family follows the theme, not the default palette.
131 expect(colors.update).toBe(accent);
132 }
133 });
134
135 it("keys status colors off the canvas, not the appearance slot", () => {
136 // Inverted seeds: a dark canvas in the light slot must still get the dark
137 // status pair, or the alert foreground lands on a dark surface unreadable.
138 const inverted = [
139 createVividThemeColors("light", "#111827", "#8ab4f8"),
140 createVividThemeColors("dark", "#f5ecf5", "#a84370"),
141 createManagedThemeColors("light", "#0d1117", "#69b1ff", { exactSeeds: true }),
142 createManagedThemeColors("dark", "#fdfdfd", "#c2571b", { exactSeeds: true }),
143 ];
144 for (const colors of inverted) {
145 expect(contrastRatio(colors.errorForeground, colors.errorSurface)).toBeGreaterThanOrEqual(
146 4.5,
147 );
148 expect(contrastRatio(colors.warningForeground, colors.warningSurface)).toBeGreaterThanOrEqual(
149 4.5,
150 );
151 }
152 });
153
154 it("merges a small user file onto the matching contrast-safe base palette", () => {
155 const theme = parseThemeFile({
156 version: THEME_FILE_VERSION,
157 name: "Ocean dusk",
158 appearance: "dark",
159 colors: {
160 canvas: "#07152f",
161 accent: "#67c2ff",
162 },
163 });
164
165 expect(theme).toMatchObject({
166 id: "ocean-dusk",
167 label: "Ocean dusk",
168 appearance: "dark",
169 colors: {
170 canvas: "#07152f",
171 accent: "#67c2ff",
172 placeholder: "#8f8699",
173 },
174 });
175 });
176
177 it("rejects unknown roles and invalid color values", () => {
178 expect(() =>
179 parseThemeFile({
180 version: THEME_FILE_VERSION,
181 name: "Broken",
182 appearance: "light",
183 colors: { background: "#ffffff" },
184 }),
185 ).toThrow('"background" is not a supported theme color role.');
186
187 expect(() =>
188 parseThemeFile({
189 version: THEME_FILE_VERSION,
190 name: "Broken",
191 appearance: "light",
192 colors: { accent: "var(--danger)" },
193 }),
194 ).toThrow('The color for "accent" must be a hex color');
195 });
196
197 it("serializes a theme back into the importable file shape", () => {
198 const serialized = serializeThemeFile(T3_CHAT_THEME);
199 expect(JSON.parse(serialized)).toMatchObject({
200 version: THEME_FILE_VERSION,
201 id: T3_CHAT_THEME.id,
202 name: T3_CHAT_THEME.label,
203 appearance: "light",
204 });
205 });
206
207 it("keeps sidebar artwork opt-in through theme files", () => {
208 const withoutArtwork = parseThemeFile({
209 version: THEME_FILE_VERSION,
210 name: "Plain sidebar",
211 appearance: "light",
212 colors: { accent: "#5b6cff" },
213 });
214 const withArtwork = parseThemeFile({
215 version: THEME_FILE_VERSION,
216 name: "Art sidebar",
217 appearance: "light",
218 colors: { accent: "#5b6cff" },
219 sidebarArtwork: true,
220 });
221
222 expect(withoutArtwork.sidebarArtwork).toBeUndefined();
223 expect(withArtwork.sidebarArtwork).toBe(true);
224 expect(JSON.parse(serializeThemeFile(withArtwork)).sidebarArtwork).toBe(true);
225 });
226
227 it("publishes sidebar artwork changes from the live theme preview", () => {
228 const listener = vi.fn();
229 const unsubscribe = subscribeToThemePreview(listener);
230 vi.stubGlobal("document", {
231 documentElement: {
232 classList: { toggle: vi.fn() },
233 dataset: {},
234 style: { removeProperty: vi.fn(), setProperty: vi.fn() },
235 },
236 });
237
238 applyThemeColorPreview(T3_CHAT_THEME.colors, "light", true);
239 expect(getThemePreviewSidebarArtwork()).toBe(true);
240 expect(listener).toHaveBeenCalledTimes(1);
241
242 applyThemePalette("system");
243 expect(getThemePreviewSidebarArtwork()).toBeNull();
244 expect(listener).toHaveBeenCalledTimes(2);
245
246 unsubscribe();
247 vi.unstubAllGlobals();
248 });
249
250 it("keeps optional light and dark palettes under one theme id", () => {
251 const theme = parseThemeFile({
252 version: THEME_FILE_VERSION,
253 id: "aurora",
254 name: "Aurora",
255 appearance: "light",
256 colors: { canvas: "#f8fbff", text: "#10243d" },
257 variants: {
258 dark: { canvas: "#101827", text: "#eef5ff" },
259 },
260 });
261
262 expect(getThemeModes(theme)).toEqual(["light", "dark"]);
263 expect(getThemeColorsForMode(theme, "dark")).toMatchObject({
264 canvas: "#101827",
265 text: "#eef5ff",
266 });
267 expect(getThemeModes(T3_CHAT_THEME)).toEqual(["light", "dark"]);
268 expect(resolveThemeAppearance(T3_CHAT_THEME.id, true, true)).toBe("dark");
269 expect(resolveDesktopTheme(T3_CHAT_THEME.id, true)).toBe("system");
270 expect(resolveThemeAppearance(T3_CHAT_THEME.id, false, false, "dark")).toBe("dark");
271 expect(resolveDesktopTheme(T3_CHAT_THEME.id, false, "dark")).toBe("dark");
272 expect(JSON.parse(serializeThemeFile(theme)).variants.dark).toMatchObject({
273 canvas: "#101827",
274 text: "#eef5ff",
275 });
276 });
277
278 it("keeps the T3 Chat palette faithful and readable", () => {
279 expect(T3_CHAT_THEME.colors).toMatchObject({
280 canvas: "#fdf7fd",
281 chrome: "#fdf7fd",
282 toolbarBorder: "#efbdeb",
283 toolbarControl: "#f3e6f5",
284 toolbarControlHover: "#eccfe3",
285 surfaceRaised: "#fdfafd",
286 input: "#e7c1dc",
287 focus: "#db2777",
288 messageSurface: "#f7def2",
289 codeBackground: "#f5ecf9",
290 codeForeground: "#673c8b",
291 accentSurface: "#f3e6f5",
292 sidebar: "#f2e1f4",
293 });
294 expect(T3_CHAT_THEME.variants?.dark).toMatchObject({
295 canvas: "#1f1a24",
296 chrome: "#1f1a24",
297 surface: "#29232d",
298 surfaceRaised: "#2c2631",
299 input: "#302029",
300 focus: "#db2777",
301 messageSurface: "#2b2431",
302 codeBackground: "#1f1a24",
303 sidebar: "#171018",
304 sidebarBorder: "#322028",
305 });
306
307 for (const mode of ["light", "dark"] as const) {
308 const colors = getThemeColorsForMode(T3_CHAT_THEME, mode)!;
309 expect(contrastRatio(colors.text, colors.canvas)).toBeGreaterThanOrEqual(7);
310 expect(contrastRatio(colors.textMuted, colors.canvas)).toBeGreaterThanOrEqual(4.5);
311 expect(contrastRatio(colors.messageForeground, colors.messageSurface)).toBeGreaterThanOrEqual(
312 4.5,
313 );
314 expect(contrastRatio(colors.secondaryForeground, colors.secondary)).toBeGreaterThanOrEqual(
315 4.5,
316 );
317 expect(contrastRatio(colors.sidebarForeground, colors.sidebar)).toBeGreaterThanOrEqual(4.5);
318 // The live light primary is intended for filled controls and clears the
319 // non-text UI-component threshold rather than normal-text AA.
320 expect(contrastRatio(colors.accentForeground, colors.accent)).toBeGreaterThanOrEqual(3);
321 }
322 });
323
324 it("includes the dual-mode maintainer themes", () => {
325 for (const theme of [T3_CHAT_THEME, GROVE_THEME, OCEAN_THEME, EMBER_THEME, IRIS_THEME]) {
326 expect(getThemeDefinition(theme.id)).toBe(theme);
327 expect(getThemeModes(theme)).toEqual(["light", "dark"]);
328 expect(theme.colors.accent).toMatch(/^#[0-9a-f]{6}$/i);
329 expect(theme.variants?.dark?.accent).toMatch(/^#[0-9a-f]{6}$/i);
330
331 for (const mode of ["light", "dark"] as const) {
332 const colors = getThemeColorsForMode(theme, mode);
333 expect(colors).not.toBeNull();
334 expect(contrastRatio(colors!.text, colors!.canvas)).toBeGreaterThanOrEqual(4.5);
335 expect(contrastRatio(colors!.textMuted, colors!.canvas)).toBeGreaterThanOrEqual(4.5);
336 if (theme !== T3_CHAT_THEME) {
337 expect(contrastRatio(colors!.textMuted, colors!.canvas)).toBeLessThan(5.5);
338 expect(contrastRatio(colors!.textMuted, colors!.canvas)).toBeCloseTo(
339 mode === "dark" ? 5.082 : 4.705,
340 1,
341 );
342 }
343 expect(contrastRatio(colors!.accentForeground, colors!.accent)).toBeGreaterThanOrEqual(
344 theme === T3_CHAT_THEME ? 3 : 4.5,
345 );
346 expect(
347 contrastRatio(colors!.toolbarControlForeground, colors!.toolbarControl),
348 ).toBeGreaterThanOrEqual(4.5);
349 expect(
350 contrastRatio(colors!.messageForeground, colors!.messageSurface),
351 ).toBeGreaterThanOrEqual(4.5);
352 expect(
353 contrastRatio(colors!.messageActionForeground, colors!.messageAction),
354 ).toBeGreaterThanOrEqual(theme === T3_CHAT_THEME ? 3 : 4.5);
355 }
356 }
357 });
358
359 it("rejects a variant that repeats the base appearance", () => {
360 expect(() =>
361 parseThemeFile({
362 version: THEME_FILE_VERSION,
363 name: "Duplicate light",
364 appearance: "light",
365 colors: { canvas: "#f8fbff" },
366 variants: { light: { canvas: "#101827" } },
367 }),
368 ).toThrow('Theme variants must not repeat the base appearance "light".');
369 });
370
371 it("keeps a single-mode theme on its only palette", () => {
372 const theme = parseThemeFile({
373 version: THEME_FILE_VERSION,
374 id: "midnight-slate",
375 name: "Midnight Slate",
376 appearance: "dark",
377 colors: { canvas: "#111827", messageAction: "#2563eb" },
378 });
379
380 expect(getThemeModes(theme)).toEqual(["dark"]);
381 expect(getThemeColorsForMode(theme, "dark")).toMatchObject({ canvas: "#111827" });
382 expect(getThemeColorsForMode(theme, "light")).toBeNull();
383 });
384
385 it("invalidates cached themes when another tab clears localStorage", () => {
386 let storedThemes: string | null = JSON.stringify([
387 {
388 id: "ocean-dusk",
389 label: "Ocean dusk",
390 appearance: "dark",
391 colors: { canvas: "#07152f" },
392 },
393 ]);
394 let storageHandler: ((event: StorageEvent) => void) | undefined;
395 vi.stubGlobal("window", {
396 addEventListener: (type: string, listener: (event: StorageEvent) => void) => {
397 if (type === "storage") storageHandler = listener;
398 },
399 removeEventListener: vi.fn(),
400 localStorage: {
401 getItem: (key: string) => (key === CUSTOM_THEMES_STORAGE_KEY ? storedThemes : null),
402 },
403 });
404
405 invalidateCustomThemes();
406 expect(getCustomThemes()).toHaveLength(1);
407 const listener = vi.fn();
408 const unsubscribe = subscribeToCustomThemes(listener);
409
410 storedThemes = null;
411 storageHandler?.({ key: null } as StorageEvent);
412
413 expect(listener).toHaveBeenCalledTimes(1);
414 expect(getCustomThemes()).toEqual([]);
415 unsubscribe();
416 invalidateCustomThemes();
417 vi.unstubAllGlobals();
418 });
419
420 it("updates a personal theme without changing its id", () => {
421 const stored = new Map<string, string>();
422 vi.stubGlobal("window", {
423 localStorage: {
424 getItem: (key: string) => stored.get(key) ?? null,
425 setItem: (key: string, value: string) => stored.set(key, value),
426 },
427 });
428
429 invalidateCustomThemes();
430 const createdTheme = installCustomTheme(
431 parseThemeFile({
432 version: THEME_FILE_VERSION,
433 id: "aurora",
434 name: "Aurora",
435 appearance: "light",
436 colors: { canvas: "#f8fbff", accent: "#5b6cff" },
437 sidebarArtwork: true,
438 }),
439 );
440 const updatedTheme = updateCustomTheme({
441 ...createdTheme,
442 label: "Aurora Night",
443 colors: { ...createdTheme.colors, accent: "#7c3aed" },
444 });
445
446 expect(updatedTheme).toMatchObject({
447 id: "aurora",
448 label: "Aurora Night",
449 sidebarArtwork: true,
450 });
451 invalidateCustomThemes();
452 expect(getCustomThemes()).toEqual([updatedTheme]);
453 expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")[0]).toMatchObject({
454 id: "aurora",
455 label: "Aurora Night",
456 sidebarArtwork: true,
457 });
458
459 vi.unstubAllGlobals();
460 invalidateCustomThemes();
461 });
462});
463
464describe("stored theme preferences", () => {
465 it("lets a configured half unlock an appearance the base theme lacks", () => {
466 // Light-only base: without halves, dark requests fall back to light.
467 const lightOnly = parseThemeFile({
468 version: THEME_FILE_VERSION,
469 id: "paper",
470 name: "Paper",
471 appearance: "light",
472 colors: { canvas: "#f8fbff" },
473 });
474 vi.stubGlobal("window", {
475 localStorage: {
476 getItem: (key: string) =>
477 key === CUSTOM_THEMES_STORAGE_KEY ? JSON.stringify([lightOnly]) : null,
478 },
479 });
480 invalidateCustomThemes();
481 try {
482 expect(resolveThemeAppearance("paper", true, true)).toBe("light");
483 const halves = { dark: GROVE_THEME.id };
484 expect(resolveThemeAppearance("paper", true, true, undefined, halves)).toBe("dark");
485 expect(resolveThemeAppearance("paper", false, false, "dark", halves)).toBe("dark");
486 expect(resolveDesktopTheme("paper", true, undefined, halves)).toBe("system");
487 } finally {
488 vi.unstubAllGlobals();
489 invalidateCustomThemes();
490 }
491 });
492
493 it("resolves the legacy t3-chat-dark preference to dark T3 Chat", () => {
494 expect(getThemeDefinition("t3-chat-dark")).toBe(T3_CHAT_THEME);
495 expect(getThemePreferenceMode("t3-chat-dark")).toBe("dark");
496 expect(resolveThemeAppearance("t3-chat-dark", true, false)).toBe("dark");
497 expect(resolveDesktopTheme("t3-chat-dark", false)).toBe("dark");
498 expect(isKnownThemePreference("t3-chat-dark")).toBe(true);
499 });
500
501 it("resolves legacy t3-prefixed ids onto the renamed themes", () => {
502 for (const [legacy, theme] of [
503 ["t3-grove", GROVE_THEME],
504 ["t3-ocean", OCEAN_THEME],
505 ["t3-ember", EMBER_THEME],
506 ["t3-iris", IRIS_THEME],
507 ] as const) {
508 expect(getThemeDefinition(legacy)).toBe(theme);
509 expect(isKnownThemePreference(legacy)).toBe(true);
510 expect(canonicalThemePreference(legacy)).toBe(theme.id);
511 }
512 // The dark-variant alias keeps its raw form: it still carries a mode hint.
513 expect(canonicalThemePreference("t3-chat-dark")).toBe("t3-chat-dark");
514 // A stored mix that predates the rename resolves to the new ids.
515 expect(parseThemeHalves(JSON.stringify({ light: "t3-ocean", dark: "t3-grove" }))).toEqual({
516 light: OCEAN_THEME.id,
517 dark: GROVE_THEME.id,
518 });
519 });
520
521 it("recognizes only preferences the runtime can render", () => {
522 for (const preference of ["light", "dark", "system", T3_CHAT_THEME.id, GROVE_THEME.id]) {
523 expect(isKnownThemePreference(preference)).toBe(true);
524 }
525 expect(isKnownThemePreference(`${GROVE_THEME.id}:dark`)).toBe(false);
526 expect(isKnownThemePreference("missing-theme")).toBe(false);
527 });
528
529 it("keeps stored themes with unknown roles and drops invalid entries", () => {
530 vi.stubGlobal("window", {
531 localStorage: {
532 getItem: (key: string) =>
533 key === CUSTOM_THEMES_STORAGE_KEY
534 ? JSON.stringify([
535 {
536 id: "aurora",
537 label: "Aurora",
538 appearance: "light",
539 colors: { canvas: "#f8fbff", futureRole: "#123456", accent: "not-a-color" },
540 variants: { light: { canvas: "#101827" } },
541 },
542 { id: "light", label: "Reserved", appearance: "light", colors: {} },
543 { id: "aurora", label: "Duplicate", appearance: "dark", colors: {} },
544 ])
545 : null,
546 },
547 });
548 invalidateCustomThemes();
549
550 const themes = getCustomThemes();
551 expect(themes).toHaveLength(1);
552 expect(themes[0]).toMatchObject({
553 id: "aurora",
554 colors: { canvas: "#f8fbff", accent: getDefaultThemeColors("light").accent },
555 });
556 // The variant shadowing the base appearance is dropped so the theme
557 // round-trips through parseThemeFile on export.
558 expect(getThemeModes(themes[0]!)).toEqual(["light"]);
559
560 vi.unstubAllGlobals();
561 invalidateCustomThemes();
562 });
563});