Open History to see the last commit
1import {
2 BUILT_IN_THEMES,
3 getThemeColorsForAppearance,
4 MOBILE_DEFAULT_THEME_ID,
5 MOBILE_THEME_IDS as SHARED_MOBILE_THEME_IDS,
6 type MobileThemeId as SharedMobileThemeId,
7 type ThemeAppearance,
8 type ThemeColors,
9} from "@t3tools/shared/themePalettes";
10import {
11 STANDARD_THEME_PREVIEW_COLORS,
12 type ThemePreviewColors,
13} from "@t3tools/shared/themePreview";
14import { DEFAULT_MOBILE_THEME_VARIABLES } from "./mobileDefaultTheme";
15
16export const DEFAULT_MOBILE_THEME_ID = MOBILE_DEFAULT_THEME_ID;
17export const MOBILE_THEME_IDS = SHARED_MOBILE_THEME_IDS;
18export type MobileThemeId = SharedMobileThemeId;
19export type MobileThemeAppearance = ThemeAppearance;
20export type MobileThemeMode = MobileThemeAppearance | "system";
21export type MobileThemeIds = Readonly<Record<MobileThemeAppearance, MobileThemeId>>;
22
23export const MOBILE_THEME_OPTIONS: ReadonlyArray<{
24 readonly id: MobileThemeId;
25 readonly label: string;
26}> = [
27 { id: DEFAULT_MOBILE_THEME_ID, label: "T3 Code" },
28 ...BUILT_IN_THEMES.map((theme) => ({ id: theme.id as MobileThemeId, label: theme.label })),
29];
30
31type MobileThemeVariable = `--color-${string}`;
32export type MobileThemeVariables = Readonly<Record<MobileThemeVariable, string>>;
33
34export function normalizeMobileThemeId(value: unknown): MobileThemeId {
35 return typeof value === "string" && (MOBILE_THEME_IDS as readonly string[]).includes(value)
36 ? (value as MobileThemeId)
37 : DEFAULT_MOBILE_THEME_ID;
38}
39
40export function normalizeMobileThemeMode(value: unknown): MobileThemeMode {
41 return value === "light" || value === "dark" || value === "system" ? value : "system";
42}
43
44export function resolveMobileThemeIds(preferences: {
45 readonly themeId?: unknown;
46 readonly lightThemeId?: unknown;
47 readonly darkThemeId?: unknown;
48}): MobileThemeIds {
49 const legacyThemeId = normalizeMobileThemeId(preferences.themeId);
50 return {
51 light:
52 preferences.lightThemeId === undefined
53 ? legacyThemeId
54 : normalizeMobileThemeId(preferences.lightThemeId),
55 dark:
56 preferences.darkThemeId === undefined
57 ? legacyThemeId
58 : normalizeMobileThemeId(preferences.darkThemeId),
59 };
60}
61
62export function createMobileThemeSelectionPatch(
63 themeIds: MobileThemeIds,
64 activeAppearance: MobileThemeAppearance,
65 selectedAppearance: MobileThemeAppearance,
66 value: MobileThemeId,
67) {
68 const nextThemeIds: MobileThemeIds = {
69 light: selectedAppearance === "light" ? value : themeIds.light,
70 dark: selectedAppearance === "dark" ? value : themeIds.dark,
71 };
72 return {
73 lightThemeId: nextThemeIds.light,
74 darkThemeId: nextThemeIds.dark,
75 // Keep older OTA bundles on the theme for the appearance currently in use.
76 themeId: nextThemeIds[activeAppearance],
77 };
78}
79
80export function createMobileThemePairPatch(value: MobileThemeId) {
81 return {
82 lightThemeId: value,
83 darkThemeId: value,
84 themeId: value,
85 };
86}
87
88const OKLCH_PATTERN = /^oklch\(\s*([\d.]+)\s+([\d.]+)\s+(-?[\d.]+)(?:\s*\/\s*([\d.]+))?\s*\)$/;
89
90function linearToSrgb(value: number): number {
91 const converted = value <= 0.0031308 ? 12.92 * value : 1.055 * value ** (1 / 2.4) - 0.055;
92 return Math.round(Math.min(1, Math.max(0, converted)) * 255);
93}
94
95/** React Native does not accept OKLCH ColorValues, so palettes cross the app boundary as sRGB. */
96export function themeColorToNativeColor(value: string): string {
97 const match = OKLCH_PATTERN.exec(value);
98 if (!match) return value;
99
100 const lightness = Number(match[1]);
101 const chroma = Number(match[2]);
102 const hue = (Number(match[3]) * Math.PI) / 180;
103 const alpha = match[4] === undefined ? 1 : Number(match[4]);
104 const a = chroma * Math.cos(hue);
105 const b = chroma * Math.sin(hue);
106 const lPrime = lightness + 0.3963377774 * a + 0.2158037573 * b;
107 const mPrime = lightness - 0.1055613458 * a - 0.0638541728 * b;
108 const sPrime = lightness - 0.0894841775 * a - 1.291485548 * b;
109 const l = lPrime ** 3;
110 const m = mPrime ** 3;
111 const s = sPrime ** 3;
112 const red = linearToSrgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s);
113 const green = linearToSrgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s);
114 const blue = linearToSrgb(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s);
115
116 return alpha < 1
117 ? `rgba(${red}, ${green}, ${blue}, ${Number(alpha.toFixed(4))})`
118 : `#${[red, green, blue].map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
119}
120
121function nativeColors(colors: ThemeColors): ThemeColors {
122 return Object.fromEntries(
123 Object.entries(colors).map(([role, color]) => [role, themeColorToNativeColor(color)]),
124 ) as ThemeColors;
125}
126
127function withAlpha(color: string, alpha: number): string {
128 const hex = color.startsWith("#") ? color.slice(1) : "";
129 if (hex.length !== 6) return color;
130 const [red, green, blue] = [0, 2, 4].map((offset) =>
131 Number.parseInt(hex.slice(offset, offset + 2), 16),
132 );
133 return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
134}
135
136function rgbChannels(color: string): readonly [number, number, number] | null {
137 const match = /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i.exec(color);
138 return match
139 ? [Number.parseInt(match[1], 16), Number.parseInt(match[2], 16), Number.parseInt(match[3], 16)]
140 : null;
141}
142
143function relativeLuminance(channels: readonly [number, number, number]): number {
144 const [red, green, blue] = channels.map((channel) => {
145 const value = channel / 255;
146 return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
147 });
148 return 0.2126 * red! + 0.7152 * green! + 0.0722 * blue!;
149}
150
151function contrastRatio(
152 first: readonly [number, number, number],
153 second: readonly [number, number, number],
154): number {
155 const firstLuminance = relativeLuminance(first);
156 const secondLuminance = relativeLuminance(second);
157 return (
158 (Math.max(firstLuminance, secondLuminance) + 0.05) /
159 (Math.min(firstLuminance, secondLuminance) + 0.05)
160 );
161}
162
163/** Preserve the theme's action hue while making it readable as skill text on a message bubble. */
164function readableMessageAccent(accent: string, surface: string): string {
165 const accentChannels = rgbChannels(accent);
166 const surfaceChannels = rgbChannels(surface);
167 if (
168 !accentChannels ||
169 !surfaceChannels ||
170 contrastRatio(accentChannels, surfaceChannels) >= 4.5
171 ) {
172 return accent;
173 }
174
175 const black = [0, 0, 0] as const;
176 const white = [255, 255, 255] as const;
177 const target =
178 contrastRatio(black, surfaceChannels) >= contrastRatio(white, surfaceChannels) ? black : white;
179 let readable: readonly [number, number, number] = target;
180 let lowerAmount = 0;
181 let upperAmount = 1;
182 for (let index = 0; index < 12; index += 1) {
183 const amount = (lowerAmount + upperAmount) / 2;
184 const candidate: readonly [number, number, number] = [
185 Math.round(accentChannels[0] + (target[0] - accentChannels[0]) * amount),
186 Math.round(accentChannels[1] + (target[1] - accentChannels[1]) * amount),
187 Math.round(accentChannels[2] + (target[2] - accentChannels[2]) * amount),
188 ];
189 if (contrastRatio(candidate, surfaceChannels) >= 4.5) {
190 readable = candidate;
191 upperAmount = amount;
192 } else {
193 lowerAmount = amount;
194 }
195 }
196 return `#${readable.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
197}
198
199export function themeColorWithAlpha(color: string, alpha: number): string {
200 const hex = /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i.exec(color);
201 if (hex) {
202 return `rgba(${Number.parseInt(hex[1], 16)}, ${Number.parseInt(hex[2], 16)}, ${Number.parseInt(hex[3], 16)}, ${alpha})`;
203 }
204 const rgb = /^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/.exec(color);
205 return rgb ? `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, ${alpha})` : color;
206}
207
208export function createMobileThemeVariables(
209 colors: ThemeColors,
210 appearance: MobileThemeAppearance,
211): MobileThemeVariables {
212 const c = nativeColors(colors);
213 return {
214 "--color-screen": c.canvas,
215 "--color-sheet": withAlpha(c.chrome, 0.98),
216 "--color-sheet-solid": c.chrome,
217 "--color-card": c.surfaceRaised,
218 "--color-card-alt": c.surface,
219 "--color-card-translucent": withAlpha(c.surfaceRaised, 0.8),
220 "--color-foreground": c.text,
221 "--color-foreground-secondary": c.textMuted,
222 "--color-foreground-muted": c.mutedForeground,
223 "--color-foreground-tertiary": c.secondaryLabel,
224 "--color-border": c.border,
225 "--color-border-subtle": withAlpha(c.border, 0.7),
226 "--color-separator": withAlpha(c.border, 0.55),
227 "--color-subtle": c.muted,
228 "--color-subtle-strong": c.secondary,
229 "--color-inline-skill-background": c.accentSurface,
230 "--color-inline-skill-border": withAlpha(c.accent, 0.42),
231 "--color-inline-skill-foreground": c.accentSurfaceForeground,
232 "--color-primary": c.accent,
233 "--color-primary-foreground": c.accentForeground,
234 "--color-primary-shadow": "#000000",
235 "--color-secondary": c.secondary,
236 "--color-secondary-foreground": c.secondaryForeground,
237 "--color-secondary-border": c.border,
238 "--color-switch-active-track": c.accent,
239 "--color-switch-active-thumb": c.accentForeground,
240 "--color-switch-inactive-track": c.secondary,
241 "--color-switch-inactive-thumb": c.mutedForeground,
242 "--color-danger": c.errorSurface,
243 "--color-danger-border": withAlpha(c.error, 0.32),
244 "--color-danger-foreground": c.errorForeground,
245 "--color-input": c.surfaceRaised,
246 "--color-input-border": c.input,
247 "--color-sidebar-search": c.sidebarControlSurface,
248 "--color-placeholder": c.placeholder,
249 "--color-icon": c.text,
250 "--color-icon-muted": c.iconMuted,
251 "--color-icon-subtle": c.secondaryLabel,
252 "--color-header": withAlpha(c.toolbar, 0.97),
253 "--color-header-border": c.toolbarBorder,
254 "--color-glass-surface": withAlpha(c.surfaceOverlay, 0.74),
255 "--color-glass-tint": withAlpha(c.surfaceOverlay, 0.22),
256 "--color-status-bar": c.canvas,
257 "--color-md-body": c.text,
258 "--color-md-strong": c.toolbarForeground,
259 "--color-md-link": c.accent,
260 "--color-md-blockquote-border": c.border,
261 "--color-md-blockquote-bg": c.muted,
262 "--color-md-code-bg": c.codeBackground,
263 "--color-md-code-text": c.codeForeground,
264 "--color-md-user-code-bg": withAlpha(c.messageForeground, 0.18),
265 "--color-md-user-code-text": c.messageForeground,
266 "--color-md-user-fence-bg": withAlpha("#000000", appearance === "dark" ? 0.28 : 0.16),
267 "--color-md-user-fence-text": c.messageForeground,
268 "--color-md-hr": c.border,
269 "--color-user-bubble": c.messageSurface,
270 "--color-user-bubble-foreground": c.messageForeground,
271 "--color-user-bubble-foreground-muted": withAlpha(c.messageForeground, 0.78),
272 "--color-user-bubble-skill-foreground": readableMessageAccent(
273 c.messageAction,
274 c.messageSurface,
275 ),
276 "--color-backdrop": withAlpha("#000000", appearance === "dark" ? 0.48 : 0.22),
277 "--color-drawer": withAlpha(c.sidebar, 0.99),
278 "--color-drawer-shadow": withAlpha("#000000", appearance === "dark" ? 0.32 : 0.12),
279 "--color-dot-separator": withAlpha(c.textMuted, 0.35),
280 "--color-wordmark": c.text,
281 "--color-chevron": withAlpha(c.textMuted, 0.42),
282 };
283}
284
285export function getMobileThemeVariables(
286 themeId: MobileThemeId,
287 appearance: MobileThemeAppearance,
288 overrides: Partial<MobileThemeVariables> | null = null,
289): MobileThemeVariables {
290 const baseVariables = (() => {
291 if (themeId === DEFAULT_MOBILE_THEME_ID) return DEFAULT_MOBILE_THEME_VARIABLES[appearance];
292 const theme =
293 BUILT_IN_THEMES.find((candidate) => candidate.id === themeId) ?? BUILT_IN_THEMES[0];
294 const colors = getThemeColorsForAppearance(theme, appearance) ?? theme.colors;
295 return createMobileThemeVariables(colors, appearance);
296 })();
297
298 // The complete base record guarantees that optional overrides cannot leave a token undefined.
299 return overrides ? ({ ...baseVariables, ...overrides } as MobileThemeVariables) : baseVariables;
300}
301
302export function getMobileThemePreviewColors(
303 themeId: MobileThemeId,
304 appearance: MobileThemeAppearance,
305): ThemePreviewColors {
306 if (themeId === DEFAULT_MOBILE_THEME_ID) return STANDARD_THEME_PREVIEW_COLORS[appearance];
307 const theme = BUILT_IN_THEMES.find((candidate) => candidate.id === themeId) ?? BUILT_IN_THEMES[0];
308 const colors = getThemeColorsForAppearance(theme, appearance) ?? theme.colors;
309 return {
310 canvas: themeColorToNativeColor(colors.canvas),
311 accent: themeColorToNativeColor(colors.accent),
312 messageAction: themeColorToNativeColor(colors.messageAction),
313 };
314}