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

themePalette.test.ts

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