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

mobileTheme.ts

438 lines16.9 KB

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