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

themePalette.test.ts

795 lines27.7 KB

1import { describe, expect, it, vi } from "vite-plus/test";
2import { converter } from "culori/fn";
3import { BUILT_IN_THEMES } from "@t3tools/shared/themePalettes";
4​
5import { CONTEXT_CHIP_ACCENTS, contextChipColorVariable } from "./lib/contextChipAccents";
6import { appAtomRegistry } from "./rpc/atomRegistry";
7​
8import {
9 applyThemePalette,
10 canonicalThemePreference,
11 contextChipVariables,
12 getThemeDefinition,
13 getThemeColorsForMode,
14 getThemeModes,
15 getCustomThemes,
16 getStandardThemeColors,
17 getStoredCustomThemeCollection,
18 invalidateCustomThemes,
19 installCustomTheme,
20 parseThemeFile,
21 parseThemeHalves,
22 publishedThemeDefinitions,
23 removeCustomTheme,
24 replaceCustomThemeCollection,
25 resolveDesktopTheme,
26 resolveThemeAppearance,
27 serializeThemeFile,
28 T3_CHAT_THEME,
29 GROVE_THEME,
30 updateCustomTheme,
31 updateThemeColorFamily,
32 CUSTOM_THEMES_STORAGE_KEY,
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);
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;
51​
52function contrastRatio(first: string, second: string): number {
53 const toRgb = (value: string) => {
54 const hex = asHex(value).slice(1);
55 return [0, 1, 2].map(
56 (channel) => Number.parseInt(hex.slice(channel * 2, channel * 2 + 2), 16) / 255,
57 );
58 };
59 const luminance = (value: string) =>
60 toRgb(value)
61 .map((channel) => (channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4))
62 .reduce((sum, channel, index) => sum + channel * [0.2126, 0.7152, 0.0722][index]!, 0);
63 const lighter = Math.max(luminance(first), luminance(second));
64 const darker = Math.min(luminance(first), luminance(second));
65 return (lighter + 0.05) / (darker + 0.05);
67​
68describe("theme files", () => {
69 it("gives non-Latin theme names distinct stable ids", () => {
70 const file = {
71 version: THEME_FILE_VERSION,
72 appearance: "dark",
73 colors: { canvas: "#101820" },
74 };
75 const night = parseThemeFile({ ...file, name: "夜" });
76 expect(parseThemeFile({ ...file, name: "朝" }).id).not.toBe(night.id);
77 expect(parseThemeFile({ ...file, name: " 夜 " }).id).toBe(night.id);
78 });
79​
80 it("keeps built-in and standard search pairs readable and distinct from inline code", () => {
81 const toOklab = converter("oklab");
82 const distance = (first: string, second: string) => {
83 const a = toOklab(first)!;
84 const b = toOklab(second)!;
85 return Math.hypot(a.l - b.l, a.a - b.a, a.b - b.b);
86 };
87 const palettes = [
88 getStandardThemeColors("light"),
89 getStandardThemeColors("dark"),
90 ...BUILT_IN_THEMES.flatMap((theme) => [theme.colors, ...Object.values(theme.variants ?? {})]),
91 ];
92 for (const colors of palettes) {
93 expect(
94 contrastRatio(colors.searchMatchForeground, colors.searchMatchBackground),
95 ).toBeGreaterThanOrEqual(4.5);
96 expect(
97 contrastRatio(colors.searchMatchActiveForeground, colors.searchMatchActiveBackground),
98 ).toBeGreaterThanOrEqual(4.5);
99 expect(
100 distance(colors.searchMatchBackground, colors.searchMatchActiveBackground),
101 ).toBeGreaterThan(0.14);
102 for (const background of [colors.muted, colors.messageSurface, colors.codeBackground]) {
103 expect(distance(colors.searchMatchBackground, background)).toBeGreaterThan(0.08);
104 expect(distance(colors.searchMatchActiveBackground, background)).toBeGreaterThan(0.08);
105 }
106 }
107 });
108​
109 it("round-trips custom search colours and fills them in for older theme files", () => {
110 const legacy = parseThemeFile({
111 version: THEME_FILE_VERSION,
112 name: "Legacy",
113 appearance: "dark",
114 colors: { canvas: "#101010" },
115 });
116 expect(legacy.colors.searchMatchBackground).toBe(
117 getDefaultThemeColors("dark").searchMatchBackground,
118 );
119 const theme = parseThemeFile({
120 version: THEME_FILE_VERSION,
121 name: "Search",
122 appearance: "dark",
123 colors: {
124 searchMatchBackground: "#224466",
125 searchMatchForeground: "#ffffff",
126 searchMatchActiveBackground: "#aaddff",
127 searchMatchActiveForeground: "#112233",
128 },
129 variants: { light: { searchMatchBackground: "#ddeeff", searchMatchForeground: "#112233" } },
130 });
131 const restored = parseThemeFile(JSON.parse(serializeThemeFile(theme)));
132 expect(restored.colors).toEqual(theme.colors);
133 expect(restored.variants).toEqual(theme.variants);
134 });
135​
136 it.each(["searchMatchBackground", "searchMatchActiveBackground"] as const)(
137 "editing %s derives readable text without changing the other match or warning colours",
138 (role) => {
139 const original = getDefaultThemeColors("dark");
140 const foreground =
141 role === "searchMatchBackground" ? "searchMatchForeground" : "searchMatchActiveForeground";
142 for (const value of ["#ffffff", "#000000", "#33669980"]) {
143 const updated = updateThemeColorFamily("dark", original, role, value);
144 expect(contrastRatio(updated[foreground], updated[role])).toBeGreaterThanOrEqual(4.5);
145 for (const key of Object.keys(original) as Array<keyof typeof original>) {
146 if (key !== role && key !== foreground) expect(updated[key]).toBe(original[key]);
147 }
148 }
149 },
150 );
151​
152 it("derives readable, distinctive vivid palettes from exact seeds", () => {
153 const seeds: ReadonlyArray<["light" | "dark", string, string]> = [
154 ["light", "#f4f9f2", "#1d8a4e"],
155 ["dark", "#101a2c", "#4f8fe8"],
156 ["dark", "#211a23", "#df5398"],
157 ["light", "#fdf6ec", "#c2571b"],
158 ["light", "#111827", "#8ab4f8"],
159 ["dark", "#f5ecf5", "#a84370"],
160 ];
161 const channels = (value: string) =>
162 [1, 3, 5].map((index) => Number.parseInt(asHex(value).slice(index, index + 2), 16)) as [
163 number,
164 number,
165 number,
166 ];
167 for (const [appearance, canvas, accent] of seeds) {
168 const colors = createVividThemeColors(appearance, canvas, accent);
169 expect(colors.canvas).toMatch(/^oklch\(/);
170 expect(colors.accent).toMatch(/^oklch\(/);
171 expect(asHex(colors.canvas)).toBe(canvas);
172 expect(asHex(colors.accent)).toBe(accent);
173 expect(contrastRatio(colors.text, colors.canvas)).toBeGreaterThanOrEqual(7);
174 expect(contrastRatio(colors.textMuted, colors.canvas)).toBeGreaterThanOrEqual(4.5);
175 expect(contrastRatio(colors.textMuted, colors.canvas)).toBeLessThan(5.5);
176 expect(contrastRatio(colors.mutedForeground, colors.muted)).toBeGreaterThanOrEqual(4.5);
177 expect(contrastRatio(colors.mutedForeground, colors.muted)).toBeLessThan(
178 contrastRatio(colors.text, colors.muted),
179 );
180 expect(contrastRatio(colors.placeholder, colors.surfaceRaised)).toBeGreaterThanOrEqual(4.5);
181 expect(contrastRatio(colors.placeholder, colors.surfaceRaised)).toBeLessThan(
182 contrastRatio(colors.text, colors.surfaceRaised),
183 );
184 expect(colors.secondaryLabel).toBe(colors.textMuted);
185 expect(contrastRatio(colors.accentForeground, colors.accent)).toBeGreaterThanOrEqual(4.5);
186 expect(
187 contrastRatio(colors.searchMatchForeground, colors.searchMatchBackground),
188 ).toBeGreaterThanOrEqual(4.5);
189 expect(
190 contrastRatio(colors.searchMatchActiveForeground, colors.searchMatchActiveBackground),
191 ).toBeGreaterThanOrEqual(4.5);
192 expect(
193 contrastRatio(colors.messageActionForeground, colors.messageAction),
194 ).toBeGreaterThanOrEqual(4.5);
195 expect(contrastRatio(colors.messageForeground, colors.messageSurface)).toBeGreaterThanOrEqual(
196 4.5,
197 );
198 expect(contrastRatio(colors.secondaryForeground, colors.secondary)).toBeGreaterThanOrEqual(
199 4.5,
200 );
201 expect(contrastRatio(colors.sidebarForeground, colors.sidebar)).toBeGreaterThanOrEqual(4.5);
202 expect(colors.messageAction).not.toBe(colors.accent);
203 expect(asHex(colors.update)).toBe(accent);
204 const [errorRed, errorGreen, errorBlue] = channels(colors.error);
205 expect(errorRed).toBeGreaterThan(errorGreen * 2);
206 expect(errorRed).toBeGreaterThan(errorBlue * 2);
207 expect(contrastRatio(colors.error, "#ffffff")).toBeGreaterThanOrEqual(2.5);
208 expect(contrastRatio(colors.errorForeground, colors.errorSurface)).toBeGreaterThanOrEqual(
209 4.5,
210 );
211 const [warnRed, warnGreen, warnBlue] = channels(colors.warning);
212 expect(warnRed).toBeGreaterThan(warnBlue);
213 expect(warnGreen).toBeGreaterThan(warnBlue);
214 }
215 });
216​
217 it("decodes literal CSS color formats into OKLCH without dropping alpha", () => {
218 const theme = parseThemeFile({
219 version: THEME_FILE_VERSION,
220 name: "Translucent",
221 appearance: "light",
222 colors: {
223 canvas: "oklch(62% 0.2 280deg / 50%)",
224 accent: "#abcd",
225 focus: "rgb(10 20 30 / 50%)",
226 error: "hsl(350 80% 50%)",
227 warning: "hwb(45 10% 20%)",
228 update: "lab(60% 40 30)",
229 messageAction: "lch(60% 50 120)",
230 sidebar: "oklab(0.6 0.1 -0.1)",
231 terminalCursor: "color(display-p3 0.8 0.2 0.3)",
232 terminalSelection: "rebeccapurple",
233 terminalScrollbar: "transparent",
234 terminalScrollbarHover: "rgb(10 20 30 / none)",
235 },
236 });
237​
238 expect(theme.colors.canvas).toBe("oklch(0.62 0.2 280 / 0.5)");
239 expect(theme.colors.accent).toBe(canonical("#abcd"));
240 expect(themeColorToHex(theme.colors.accent)).toBe("#aabbccdd");
241 expect(themeColorToHex(theme.colors.focus)).toBe("#0a141e80");
242 expect(themeColorToHex(theme.colors.terminalSelection)).toBe("#663399");
243 expect(theme.colors.terminalScrollbar).toBe("oklch(0 0 0 / 0)");
244 expect(themeColorToHex(theme.colors.terminalScrollbarHover)).toBe("#0a141e00");
245 for (const role of [
246 "error",
247 "warning",
248 "update",
249 "messageAction",
250 "sidebar",
251 "terminalCursor",
252 ] as const) {
253 expect(theme.colors[role]).toMatch(/^oklch\(/);
254 }
255 });
256​
257 it("gamut maps extreme finite OKLCH chroma from theme files", () => {
258 const theme = parseThemeFile({
259 version: THEME_FILE_VERSION,
260 name: "Extreme chroma",
261 appearance: "light",
262 colors: { accent: "oklch(0.5 1e303 0)" },
263 });
264​
265 expect(theme.colors.accent).toBe("oklch(0.5 1e+303 0)");
266 expect(themeColorToHex(theme.colors.accent)).toBe("#b5005e");
267 });
268​
269 it("keeps optional light and dark palettes under one theme id", () => {
270 const theme = parseThemeFile({
271 version: THEME_FILE_VERSION,
272 id: "aurora",
273 name: "Aurora",
274 appearance: "light",
275 colors: { canvas: "#f8fbff", text: "#10243d" },
276 variants: {
277 dark: { canvas: "#101827", text: "#eef5ff" },
278 },
279 css: "[data-chat-header] { border-bottom: 1px solid red; }",
280 });
281​
282 expect(JSON.parse(serializeThemeFile(theme)).css).toBe(theme.css);
283 expect(getThemeModes(theme)).toEqual(["light", "dark"]);
284 expect(getThemeColorsForMode(theme, "dark")).toMatchObject({
285 canvas: canonical("#101827"),
286 text: canonical("#eef5ff"),
287 });
288 expect(getThemeModes(T3_CHAT_THEME)).toEqual(["light", "dark"]);
289 expect(resolveThemeAppearance(T3_CHAT_THEME.id, true, true)).toBe("dark");
290 expect(resolveDesktopTheme(T3_CHAT_THEME.id, true)).toBe("system");
291 expect(resolveThemeAppearance(T3_CHAT_THEME.id, false, false, "dark")).toBe("dark");
292 expect(resolveDesktopTheme(T3_CHAT_THEME.id, false, "dark")).toBe("dark");
293 expect(JSON.parse(serializeThemeFile(theme)).variants.dark).toMatchObject({
294 canvas: canonical("#101827"),
295 text: canonical("#eef5ff"),
296 });
297 });
298​
299 it("preserves valid imported-theme collections and drops malformed metadata", () => {
300 vi.stubGlobal("window", {
301 localStorage: {
302 getItem: (key: string) =>
303 key === CUSTOM_THEMES_STORAGE_KEY
304 ? JSON.stringify([
305 {
306 id: "github-dark",
307 label: "GitHub Dark",
308 appearance: "dark",
309 colors: { canvas: "#0d1117" },
310 collection: { id: "open-vsx:github.github-vscode-theme", label: "GitHub Theme" },
311 },
312 {
313 id: "github-light",
314 label: "GitHub Light",
315 appearance: "light",
316 colors: { canvas: "#ffffff" },
317 collection: { id: "bad collection id", label: "GitHub Theme" },
318 },
319 ])
320 : null,
321 },
322 });
323​
324 invalidateCustomThemes();
325 expect(getCustomThemes()).toMatchObject([
326 { collection: { id: "open-vsx:github.github-vscode-theme", label: "GitHub Theme" } },
327 { id: "github-light" },
328 ]);
329 expect(getCustomThemes()[1]).not.toHaveProperty("collection");
330​
331 vi.unstubAllGlobals();
332 invalidateCustomThemes();
333 });
334​
335 it("atomically replaces an imported collection and removes stale variants", () => {
336 const collection = { id: "open-vsx:demo.theme", label: "Demo Theme" };
337 const personalTheme = {
338 id: "personal",
339 label: "Personal",
340 appearance: "dark",
341 colors: { canvas: "#111111", futureRole: "hsl(10 20% 30%)" },
342 futureMetadata: { version: 2 },
343 };
344 const stored = new Map<string, string>([
345 [
346 CUSTOM_THEMES_STORAGE_KEY,
347 JSON.stringify([
348 personalTheme,
349 {
350 id: "old-light",
351 label: "Old Light",
352 appearance: "light",
353 colors: { canvas: "#ffffff" },
354 collection,
355 },
356 {
357 id: "removed-dark",
358 label: "Removed Dark",
359 appearance: "dark",
360 colors: { canvas: "#000000" },
361 collection,
362 },
363 ]),
364 ],
365 ]);
366 const setItem = vi.fn((key: string, value: string) => stored.set(key, value));
367 vi.stubGlobal("window", {
368 localStorage: {
369 getItem: (key: string) => stored.get(key) ?? null,
370 setItem,
371 },
372 });
373​
374 invalidateCustomThemes();
375 const expectedCollection = getStoredCustomThemeCollection(collection.id);
376 getCustomThemes();
377 const concurrentlyAddedTheme = {
378 id: "other-tab",
379 label: "Other Tab",
380 appearance: "dark",
381 colors: { canvas: "#222222" },
382 };
383 stored.set(
384 CUSTOM_THEMES_STORAGE_KEY,
385 JSON.stringify([
386 ...JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]"),
387 concurrentlyAddedTheme,
388 ]),
389 );
390 const replacement = [
391 {
392 ...parseThemeFile({
393 version: THEME_FILE_VERSION,
394 id: "old-light",
395 name: "New Light",
396 appearance: "light",
397 colors: { canvas: "#fafafa" },
398 }),
399 collection,
400 },
401 {
402 ...parseThemeFile({
403 version: THEME_FILE_VERSION,
404 id: "new-dark",
405 name: "New Dark",
406 appearance: "dark",
407 colors: { canvas: "#101010" },
408 }),
409 collection,
410 },
411 ];
412​
413 expect(
414 replaceCustomThemeCollection(collection.id, replacement, { expectedCollection }),
415 ).toEqual(replacement);
416 expect(getCustomThemes().map((theme) => theme.id)).toEqual([
417 "personal",
418 "old-light",
419 "new-dark",
420 "other-tab",
421 ]);
422 expect(setItem).toHaveBeenCalledTimes(1);
423 expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")[0]).toEqual(personalTheme);
424​
425 vi.unstubAllGlobals();
426 invalidateCustomThemes();
427 });
428​
429 it("canonicalizes explicit writes without migrating untouched themes", () => {
430 const stored = new Map<string, string>();
431 const untouchedTheme = {
432 id: "legacy",
433 label: "Legacy",
434 appearance: "dark",
435 colors: { accent: "#5b6cff", futureRole: "hsl(10 20% 30%)" },
436 futureMetadata: { version: 2 },
437 };
438 stored.set(CUSTOM_THEMES_STORAGE_KEY, JSON.stringify([untouchedTheme]));
439 vi.stubGlobal("window", {
440 localStorage: {
441 getItem: (key: string) => stored.get(key) ?? null,
442 setItem: (key: string, value: string) => stored.set(key, value),
443 },
444 });
445​
446 invalidateCustomThemes();
447 const createdTheme = installCustomTheme(
448 parseThemeFile({
449 version: THEME_FILE_VERSION,
450 id: "aurora",
451 name: "Aurora",
452 appearance: "light",
453 colors: { canvas: "#f8fbff", accent: "#5b6cff" },
454 sidebarArtwork: true,
455 }),
456 );
457 const updatedTheme = updateCustomTheme({
458 ...createdTheme,
459 label: "Aurora Night",
460 colors: { ...createdTheme.colors, accent: "hsl(263 70% 58%)" },
461 });
462​
463 expect(updatedTheme).toMatchObject({
464 id: "aurora",
465 label: "Aurora Night",
466 colors: { accent: canonical("hsl(263 70% 58%)") },
467 });
468 expect(updatedTheme).not.toHaveProperty("sidebarArtwork");
469 const storedThemes = JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]");
470 expect(storedThemes[0]).toEqual(untouchedTheme);
471 expect(storedThemes[1]).toMatchObject({
472 id: "aurora",
473 label: "Aurora Night",
474 colors: { accent: canonical("hsl(263 70% 58%)") },
475 });
476 expect(storedThemes[1]).not.toHaveProperty("sidebarArtwork");
477 invalidateCustomThemes();
478 expect(getCustomThemes().find((theme) => theme.id === "aurora")).toMatchObject({
479 id: "aurora",
480 colors: { accent: canonical("hsl(263 70% 58%)") },
481 });
482 removeCustomTheme("aurora");
483 expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")).toEqual([untouchedTheme]);
484​
485 vi.unstubAllGlobals();
486 invalidateCustomThemes();
487 });
488​
489 it("writes from the cached raw snapshot without risking a destructive reread", () => {
490 const legacyTheme = {
491 id: "legacy",
492 label: "Legacy",
493 appearance: "dark",
494 colors: { accent: "#5b6cff" },
495 futureMetadata: true,
496 };
497 let storedThemes = JSON.stringify([legacyTheme]);
498 let readCount = 0;
499 const setItem = vi.fn((_key: string, value: string) => {
500 storedThemes = value;
501 });
502 vi.stubGlobal("window", {
503 localStorage: {
504 getItem: () => {
505 readCount += 1;
506 if (readCount > 1) throw new Error("transient read failure");
507 return storedThemes;
508 },
509 setItem,
510 },
511 });
512​
513 invalidateCustomThemes();
514 expect(getCustomThemes()).toHaveLength(1);
515 installCustomTheme(
516 parseThemeFile({
517 version: THEME_FILE_VERSION,
518 id: "aurora",
519 name: "Aurora",
520 appearance: "light",
521 colors: { accent: "hsl(263 70% 58%)" },
522 }),
523 );
524​
525 expect(readCount).toBe(1);
526 expect(setItem).toHaveBeenCalledOnce();
527 expect(JSON.parse(storedThemes)[0]).toEqual(legacyTheme);
528​
529 vi.unstubAllGlobals();
530 invalidateCustomThemes();
531 });
532​
533 it("refuses to overwrite a theme library that could not be read", () => {
534 const setItem = vi.fn();
535 vi.stubGlobal("window", {
536 localStorage: {
537 getItem: () => {
538 throw new Error("storage unavailable");
539 },
540 setItem,
541 },
542 });
543​
544 invalidateCustomThemes();
545 expect(getCustomThemes()).toEqual([]);
546 expect(() =>
547 installCustomTheme(
548 parseThemeFile({
549 version: THEME_FILE_VERSION,
550 id: "aurora",
551 name: "Aurora",
552 appearance: "light",
553 colors: { accent: "#5b6cff" },
554 }),
555 ),
556 ).toThrow(`Failed to read the theme library from ${CUSTOM_THEMES_STORAGE_KEY}.`);
557 expect(setItem).not.toHaveBeenCalled();
558​
559 vi.unstubAllGlobals();
560 invalidateCustomThemes();
561 });
562});
563​
564describe("context chip colors", () => {
565 it.each([
566 ["#ffffff", 5],
567 ["#777777", 4.5],
568 ] as const)(
569 "chooses readable chip lightness on %s when the text is medium gray",
570 (surface, minimum) => {
571 const colors = {
572 ...getStandardThemeColors("light"),
573 canvas: surface,
574 surface,
575 surfaceRaised: surface,
576 messageSurface: surface,
577 text: "#767676",
578 messageForeground: "#767676",
579 };
580 for (const color of Object.values(contextChipVariables(colors))) {
581 expect(contrastRatio(color, surface)).toBeGreaterThanOrEqual(minimum);
582 }
583 },
584 );
585​
586 const toOklch = converter("oklch");
587 const toRgb = converter("rgb");
588 // Surfaces stay unrounded, as CSS paints them; the chip is the 8-bit hex the solver returns.
589 const paintedContrastRatio = (chip: string, surface: string, canvas: string) => {
590 const channels = (value: string) => {
591 const rgb = toRgb(value)!;
592 return [rgb.r, rgb.g, rgb.b].map((channel) => Math.min(1, Math.max(0, channel)));
593 };
594 const back = channels(canvas);
595 const alpha = toRgb(surface)!.alpha ?? 1;
596 const painted = channels(surface).map(
597 (channel, index) => back[index]! * (1 - alpha) + channel * alpha,
598 );
599 const luminance = (rgb: number[]) =>
600 rgb
601 .map((channel) =>
602 channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4,
603 )
604 .reduce((sum, channel, index) => sum + channel * [0.2126, 0.7152, 0.0722][index]!, 0);
605 const first = luminance(channels(asHex(chip)));
606 const second = luminance(painted);
607 return (Math.max(first, second) + 0.05) / (Math.min(first, second) + 0.05);
608 };
609 const palettes = [
610 getStandardThemeColors("light"),
611 getStandardThemeColors("dark"),
612 ...BUILT_IN_THEMES.flatMap((theme) =>
613 getThemeModes(theme).map((mode) => getThemeColorsForMode(theme, mode)!),
614 ),
615 ];
616​
617 it("reads at 5:1 on every chip surface of every built-in theme and keeps each hue", () => {
618 for (const colors of palettes) {
619 const variables = contextChipVariables(colors);
620 expect(variables["--context-chip-message"]).toBeUndefined();
621 for (const [kind, accent] of Object.entries(CONTEXT_CHIP_ACCENTS)) {
622 const chip =
623 variables[contextChipColorVariable(kind as keyof typeof CONTEXT_CHIP_ACCENTS)]!;
624 for (const surface of [
625 colors.canvas,
626 colors.surface,
627 colors.surfaceRaised,
628 colors.messageSurface,
629 ]) {
630 expect(paintedContrastRatio(chip, surface, colors.canvas)).toBeGreaterThanOrEqual(5);
631 }
632 const solved = toOklch(chip)!;
633 if ((solved.c ?? 0) > 0.04) {
634 const drift = Math.abs((((solved.h ?? 0) - toOklch(accent)!.h! + 540) % 360) - 180);
635 expect(drift).toBeLessThan(4);
636 }
637 }
638 }
639 });
640​
641 it("reads at 5:1 on the standard surfaces as index.css paints them", () => {
642 const painted = {
643 light: ["#fcfcfc", "#ffffff", "#ebebed"],
644 dark: ["#000000", "#0a0a0a", "#111111", "#141414", "#1e1e1e"],
645 } as const;
646 const properties = new Map<string, string>();
647 vi.stubGlobal("window", { localStorage: { getItem: () => null } });
648 vi.stubGlobal("document", {
649 documentElement: {
650 dataset: {},
651 style: {
652 setProperty: (name: string, value: string) => properties.set(name, value),
653 removeProperty: (name: string) => properties.delete(name),
654 },
655 },
656 });
657 invalidateCustomThemes();
658 try {
659 for (const appearance of ["light", "dark"] as const) {
660 applyThemePalette("system", appearance);
661 for (const kind of Object.keys(CONTEXT_CHIP_ACCENTS) as Array<
662 keyof typeof CONTEXT_CHIP_ACCENTS
663 >) {
664 for (const surface of painted[appearance]) {
665 expect(
666 contrastRatio(properties.get(contextChipColorVariable(kind))!, surface),
667 ).toBeGreaterThanOrEqual(5);
668 }
669 }
670 }
671 } finally {
672 vi.unstubAllGlobals();
673 invalidateCustomThemes();
674 }
675 });
676​
677 it("solves the invalid state's error color to 5:1 on every chip surface", () => {
678 for (const colors of palettes) {
679 const invalid = contextChipVariables(colors)["--context-chip-invalid"];
680 expect(invalid).toBeDefined();
681 for (const surface of [
682 colors.canvas,
683 colors.surface,
684 colors.surfaceRaised,
685 colors.messageSurface,
686 ]) {
687 expect(paintedContrastRatio(invalid!, surface, colors.canvas)).toBeGreaterThanOrEqual(5);
688 }
689 }
690 });
691​
692 it("leaves a bubble with opposite-shade text out of the shared solve", () => {
693 const colors = {
694 ...getStandardThemeColors("light"),
695 messageSurface: "#1b4ed8",
696 messageForeground: "#ffffff",
697 };
698 const variables = contextChipVariables(colors);
699 expect(variables["--context-chip-message"]).toBe("#ffffff");
700 for (const kind of Object.keys(CONTEXT_CHIP_ACCENTS) as Array<
701 keyof typeof CONTEXT_CHIP_ACCENTS
702 >) {
703 expect(
704 contrastRatio(variables[contextChipColorVariable(kind)]!, colors.canvas),
705 ).toBeGreaterThanOrEqual(5);
706 }
707 expect(toOklch(variables[contextChipColorVariable("file")])!.c).toBeGreaterThan(0.08);
708 });
709});
710​
711describe("stored theme preferences", () => {
712 it("lets built-in and published halves unlock an appearance the base theme lacks", () => {
713 const lightOnly = parseThemeFile({
714 version: THEME_FILE_VERSION,
715 id: "paper",
716 name: "Paper",
717 appearance: "light",
718 colors: { canvas: "#f8fbff" },
719 });
720 const [publishedTheme] = publishedThemeDefinitions([
721 {
722 id: "constructor",
723 name: "Constructor",
724 appearance: "dark",
725 canvas: "#1a1b26",
726 accent: "#7aa2f7",
727 },
728 ]);
729 expect(publishedTheme).toBeDefined();
730 using _environmentThemes = vi.spyOn(appAtomRegistry, "get").mockReturnValue([publishedTheme]);
731 vi.stubGlobal("window", {
732 localStorage: {
733 getItem: (key: string) =>
734 key === CUSTOM_THEMES_STORAGE_KEY ? JSON.stringify([lightOnly]) : null,
735 },
736 });
737 invalidateCustomThemes();
738 try {
739 expect(resolveThemeAppearance("paper", true, true)).toBe("light");
740 const halves = { dark: GROVE_THEME.id };
741 expect(resolveThemeAppearance("paper", true, true, undefined, halves)).toBe("dark");
742 expect(resolveThemeAppearance("paper", false, false, "dark", halves)).toBe("dark");
743 expect(resolveDesktopTheme("paper", true, undefined, halves)).toBe("system");
744​
745 expect(getThemeDefinition("constructor")).toEqual(publishedTheme);
746 expect(canonicalThemePreference("constructor")).toBe("constructor");
747 const publishedHalves = parseThemeHalves(JSON.stringify({ dark: "constructor" }));
748 expect(publishedHalves).toEqual({ dark: "constructor" });
749 expect(resolveThemeAppearance("paper", true, true, undefined, publishedHalves)).toBe("dark");
750 } finally {
751 vi.unstubAllGlobals();
752 invalidateCustomThemes();
753 }
754 });
755​
756 it("decodes stored colors in memory without writing during reads", () => {
757 const storedThemes = JSON.stringify([
758 {
759 id: "aurora",
760 label: "Aurora",
761 appearance: "light",
762 colors: { canvas: "#f8fbff", futureRole: "#123456", accent: "not-a-color" },
763 variants: { dark: { canvas: "rgb(16 24 39)" } },
764 },
765 { id: "light", label: "Reserved", appearance: "light", colors: {} },
766 { id: "aurora", label: "Duplicate", appearance: "dark", colors: {} },
767 ]);
768 const setItem = vi.fn();
769 vi.stubGlobal("window", {
770 localStorage: {
771 getItem: (key: string) => (key === CUSTOM_THEMES_STORAGE_KEY ? storedThemes : null),
772 setItem,
773 },
774 });
775 invalidateCustomThemes();
776​
777 const themes = getCustomThemes();
778 expect(themes).toHaveLength(1);
779 expect(themes[0]).toMatchObject({
780 id: "aurora",
781 colors: { canvas: canonical("#f8fbff"), accent: getDefaultThemeColors("light").accent },
782 });
783 expect(getThemeModes(themes[0]!)).toEqual(["light", "dark"]);
784 expect(getThemeColorsForMode(themes[0]!, "dark")?.canvas).toBe(canonical("rgb(16 24 39)"));
785 expect(setItem).not.toHaveBeenCalled();
786 expect(JSON.parse(storedThemes)[0].colors).toEqual({
787 canvas: "#f8fbff",
788 futureRole: "#123456",
789 accent: "not-a-color",
790 });
791​
792 vi.unstubAllGlobals();
793 invalidateCustomThemes();
794 });
795});