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