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

mobileTheme.ts

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