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

mobileTheme.ts

520 lines19.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​
97function oklabToLinearSrgb(lightness: number, a: number, b: number) {
98 const l = (lightness + 0.3963377774 * a + 0.2158037573 * b) ** 3;
99 const m = (lightness - 0.1055613458 * a - 0.0638541728 * b) ** 3;
100 const s = (lightness - 0.0894841775 * a - 1.291485548 * b) ** 3;
101 return [
102 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
103 -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
104 -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
105 ] as const;
107​
108function oklabToSrgb(lightness: number, a: number, b: number) {
109 const [red, green, blue] = oklabToLinearSrgb(lightness, a, b);
110 return [linearToSrgb(red), linearToSrgb(green), linearToSrgb(blue)] as const;
112​
113/** React Native does not accept OKLCH ColorValues, so palettes cross the app boundary as sRGB. */
114export function themeColorToNativeColor(value: string): string {
115 const match = OKLCH_PATTERN.exec(value);
116 if (!match) return value;
117​
118 const lightness = Number(match[1]);
119 const chroma = Number(match[2]);
120 const hue = (Number(match[3]) * Math.PI) / 180;
121 const alpha = match[4] === undefined ? 1 : Number(match[4]);
122 const [red, green, blue] = oklabToSrgb(lightness, chroma * Math.cos(hue), chroma * Math.sin(hue));
123​
124 return alpha < 1
125 ? `rgba(${red}, ${green}, ${blue}, ${Number(alpha.toFixed(4))})`
126 : `#${[red, green, blue].map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
128​
129export function nativeColors(colors: ThemeColors): ThemeColors {
130 return Object.fromEntries(
131 Object.entries(colors).map(([role, color]) => [role, themeColorToNativeColor(color)]),
132 ) as ThemeColors;
134​
135function withAlpha(color: string, alpha: number): string {
136 const hex = color.startsWith("#") ? color.slice(1) : "";
137 if (hex.length !== 6) return color;
138 const [red, green, blue] = [0, 2, 4].map((offset) =>
139 Number.parseInt(hex.slice(offset, offset + 2), 16),
140 );
141 return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
143​
144function rgbChannels(color: string): readonly [number, number, number] | null {
145 const match = /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})(?:[\da-f]{2})?$/i.exec(color);
146 if (!match) return null;
147 const [, red = "0", green = "0", blue = "0"] = match;
148 return [Number.parseInt(red, 16), Number.parseInt(green, 16), Number.parseInt(blue, 16)];
150​
151/**
152 * Native chip drawing parses only opaque hex — an `rgba()` string falls back to a default that
153 * is nothing like the colour asked for — so a translucent role like `--color-border` has to be
154 * flattened first.
155 */
156export function flattenThemeColor(color: string, surface: string): string {
157 const alphaHex = /^#([\da-f]{6})([\da-f]{2})$/i.exec(color);
158 if (alphaHex) {
159 const channels = rgbChannels(color)!;
160 return flattenThemeColor(
161 `rgba(${channels[0]}, ${channels[1]}, ${channels[2]}, ${Number.parseInt(alphaHex[2]!, 16) / 255})`,
162 surface,
163 );
164 }
165 const match = /^rgba?\(\s*(\d+)[,\s]+(\d+)[,\s]+(\d+)(?:[,\s/]+([\d.]+))?\s*\)$/i.exec(
166 color.trim(),
167 );
168 if (!match) return color;
169 const alpha = match[4] === undefined ? 1 : Number(match[4]);
170 const behind = rgbChannels(surface) ?? [0, 0, 0];
171 const channels = [match[1], match[2], match[3]].map((channel, index) =>
172 Math.max(0, Math.min(255, Math.round(Number(channel) * alpha + behind[index]! * (1 - alpha)))),
173 );
174 return `#${channels.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
176​
177function srgbToLinear(channel: number): number {
178 const value = channel / 255;
179 return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
181​
182function srgbToOklab(channels: readonly [number, number, number]) {
183 const [red = 0, green = 0, blue = 0] = channels.map(srgbToLinear);
184 const l = Math.cbrt(0.4122214708 * red + 0.5363325363 * green + 0.0514459929 * blue);
185 const m = Math.cbrt(0.2119034982 * red + 0.6806995451 * green + 0.1073969566 * blue);
186 const s = Math.cbrt(0.0883024619 * red + 0.2817188376 * green + 0.6299787005 * blue);
187 return [
188 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
189 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
190 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,
191 ] as const;
193​
194function relativeLuminance(channels: readonly [number, number, number]): number {
195 const [red, green, blue] = channels.map(srgbToLinear);
196 return 0.2126 * red! + 0.7152 * green! + 0.0722 * blue!;
198​
199export function isDarkThemeColor(color: string): boolean {
200 const channels = rgbChannels(color);
201 return channels !== null && relativeLuminance(channels) < 0.18;
203​
204function contrastRatio(
205 first: readonly [number, number, number],
206 second: readonly [number, number, number],
207): number {
208 const firstLuminance = relativeLuminance(first);
209 const secondLuminance = relativeLuminance(second);
210 return (
211 (Math.max(firstLuminance, secondLuminance) + 0.05) /
212 (Math.min(firstLuminance, secondLuminance) + 0.05)
213 );
215​
216export function themeColorWithContrast(
217 accent: string,
218 surface: string | ReadonlyArray<string>,
219 minimum = 4.5,
220): string {
221 const accentChannels = rgbChannels(accent);
222 const surfaceChannels = (typeof surface === "string" ? [surface] : surface)
223 .map(rgbChannels)
224 .filter((channels) => channels !== null);
225 const minimumContrast = (channels: readonly [number, number, number]) =>
226 Math.min(...surfaceChannels.map((surface) => contrastRatio(channels, surface)));
227 if (
228 !accentChannels ||
229 surfaceChannels.length === 0 ||
230 minimumContrast(accentChannels) >= minimum
231 ) {
232 return accent;
233 }
234​
235 const black = [0, 0, 0] as const;
236 const white = [255, 255, 255] as const;
237 const target = minimumContrast(black) >= minimumContrast(white) ? black : white;
238 let readable: readonly [number, number, number] = target;
239 let lowerAmount = 0;
240 let upperAmount = 1;
241 for (let index = 0; index < 12; index += 1) {
242 const amount = (lowerAmount + upperAmount) / 2;
243 const candidate: readonly [number, number, number] = [
244 Math.round(accentChannels[0] + (target[0] - accentChannels[0]) * amount),
245 Math.round(accentChannels[1] + (target[1] - accentChannels[1]) * amount),
246 Math.round(accentChannels[2] + (target[2] - accentChannels[2]) * amount),
247 ];
248 if (minimumContrast(candidate) >= minimum) {
249 readable = candidate;
250 upperAmount = amount;
251 } else {
252 lowerAmount = amount;
253 }
254 }
255 return `#${readable.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
257​
258/**
259 * Unlike `themeColorWithContrast`, which blends toward black or white and greys the color out,
260 * this moves only OKLCH lightness and takes the most chroma sRGB allows at each step, so a vivid
261 * accent stays vivid at the contrast it needs.
262 */
263export function themeAccentWithContrast(
264 accent: string,
265 surfaces: ReadonlyArray<string>,
266 minimum = 4.5,
267): string {
268 const accentChannels = rgbChannels(accent);
269 const surfaceChannels = surfaces.map(rgbChannels).filter((channels) => channels !== null);
270 const minimumContrast = (channels: readonly [number, number, number]) =>
271 Math.min(...surfaceChannels.map((surface) => contrastRatio(channels, surface)));
272 if (
273 !accentChannels ||
274 surfaceChannels.length === 0 ||
275 minimumContrast(accentChannels) >= minimum
276 ) {
277 return accent;
278 }
279​
280 const [lightness, a, b] = srgbToOklab(accentChannels);
281 const hue = Math.atan2(b, a);
282 const inGamut = (channels: ReadonlyArray<number>) =>
283 channels.every((channel) => channel >= -1e-4 && channel <= 1 + 1e-4);
284 const mostVivid = (stepLightness: number) => {
285 let chroma = 0;
286 let lower = 0;
287 let upper = Math.max(Math.hypot(a, b), 0.2);
288 for (let index = 0; index < 20; index += 1) {
289 const candidate = (lower + upper) / 2;
290 if (
291 inGamut(
292 oklabToLinearSrgb(stepLightness, candidate * Math.cos(hue), candidate * Math.sin(hue)),
293 )
294 ) {
295 chroma = candidate;
296 lower = candidate;
297 } else {
298 upper = candidate;
299 }
300 }
301 return oklabToSrgb(stepLightness, chroma * Math.cos(hue), chroma * Math.sin(hue));
302 };
303​
304 const lighten = minimumContrast([255, 255, 255]) >= minimumContrast([0, 0, 0]);
305 const step = lighten ? 0.002 : -0.002;
306 for (let next = lightness; lighten ? next <= 1 : next >= 0; next += step) {
307 const candidate = mostVivid(next);
308 if (minimumContrast(candidate) >= minimum) {
309 return `#${candidate.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
310 }
311 }
312 return lighten ? "#ffffff" : "#000000";
314​
315export function themeColorWithAlpha(color: string, alpha: number): string {
316 const channels = rgbChannels(color);
317 if (channels) {
318 return `rgba(${channels[0]}, ${channels[1]}, ${channels[2]}, ${alpha})`;
319 }
320 const rgb = /^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/.exec(color);
321 return rgb ? `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, ${alpha})` : color;
323​
324export function createMobileThemeVariables(
325 colors: ThemeColors,
326 appearance: MobileThemeAppearance,
327 groupedCardColor = colors.surface,
328 prominentAction: readonly [string, string] = [colors.text, colors.canvas],
329) {
330 const c = nativeColors(colors);
331 const groupedCard = themeColorToNativeColor(groupedCardColor);
332 const textSurfaces = [
333 c.canvas,
334 c.surface,
335 c.surfaceRaised,
336 c.chrome,
337 c.sidebar,
338 c.secondary,
339 groupedCard,
340 ];
341 return {
342 "--color-screen": c.canvas,
343 "--color-sheet": withAlpha(c.chrome, 0.98),
344 "--color-sheet-solid": c.chrome,
345 "--color-card": c.surface,
346 "--color-grouped-card": groupedCard,
347 "--color-card-alt": c.surfaceRaised,
348 "--color-card-translucent": withAlpha(c.surface, 0.8),
349 "--color-thread-canvas": c.canvas,
350 "--color-thread-selected": c.sidebarRowActive,
351 "--color-thread-selected-foreground": c.sidebarForeground,
352 "--color-thread-selected-foreground-muted": themeColorWithContrast(
353 c.sidebarMutedForeground,
354 c.sidebarRowActive,
355 ),
356 "--color-thread-hover": c.sidebarRowHover,
357 "--color-row-hover": c.toolbarControlHover,
358 "--color-composer-panel": themeColorWithAlpha(c.canvas, appearance === "dark" ? 0.92 : 0.88),
359 "--color-composer-surface": themeColorWithAlpha(
360 groupedCard,
361 appearance === "dark" ? 0.9 : 0.94,
362 ),
363 "--color-composer-border": themeColorWithAlpha(
364 c.border,
365 groupedCard === c.surface ? (appearance === "dark" ? 0.46 : 0.54) : 0.8,
366 ),
367 "--color-foreground": c.text,
368 "--color-foreground-secondary": themeColorWithContrast(c.textMuted, textSurfaces),
369 "--color-foreground-muted": themeColorWithContrast(c.mutedForeground, textSurfaces),
370 "--color-foreground-tertiary": c.secondaryLabel,
371 "--color-border": c.border,
372 "--color-focus": c.focus,
373 "--color-border-subtle": withAlpha(c.border, 0.7),
374 "--color-separator": withAlpha(c.border, 0.55),
375 "--color-subtle": c.muted,
376 "--color-subtle-strong": c.secondary,
377 "--color-inline-skill-background": c.accentSurface,
378 "--color-inline-skill-border": withAlpha(c.accent, 0.42),
379 "--color-inline-skill-foreground": c.accentSurfaceForeground,
380 "--color-primary": c.messageAction,
381 "--color-prominent-action": themeColorToNativeColor(prominentAction[0]),
382 "--color-prominent-action-foreground": themeColorToNativeColor(prominentAction[1]),
383 "--color-primary-foreground": c.messageActionForeground,
384 "--color-primary-text": themeColorWithContrast(c.messageAction, textSurfaces),
385 "--color-primary-shadow": "#000000",
386 "--color-secondary": c.secondary,
387 "--color-secondary-foreground": c.secondaryForeground,
388 "--color-secondary-border": c.border,
389 "--color-switch-active-track": c.messageAction,
390 "--color-switch-active-thumb": c.messageActionForeground,
391 "--color-switch-inactive-track": c.secondary,
392 "--color-switch-inactive-thumb": c.mutedForeground,
393 "--color-warning": c.warningSurface,
394 "--color-warning-border": withAlpha(c.warning, 0.32),
395 "--color-warning-foreground": c.warningForeground,
396 "--color-danger": c.errorSurface,
397 "--color-danger-border": withAlpha(c.error, 0.32),
398 "--color-danger-foreground": c.errorForeground,
399 "--color-update": c.updateSurface,
400 "--color-update-foreground": c.updateForeground,
401 "--color-input": c.surface,
402 "--color-input-border": c.input,
403 "--color-sidebar-search": c.sidebarControlSurface,
404 "--color-placeholder": themeColorWithContrast(c.placeholder, textSurfaces),
405 "--color-icon": c.text,
406 "--color-icon-muted": c.iconMuted,
407 "--color-icon-subtle": c.secondaryLabel,
408 "--color-header": withAlpha(c.toolbar, 0.97),
409 "--color-header-foreground": c.toolbarForeground,
410 "--color-header-border": c.toolbarBorder,
411 "--color-glass-surface": withAlpha(c.surfaceOverlay, 0.74),
412 "--color-glass-fallback": themeColorWithAlpha(groupedCard, appearance === "dark" ? 0.9 : 0.94),
413 "--color-glass-tint": withAlpha(c.surfaceOverlay, 0.22),
414 "--color-status-bar": c.canvas,
415 "--color-md-body": c.text,
416 "--color-md-strong": c.text,
417 "--color-md-link": themeColorWithContrast(c.messageAction, c.canvas),
418 "--color-md-blockquote-border": c.border,
419 "--color-md-blockquote-bg": c.muted,
420 "--color-md-code-bg": c.codeBackground,
421 "--color-md-code-text": c.codeForeground,
422 "--color-md-user-code-bg": withAlpha(c.messageForeground, 0.18),
423 "--color-md-user-code-text": c.messageForeground,
424 "--color-md-user-fence-bg": withAlpha("#000000", appearance === "dark" ? 0.28 : 0.16),
425 "--color-md-user-fence-text": c.messageForeground,
426 "--color-md-hr": c.border,
427 "--color-user-bubble": c.messageSurface,
428 "--color-user-bubble-foreground": c.messageForeground,
429 "--color-user-bubble-foreground-muted": withAlpha(c.messageForeground, 0.78),
430 "--color-user-bubble-skill-foreground": themeColorWithContrast(
431 c.messageAction,
432 c.messageSurface,
433 ),
434 "--color-backdrop": withAlpha("#000000", appearance === "dark" ? 0.48 : 0.22),
435 "--color-drawer": c.sidebar,
436 "--color-drawer-foreground": c.sidebarForeground,
437 "--color-drawer-foreground-muted": themeColorWithContrast(c.sidebarMutedForeground, [
438 c.sidebar,
439 c.sidebarRowHover,
440 ]),
441 "--color-drawer-border": c.sidebarBorder,
442 "--color-drawer-shadow": withAlpha("#000000", appearance === "dark" ? 0.32 : 0.12),
443 "--color-dot-separator": withAlpha(c.textMuted, 0.35),
444 "--color-wordmark": c.text,
445 "--color-chevron": withAlpha(c.textMuted, 0.42),
446 };
448​
449export const MOBILE_THEME_VARIABLE_NAMES = Object.keys(
450 createMobileThemeVariables(T3_CHAT_THEME.colors, "light"),
451) as ReadonlyArray<MobileThemeVariable>;
452​
453export function getMobileThemeColors(
454 themeId: SharedMobileThemeId,
455 appearance: MobileThemeAppearance,
456): ThemeColors {
457 if (themeId === DEFAULT_MOBILE_THEME_ID) {
458 return appearance === "dark" ? T3_CODE_DARK_THEME_COLORS : T3_CODE_LIGHT_THEME_COLORS;
459 }
460 const theme = BUILT_IN_THEMES.find((candidate) => candidate.id === themeId) ?? T3_CHAT_THEME;
461 return getThemeColorsForAppearance(theme, appearance) ?? theme.colors;
463​
464export function getMobileThemeVariables(
465 themeId: SharedMobileThemeId,
466 appearance: MobileThemeAppearance,
467 overrides: Partial<MobileThemeVariables> | null = null,
468): MobileThemeVariables {
469 const colors = getMobileThemeColors(themeId, appearance);
470 const groupedCard =
471 themeId === DEFAULT_MOBILE_THEME_ID
472 ? appearance === "light"
473 ? colors.toolbarControlHover
474 : colors.sidebarRowActive
475 : themeId === "t3-chat"
476 ? appearance === "light"
477 ? colors.toolbarControl
478 : colors.surface
479 : colors.muted;
480 const mobileColors =
481 themeId === DEFAULT_MOBILE_THEME_ID
482 ? {
483 ...colors,
484 messageSurface: flattenThemeColor(
485 themeColorWithAlpha(
486 appearance === "dark" ? colors.sidebarRowActive : colors.border,
487 0.3,
488 ),
489 colors.messageSurface,
490 ),
491 }
492 : colors;
493 const baseVariables = createMobileThemeVariables(
494 mobileColors,
495 appearance,
496 groupedCard,
497 themeId === "t3-chat" && appearance === "dark"
498 ? [colors.messageActionForeground, colors.messageAction]
499 : themeId !== DEFAULT_MOBILE_THEME_ID && themeId !== "t3-chat"
500 ? [colors.messageAction, colors.messageActionForeground]
501 : undefined,
502 );
503​
504 return overrides ? ({ ...baseVariables, ...overrides } as MobileThemeVariables) : baseVariables;
506​
507export function getMobileThemePreviewColors(
508 themeId: MobileThemeId,
509 appearance: MobileThemeAppearance,
510): ThemePreviewColors {
511 if (themeId === DEFAULT_MOBILE_THEME_ID || themeId === "material-you")
512 return STANDARD_THEME_PREVIEW_COLORS[appearance];
513 const theme = BUILT_IN_THEMES.find((candidate) => candidate.id === themeId) ?? T3_CHAT_THEME;
514 const colors = getThemeColorsForAppearance(theme, appearance) ?? theme.colors;
515 return {
516 canvas: themeColorToNativeColor(colors.canvas),
517 accent: themeColorToNativeColor(colors.accent),
518 messageAction: themeColorToNativeColor(colors.messageAction),
519 };