feat(web): use OKLCH for theme palettes (#6036)

This commit is contained in:
Wout Stiens authored and GitHub committed 2026-08-11 20:00:17 +02:00
1 parent 35172010b1
commit 083fa4ab24
10 files changed
+981 -483

No files matched your search

+72 -55
View File
@@ -35,16 +35,16 @@
// app colors before React mounts.
const DEFAULT_THEME_PALETTES = {
light: {
background: "#fdf7fd",
foreground: "#501854",
accent: "#db2777",
chrome: "#fdf7fd",
background: "oklch(0.982446 0.010114 325.653)",
foreground: "oklch(0.325698 0.116116 325.037)",
accent: "oklch(0.591646 0.217985 0.584)",
chrome: "oklch(0.982446 0.010114 325.653)",
},
dark: {
background: "#1f1a24",
foreground: "#f9f8fb",
accent: "#a3004c",
chrome: "#1f1a24",
background: "oklch(0.22813 0.020366 307.469)",
foreground: "oklch(0.980735 0.004092 301.426)",
accent: "oklch(0.460685 0.185347 4.099)",
chrome: "oklch(0.22813 0.020366 307.469)",
},
};
// Keep this small boot-time copy in sync with the built-in palettes so
@@ -52,72 +52,72 @@
const BUILT_IN_THEME_PALETTES = {
"t3-chat": {
light: {
background: "#fdf7fd",
foreground: "#501854",
accent: "#db2777",
chrome: "#fdf7fd",
background: "oklch(0.982446 0.010114 325.653)",
foreground: "oklch(0.325698 0.116116 325.037)",
accent: "oklch(0.591646 0.217985 0.584)",
chrome: "oklch(0.982446 0.010114 325.653)",
},
dark: {
background: "#1f1a24",
foreground: "#f9f8fb",
accent: "#a3004c",
chrome: "#1f1a24",
background: "oklch(0.22813 0.020366 307.469)",
foreground: "oklch(0.980735 0.004092 301.426)",
accent: "oklch(0.460685 0.185347 4.099)",
chrome: "oklch(0.22813 0.020366 307.469)",
},
},
grove: {
light: {
background: "#f3f7f4",
foreground: "#241523",
accent: "#1b7d50",
chrome: "#f3f7f4",
background: "oklch(0.972369 0.005497 157.15)",
foreground: "oklch(0.222003 0.03479 328.979)",
accent: "oklch(0.523295 0.112292 158.089)",
chrome: "oklch(0.972369 0.005497 157.15)",
},
dark: {
background: "#1b2821",
foreground: "#fffaff",
accent: "#69d69a",
chrome: "#1b2821",
background: "oklch(0.260865 0.02152 162.75)",
foreground: "oklch(0.990339 0.008411 325.64)",
accent: "oklch(0.796228 0.133058 157.319)",
chrome: "oklch(0.260865 0.02152 162.75)",
},
},
ocean: {
light: {
background: "#f5f7f8",
foreground: "#241523",
accent: "#2672af",
chrome: "#f5f7f8",
background: "oklch(0.974199 0.002856 241.597)",
foreground: "oklch(0.222003 0.03479 328.979)",
accent: "oklch(0.536684 0.120219 247.01)",
chrome: "oklch(0.974199 0.002856 241.597)",
},
dark: {
background: "#17212b",
foreground: "#fffaff",
accent: "#70b9ee",
chrome: "#17212b",
background: "oklch(0.242641 0.024125 250.573)",
foreground: "oklch(0.990339 0.008411 325.64)",
accent: "oklch(0.758933 0.105833 241.548)",
chrome: "oklch(0.242641 0.024125 250.573)",
},
},
ember: {
light: {
background: "#f9f7f5",
foreground: "#241523",
accent: "#ae552a",
chrome: "#f9f7f5",
background: "oklch(0.976527 0.002685 60.725)",
foreground: "oklch(0.222003 0.03479 328.979)",
accent: "oklch(0.552831 0.129438 44.656)",
chrome: "oklch(0.976527 0.002685 60.725)",
},
dark: {
background: "#291e1a",
foreground: "#fffaff",
accent: "#f09a64",
chrome: "#291e1a",
background: "oklch(0.245899 0.019144 42.044)",
foreground: "oklch(0.990339 0.008411 325.64)",
accent: "oklch(0.762174 0.124117 52.082)",
chrome: "oklch(0.245899 0.019144 42.044)",
},
},
iris: {
light: {
background: "#f8f7f9",
foreground: "#241523",
accent: "#7253b9",
chrome: "#f8f7f9",
background: "oklch(0.976531 0.003855 303.226)",
foreground: "oklch(0.222003 0.03479 328.979)",
accent: "oklch(0.525348 0.15373 294.176)",
chrome: "oklch(0.976531 0.003855 303.226)",
},
dark: {
background: "#1d1929",
foreground: "#fffaff",
accent: "#9d7df2",
chrome: "#1d1929",
background: "oklch(0.225975 0.031062 293.741)",
foreground: "oklch(0.990339 0.008411 325.64)",
accent: "oklch(0.671712 0.169136 293.929)",
chrome: "oklch(0.225975 0.031062 293.741)",
},
},
};
@@ -152,9 +152,26 @@
}
};
const isHexColor = (value) =>
typeof value === "string" &&
/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(value);
// The runtime decodes the same literal CSS formats into OKLCH. Keep
// contextual colors out: they cannot be resolved from stored data.
const SYSTEM_COLOR_KEYWORD =
/^(?:accentcolor(?:text)?|active(?:border|caption|text)|appworkspace|background|button(?:border|face|highlight|shadow|text)|canvas(?:text)?|captiontext|field(?:text)?|graytext|highlight(?:text)?|inactive(?:border|caption(?:text)?)|info(?:background|text)|linktext|mark(?:text)?|menu(?:text)?|scrollbar|selecteditem(?:text)?|threed(?:darkshadow|face|highlight|lightshadow|shadow)|visitedtext|window(?:frame|text)?)$/i;
const isThemeColor = (value) => {
if (typeof value !== "string" || typeof CSS === "undefined") return false;
const color = value.trim();
if (
/^(?:currentcolor|inherit|initial|revert|revert-layer|unset)$/i.test(color) ||
SYSTEM_COLOR_KEYWORD.test(color) ||
/\bfrom\b|(?:var|env|attr|calc|min|max|clamp)\(/i.test(color)
) {
return false;
}
const isLiteralColor =
/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(color) ||
/^[a-z]+$/i.test(color) ||
/^(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\(/i.test(color);
return isLiteralColor && CSS.supports("color", color);
};
const isRecord = (value) =>
typeof value === "object" && value !== null && !Array.isArray(value);
const isThemeId = (value) =>
@@ -322,13 +339,13 @@
const fallbackSplash = isDark ? SPLASH_COLORS.dark : SPLASH_COLORS.light;
const customSplash = customColors
? {
background: isHexColor(customColors.canvas)
background: isThemeColor(customColors.canvas)
? customColors.canvas
: (customDefaults?.background ?? fallbackSplash.background),
foreground: isHexColor(customColors.text)
foreground: isThemeColor(customColors.text)
? customColors.text
: (customDefaults?.foreground ?? fallbackSplash.foreground),
accent: isHexColor(customColors.accent)
accent: isThemeColor(customColors.accent)
? customColors.accent
: (customDefaults?.accent ?? fallbackSplash.accent),
}
@@ -350,7 +367,7 @@
}
document.documentElement.classList.toggle("dark", isDark);
const chromeColor = customColors
? isHexColor(customColors.chrome)
? isThemeColor(customColors.chrome)
? customColors.chrome
: (customDefaults?.chrome ?? fallbackSplash.background)
: builtInSplash
+2
View File
@@ -31,6 +31,7 @@
"@tanstack/react-pacer": "^0.19.4",
"@tanstack/react-router": "^1.160.2",
"class-variance-authority": "^0.7.1",
"culori": "^4.0.2",
"effect": "catalog:",
"jose": "catalog:",
"lexical": "^0.41.0",
@@ -53,6 +54,7 @@
"@tanstack/router-plugin": "^1.161.0",
"@types/babel__core": "^7.20.5",
"@types/compression": "^1.8.1",
"@types/culori": "^4.0.1",
"@types/react": "~19.2.14",
"@types/react-dom": "~19.2.3",
"@vercel/config": "^0.3.0",
@@ -1,6 +1,6 @@
import type { KeyboardEvent, PointerEvent } from "react";
import { memo, useCallback, useEffect, useRef, useState } from "react";
import { isThemeColor, type ThemeColorRole } from "../../themePalette";
import { isThemeColor, themeColorToHex, type ThemeColorRole } from "../../themePalette";
import { cn } from "../../lib/utils";
import { Input } from "../ui/input";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
@@ -37,39 +37,18 @@ function clampThemeColor(value: number, min = 0, max = 1) {
}
/**
* The picker's plane and sliders operate on opaque six-digit hex, but theme
* colors may carry alpha. The suffix is preserved separately and re-attached
* on commit so adjusting hue or brightness cannot change transparency.
* The picker remains an sRGB/hex adapter over the OKLCH palette engine. Alpha
* is preserved separately and re-attached on commit so adjusting hue or
* brightness cannot change transparency.
*/
function themePickerAlphaSuffix(value: string): string {
const trimmed = value.trim().toLowerCase();
const alpha = /^#[0-9a-f]{4}$/.test(trimmed)
? trimmed.slice(4).repeat(2)
: /^#[0-9a-f]{8}$/.test(trimmed)
? trimmed.slice(7)
: "";
const normalized = themeColorToHex(value) ?? "";
const alpha = normalized.length === 9 ? normalized.slice(7) : "";
return alpha === "ff" ? "" : alpha;
}
function normalizeThemePickerColor(value: string): string {
const trimmed = value.trim();
if (/^#[0-9a-f]{3}$/i.test(trimmed)) {
return `#${trimmed
.slice(1)
.split("")
.map((character) => `${character}${character}`)
.join("")}`;
}
if (/^#[0-9a-f]{4}$/i.test(trimmed)) {
return `#${trimmed
.slice(1, 4)
.split("")
.map((character) => `${character}${character}`)
.join("")}`;
}
if (/^#[0-9a-f]{6}$/i.test(trimmed)) return trimmed;
if (/^#[0-9a-f]{8}$/i.test(trimmed)) return trimmed.slice(0, 7);
return "#000000";
return (themeColorToHex(value) ?? "#000000").slice(0, 7);
}
function themeHexToHsv(hex: string): ThemeColorHsv {
@@ -505,6 +484,9 @@ export const ThemeColorField = memo(function ThemeColorField({
const label = customLabel ?? getThemeRoleLabel(role);
const isColorValue = isThemeColor(value);
const swatchValue = isColorValue ? value : "#000000";
const editorValue = value.trim().toLowerCase().startsWith("oklch(")
? (themeColorToHex(value) ?? value)
: value;
return (
<div
@@ -542,7 +524,7 @@ export const ThemeColorField = memo(function ThemeColorField({
onPointerDown={() => onSelect?.(role)}
size="sm"
unstyled
value={value}
value={editorValue}
/>
</div>
</div>
+124 -112
View File
@@ -268,16 +268,28 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
:root {
/* Dev artwork defaults. Built-in themes override these seven pigments in
the components layer; Nightly derives a darker matching palette. */
--stage-art-top: #67c2ff;
--stage-art-mid: #347ff8;
--stage-art-bottom: #1538d0;
--stage-art-highlight: #d4f6ff;
--stage-art-secondary: #65c8ff;
--stage-art-tertiary: #7c8bff;
--stage-art-line: #ddf7ff;
--stage-night-top: color-mix(in oklch, var(--stage-art-top) 38%, #32155b);
--stage-night-mid: color-mix(in oklch, var(--stage-art-mid) 38%, #151443);
--stage-night-bottom: color-mix(in oklch, var(--stage-art-bottom) 38%, #07152f);
--stage-art-top: oklch(0.782169 0.123386 240.226);
--stage-art-mid: oklch(0.616111 0.195824 259.735);
--stage-art-bottom: oklch(0.441553 0.232394 265.474);
--stage-art-highlight: oklch(0.951597 0.037289 215.482);
--stage-art-secondary: oklch(0.794668 0.12136 235.46);
--stage-art-tertiary: oklch(0.678991 0.170261 275.365);
--stage-art-line: oklch(0.959666 0.029238 218.179);
--stage-night-top: color-mix(
in oklch,
var(--stage-art-top) 38%,
oklch(0.283792 0.117327 297.201)
);
--stage-night-mid: color-mix(
in oklch,
var(--stage-art-mid) 38%,
oklch(0.227147 0.086086 277.99)
);
--stage-night-bottom: color-mix(
in oklch,
var(--stage-art-bottom) 38%,
oklch(0.200528 0.055699 261.216)
);
--stage-night-highlight: var(--stage-art-highlight);
--stage-night-secondary: color-mix(
in oklch,
@@ -289,13 +301,13 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
var(--stage-art-tertiary) 60%,
var(--stage-night-top)
);
--stage-night-line: color-mix(in oklch, var(--stage-art-line) 82%, white);
--stage-night-line: color-mix(in oklch, var(--stage-art-line) 82%, oklch(1 0 0));
}
.dark {
--stage-art-top: #3a7ad1;
--stage-art-mid: #2050ae;
--stage-art-bottom: #101f6e;
--stage-art-top: oklch(0.581473 0.149124 256.9);
--stage-art-mid: oklch(0.456509 0.159377 261.945);
--stage-art-bottom: oklch(0.291327 0.136578 267.649);
}
* {
@@ -373,131 +385,131 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
These colors stay deliberately deep at the top edge so the white stage
wordmark and controls retain contrast in both appearance modes. */
html[data-theme-id="t3-chat"] {
--stage-art-top: #f28ac1;
--stage-art-mid: #cb3e86;
--stage-art-bottom: #73194f;
--stage-art-highlight: #ffe6f6;
--stage-art-secondary: #ff82bc;
--stage-art-tertiary: #c67bf1;
--stage-art-line: #ffe7f8;
--stage-art-top: oklch(0.760675 0.141361 348.019);
--stage-art-mid: oklch(0.588093 0.188832 353.138);
--stage-art-bottom: oklch(0.383959 0.135096 348.656);
--stage-art-highlight: oklch(0.949689 0.034241 339.171);
--stage-art-secondary: oklch(0.763402 0.163836 352.525);
--stage-art-tertiary: oklch(0.70819 0.180285 311.949);
--stage-art-line: oklch(0.952158 0.034194 336.179);
}
html.dark[data-theme-id="t3-chat"] {
--stage-art-top: #a8467e;
--stage-art-mid: #742253;
--stage-art-bottom: #390e2d;
--stage-art-highlight: #ffd8ee;
--stage-art-secondary: #de639e;
--stage-art-tertiary: #9c64cf;
--stage-art-line: #ffe4f4;
--stage-art-top: oklch(0.540689 0.143665 347.587);
--stage-art-mid: oklch(0.396586 0.126592 347.6);
--stage-art-bottom: oklch(0.249959 0.079694 340.523);
--stage-art-highlight: oklch(0.921297 0.051708 343.229);
--stage-art-secondary: oklch(0.667398 0.165674 352.549);
--stage-art-tertiary: oklch(0.609315 0.163722 306.315);
--stage-art-line: oklch(0.945349 0.036045 341.433);
}
html[data-theme-id="grove"] {
--stage-art-top: #6cc492;
--stage-art-mid: #2d8a5e;
--stage-art-bottom: #174a33;
--stage-art-highlight: #e4fff0;
--stage-art-secondary: #79d8a5;
--stage-art-tertiary: #d5b563;
--stage-art-line: #eafff2;
--stage-night-top: #286548;
--stage-night-mid: #174a35;
--stage-night-bottom: #0a2c21;
--stage-night-highlight: #c4eed5;
--stage-night-secondary: #54a878;
--stage-night-tertiary: #b79b4d;
--stage-night-line: #d7f6e2;
--stage-art-top: oklch(0.751465 0.112731 157.313);
--stage-art-mid: oklch(0.567105 0.11099 158.859);
--stage-art-bottom: oklch(0.367918 0.067635 160.558);
--stage-art-highlight: oklch(0.976387 0.034353 161.456);
--stage-art-secondary: oklch(0.80968 0.117071 158.817);
--stage-art-tertiary: oklch(0.784102 0.108047 88.516);
--stage-art-line: oklch(0.981098 0.027812 158.718);
--stage-night-top: oklch(0.45805 0.079616 160.092);
--stage-night-mid: oklch(0.368483 0.065631 162.719);
--stage-night-bottom: oklch(0.264797 0.044397 168.088);
--stage-night-highlight: oklch(0.912563 0.055173 158.974);
--stage-night-secondary: oklch(0.665652 0.109731 156.599);
--stage-night-tertiary: oklch(0.698651 0.103024 89.828);
--stage-night-line: oklch(0.945336 0.041923 157.222);
}
html.dark[data-theme-id="grove"] {
--stage-art-top: #438e65;
--stage-art-mid: #286447;
--stage-art-bottom: #123525;
--stage-art-highlight: #d2fbe2;
--stage-art-secondary: #62bf88;
--stage-art-tertiary: #c99b45;
--stage-art-line: #e0fae9;
--stage-night-top: #24523a;
--stage-night-mid: #113323;
--stage-night-bottom: #071d16;
--stage-night-highlight: #b5dfc4;
--stage-night-secondary: #478d66;
--stage-night-tertiary: #a9853b;
--stage-night-line: #d0ead9;
--stage-art-top: oklch(0.58719 0.09869 157.426);
--stage-art-mid: oklch(0.454979 0.079031 159.756);
--stage-art-bottom: oklch(0.297856 0.050355 161.167);
--stage-art-highlight: oklch(0.952407 0.053872 158.44);
--stage-art-secondary: oklch(0.732591 0.120606 155.853);
--stage-art-tertiary: oklch(0.716282 0.116547 80.563);
--stage-art-line: oklch(0.961577 0.035285 157.03);
--stage-night-top: oklch(0.398632 0.065534 158.601);
--stage-night-mid: oklch(0.290561 0.049694 160.456);
--stage-night-bottom: oklch(0.210147 0.03173 169.818);
--stage-night-highlight: oklch(0.866303 0.057526 156.796);
--stage-night-secondary: oklch(0.586553 0.093722 157.365);
--stage-night-tertiary: oklch(0.6364 0.101769 82.985);
--stage-night-line: oklch(0.913292 0.035718 156.976);
}
html[data-theme-id="ocean"] {
--stage-art-top: #77c9e3;
--stage-art-mid: #3384bd;
--stage-art-bottom: #174d7a;
--stage-art-highlight: #e5faff;
--stage-art-secondary: #70c9df;
--stage-art-tertiary: #5cc7be;
--stage-art-line: #e9fbff;
--stage-art-top: oklch(0.792993 0.088072 220.421);
--stage-art-mid: oklch(0.590296 0.116841 243.184);
--stage-art-bottom: oklch(0.409123 0.093718 247.98);
--stage-art-highlight: oklch(0.971217 0.023008 213.615);
--stage-art-secondary: oklch(0.788391 0.090856 215.684);
--stage-art-tertiary: oklch(0.76441 0.099607 187.893);
--stage-art-line: oklch(0.976025 0.019647 212.543);
}
html.dark[data-theme-id="ocean"] {
--stage-art-top: #4288ac;
--stage-art-mid: #285d84;
--stage-art-bottom: #132e49;
--stage-art-highlight: #d9f5ff;
--stage-art-secondary: #61b5d4;
--stage-art-tertiary: #51b8b3;
--stage-art-line: #dff7ff;
--stage-art-top: oklch(0.59663 0.089167 233.427);
--stage-art-mid: oklch(0.461094 0.084904 243.478);
--stage-art-bottom: oklch(0.294818 0.05947 250.526);
--stage-art-highlight: oklch(0.952907 0.032224 221.27);
--stage-art-secondary: oklch(0.732079 0.09296 224.414);
--stage-art-tertiary: oklch(0.720885 0.095495 190.903);
--stage-art-line: oklch(0.961039 0.027355 219.756);
}
html[data-theme-id="ember"] {
--stage-art-top: #f4a26e;
--stage-art-mid: #d66036;
--stage-art-bottom: #7c291e;
--stage-art-highlight: #fff0df;
--stage-art-secondary: #ffad77;
--stage-art-tertiary: #ef6f69;
--stage-art-line: #fff3e7;
--stage-night-top: #8a442c;
--stage-night-mid: #5c271c;
--stage-night-bottom: #32100d;
--stage-night-highlight: #ffd6ba;
--stage-night-secondary: #cb7148;
--stage-night-tertiary: #ad4b45;
--stage-night-line: #ffe0c9;
--stage-art-top: oklch(0.782439 0.118806 52.569);
--stage-art-mid: oklch(0.62863 0.15922 39.401);
--stage-art-bottom: oklch(0.404251 0.117664 30.424);
--stage-art-highlight: oklch(0.962469 0.02774 70.95);
--stage-art-secondary: oklch(0.815735 0.11904 53.659);
--stage-art-tertiary: oklch(0.69361 0.159346 24.787);
--stage-art-line: oklch(0.970313 0.02052 67.583);
--stage-night-top: oklch(0.470236 0.102322 39.355);
--stage-night-mid: oklch(0.345367 0.080697 33.217);
--stage-night-bottom: oklch(0.227386 0.056077 27.437);
--stage-night-highlight: oklch(0.903891 0.059281 56.181);
--stage-night-secondary: oklch(0.641705 0.126508 44.376);
--stage-night-tertiary: oklch(0.538694 0.129931 25.865);
--stage-night-line: oklch(0.926348 0.046029 58.73);
}
html.dark[data-theme-id="ember"] {
--stage-art-top: #ba6540;
--stage-art-mid: #803a29;
--stage-art-bottom: #3c1916;
--stage-art-highlight: #ffe1cd;
--stage-art-secondary: #e68156;
--stage-art-tertiary: #d85b58;
--stage-art-line: #ffe8d7;
--stage-night-top: #6a3425;
--stage-night-mid: #3e1b15;
--stage-night-bottom: #1d0d0b;
--stage-night-highlight: #efc4a9;
--stage-night-secondary: #a85e3f;
--stage-night-tertiary: #8f413e;
--stage-night-line: #f2d2bc;
--stage-art-top: oklch(0.597533 0.120694 43.455);
--stage-art-mid: oklch(0.437763 0.101287 34.86);
--stage-art-bottom: oklch(0.264269 0.055858 26.548);
--stage-art-highlight: oklch(0.929214 0.042638 55.801);
--stage-art-secondary: oklch(0.705592 0.137369 43.176);
--stage-art-tertiary: oklch(0.629583 0.158322 24.088);
--stage-art-line: oklch(0.945058 0.033906 58.824);
--stage-night-top: oklch(0.392352 0.081287 36.444);
--stage-night-mid: oklch(0.271305 0.056352 31.135);
--stage-night-bottom: oklch(0.182126 0.028154 27.774);
--stage-night-highlight: oklch(0.851007 0.061294 53.805);
--stage-night-secondary: oklch(0.560789 0.10645 42.953);
--stage-night-tertiary: oklch(0.476228 0.106656 24.165);
--stage-night-line: oklch(0.884931 0.046607 56.556);
}
html[data-theme-id="iris"] {
--stage-art-top: #b49ae8;
--stage-art-mid: #7a5ac4;
--stage-art-bottom: #422d80;
--stage-art-highlight: #f2eaff;
--stage-art-secondary: #b79af1;
--stage-art-tertiary: #ec79c7;
--stage-art-line: #f6eeff;
--stage-art-top: oklch(0.738305 0.113454 298.926);
--stage-art-mid: oklch(0.551826 0.159189 294.531);
--stage-art-bottom: oklch(0.37147 0.133317 289.999);
--stage-art-highlight: oklch(0.949472 0.029204 303.081);
--stage-art-secondary: oklch(0.745085 0.125892 298.647);
--stage-art-tertiary: oklch(0.73066 0.167815 340.964);
--stage-art-line: oklch(0.960278 0.024064 306.969);
}
html.dark[data-theme-id="iris"] {
--stage-art-top: #8063c4;
--stage-art-mid: #513990;
--stage-art-bottom: #261c53;
--stage-art-highlight: #e8ddff;
--stage-art-secondary: #9e83dc;
--stage-art-tertiary: #d96ab7;
--stage-art-line: #eee7ff;
--stage-art-top: oklch(0.57297 0.145973 295.185);
--stage-art-mid: oklch(0.419499 0.13752 292.131);
--stage-art-bottom: oklch(0.274235 0.095798 286.608);
--stage-art-highlight: oklch(0.916698 0.047206 300.224);
--stage-art-secondary: oklch(0.670994 0.13095 296.689);
--stage-art-tertiary: oklch(0.679357 0.165376 340.439);
--stage-art-line: oklch(0.940582 0.032921 299.076);
}
.workspace-topbar {
+66 -3
View File
@@ -15,6 +15,7 @@ import {
OCEAN_THEME,
THEME_APPEARANCE_MODE_STORAGE_KEY,
THEME_FOLLOW_SYSTEM_STORAGE_KEY,
toCanonicalThemeColor,
} from "./themePalette";
const THEME_STORAGE_KEY = "t3code:theme";
@@ -83,7 +84,12 @@ function runBootScript(options: {
matchMedia: () => ({ matches: options.prefersDark }),
};
new Function("window", "document", bootScript)(fakeWindow, fakeDocument);
const fakeCss = {
supports: (property: string, value: string) =>
property === "color" && toCanonicalThemeColor(value) !== null,
};
new Function("window", "document", "CSS", bootScript)(fakeWindow, fakeDocument, fakeCss);
return {
isDark: classes.has("dark"),
@@ -275,6 +281,63 @@ describe("index.html boot script", () => {
expect(aurora.metaContent).toBe(DEFAULT_DARK_CHROME);
});
it("accepts exponent-form OKLCH before the runtime mounts", () => {
const colors = {
canvas: "oklch(9.5e-1 1e-2 2.8e2)",
chrome: "oklch(9.4e-1 1e-2 2.8e2)",
text: "oklch(2e-1 0 0 / 9e-1)",
accent: "oklch(6.2e-1 0.2 2.8e2)",
};
const boot = runBootScript({
storage: {
[THEME_STORAGE_KEY]: "scientific",
[CUSTOM_THEMES_STORAGE_KEY]: JSON.stringify([
{
id: "scientific",
label: "Scientific",
appearance: "light",
colors,
},
]),
},
prefersDark: false,
});
expect(boot.bootVariables["--boot-background"]).toBe(colors.canvas);
expect(boot.bootVariables["--boot-foreground"]).toBe(colors.text);
expect(boot.bootVariables["--boot-accent"]).toBe(colors.accent);
expect(boot.backgroundColor).toBe(colors.chrome);
expect(boot.metaContent).toBe(colors.chrome);
});
it("accepts legacy CSS color formats before the runtime mounts", () => {
const colors = {
canvas: "rgb(248 251 255)",
chrome: "hsl(210 100% 99%)",
text: "rebeccapurple",
accent: "color(display-p3 0.36 0.42 1)",
};
const boot = runBootScript({
storage: {
[THEME_STORAGE_KEY]: "legacy-css",
[CUSTOM_THEMES_STORAGE_KEY]: JSON.stringify([
{
id: "legacy-css",
label: "Legacy CSS",
appearance: "light",
colors,
},
]),
},
prefersDark: false,
});
expect(boot.bootVariables["--boot-background"]).toBe(colors.canvas);
expect(boot.bootVariables["--boot-foreground"]).toBe(colors.text);
expect(boot.bootVariables["--boot-accent"]).toBe(colors.accent);
expect(boot.backgroundColor).toBe(colors.chrome);
});
// Asserting against the real palette definitions (not literals) turns the
// boot script's hand-maintained copy into a CI-enforced contract: any
// palette change breaks this test until the copy in index.html is updated.
@@ -410,9 +473,9 @@ describe("index.html boot script", () => {
});
expect(boot.themeId).toBe("partial");
expect(boot.bootVariables["--boot-background"]).toBe("#1f1a24");
expect(boot.bootVariables["--boot-background"]).toBe(getDefaultThemeColors("dark").canvas);
expect(boot.bootVariables["--boot-foreground"]).toBe("#fffaff");
expect(boot.bootVariables["--boot-accent"]).toBe("#a3004c");
expect(boot.bootVariables["--boot-accent"]).toBe(getDefaultThemeColors("dark").accent);
expect(boot.backgroundColor).toBe(DEFAULT_DARK_CHROME);
expect(boot.metaContent).toBe(DEFAULT_DARK_CHROME);
});
+286 -49
View File
@@ -15,6 +15,7 @@ import {
canonicalThemePreference,
parseThemeFile,
parseThemeHalves,
removeCustomTheme,
resolveDesktopTheme,
resolveThemeAppearance,
serializeThemeFile,
@@ -31,12 +32,35 @@ import {
createManagedThemeColors,
createVividThemeColors,
getDefaultThemeColors,
themeColorToHex,
toCanonicalThemeColor,
THEME_FILE_VERSION,
} from "./themePalette";
function asHex(value: string): string {
const hex = themeColorToHex(value);
if (!hex) throw new Error(`Expected a theme color, received ${value}`);
return hex.slice(0, 7);
}
function canonical(value: string): string {
const color = toCanonicalThemeColor(value);
if (!color) throw new Error(`Expected a theme color, received ${value}`);
return color;
}
function expectThemeColors(
colors: Readonly<Record<string, string>>,
expected: Readonly<Record<string, string>>,
): void {
for (const [role, value] of Object.entries(expected)) {
expect(asHex(colors[role]!)).toBe(value);
}
}
function contrastRatio(first: string, second: string): number {
const toRgb = (value: string) => {
const hex = value.slice(1);
const hex = asHex(value).slice(1);
return [0, 1, 2].map(
(channel) => Number.parseInt(hex.slice(channel * 2, channel * 2 + 2), 16) / 255,
);
@@ -56,8 +80,8 @@ describe("theme files", () => {
const dark = createManagedThemeColors("dark", "#ffffff", "#ffff00");
const darkDefaults = getDefaultThemeColors("dark");
expect(light.canvas).not.toBe("#111827");
expect(dark.canvas).not.toBe("#ffffff");
expect(asHex(light.canvas)).not.toBe("#111827");
expect(asHex(dark.canvas)).not.toBe("#ffffff");
expect(contrastRatio(light.accent, light.canvas)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(dark.accent, dark.canvas)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(light.textMuted, light.canvas)).toBeGreaterThanOrEqual(4.5);
@@ -73,7 +97,7 @@ describe("theme files", () => {
// Status colors fall back to T3 Code's standard red and amber rather than
// the flagship palette's, so no generated theme inherits a brand tint.
const channels = (value: string) =>
[1, 3, 5].map((index) => Number.parseInt(value.slice(index, index + 2), 16)) as [
[1, 3, 5].map((index) => Number.parseInt(asHex(value).slice(index, index + 2), 16)) as [
number,
number,
number,
@@ -92,7 +116,7 @@ describe("theme files", () => {
expect(warnRed).toBeGreaterThan(warnBlue);
expect(warnGreen).toBeGreaterThan(warnBlue);
}
expect(dark.error).not.toBe(darkDefaults.error);
expect(asHex(dark.error)).not.toBe(asHex(darkDefaults.error));
});
it("derives readable, distinctive vivid palettes from exact seeds", () => {
@@ -108,8 +132,10 @@ describe("theme files", () => {
for (const [appearance, canvas, accent] of seeds) {
const colors = createVividThemeColors(appearance, canvas, accent);
// Exact seeds are honored.
expect(colors.canvas).toBe(canvas);
expect(colors.accent).toBe(accent);
expect(colors.canvas).toMatch(/^oklch\(/);
expect(colors.accent).toMatch(/^oklch\(/);
expect(asHex(colors.canvas)).toBe(canvas);
expect(asHex(colors.accent)).toBe(accent);
// Readability is solved per surface.
expect(contrastRatio(colors.text, colors.canvas)).toBeGreaterThanOrEqual(7);
expect(contrastRatio(colors.textMuted, colors.canvas)).toBeGreaterThanOrEqual(4.5);
@@ -131,7 +157,7 @@ describe("theme files", () => {
// The companion action is a distinct voice, not the accent again.
expect(colors.messageAction).not.toBe(colors.accent);
// Update family follows the theme, not the default palette.
expect(colors.update).toBe(accent);
expect(asHex(colors.update)).toBe(accent);
}
});
@@ -170,13 +196,53 @@ describe("theme files", () => {
label: "Ocean dusk",
appearance: "dark",
colors: {
canvas: "#07152f",
accent: "#67c2ff",
placeholder: "#968d9f",
canvas: canonical("#07152f"),
accent: canonical("#67c2ff"),
placeholder: canonical("#968d9f"),
},
});
});
it("decodes literal CSS color formats into OKLCH without dropping alpha", () => {
const theme = parseThemeFile({
version: THEME_FILE_VERSION,
name: "Translucent",
appearance: "light",
colors: {
canvas: "oklch(62% 0.2 280deg / 50%)",
accent: "#abcd",
focus: "rgb(10 20 30 / 50%)",
error: "hsl(350 80% 50%)",
warning: "hwb(45 10% 20%)",
update: "lab(60% 40 30)",
messageAction: "lch(60% 50 120)",
sidebar: "oklab(0.6 0.1 -0.1)",
terminalCursor: "color(display-p3 0.8 0.2 0.3)",
terminalSelection: "rebeccapurple",
terminalScrollbar: "transparent",
terminalScrollbarHover: "rgb(10 20 30 / none)",
},
});
expect(theme.colors.canvas).toBe("oklch(0.62 0.2 280 / 0.5)");
expect(theme.colors.accent).toBe(canonical("#abcd"));
expect(themeColorToHex(theme.colors.accent)).toBe("#aabbccdd");
expect(themeColorToHex(theme.colors.focus)).toBe("#0a141e80");
expect(themeColorToHex(theme.colors.terminalSelection)).toBe("#663399");
expect(theme.colors.terminalScrollbar).toBe("oklch(0 0 0 / 0)");
expect(themeColorToHex(theme.colors.terminalScrollbarHover)).toBe("#0a141e00");
for (const role of [
"error",
"warning",
"update",
"messageAction",
"sidebar",
"terminalCursor",
] as const) {
expect(theme.colors[role]).toMatch(/^oklch\(/);
}
});
it("rejects unknown roles and invalid color values", () => {
expect(() =>
parseThemeFile({
@@ -194,16 +260,20 @@ describe("theme files", () => {
appearance: "light",
colors: { accent: "var(--danger)" },
}),
).toThrow('The color for "accent" must be a hex color');
).toThrow('The color for "accent" must be a literal CSS color');
});
it("serializes a theme back into the importable file shape", () => {
const serialized = serializeThemeFile(T3_CHAT_THEME);
it("canonicalizes the explicitly exported theme", () => {
const serialized = serializeThemeFile({
...T3_CHAT_THEME,
colors: { ...T3_CHAT_THEME.colors, accent: "hsl(263 70% 58%)" },
});
expect(JSON.parse(serialized)).toMatchObject({
version: THEME_FILE_VERSION,
id: T3_CHAT_THEME.id,
name: T3_CHAT_THEME.label,
appearance: "light",
colors: { accent: canonical("hsl(263 70% 58%)") },
});
});
@@ -257,8 +327,8 @@ describe("theme files", () => {
expect(getThemeModes(theme)).toEqual(["light", "dark"]);
expect(getThemeColorsForMode(theme, "dark")).toMatchObject({
canvas: "#101827",
text: "#eef5ff",
canvas: canonical("#101827"),
text: canonical("#eef5ff"),
});
expect(getThemeModes(T3_CHAT_THEME)).toEqual(["light", "dark"]);
expect(resolveThemeAppearance(T3_CHAT_THEME.id, true, true)).toBe("dark");
@@ -266,13 +336,13 @@ describe("theme files", () => {
expect(resolveThemeAppearance(T3_CHAT_THEME.id, false, false, "dark")).toBe("dark");
expect(resolveDesktopTheme(T3_CHAT_THEME.id, false, "dark")).toBe("dark");
expect(JSON.parse(serializeThemeFile(theme)).variants.dark).toMatchObject({
canvas: "#101827",
text: "#eef5ff",
canvas: canonical("#101827"),
text: canonical("#eef5ff"),
});
});
it("keeps the T3 Chat palette faithful and readable", () => {
expect(T3_CHAT_THEME.colors).toMatchObject({
expectThemeColors(T3_CHAT_THEME.colors, {
canvas: "#fdf7fd",
chrome: "#fdf7fd",
toolbarBorder: "#efbdeb",
@@ -287,7 +357,7 @@ describe("theme files", () => {
accentSurface: "#f3e6f5",
sidebar: "#f2e1f4",
});
expect(T3_CHAT_THEME.variants?.dark).toMatchObject({
expectThemeColors(T3_CHAT_THEME.variants!.dark!, {
canvas: "#1f1a24",
chrome: "#1f1a24",
surface: "#29232d",
@@ -321,8 +391,8 @@ describe("theme files", () => {
expect(getThemeModes(theme)).toEqual(["light", "dark"]);
expect(theme.sidebarArtwork).toBe(true);
expect(themeAllowsSidebarArtwork(theme.id)).toBe(true);
expect(theme.colors.accent).toMatch(/^#[0-9a-f]{6}$/i);
expect(theme.variants?.dark?.accent).toMatch(/^#[0-9a-f]{6}$/i);
expect(theme.colors.accent).toMatch(/^oklch\(/);
expect(theme.variants?.dark?.accent).toMatch(/^oklch\(/);
for (const mode of ["light", "dark"] as const) {
const colors = getThemeColorsForMode(theme, mode);
@@ -380,7 +450,9 @@ describe("theme files", () => {
});
expect(getThemeModes(theme)).toEqual(["dark"]);
expect(getThemeColorsForMode(theme, "dark")).toMatchObject({ canvas: "#111827" });
expect(getThemeColorsForMode(theme, "dark")).toMatchObject({
canvas: canonical("#111827"),
});
expect(getThemeColorsForMode(theme, "light")).toBeNull();
});
@@ -419,8 +491,16 @@ describe("theme files", () => {
vi.unstubAllGlobals();
});
it("updates a personal theme without changing its id", () => {
it("canonicalizes explicit writes without migrating untouched themes", () => {
const stored = new Map<string, string>();
const untouchedTheme = {
id: "legacy",
label: "Legacy",
appearance: "dark",
colors: { accent: "#5b6cff", futureRole: "hsl(10 20% 30%)" },
futureMetadata: { version: 2 },
};
stored.set(CUSTOM_THEMES_STORAGE_KEY, JSON.stringify([untouchedTheme]));
vi.stubGlobal("window", {
localStorage: {
getItem: (key: string) => stored.get(key) ?? null,
@@ -442,24 +522,176 @@ describe("theme files", () => {
const updatedTheme = updateCustomTheme({
...createdTheme,
label: "Aurora Night",
colors: { ...createdTheme.colors, accent: "#7c3aed" },
colors: { ...createdTheme.colors, accent: "hsl(263 70% 58%)" },
});
expect(updatedTheme).toMatchObject({
id: "aurora",
label: "Aurora Night",
colors: { accent: canonical("hsl(263 70% 58%)") },
});
expect(updatedTheme).not.toHaveProperty("sidebarArtwork");
invalidateCustomThemes();
expect(getCustomThemes()).toEqual([updatedTheme]);
expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")[0]).toMatchObject({
const storedThemes = JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]");
expect(storedThemes[0]).toEqual(untouchedTheme);
expect(storedThemes[1]).toMatchObject({
id: "aurora",
label: "Aurora Night",
colors: { accent: canonical("hsl(263 70% 58%)") },
});
expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")[0]).not.toHaveProperty(
"sidebarArtwork",
expect(storedThemes[1]).not.toHaveProperty("sidebarArtwork");
invalidateCustomThemes();
expect(getCustomThemes().find((theme) => theme.id === "aurora")).toMatchObject({
id: "aurora",
colors: { accent: canonical("hsl(263 70% 58%)") },
});
removeCustomTheme("aurora");
expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")).toEqual([untouchedTheme]);
vi.unstubAllGlobals();
invalidateCustomThemes();
});
it("writes from the cached raw snapshot without risking a destructive reread", () => {
const legacyTheme = {
id: "legacy",
label: "Legacy",
appearance: "dark",
colors: { accent: "#5b6cff" },
futureMetadata: true,
};
let storedThemes = JSON.stringify([legacyTheme]);
let readCount = 0;
const setItem = vi.fn((_key: string, value: string) => {
storedThemes = value;
});
vi.stubGlobal("window", {
localStorage: {
getItem: () => {
readCount += 1;
if (readCount > 1) throw new Error("transient read failure");
return storedThemes;
},
setItem,
},
});
invalidateCustomThemes();
expect(getCustomThemes()).toHaveLength(1);
installCustomTheme(
parseThemeFile({
version: THEME_FILE_VERSION,
id: "aurora",
name: "Aurora",
appearance: "light",
colors: { accent: "hsl(263 70% 58%)" },
}),
);
expect(readCount).toBe(1);
expect(setItem).toHaveBeenCalledOnce();
expect(JSON.parse(storedThemes)[0]).toEqual(legacyTheme);
vi.unstubAllGlobals();
invalidateCustomThemes();
});
it("refuses to overwrite a theme library that could not be read", () => {
const setItem = vi.fn();
vi.stubGlobal("window", {
localStorage: {
getItem: () => {
throw new Error("storage unavailable");
},
setItem,
},
});
invalidateCustomThemes();
expect(getCustomThemes()).toEqual([]);
expect(() =>
installCustomTheme(
parseThemeFile({
version: THEME_FILE_VERSION,
id: "aurora",
name: "Aurora",
appearance: "light",
colors: { accent: "#5b6cff" },
}),
),
).toThrow(`Failed to read the theme library from ${CUSTOM_THEMES_STORAGE_KEY}.`);
expect(setItem).not.toHaveBeenCalled();
vi.unstubAllGlobals();
invalidateCustomThemes();
});
it("rejects malformed stored entries that reuse an installed theme id", () => {
const storedThemes = JSON.stringify([{ id: "aurora", malformed: true }]);
const setItem = vi.fn();
vi.stubGlobal("window", {
localStorage: {
getItem: () => storedThemes,
setItem,
},
});
invalidateCustomThemes();
expect(() =>
installCustomTheme(
parseThemeFile({
version: THEME_FILE_VERSION,
id: "aurora",
name: "Aurora",
appearance: "light",
colors: { accent: "#5b6cff" },
}),
),
).toThrow('A theme named "Aurora" is already installed.');
expect(setItem).not.toHaveBeenCalled();
vi.unstubAllGlobals();
invalidateCustomThemes();
});
it("collapses duplicate raw entries when their theme is explicitly updated", () => {
const stored = new Map<string, string>();
const theme = {
id: "aurora",
label: "Aurora",
appearance: "light",
colors: { accent: "#5b6cff" },
};
const untouchedTheme = { id: "future", malformed: true, metadata: { version: 2 } };
stored.set(
CUSTOM_THEMES_STORAGE_KEY,
JSON.stringify([theme, { id: "aurora", malformed: true }, untouchedTheme]),
);
vi.stubGlobal("window", {
localStorage: {
getItem: (key: string) => stored.get(key) ?? null,
setItem: (key: string, value: string) => stored.set(key, value),
},
});
invalidateCustomThemes();
const installedTheme = getCustomThemes()[0]!;
updateCustomTheme({
...installedTheme,
label: "Aurora Night",
colors: { ...installedTheme.colors, accent: "hsl(263 70% 58%)" },
});
const updatedLibrary = JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]");
expect(updatedLibrary.filter((entry: { id?: string }) => entry.id === "aurora")).toHaveLength(
1,
);
expect(updatedLibrary[0]).toMatchObject({
id: "aurora",
label: "Aurora Night",
colors: { accent: canonical("hsl(263 70% 58%)") },
});
expect(updatedLibrary[1]).toEqual(untouchedTheme);
vi.unstubAllGlobals();
invalidateCustomThemes();
});
@@ -530,23 +762,23 @@ describe("stored theme preferences", () => {
expect(isKnownThemePreference("missing-theme")).toBe(false);
});
it("keeps stored themes with unknown roles and drops invalid entries", () => {
it("decodes stored colors in memory without writing during reads", () => {
const storedThemes = JSON.stringify([
{
id: "aurora",
label: "Aurora",
appearance: "light",
colors: { canvas: "#f8fbff", futureRole: "#123456", accent: "not-a-color" },
variants: { dark: { canvas: "rgb(16 24 39)" } },
},
{ id: "light", label: "Reserved", appearance: "light", colors: {} },
{ id: "aurora", label: "Duplicate", appearance: "dark", colors: {} },
]);
const setItem = vi.fn();
vi.stubGlobal("window", {
localStorage: {
getItem: (key: string) =>
key === CUSTOM_THEMES_STORAGE_KEY
? JSON.stringify([
{
id: "aurora",
label: "Aurora",
appearance: "light",
colors: { canvas: "#f8fbff", futureRole: "#123456", accent: "not-a-color" },
variants: { light: { canvas: "#101827" } },
},
{ id: "light", label: "Reserved", appearance: "light", colors: {} },
{ id: "aurora", label: "Duplicate", appearance: "dark", colors: {} },
])
: null,
getItem: (key: string) => (key === CUSTOM_THEMES_STORAGE_KEY ? storedThemes : null),
setItem,
},
});
invalidateCustomThemes();
@@ -555,11 +787,16 @@ describe("stored theme preferences", () => {
expect(themes).toHaveLength(1);
expect(themes[0]).toMatchObject({
id: "aurora",
colors: { canvas: "#f8fbff", accent: getDefaultThemeColors("light").accent },
colors: { canvas: canonical("#f8fbff"), accent: getDefaultThemeColors("light").accent },
});
expect(getThemeModes(themes[0]!)).toEqual(["light", "dark"]);
expect(getThemeColorsForMode(themes[0]!, "dark")?.canvas).toBe(canonical("rgb(16 24 39)"));
expect(setItem).not.toHaveBeenCalled();
expect(JSON.parse(storedThemes)[0].colors).toEqual({
canvas: "#f8fbff",
futureRole: "#123456",
accent: "not-a-color",
});
// The variant shadowing the base appearance is dropped so the theme
// round-trips through parseThemeFile on export.
expect(getThemeModes(themes[0]!)).toEqual(["light"]);
vi.unstubAllGlobals();
invalidateCustomThemes();
+381 -215
View File
@@ -1,4 +1,6 @@
import * as Schema from "effect/Schema";
import "culori/css";
import { converter, parse } from "culori/fn";
export const T3_CHAT_THEME_ID = "t3-chat" as const;
export const T3_CHAT_THEME_LABEL = "T3 Chat";
@@ -129,7 +131,16 @@ const RESERVED_THEME_IDS = new Set([
]);
const customThemeListeners = new Set<() => void>();
let customThemesSnapshot: ReadonlyArray<ThemeDefinition> | null = null;
type CustomThemeLibrarySnapshot =
| Readonly<{
status: "ready";
storedThemes: ReadonlyArray<unknown>;
themes: ReadonlyArray<ThemeDefinition>;
}>
| Readonly<{ status: "unavailable"; reason: "malformed" }>
| Readonly<{ status: "unavailable"; reason: "storage-unavailable"; cause: unknown }>;
let customThemeLibrarySnapshot: CustomThemeLibrarySnapshot | null = null;
const themePreviewListeners = new Set<() => void>();
let themePreviewSidebarArtwork: boolean | null = null;
@@ -157,10 +168,7 @@ function isThemeAppearance(value: unknown): value is ThemeAppearance {
}
export function isThemeColor(value: unknown): value is string {
return (
typeof value === "string" &&
/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(value)
);
return typeof value === "string" && toCanonicalThemeColor(value) !== null;
}
function isThemeId(value: unknown): value is string {
@@ -180,8 +188,9 @@ function parseStoredThemeColors(value: unknown, appearance: ThemeAppearance): Th
// Tolerate unknown roles and malformed values so themes saved by other
// builds (for example one that adds a new role) keep their remaining colors.
for (const [role, color] of Object.entries(value)) {
if (THEME_COLOR_ROLE_SET.has(role) && isThemeColor(color)) {
colors[role as ThemeColorRole] = color;
const normalized = toCanonicalThemeColor(color);
if (THEME_COLOR_ROLE_SET.has(role) && normalized) {
colors[role as ThemeColorRole] = normalized;
}
}
return colors as ThemeColors;
@@ -226,26 +235,43 @@ function parseStoredTheme(value: unknown): ThemeDefinition | null {
};
}
function readCustomThemesFromStorage(): ReadonlyArray<ThemeDefinition> {
if (typeof window === "undefined") return [];
try {
const raw = window.localStorage.getItem(CUSTOM_THEMES_STORAGE_KEY);
if (!raw) return [];
const parsed: unknown = JSON.parse(raw);
if (!Array.isArray(parsed)) return [];
const themes: ThemeDefinition[] = [];
for (const value of parsed) {
const theme = parseStoredTheme(value);
if (theme && !themes.some((existing) => existing.id === theme.id)) {
themes.push(theme);
}
}
return themes;
} catch {
return [];
function readCustomThemeLibrarySnapshot(): CustomThemeLibrarySnapshot {
if (typeof window === "undefined") {
return { status: "ready", storedThemes: [], themes: [] };
}
let raw: string | null;
try {
raw = window.localStorage.getItem(CUSTOM_THEMES_STORAGE_KEY);
} catch (cause) {
return { status: "unavailable", reason: "storage-unavailable", cause };
}
if (!raw) return { status: "ready", storedThemes: [], themes: [] };
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
return { status: "unavailable", reason: "malformed" };
}
if (!Array.isArray(parsed)) return { status: "unavailable", reason: "malformed" };
const themes: ThemeDefinition[] = [];
for (const value of parsed) {
const theme = parseStoredTheme(value);
if (theme && !themes.some((existing) => existing.id === theme.id)) {
themes.push(theme);
}
}
return { status: "ready", storedThemes: parsed, themes };
}
function getCustomThemeLibrarySnapshot(): CustomThemeLibrarySnapshot {
if (customThemeLibrarySnapshot === null) {
customThemeLibrarySnapshot = readCustomThemeLibrarySnapshot();
}
return customThemeLibrarySnapshot;
}
function notifyCustomThemeListeners() {
@@ -253,15 +279,13 @@ function notifyCustomThemeListeners() {
}
export function invalidateCustomThemes() {
customThemesSnapshot = null;
customThemeLibrarySnapshot = null;
notifyCustomThemeListeners();
}
export function getCustomThemes(): ReadonlyArray<ThemeDefinition> {
if (customThemesSnapshot === null) {
customThemesSnapshot = readCustomThemesFromStorage();
}
return customThemesSnapshot;
const snapshot = getCustomThemeLibrarySnapshot();
return snapshot.status === "ready" ? snapshot.themes : [];
}
export function subscribeToCustomThemes(listener: () => void): () => void {
@@ -470,7 +494,7 @@ const T3_CHAT_DARK_COLORS: ThemeColors = {
* stock tokens (index.css) so a draft seeded from the default look paints the
* pixels the user is already seeing. Alpha-bearing tokens are flattened over
* their real backdrops (canvas, or the sidebar for its rows) because theme
* colors must be opaque hex.
* colors are stored as opaque OKLCH tokens.
*/
const T3_CODE_LIGHT_THEME_COLORS: ThemeColors = {
canvas: "#fcfcfc",
@@ -599,7 +623,10 @@ const T3_CODE_DARK_THEME_COLORS: ThemeColors = {
* files.
*/
export function getStandardThemeColors(appearance: ThemeAppearance): ThemeColors {
return appearance === "dark" ? T3_CODE_DARK_THEME_COLORS : T3_CODE_LIGHT_THEME_COLORS;
if (appearance === "dark") {
return (standardDarkThemeColors ??= decodeThemeColors(T3_CODE_DARK_THEME_COLORS));
}
return (standardLightThemeColors ??= decodeThemeColors(T3_CODE_LIGHT_THEME_COLORS));
}
type ThemeRgbColor = {
@@ -614,34 +641,81 @@ type ThemeHslColor = {
l: number;
};
type ThemeOklch = { L: number; C: number; h: number };
type ParsedThemeColor = { color: ThemeOklch; alpha: number };
let standardLightThemeColors: ThemeColors | undefined;
let standardDarkThemeColors: ThemeColors | undefined;
const THEME_LIGHT_FOREGROUND: ThemeRgbColor = { r: 255, g: 250, b: 255 };
const THEME_DARK_FOREGROUND: ThemeRgbColor = { r: 36, g: 21, b: 35 };
const THEME_WHITE_FOREGROUND: ThemeRgbColor = { r: 255, g: 255, b: 255 };
const THEME_BLACK_FOREGROUND: ThemeRgbColor = { r: 0, g: 0, b: 0 };
function parseThemeRgbColor(value: string, fallback: ThemeRgbColor): ThemeRgbColor {
const match = value.trim().match(/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
if (!match) return fallback;
const raw = match[1];
if (!raw) return fallback;
const hex =
raw.length <= 4
? raw
.slice(0, 3)
.split("")
.map((part) => part.repeat(2))
.join("")
: raw.slice(0, 6);
if (hex.length !== 6) return fallback;
const convertToOklch = converter("oklch");
function parseThemeColor(value: unknown): ParsedThemeColor | null {
if (typeof value !== "string") return null;
const input = value.trim();
const parsed = parse(input);
if (!parsed) return null;
const color = convertToOklch(parsed);
const lightness = color.l ?? 0;
const chroma = color.c ?? 0;
const hue = color.h ?? 0;
// CSS missing components behave as zero outside interpolation. Culori omits
// a `none` alpha from its parsed object, so distinguish it from omitted alpha.
const alpha = /\/\s*none\s*\)$/i.test(input) ? 0 : (color.alpha ?? 1);
if (![lightness, chroma, hue, alpha].every(Number.isFinite)) return null;
return {
r: Number.parseInt(hex.slice(0, 2), 16),
g: Number.parseInt(hex.slice(2, 4), 16),
b: Number.parseInt(hex.slice(4, 6), 16),
color: {
L: Math.min(1, Math.max(0, lightness)),
C: Math.max(0, chroma),
h: hue,
},
alpha: Math.min(1, Math.max(0, alpha)),
};
}
function formatThemeColorNumber(value: number, precision: number): string {
const rounded = Math.abs(value) < 10 ** -precision / 2 ? 0 : value;
return rounded.toFixed(precision).replace(/(?:\.0+|(?:(\.[0-9]*?)0+))$/, "$1");
}
function formatOklchThemeColor(color: ThemeOklch, alpha = 1): string {
const normalizedHue = color.C < 0.0000005 ? 0 : ((color.h % 360) + 360) % 360;
const body = `${formatThemeColorNumber(color.L, 6)} ${formatThemeColorNumber(color.C, 6)} ${formatThemeColorNumber(normalizedHue, 3)}`;
return alpha < 1 ? `oklch(${body} / ${formatThemeColorNumber(alpha, 4)})` : `oklch(${body})`;
}
/**
* Decode a literal CSS color into the runtime's canonical OKLCH form. Stored
* values use this path in memory without mutating localStorage.
*/
export function toCanonicalThemeColor(value: unknown): string | null {
const parsed = parseThemeColor(value);
return parsed ? formatOklchThemeColor(parsed.color, parsed.alpha) : null;
}
/** Convert a runtime theme color for hex-only editor and import adapters. */
export function themeColorToHex(value: string): string | null {
const color = parseThemeColor(value);
const parsed = color ? { rgb: themeOklchToRgb(color.color), alpha: color.alpha } : null;
if (!parsed) return null;
const opaque = themeRgbToHexColor(parsed.rgb);
if (parsed.alpha >= 1) return opaque;
const alpha = Math.round(parsed.alpha * 255)
.toString(16)
.padStart(2, "0");
return `${opaque}${alpha}`;
}
function parseThemeRgbColor(value: string, fallback: ThemeRgbColor): ThemeRgbColor {
const parsed = parseThemeColor(value);
return parsed ? themeOklchToRgb(parsed.color) : fallback;
}
function themeRgbToHexColor(color: ThemeRgbColor): string {
return `#${[color.r, color.g, color.b]
.map((channel) =>
@@ -652,6 +726,41 @@ function themeRgbToHexColor(color: ThemeRgbColor): string {
.join("")}`;
}
function themeRgbToThemeColor(color: ThemeRgbColor): string {
return formatOklchThemeColor(themeRgbToOklch(color));
}
function decodeThemeColors(colors: ThemeColors): ThemeColors {
return Object.fromEntries(
THEME_COLOR_ROLES.map((role) => {
const color = toCanonicalThemeColor(colors[role]);
if (!color) {
throw new Error(
`The color for "${role}" must be a literal CSS color such as oklch(0.62 0.2 280).`,
);
}
return [role, color];
}),
) as Record<ThemeColorRole, string>;
}
function canonicalizeThemeDefinition(theme: ThemeDefinition): ThemeDefinition {
return {
...theme,
colors: decodeThemeColors(theme.colors),
...(theme.variants
? {
variants: Object.fromEntries(
Object.entries(theme.variants).map(([appearance, colors]) => [
appearance,
decodeThemeColors(colors),
]),
) as ThemeVariants,
}
: {}),
};
}
function themeRgbToHsl(color: ThemeRgbColor): ThemeHslColor {
const red = color.r / 255;
const green = color.g / 255;
@@ -717,10 +826,6 @@ function themeRelativeLuminance(color: ThemeRgbColor): number {
// ---------------------------------------------------------------------------
// Vivid palette engine: perceptual (OKLCH) derivation for user-created themes.
// Built-in themes keep the legacy derivation so their shipped palettes and the
// boot splash copies stay byte-identical.
type ThemeOklch = { L: number; C: number; h: number };
function srgbChannelToLinear(channel: number): number {
const c = channel / 255;
@@ -759,24 +864,30 @@ function oklchToRgbUnclamped({ L, C, h }: ThemeOklch): { r: number; g: number; b
};
}
/** Convert to sRGB, walking chroma toward grey until the color is in gamut. */
function themeOklchToRgb(color: ThemeOklch): ThemeRgbColor {
let { C } = color;
for (let step = 0; step < 12; step += 1) {
/** Find the greatest chroma along the same lightness and hue that fits in sRGB. */
function mapThemeOklchToSrgbGamut(color: ThemeOklch): ThemeOklch {
const isInGamut = (C: number) => {
const linear = oklchToRgbUnclamped({ ...color, C });
const inGamut = [linear.r, linear.g, linear.b].every(
return [linear.r, linear.g, linear.b].every(
(channel) => channel >= -0.0001 && channel <= 1.0001,
);
if (inGamut) {
return {
r: linearChannelToSrgb(linear.r),
g: linearChannelToSrgb(linear.g),
b: linearChannelToSrgb(linear.b),
};
}
C *= 0.82;
};
if (isInGamut(color.C)) return color;
let low = 0;
let high = color.C;
const steps = Math.max(1, Math.ceil(Math.log2(Math.max(color.C, 0.000001) / 0.000001)));
for (let step = 0; step < steps; step += 1) {
const mid = (low + high) / 2;
if (isInGamut(mid)) low = mid;
else high = mid;
}
const linear = oklchToRgbUnclamped({ ...color, C: 0 });
return { ...color, C: low };
}
/** Convert to sRGB after applying the palette engine's gamut mapping. */
function themeOklchToRgb(color: ThemeOklch): ThemeRgbColor {
const linear = oklchToRgbUnclamped(mapThemeOklchToSrgbGamut(color));
return {
r: linearChannelToSrgb(linear.r),
g: linearChannelToSrgb(linear.g),
@@ -784,6 +895,10 @@ function themeOklchToRgb(color: ThemeOklch): ThemeRgbColor {
};
}
function themeOklchToThemeColor(color: ThemeOklch): string {
return formatOklchThemeColor(mapThemeOklchToSrgbGamut(color));
}
/** Binary-search the lightness that reaches the contrast target against a background. */
function solveOklchLightness(
base: ThemeOklch,
@@ -856,26 +971,24 @@ function standardStatusColors(canvas: ThemeRgbColor): {
// tinted one they can fall just short, so lightness is nudged until the
// pair clears 4.5 while the hue stays standard.
const readableOn = (foreground: string, surface: ThemeRgbColor) =>
themeRgbToHexColor(
themeOklchToRgb(
solveOklchLightness(
themeRgbToOklch(parseThemeRgbColor(foreground, canvas)),
surface,
// A hair above 4.5: the solve happens in OKLCH and the result is
// quantized to 8-bit hex, which can shave the last hundredth off.
4.6,
appearance === "dark" ? "lighter" : "darker",
),
themeOklchToThemeColor(
solveOklchLightness(
themeRgbToOklch(parseThemeRgbColor(foreground, canvas)),
surface,
// Leave a little headroom for browser color conversion at render time.
4.6,
appearance === "dark" ? "lighter" : "darker",
),
);
const errorSurface = surfaceOf(standard.error);
const warningSurface = surfaceOf(standard.warning);
return {
...standard,
error: toCanonicalThemeColor(standard.error)!,
errorForeground: readableOn(standard.errorForeground, errorSurface),
errorSurface: themeRgbToHexColor(errorSurface),
errorSurface: themeRgbToThemeColor(errorSurface),
warning: toCanonicalThemeColor(standard.warning)!,
warningForeground: readableOn(standard.warningForeground, warningSurface),
warningSurface: themeRgbToHexColor(warningSurface),
warningSurface: themeRgbToThemeColor(warningSurface),
};
}
@@ -912,7 +1025,7 @@ export function createVividThemeColors(
C: chroma,
h: hue,
});
const hex = (color: ThemeOklch) => themeRgbToHexColor(themeOklchToRgb(color));
const themeColor = (color: ThemeOklch) => themeOklchToThemeColor(color);
// Text carries a whisper of the accent hue instead of falling back to a
// fixed foreground, and is solved to WCAG AAA against the canvas.
@@ -956,8 +1069,8 @@ export function createVividThemeColors(
const updateSurface = surfaceAt(dark ? 0.14 : 0.09, Math.min(0.12, accent.C * 0.55));
const foregroundOn = (surfaceRgb: ThemeRgbColor): string =>
themeRgbToHexColor(
themeOklchToRgb(solveOklchLightness(textBase, surfaceRgb, 4.6, dark ? "lighter" : "darker")),
themeOklchToThemeColor(
solveOklchLightness(textBase, surfaceRgb, 4.6, dark ? "lighter" : "darker"),
);
const mutedForeground = foregroundOn(mutedRgb);
const placeholder = foregroundOn(surfaceRaisedRgb);
@@ -967,58 +1080,58 @@ export function createVividThemeColors(
return {
...defaults,
...standardStatusColors(canvasRgb),
canvas: themeRgbToHexColor(canvasRgb),
canvas: themeRgbToThemeColor(canvasRgb),
// The top bar shares the canvas so the main panel reads as one surface.
chrome: themeRgbToHexColor(canvasRgb),
toolbar: themeRgbToHexColor(canvasRgb),
toolbarForeground: themeRgbToHexColor(textRgb),
toolbarBorder: hex(surfaceAt(dark ? 0.14 : 0.1, Math.min(0.08, accent.C * 0.4))),
toolbarControl: hex(surfaceAt(dark ? 0.09 : 0.05, tintC * 1.3)),
toolbarControlForeground: themeRgbToHexColor(textRgb),
toolbarControlHover: hex(surfaceAt(dark ? 0.14 : 0.09, tintC * 1.6)),
surface: hex(surface),
surfaceRaised: hex(surfaceRaised),
surfaceOverlay: hex(surfaceOverlay),
text: themeRgbToHexColor(textRgb),
textMuted: themeRgbToHexColor(textMutedRgb),
border: hex(border),
input: hex(input),
focus: themeRgbToHexColor(accentRgb),
accent: themeRgbToHexColor(accentRgb),
accentForeground: themeRgbToHexColor(accentForeground),
secondary: hex(secondary),
chrome: themeRgbToThemeColor(canvasRgb),
toolbar: themeRgbToThemeColor(canvasRgb),
toolbarForeground: themeRgbToThemeColor(textRgb),
toolbarBorder: themeColor(surfaceAt(dark ? 0.14 : 0.1, Math.min(0.08, accent.C * 0.4))),
toolbarControl: themeColor(surfaceAt(dark ? 0.09 : 0.05, tintC * 1.3)),
toolbarControlForeground: themeRgbToThemeColor(textRgb),
toolbarControlHover: themeColor(surfaceAt(dark ? 0.14 : 0.09, tintC * 1.6)),
surface: themeColor(surface),
surfaceRaised: themeColor(surfaceRaised),
surfaceOverlay: themeColor(surfaceOverlay),
text: themeRgbToThemeColor(textRgb),
textMuted: themeRgbToThemeColor(textMutedRgb),
border: themeColor(border),
input: themeColor(input),
focus: themeRgbToThemeColor(accentRgb),
accent: themeRgbToThemeColor(accentRgb),
accentForeground: themeRgbToThemeColor(accentForeground),
secondary: themeColor(secondary),
secondaryForeground: foregroundOn(secondaryRgb),
muted: hex(muted),
muted: themeColor(muted),
mutedForeground,
placeholder,
secondaryLabel: themeRgbToHexColor(textMutedRgb),
iconMuted: themeRgbToHexColor(textMutedRgb),
update: themeRgbToHexColor(accentRgb),
secondaryLabel: themeRgbToThemeColor(textMutedRgb),
iconMuted: themeRgbToThemeColor(textMutedRgb),
update: themeRgbToThemeColor(accentRgb),
updateForeground: foregroundOn(themeOklchToRgb(updateSurface)),
updateSurface: hex(updateSurface),
accentSurface: hex(accentSurface),
updateSurface: themeColor(updateSurface),
accentSurface: themeColor(accentSurface),
accentSurfaceForeground: foregroundOn(accentSurfaceRgb),
messageSurface: hex(messageSurface),
messageSurface: themeColor(messageSurface),
messageForeground: foregroundOn(messageSurfaceRgb),
messageAction: themeRgbToHexColor(actionRgb),
messageActionForeground: themeRgbToHexColor(actionForeground),
messageActionHover: hex(actionHover),
codeBackground: hex(codeBackground),
codeForeground: themeRgbToHexColor(textRgb),
sidebar: hex(sidebar),
messageAction: themeRgbToThemeColor(actionRgb),
messageActionForeground: themeRgbToThemeColor(actionForeground),
messageActionHover: themeColor(actionHover),
codeBackground: themeColor(codeBackground),
codeForeground: themeRgbToThemeColor(textRgb),
sidebar: themeColor(sidebar),
sidebarForeground: foregroundOn(sidebarRgb),
sidebarMutedForeground: themeRgbToHexColor(standardMutedThemeText(sidebarRgb, textRgb)),
sidebarControlSurface: hex(surfaceAt(dark ? 0.1 : 0.07, tintC * 1.5)),
sidebarRowHover: hex(surfaceAt(dark ? 0.08 : 0.06, Math.min(0.08, accent.C * 0.45))),
sidebarRowActive: hex(surfaceAt(dark ? 0.12 : 0.09, Math.min(0.1, accent.C * 0.55))),
sidebarRowSelected: hex(surfaceAt(dark ? 0.14 : 0.1, Math.min(0.11, accent.C * 0.6))),
sidebarBorder: hex(surfaceAt(dark ? 0.17 : 0.12, Math.min(0.08, accent.C * 0.4))),
terminalBackground: themeRgbToHexColor(canvasRgb),
terminalForeground: themeRgbToHexColor(textRgb),
terminalCursor: themeRgbToHexColor(accentRgb),
terminalSelection: hex(surfaceAt(dark ? 0.18 : 0.12, Math.min(0.12, accent.C * 0.55))),
terminalScrollbar: hex(surfaceAt(dark ? 0.22 : 0.16, tintC)),
terminalScrollbarHover: hex(surfaceAt(dark ? 0.3 : 0.22, tintC)),
sidebarMutedForeground: themeRgbToThemeColor(standardMutedThemeText(sidebarRgb, textRgb)),
sidebarControlSurface: themeColor(surfaceAt(dark ? 0.1 : 0.07, tintC * 1.5)),
sidebarRowHover: themeColor(surfaceAt(dark ? 0.08 : 0.06, Math.min(0.08, accent.C * 0.45))),
sidebarRowActive: themeColor(surfaceAt(dark ? 0.12 : 0.09, Math.min(0.1, accent.C * 0.55))),
sidebarRowSelected: themeColor(surfaceAt(dark ? 0.14 : 0.1, Math.min(0.11, accent.C * 0.6))),
sidebarBorder: themeColor(surfaceAt(dark ? 0.17 : 0.12, Math.min(0.08, accent.C * 0.4))),
terminalBackground: themeRgbToThemeColor(canvasRgb),
terminalForeground: themeRgbToThemeColor(textRgb),
terminalCursor: themeRgbToThemeColor(accentRgb),
terminalSelection: themeColor(surfaceAt(dark ? 0.18 : 0.12, Math.min(0.12, accent.C * 0.55))),
terminalScrollbar: themeColor(surfaceAt(dark ? 0.22 : 0.16, tintC)),
terminalScrollbarHover: themeColor(surfaceAt(dark ? 0.3 : 0.22, tintC)),
};
}
@@ -1127,8 +1240,7 @@ function managedThemeAccent(
const color = themeHslToRgb({ h: hsl.h, s: saturation, l: lightness });
return { color, lightness, contrast: themeContrastRatio(color, background) };
});
// Leave a little room for rounding when the generated RGB values become a
// six-digit hex token.
// Leave a little room for browser color conversion at render time.
const readableCandidates = candidates.filter((candidate) => candidate.contrast >= 4.7);
const pool = readableCandidates.length > 0 ? readableCandidates : candidates;
@@ -1210,80 +1322,80 @@ export function createManagedThemeColors(
return {
...defaults,
...standardStatusColors(canvas),
update: themeRgbToHexColor(accent),
updateForeground: themeRgbToHexColor(updateForeground),
updateSurface: themeRgbToHexColor(updateSurface),
canvas: themeRgbToHexColor(canvas),
chrome: themeRgbToHexColor(chrome),
toolbar: themeRgbToHexColor(chrome),
toolbarForeground: themeRgbToHexColor(text),
toolbarBorder: themeRgbToHexColor(toolbarBorder),
toolbarControl: themeRgbToHexColor(toolbarControl),
toolbarControlForeground: themeRgbToHexColor(text),
toolbarControlHover: themeRgbToHexColor(accentSurface),
surface: themeRgbToHexColor(canvas),
surfaceRaised: themeRgbToHexColor(surfaceRaised),
surfaceOverlay: themeRgbToHexColor(surfaceOverlay),
text: themeRgbToHexColor(text),
textMuted: themeRgbToHexColor(textMuted),
update: themeRgbToThemeColor(accent),
updateForeground: themeRgbToThemeColor(updateForeground),
updateSurface: themeRgbToThemeColor(updateSurface),
canvas: themeRgbToThemeColor(canvas),
chrome: themeRgbToThemeColor(chrome),
toolbar: themeRgbToThemeColor(chrome),
toolbarForeground: themeRgbToThemeColor(text),
toolbarBorder: themeRgbToThemeColor(toolbarBorder),
toolbarControl: themeRgbToThemeColor(toolbarControl),
toolbarControlForeground: themeRgbToThemeColor(text),
toolbarControlHover: themeRgbToThemeColor(accentSurface),
surface: themeRgbToThemeColor(canvas),
surfaceRaised: themeRgbToThemeColor(surfaceRaised),
surfaceOverlay: themeRgbToThemeColor(surfaceOverlay),
text: themeRgbToThemeColor(text),
textMuted: themeRgbToThemeColor(textMuted),
// Borders blend through the accent before lightening so control chrome
// carries the theme hue like the hand-tuned palettes (#5c345b, #e0d3e1)
// instead of flattening to grey.
border: themeRgbToHexColor(
border: themeRgbToThemeColor(
mixThemeRgbColors(
mixThemeRgbColors(canvas, accent, appearance === "dark" ? 0.22 : 0.1),
text,
0.1,
),
),
input: themeRgbToHexColor(
input: themeRgbToThemeColor(
mixThemeRgbColors(
mixThemeRgbColors(canvas, accent, appearance === "dark" ? 0.3 : 0.14),
text,
appearance === "dark" ? 0.14 : 0.13,
),
),
focus: themeRgbToHexColor(accent),
accent: themeRgbToHexColor(accent),
accentForeground: themeRgbToHexColor(accentForeground),
secondary: themeRgbToHexColor(secondary),
secondaryForeground: themeRgbToHexColor(readableThemeForeground(secondary)),
muted: themeRgbToHexColor(muted),
mutedForeground: themeRgbToHexColor(mutedForeground),
placeholder: themeRgbToHexColor(placeholder),
secondaryLabel: themeRgbToHexColor(textMuted),
iconMuted: themeRgbToHexColor(textMuted),
accentSurface: themeRgbToHexColor(accentSurface),
accentSurfaceForeground: themeRgbToHexColor(readableThemeForeground(accentSurface)),
messageSurface: themeRgbToHexColor(messageSurface),
messageForeground: themeRgbToHexColor(readableThemeForeground(messageSurface)),
messageAction: themeRgbToHexColor(accent),
messageActionForeground: themeRgbToHexColor(accentForeground),
messageActionHover: themeRgbToHexColor(messageActionHover),
codeBackground: themeRgbToHexColor(codeBackground),
codeForeground: themeRgbToHexColor(readableThemeForeground(codeBackground)),
sidebar: themeRgbToHexColor(sidebar),
sidebarForeground: themeRgbToHexColor(readableThemeForeground(sidebar)),
sidebarMutedForeground: themeRgbToHexColor(standardMutedThemeText(sidebar, text)),
sidebarControlSurface: themeRgbToHexColor(
focus: themeRgbToThemeColor(accent),
accent: themeRgbToThemeColor(accent),
accentForeground: themeRgbToThemeColor(accentForeground),
secondary: themeRgbToThemeColor(secondary),
secondaryForeground: themeRgbToThemeColor(readableThemeForeground(secondary)),
muted: themeRgbToThemeColor(muted),
mutedForeground: themeRgbToThemeColor(mutedForeground),
placeholder: themeRgbToThemeColor(placeholder),
secondaryLabel: themeRgbToThemeColor(textMuted),
iconMuted: themeRgbToThemeColor(textMuted),
accentSurface: themeRgbToThemeColor(accentSurface),
accentSurfaceForeground: themeRgbToThemeColor(readableThemeForeground(accentSurface)),
messageSurface: themeRgbToThemeColor(messageSurface),
messageForeground: themeRgbToThemeColor(readableThemeForeground(messageSurface)),
messageAction: themeRgbToThemeColor(accent),
messageActionForeground: themeRgbToThemeColor(accentForeground),
messageActionHover: themeRgbToThemeColor(messageActionHover),
codeBackground: themeRgbToThemeColor(codeBackground),
codeForeground: themeRgbToThemeColor(readableThemeForeground(codeBackground)),
sidebar: themeRgbToThemeColor(sidebar),
sidebarForeground: themeRgbToThemeColor(readableThemeForeground(sidebar)),
sidebarMutedForeground: themeRgbToThemeColor(standardMutedThemeText(sidebar, text)),
sidebarControlSurface: themeRgbToThemeColor(
mixThemeRgbColors(sidebar, text, appearance === "dark" ? 0.16 : 0.08),
),
sidebarRowHover: themeRgbToHexColor(mixThemeRgbColors(sidebar, accent, 0.12)),
sidebarRowActive: themeRgbToHexColor(mixThemeRgbColors(sidebar, accent, 0.2)),
sidebarRowSelected: themeRgbToHexColor(mixThemeRgbColors(sidebar, accent, 0.24)),
sidebarBorder: themeRgbToHexColor(
sidebarRowHover: themeRgbToThemeColor(mixThemeRgbColors(sidebar, accent, 0.12)),
sidebarRowActive: themeRgbToThemeColor(mixThemeRgbColors(sidebar, accent, 0.2)),
sidebarRowSelected: themeRgbToThemeColor(mixThemeRgbColors(sidebar, accent, 0.24)),
sidebarBorder: themeRgbToThemeColor(
mixThemeRgbColors(sidebar, text, appearance === "dark" ? 0.35 : 0.12),
),
terminalBackground: themeRgbToHexColor(terminalBackground),
terminalForeground: themeRgbToHexColor(readableThemeForeground(terminalBackground)),
terminalCursor: themeRgbToHexColor(accent),
terminalSelection: themeRgbToHexColor(
terminalBackground: themeRgbToThemeColor(terminalBackground),
terminalForeground: themeRgbToThemeColor(readableThemeForeground(terminalBackground)),
terminalCursor: themeRgbToThemeColor(accent),
terminalSelection: themeRgbToThemeColor(
mixThemeRgbColors(canvas, accent, appearance === "dark" ? 0.35 : 0.18),
),
terminalScrollbar: themeRgbToHexColor(
terminalScrollbar: themeRgbToThemeColor(
mixThemeRgbColors(canvas, text, appearance === "dark" ? 0.42 : 0.22),
),
terminalScrollbarHover: themeRgbToHexColor(
terminalScrollbarHover: themeRgbToThemeColor(
mixThemeRgbColors(canvas, text, appearance === "dark" ? 0.55 : 0.32),
),
};
@@ -1293,16 +1405,16 @@ export const T3_CHAT_THEME: ThemeDefinition = {
id: T3_CHAT_THEME_ID,
label: T3_CHAT_THEME_LABEL,
appearance: "light",
colors: T3_CHAT_LIGHT_COLORS,
colors: decodeThemeColors(T3_CHAT_LIGHT_COLORS),
variants: {
dark: T3_CHAT_DARK_COLORS,
dark: decodeThemeColors(T3_CHAT_DARK_COLORS),
},
sidebarArtwork: true,
};
/** Theme-file defaults follow the flagship palette for the requested mode. */
export function getDefaultThemeColors(appearance: ThemeAppearance): ThemeColors {
return appearance === "dark" ? T3_CHAT_DARK_COLORS : T3_CHAT_LIGHT_COLORS;
return appearance === "dark" ? T3_CHAT_THEME.variants!.dark! : T3_CHAT_THEME.colors;
}
/**
@@ -1320,9 +1432,9 @@ function themeActionColors(
? THEME_BLACK_FOREGROUND
: THEME_WHITE_FOREGROUND;
return {
messageAction: action,
messageActionForeground: themeRgbToHexColor(foreground),
messageActionHover: themeRgbToHexColor(mixThemeRgbColors(rgb, towardOpposite, 0.12)),
messageAction: toCanonicalThemeColor(action) ?? themeRgbToThemeColor(rgb),
messageActionForeground: themeRgbToThemeColor(foreground),
messageActionHover: themeRgbToThemeColor(mixThemeRgbColors(rgb, towardOpposite, 0.12)),
};
}
@@ -1452,39 +1564,72 @@ export function themeIdFromName(name: string): string {
export class ThemeLibraryStorageError extends Schema.TaggedErrorClass<ThemeLibraryStorageError>()(
"ThemeLibraryStorageError",
{ storageKey: Schema.String, cause: Schema.Defect() },
{
storageKey: Schema.String,
operation: Schema.Literals(["read", "write"]),
reason: Schema.Literals(["malformed", "storage-unavailable"]),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to write the theme library to ${this.storageKey}.`;
const direction = this.operation === "read" ? "from" : "to";
return `Failed to ${this.operation} the theme library ${direction} ${this.storageKey}.`;
}
}
export const isThemeLibraryStorageError = Schema.is(ThemeLibraryStorageError);
function saveCustomThemes(themes: ReadonlyArray<ThemeDefinition>): void {
function saveCustomThemes(
storedThemes: ReadonlyArray<unknown>,
themes: ReadonlyArray<ThemeDefinition>,
): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(CUSTOM_THEMES_STORAGE_KEY, JSON.stringify(themes));
customThemesSnapshot = themes;
window.localStorage.setItem(CUSTOM_THEMES_STORAGE_KEY, JSON.stringify(storedThemes));
customThemeLibrarySnapshot = { status: "ready", storedThemes, themes };
} catch (cause) {
throw new ThemeLibraryStorageError({ storageKey: CUSTOM_THEMES_STORAGE_KEY, cause });
throw new ThemeLibraryStorageError({
storageKey: CUSTOM_THEMES_STORAGE_KEY,
operation: "write",
reason: "storage-unavailable",
cause,
});
}
notifyCustomThemeListeners();
}
function getWritableCustomThemeLibrary(): Extract<CustomThemeLibrarySnapshot, { status: "ready" }> {
const snapshot = getCustomThemeLibrarySnapshot();
if (snapshot.status === "unavailable") {
throw new ThemeLibraryStorageError({
storageKey: CUSTOM_THEMES_STORAGE_KEY,
operation: "read",
reason: snapshot.reason,
...("cause" in snapshot ? { cause: snapshot.cause } : {}),
});
}
return snapshot;
}
function storedThemeHasId(storedTheme: unknown, themeId: string): boolean {
return isRecord(storedTheme) && storedTheme.id === themeId;
}
export function installCustomTheme(theme: ThemeDefinition): ThemeDefinition {
if (RESERVED_THEME_IDS.has(theme.id)) {
throw new Error(`The theme id "${theme.id}" is reserved.`);
}
const library = getWritableCustomThemeLibrary();
if (
[...BUILT_IN_THEME_DEFINITIONS, ...getCustomThemes()].some(
(existing) => existing.id === theme.id,
)
BUILT_IN_THEME_DEFINITIONS.some((existing) => existing.id === theme.id) ||
library.storedThemes.some((storedTheme) => storedThemeHasId(storedTheme, theme.id))
) {
throw new Error(`A theme named "${theme.label}" is already installed.`);
}
saveCustomThemes([...getCustomThemes(), theme]);
return theme;
const canonicalTheme = canonicalizeThemeDefinition(theme);
const themes = [...library.themes, canonicalTheme];
saveCustomThemes([...library.storedThemes, canonicalTheme], themes);
return canonicalTheme;
}
export function updateCustomTheme(theme: ThemeDefinition): ThemeDefinition {
@@ -1492,22 +1637,39 @@ export function updateCustomTheme(theme: ThemeDefinition): ThemeDefinition {
throw new Error(`The theme id "${theme.id}" is reserved.`);
}
const themes = getCustomThemes();
const library = getWritableCustomThemeLibrary();
const themes = library.themes;
const themeIndex = themes.findIndex((existing) => existing.id === theme.id);
if (themeIndex === -1) {
throw new Error(`The theme "${theme.label}" is not installed.`);
}
const canonicalTheme = canonicalizeThemeDefinition(theme);
const nextThemes = [...themes];
nextThemes[themeIndex] = theme;
saveCustomThemes(nextThemes);
return theme;
nextThemes[themeIndex] = canonicalTheme;
const nextStoredThemes: unknown[] = [];
let replaced = false;
for (const storedTheme of library.storedThemes) {
if (!storedThemeHasId(storedTheme, theme.id)) {
nextStoredThemes.push(storedTheme);
} else if (!replaced) {
nextStoredThemes.push(canonicalTheme);
replaced = true;
}
}
saveCustomThemes(nextStoredThemes, nextThemes);
return canonicalTheme;
}
export function removeCustomTheme(themeId: string): void {
const nextThemes = getCustomThemes().filter((theme) => theme.id !== themeId);
if (nextThemes.length === getCustomThemes().length) return;
saveCustomThemes(nextThemes);
const library = getWritableCustomThemeLibrary();
const nextThemes = library.themes.filter((theme) => theme.id !== themeId);
if (nextThemes.length === library.themes.length) return;
saveCustomThemes(
library.storedThemes.filter((storedTheme) => !storedThemeHasId(storedTheme, themeId)),
nextThemes,
);
}
function parseThemeColorOverrides(value: unknown): ThemeColorOverrides {
@@ -1518,10 +1680,13 @@ function parseThemeColorOverrides(value: unknown): ThemeColorOverrides {
if (!THEME_COLOR_ROLE_SET.has(role)) {
throw new Error(`"${role}" is not a supported theme color role.`);
}
if (!isThemeColor(color)) {
throw new Error(`The color for "${role}" must be a hex color such as #8b5cf6.`);
const normalized = toCanonicalThemeColor(color);
if (!normalized) {
throw new Error(
`The color for "${role}" must be a literal CSS color such as oklch(0.62 0.2 280).`,
);
}
overrides[role as ThemeColorRole] = color;
overrides[role as ThemeColorRole] = normalized;
}
if (Object.keys(overrides).length === 0) {
throw new Error("Add at least one color role to the theme file.");
@@ -1586,14 +1751,15 @@ export function parseThemeFile(value: unknown): ThemeDefinition {
}
export function serializeThemeFile(theme: ThemeDefinition): string {
const canonicalTheme = canonicalizeThemeDefinition(theme);
const file: ThemeFile = {
version: THEME_FILE_VERSION,
id: theme.id,
name: theme.label,
appearance: theme.appearance,
colors: theme.colors,
...(theme.variants ? { variants: theme.variants } : {}),
...(theme.managed ? { managed: true } : {}),
id: canonicalTheme.id,
name: canonicalTheme.label,
appearance: canonicalTheme.appearance,
colors: canonicalTheme.colors,
...(canonicalTheme.variants ? { variants: canonicalTheme.variants } : {}),
...(canonicalTheme.managed ? { managed: true } : {}),
};
return `${JSON.stringify(file, null, 2)}\n`;
}
+26 -19
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import { getThemeColorsForMode, THEME_FILE_VERSION } from "./themePalette";
import { getThemeColorsForMode, themeColorToHex, THEME_FILE_VERSION } from "./themePalette";
import {
isVsCodeThemeFile,
pairVsCodeThemes,
@@ -8,9 +8,15 @@ import {
resolveThemeLabelCollisions,
} from "./vscodeThemeImport";
function asHex(value: string): string {
const hex = themeColorToHex(value);
if (!hex) throw new Error(`Expected a theme color, received ${value}`);
return hex;
}
function contrastRatio(first: string, second: string): number {
const toChannels = (value: string) => {
const hex = value.slice(1);
const hex = asHex(value).slice(1);
return [0, 1, 2].map(
(channel) => Number.parseInt(hex.slice(channel * 2, channel * 2 + 2), 16) / 255,
);
@@ -69,18 +75,18 @@ describe("VS Code theme import", () => {
// The slug name is read as words; a displayName would win verbatim.
expect(theme.label).toBe("Pierre Dark Soft");
expect(theme.appearance).toBe("dark");
expect(theme.colors.canvas).toBe("#171717");
expect(theme.colors.text).toBe("#d4d4d4");
expect(theme.colors.accent).toBe("#69b1ff");
expect(theme.colors.sidebar).toBe("#101010");
expect(theme.colors.terminalBackground).toBe("#101010");
expect(asHex(theme.colors.canvas)).toBe("#171717");
expect(asHex(theme.colors.text)).toBe("#d4d4d4");
expect(asHex(theme.colors.accent)).toBe("#69b1ff");
expect(asHex(theme.colors.sidebar)).toBe("#101010");
expect(asHex(theme.colors.terminalBackground)).toBe("#101010");
});
it("flattens alpha overlays onto the surface they sit on", () => {
const theme = parseVsCodeThemeFile(VSCODE_DARK);
// #1f3e5e59 over the #101010 sidebar, not left semi-transparent.
expect(theme.colors.sidebarRowHover).toMatch(/^#[0-9a-f]{6}$/);
expect(theme.colors.sidebarRowHover).not.toBe("#1f3e5e59");
expect(theme.colors.sidebarRowHover).toMatch(/^oklch\(/);
expect(asHex(theme.colors.sidebarRowHover)).not.toBe("#1f3e5e59");
expect(theme.colors.sidebarRowSelected).not.toBe(theme.colors.sidebar);
});
@@ -88,7 +94,7 @@ describe("VS Code theme import", () => {
const theme = parseVsCodeThemeFile(VSCODE_DARK);
const colors = getThemeColorsForMode(theme, "dark")!;
for (const value of Object.values(colors)) {
expect(value).toMatch(/^#[0-9a-f]{3,8}$/i);
expect(value).toMatch(/^oklch\(/);
}
expect(contrastRatio(colors.text, colors.canvas)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(colors.sidebarForeground, colors.sidebar)).toBeGreaterThanOrEqual(4.5);
@@ -117,7 +123,7 @@ describe("VS Code theme import", () => {
type: "dark",
colors: { "editor.background": "#101010", "editor.foreground": "#111111" },
});
expect(theme.colors.text).not.toBe("#111111");
expect(asHex(theme.colors.text)).not.toBe("#111111");
expect(contrastRatio(theme.colors.text, theme.colors.canvas)).toBeGreaterThanOrEqual(4.5);
});
@@ -134,7 +140,7 @@ describe("VS Code theme import", () => {
"terminal.background": "#fbfbfb",
},
});
expect(theme.colors.sidebar).toBe("#fafafa");
expect(asHex(theme.colors.sidebar)).toBe("#fafafa");
expect(
contrastRatio(theme.colors.sidebarForeground, theme.colors.sidebar),
).toBeGreaterThanOrEqual(4.5);
@@ -156,10 +162,10 @@ describe("VS Code theme import", () => {
"editor.selectionBackground": "color(display-p3 0.308664 0.645271 1.000000 / 0.300000)",
},
});
expect(theme.colors.canvas).toMatch(/^#0[89ab]/);
expect(theme.colors.text).toMatch(/^#f[a-f0-9]/);
expect(asHex(theme.colors.canvas)).toMatch(/^#0[89ab]/);
expect(asHex(theme.colors.text)).toMatch(/^#f[a-f0-9]/);
// The P3 blue lands in sRGB blue, not black or a clipped grey.
const accent = theme.colors.accent;
const accent = asHex(theme.colors.accent);
const [red, green, blue] = [1, 3, 5].map((index) =>
Number.parseInt(accent.slice(index, index + 2), 16),
) as [number, number, number];
@@ -192,8 +198,8 @@ describe("VS Code theme import", () => {
const github = themes[0]!;
expect(github.appearance).toBe("light");
expect(getThemeColorsForMode(github, "dark")).not.toBeNull();
expect(getThemeColorsForMode(github, "dark")!.canvas).toBe("#101014");
expect(github.colors.canvas).toBe("#fdfdfd");
expect(asHex(getThemeColorsForMode(github, "dark")!.canvas)).toBe("#101014");
expect(asHex(github.colors.canvas)).toBe("#fdfdfd");
// The unpaired dimmed variant stays a single dark theme.
expect(getThemeColorsForMode(themes[2]!, "light")).toBeNull();
});
@@ -220,14 +226,15 @@ describe("VS Code theme import", () => {
// surface, plain surfaces) must stay near the canvas, not turn blue.
const theme = parseVsCodeThemeFile(VSCODE_DARK);
const spread = (value: string) => {
const channels = [1, 3, 5].map((index) => Number.parseInt(value.slice(index, index + 2), 16));
const hex = asHex(value);
const channels = [1, 3, 5].map((index) => Number.parseInt(hex.slice(index, index + 2), 16));
return Math.max(...channels) - Math.min(...channels);
};
expect(spread(theme.colors.codeBackground)).toBeLessThanOrEqual(8);
expect(spread(theme.colors.surface)).toBeLessThanOrEqual(8);
expect(spread(theme.colors.text)).toBeLessThanOrEqual(12);
// The accent itself keeps the file's color.
expect(theme.colors.accent).toBe("#69b1ff");
expect(asHex(theme.colors.accent)).toBe("#69b1ff");
});
it("tells same-named variants apart by their file names", () => {
+2 -1
View File
@@ -2,6 +2,7 @@ import {
createVividThemeColors,
getThemeModes,
parseThemeFile,
themeColorToHex,
THEME_FILE_VERSION,
type ThemeAppearance,
type ThemeColorRole,
@@ -138,7 +139,7 @@ function contrastRatio(first: VsCodeRgb, second: VsCodeRgb): number {
}
function hexToRgb(value: string): VsCodeRgb {
return parseVsCodeColor(value) ?? { r: 0, g: 0, b: 0, a: 1 };
return parseVsCodeColor(themeColorToHex(value) ?? value) ?? { r: 0, g: 0, b: 0, a: 1 };
}
/**
+11
View File
@@ -570,6 +570,9 @@ importers:
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
culori:
specifier: ^4.0.2
version: 4.0.2
effect:
specifier: 4.0.0-beta.103
version: 4.0.0-beta.103(patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6)
@@ -631,6 +634,9 @@ importers:
'@types/compression':
specifier: ^1.8.1
version: 1.8.1
'@types/culori':
specifier: ^4.0.1
version: 4.0.1
'@types/react':
specifier: ~19.2.14
version: 19.2.16
@@ -4794,6 +4800,9 @@ packages:
'@types/[email protected]':
resolution: {integrity: sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==}
'@types/[email protected]':
resolution: {integrity: sha512-43M51r/22CjhbOXyGT361GZ9vncSVQ39u62x5eJdBQFviI8zWp2X5jzqg7k4M6PVgDQAClpy2bUe2dtwEgEDVQ==}
'@types/[email protected]':
resolution: {integrity: sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==}
@@ -14972,6 +14981,8 @@ snapshots:
dependencies:
'@types/node': 24.12.4
'@types/[email protected]': {}
'@types/[email protected]':
dependencies:
'@types/ms': 2.1.0