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

themePalette.test.ts

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