Open History to see the last commit
1import {
2 BUILT_IN_THEMES,
3 T3_CHAT_THEME,
4 T3_CODE_LIGHT_THEME_COLORS,
5 T3_CODE_DARK_THEME_COLORS,
6 getThemeColorsForAppearance,
7 MOBILE_DEFAULT_THEME_ID,
8 MOBILE_THEME_IDS as SHARED_MOBILE_THEME_IDS,
9 type MobileThemeId as SharedMobileThemeId,
10 type ThemeAppearance,
11 type ThemeColors,
12} from "@t3tools/shared/themePalettes";
13import {
14 STANDARD_THEME_PREVIEW_COLORS,
15 type ThemePreviewColors,
16} from "@t3tools/shared/themePreview";
17
18export const DEFAULT_MOBILE_THEME_ID = MOBILE_DEFAULT_THEME_ID;
19export const MOBILE_THEME_IDS = [...SHARED_MOBILE_THEME_IDS, "material-you"] as const;
20export type MobileThemeId = SharedMobileThemeId | "material-you";
21export type MobileThemeAppearance = ThemeAppearance;
22export type MobileThemeMode = MobileThemeAppearance | "system";
23export type MobileThemeIds = Readonly<Record<MobileThemeAppearance, MobileThemeId>>;
24
25export const MOBILE_THEME_OPTIONS: ReadonlyArray<{
26 readonly id: MobileThemeId;
27 readonly label: string;
28}> = [
29 { id: DEFAULT_MOBILE_THEME_ID, label: "T3 Code" },
30 { id: "material-you", label: "Material You" },
31 ...BUILT_IN_THEMES.map((theme) => ({ id: theme.id as MobileThemeId, label: theme.label })),
32];
33
34// Closed set: every key `createMobileThemeVariables` writes. Reads of a
35// misspelled variable then fail to compile instead of yielding undefined.
36export type MobileThemeVariable = keyof ReturnType<typeof createMobileThemeVariables>;
37export type MobileThemeVariables = Readonly<Record<MobileThemeVariable, string>>;
38
39export function normalizeMobileThemeId(value: unknown): MobileThemeId {
40 return typeof value === "string" && (MOBILE_THEME_IDS as readonly string[]).includes(value)
41 ? (value as MobileThemeId)
42 : DEFAULT_MOBILE_THEME_ID;
43}
44
45export function normalizeMobileThemeMode(value: unknown): MobileThemeMode {
46 return value === "light" || value === "dark" || value === "system" ? value : "system";
47}
48
49export function resolveMobileThemeIds(preferences: {
50 readonly themeId?: unknown;
51 readonly lightThemeId?: unknown;
52 readonly darkThemeId?: unknown;
53}): MobileThemeIds {
54 const legacyThemeId = normalizeMobileThemeId(preferences.themeId);
55 return {
56 light:
57 preferences.lightThemeId === undefined
58 ? legacyThemeId
59 : normalizeMobileThemeId(preferences.lightThemeId),
60 dark:
61 preferences.darkThemeId === undefined
62 ? legacyThemeId
63 : normalizeMobileThemeId(preferences.darkThemeId),
64 };
65}
66
67export function createMobileThemeSelectionPatch(
68 themeIds: MobileThemeIds,
69 activeAppearance: MobileThemeAppearance,
70 selectedAppearance: MobileThemeAppearance,
71 value: MobileThemeId,
72) {
73 const nextThemeIds: MobileThemeIds = {
74 light: selectedAppearance === "light" ? value : themeIds.light,
75 dark: selectedAppearance === "dark" ? value : themeIds.dark,
76 };
77 return {
78 lightThemeId: nextThemeIds.light,
79 darkThemeId: nextThemeIds.dark,
80 // Keep older OTA bundles on the theme for the appearance currently in use.
81 themeId: nextThemeIds[activeAppearance],
82 };
83}
84
85export function createMobileThemePairPatch(value: MobileThemeId) {
86 return {
87 lightThemeId: value,
88 darkThemeId: value,
89 themeId: value,
90 };
91}
92
93const OKLCH_PATTERN = /^oklch\(\s*([\d.]+)\s+([\d.]+)\s+(-?[\d.]+)(?:\s*\/\s*([\d.]+))?\s*\)$/;
94
95function linearToSrgb(value: number): number {
96 const converted = value <= 0.0031308 ? 12.92 * value : 1.055 * value ** (1 / 2.4) - 0.055;
97 return Math.round(Math.min(1, Math.max(0, converted)) * 255);
98}
99
100/** React Native does not accept OKLCH ColorValues, so palettes cross the app boundary as sRGB. */
101export function themeColorToNativeColor(value: string): string {
102 const match = OKLCH_PATTERN.exec(value);
103 if (!match) return value;
104
105 const lightness = Number(match[1]);
106 const chroma = Number(match[2]);
107 const hue = (Number(match[3]) * Math.PI) / 180;
108 const alpha = match[4] === undefined ? 1 : Number(match[4]);
109 const a = chroma * Math.cos(hue);
110 const b = chroma * Math.sin(hue);
111 const lPrime = lightness + 0.3963377774 * a + 0.2158037573 * b;
112 const mPrime = lightness - 0.1055613458 * a - 0.0638541728 * b;
113 const sPrime = lightness - 0.0894841775 * a - 1.291485548 * b;
114 const l = lPrime ** 3;
115 const m = mPrime ** 3;
116 const s = sPrime ** 3;
117 const red = linearToSrgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s);
118 const green = linearToSrgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s);
119 const blue = linearToSrgb(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s);
120
121 return alpha < 1
122 ? `rgba(${red}, ${green}, ${blue}, ${Number(alpha.toFixed(4))})`
123 : `#${[red, green, blue].map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
124}
125
126export function nativeColors(colors: ThemeColors): ThemeColors {
127 return Object.fromEntries(
128 Object.entries(colors).map(([role, color]) => [role, themeColorToNativeColor(color)]),
129 ) as ThemeColors;
130}
131
132function withAlpha(color: string, alpha: number): string {
133 const hex = color.startsWith("#") ? color.slice(1) : "";
134 if (hex.length !== 6) return color;
135 const [red, green, blue] = [0, 2, 4].map((offset) =>
136 Number.parseInt(hex.slice(offset, offset + 2), 16),
137 );
138 return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
139}
140
141function rgbChannels(color: string): readonly [number, number, number] | null {
142 const match = /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})(?:[\da-f]{2})?$/i.exec(color);
143 if (!match) return null;
144 const [, red = "0", green = "0", blue = "0"] = match;
145 return [Number.parseInt(red, 16), Number.parseInt(green, 16), Number.parseInt(blue, 16)];
146}
147
148/**
149 * An opaque form of a theme colour, composited over the surface behind it. Native chip drawing
150 * parses only opaque hex — an `rgba()` string falls back to a default that is nothing like the
151 * colour asked for — so a translucent role like `--color-border` has to be flattened first.
152 */
153export function flattenThemeColor(color: string, surface: string): string {
154 const alphaHex = /^#([\da-f]{6})([\da-f]{2})$/i.exec(color);
155 if (alphaHex) {
156 const channels = rgbChannels(color)!;
157 return flattenThemeColor(
158 `rgba(${channels[0]}, ${channels[1]}, ${channels[2]}, ${Number.parseInt(alphaHex[2]!, 16) / 255})`,
159 surface,
160 );
161 }
162 const match = /^rgba?\(\s*(\d+)[,\s]+(\d+)[,\s]+(\d+)(?:[,\s/]+([\d.]+))?\s*\)$/i.exec(
163 color.trim(),
164 );
165 if (!match) return color;
166 const alpha = match[4] === undefined ? 1 : Number(match[4]);
167 const behind = rgbChannels(surface) ?? [0, 0, 0];
168 const channels = [match[1], match[2], match[3]].map((channel, index) =>
169 Math.max(0, Math.min(255, Math.round(Number(channel) * alpha + behind[index]! * (1 - alpha)))),
170 );
171 return `#${channels.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
172}
173
174function relativeLuminance(channels: readonly [number, number, number]): number {
175 const [red, green, blue] = channels.map((channel) => {
176 const value = channel / 255;
177 return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
178 });
179 return 0.2126 * red! + 0.7152 * green! + 0.0722 * blue!;
180}
181
182function contrastRatio(
183 first: readonly [number, number, number],
184 second: readonly [number, number, number],
185): number {
186 const firstLuminance = relativeLuminance(first);
187 const secondLuminance = relativeLuminance(second);
188 return (
189 (Math.max(firstLuminance, secondLuminance) + 0.05) /
190 (Math.min(firstLuminance, secondLuminance) + 0.05)
191 );
192}
193
194/** Preserve the color's hue while giving text 4.5:1 contrast on every supplied surface. */
195function readableTextColor(accent: string, surface: string | ReadonlyArray<string>): string {
196 const accentChannels = rgbChannels(accent);
197 const surfaceChannels = (typeof surface === "string" ? [surface] : surface)
198 .map(rgbChannels)
199 .filter((channels) => channels !== null);
200 const minimumContrast = (channels: readonly [number, number, number]) =>
201 Math.min(...surfaceChannels.map((surface) => contrastRatio(channels, surface)));
202 if (!accentChannels || surfaceChannels.length === 0 || minimumContrast(accentChannels) >= 4.5) {
203 return accent;
204 }
205
206 const black = [0, 0, 0] as const;
207 const white = [255, 255, 255] as const;
208 const target = minimumContrast(black) >= minimumContrast(white) ? black : white;
209 let readable: readonly [number, number, number] = target;
210 let lowerAmount = 0;
211 let upperAmount = 1;
212 for (let index = 0; index < 12; index += 1) {
213 const amount = (lowerAmount + upperAmount) / 2;
214 const candidate: readonly [number, number, number] = [
215 Math.round(accentChannels[0] + (target[0] - accentChannels[0]) * amount),
216 Math.round(accentChannels[1] + (target[1] - accentChannels[1]) * amount),
217 Math.round(accentChannels[2] + (target[2] - accentChannels[2]) * amount),
218 ];
219 if (minimumContrast(candidate) >= 4.5) {
220 readable = candidate;
221 upperAmount = amount;
222 } else {
223 lowerAmount = amount;
224 }
225 }
226 return `#${readable.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
227}
228
229export function themeColorWithAlpha(color: string, alpha: number): string {
230 const channels = rgbChannels(color);
231 if (channels) {
232 return `rgba(${channels[0]}, ${channels[1]}, ${channels[2]}, ${alpha})`;
233 }
234 const rgb = /^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/.exec(color);
235 return rgb ? `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, ${alpha})` : color;
236}
237
238export function createMobileThemeVariables(
239 colors: ThemeColors,
240 appearance: MobileThemeAppearance,
241 groupedCardColor = colors.surface,
242) {
243 const c = nativeColors(colors);
244 const groupedCard = themeColorToNativeColor(groupedCardColor);
245 const textSurfaces = [c.canvas, c.surface, c.surfaceRaised, c.chrome, groupedCard];
246 return {
247 "--color-screen": c.canvas,
248 "--color-sheet": withAlpha(c.chrome, 0.98),
249 "--color-sheet-solid": c.chrome,
250 "--color-card": c.surface,
251 "--color-grouped-card": groupedCard,
252 "--color-card-alt": c.surfaceRaised,
253 "--color-card-translucent": withAlpha(c.surface, 0.8),
254 "--color-thread-canvas": c.canvas,
255 "--color-thread-selected": c.sidebarRowActive,
256 "--color-thread-selected-foreground": c.sidebarForeground,
257 "--color-thread-selected-foreground-muted": readableTextColor(
258 c.sidebarMutedForeground,
259 c.sidebarRowActive,
260 ),
261 "--color-thread-hover": c.sidebarRowHover,
262 "--color-row-hover": c.toolbarControlHover,
263 "--color-composer-panel": themeColorWithAlpha(c.canvas, appearance === "dark" ? 0.92 : 0.88),
264 "--color-composer-surface": themeColorWithAlpha(
265 groupedCard,
266 appearance === "dark" ? 0.9 : 0.94,
267 ),
268 "--color-composer-border": themeColorWithAlpha(
269 c.border,
270 groupedCard === c.surface ? (appearance === "dark" ? 0.46 : 0.54) : 0.8,
271 ),
272 "--color-foreground": c.text,
273 "--color-foreground-secondary": readableTextColor(c.textMuted, textSurfaces),
274 "--color-foreground-muted": readableTextColor(c.mutedForeground, textSurfaces),
275 "--color-foreground-tertiary": c.secondaryLabel,
276 "--color-border": c.border,
277 "--color-focus": c.focus,
278 "--color-border-subtle": withAlpha(c.border, 0.7),
279 "--color-separator": withAlpha(c.border, 0.55),
280 "--color-subtle": c.muted,
281 "--color-subtle-strong": c.secondary,
282 "--color-inline-skill-background": c.accentSurface,
283 "--color-inline-skill-border": withAlpha(c.accent, 0.42),
284 "--color-inline-skill-foreground": c.accentSurfaceForeground,
285 "--color-primary": c.messageAction,
286 "--color-primary-foreground": c.messageActionForeground,
287 "--color-primary-text": readableTextColor(c.messageAction, textSurfaces),
288 "--color-primary-shadow": "#000000",
289 "--color-secondary": c.secondary,
290 "--color-secondary-foreground": c.secondaryForeground,
291 "--color-secondary-border": c.border,
292 "--color-switch-active-track": c.messageAction,
293 "--color-switch-active-thumb": c.messageActionForeground,
294 "--color-switch-inactive-track": c.secondary,
295 "--color-switch-inactive-thumb": c.mutedForeground,
296 "--color-warning": c.warningSurface,
297 "--color-warning-border": withAlpha(c.warning, 0.32),
298 "--color-warning-foreground": c.warningForeground,
299 "--color-danger": c.errorSurface,
300 "--color-danger-border": withAlpha(c.error, 0.32),
301 "--color-danger-foreground": c.errorForeground,
302 "--color-update": c.updateSurface,
303 "--color-update-foreground": c.updateForeground,
304 "--color-input": c.surface,
305 "--color-input-border": c.input,
306 "--color-sidebar-search": c.sidebarControlSurface,
307 "--color-placeholder": readableTextColor(c.placeholder, textSurfaces),
308 "--color-icon": c.text,
309 "--color-icon-muted": c.iconMuted,
310 "--color-icon-subtle": c.secondaryLabel,
311 "--color-header": withAlpha(c.toolbar, 0.97),
312 "--color-header-foreground": c.toolbarForeground,
313 "--color-header-border": c.toolbarBorder,
314 "--color-glass-surface": withAlpha(c.surfaceOverlay, 0.74),
315 "--color-glass-fallback": themeColorWithAlpha(groupedCard, appearance === "dark" ? 0.9 : 0.94),
316 "--color-glass-tint": withAlpha(c.surfaceOverlay, 0.22),
317 "--color-status-bar": c.canvas,
318 "--color-md-body": c.text,
319 "--color-md-strong": c.text,
320 "--color-md-link": readableTextColor(c.messageAction, c.canvas),
321 "--color-md-blockquote-border": c.border,
322 "--color-md-blockquote-bg": c.muted,
323 "--color-md-code-bg": c.codeBackground,
324 "--color-md-code-text": c.codeForeground,
325 "--color-md-user-code-bg": withAlpha(c.messageForeground, 0.18),
326 "--color-md-user-code-text": c.messageForeground,
327 "--color-md-user-fence-bg": withAlpha("#000000", appearance === "dark" ? 0.28 : 0.16),
328 "--color-md-user-fence-text": c.messageForeground,
329 "--color-md-hr": c.border,
330 "--color-user-bubble": c.messageSurface,
331 "--color-user-bubble-foreground": c.messageForeground,
332 "--color-user-bubble-foreground-muted": withAlpha(c.messageForeground, 0.78),
333 "--color-user-bubble-skill-foreground": readableTextColor(c.messageAction, c.messageSurface),
334 "--color-backdrop": withAlpha("#000000", appearance === "dark" ? 0.48 : 0.22),
335 "--color-drawer": c.sidebar,
336 "--color-drawer-foreground": c.sidebarForeground,
337 "--color-drawer-foreground-muted": readableTextColor(c.sidebarMutedForeground, [
338 c.sidebar,
339 c.sidebarRowHover,
340 ]),
341 "--color-drawer-border": c.sidebarBorder,
342 "--color-drawer-shadow": withAlpha("#000000", appearance === "dark" ? 0.32 : 0.12),
343 "--color-dot-separator": withAlpha(c.textMuted, 0.35),
344 "--color-wordmark": c.text,
345 "--color-chevron": withAlpha(c.textMuted, 0.42),
346 };
347}
348
349export const MOBILE_THEME_VARIABLE_NAMES = Object.keys(
350 createMobileThemeVariables(T3_CHAT_THEME.colors, "light"),
351) as ReadonlyArray<MobileThemeVariable>;
352
353export function getMobileThemeColors(
354 themeId: SharedMobileThemeId,
355 appearance: MobileThemeAppearance,
356): ThemeColors {
357 if (themeId === DEFAULT_MOBILE_THEME_ID) {
358 return appearance === "dark" ? T3_CODE_DARK_THEME_COLORS : T3_CODE_LIGHT_THEME_COLORS;
359 }
360 const theme = BUILT_IN_THEMES.find((candidate) => candidate.id === themeId) ?? T3_CHAT_THEME;
361 return getThemeColorsForAppearance(theme, appearance) ?? theme.colors;
362}
363
364export function getMobileThemeVariables(
365 themeId: SharedMobileThemeId,
366 appearance: MobileThemeAppearance,
367 overrides: Partial<MobileThemeVariables> | null = null,
368): MobileThemeVariables {
369 const colors = getMobileThemeColors(themeId, appearance);
370 // Mobile settings groups and fallback materials use tonal fills where desktop
371 // uses outlined cards. Regular cards retain their shared desktop surface.
372 const groupedCard =
373 themeId === DEFAULT_MOBILE_THEME_ID
374 ? appearance === "light"
375 ? colors.toolbarControlHover
376 : colors.sidebarRowActive
377 : colors.surface;
378 const mobileColors =
379 themeId === DEFAULT_MOBILE_THEME_ID
380 ? {
381 ...colors,
382 messageSurface: flattenThemeColor(
383 themeColorWithAlpha(
384 appearance === "dark" ? colors.sidebarRowActive : colors.border,
385 0.3,
386 ),
387 colors.messageSurface,
388 ),
389 }
390 : colors;
391 const baseVariables = createMobileThemeVariables(mobileColors, appearance, groupedCard);
392
393 // The complete base record guarantees that optional overrides cannot leave a token undefined.
394 return overrides ? ({ ...baseVariables, ...overrides } as MobileThemeVariables) : baseVariables;
395}
396
397export function getMobileThemePreviewColors(
398 themeId: MobileThemeId,
399 appearance: MobileThemeAppearance,
400): ThemePreviewColors {
401 if (themeId === DEFAULT_MOBILE_THEME_ID || themeId === "material-you")
402 return STANDARD_THEME_PREVIEW_COLORS[appearance];
403 const theme = BUILT_IN_THEMES.find((candidate) => candidate.id === themeId) ?? T3_CHAT_THEME;
404 const colors = getThemeColorsForAppearance(theme, appearance) ?? theme.colors;
405 return {
406 canvas: themeColorToNativeColor(colors.canvas),
407 accent: themeColorToNativeColor(colors.accent),
408 messageAction: themeColorToNativeColor(colors.messageAction),
409 };
410}