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