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

mobileTheme.ts

347 lines14.0 KB

1import {
2 BUILT_IN_THEMES,
3 T3_CHAT_THEME,
4 getThemeColorsForAppearance,
5 MOBILE_DEFAULT_THEME_ID,
6 MOBILE_THEME_IDS as SHARED_MOBILE_THEME_IDS,
7 type BuiltInThemeId,
8 type MobileThemeId as SharedMobileThemeId,
9 type ThemeAppearance,
10 type ThemeColors,
11} from "@t3tools/shared/themePalettes";
12import {
13 STANDARD_THEME_PREVIEW_COLORS,
14 type ThemePreviewColors,
15} from "@t3tools/shared/themePreview";
16​
17export const DEFAULT_MOBILE_THEME_ID = MOBILE_DEFAULT_THEME_ID;
18export const MOBILE_THEME_IDS = [...SHARED_MOBILE_THEME_IDS, "material-you"] as const;
19export type MobileThemeId = SharedMobileThemeId | "material-you";
20export type MobileThemeAppearance = ThemeAppearance;
21export type MobileThemeMode = MobileThemeAppearance | "system";
22export type MobileThemeIds = Readonly<Record<MobileThemeAppearance, MobileThemeId>>;
23​
24export const MOBILE_THEME_OPTIONS: ReadonlyArray<{
25 readonly id: MobileThemeId;
26 readonly label: string;
27}> = [
28 { id: DEFAULT_MOBILE_THEME_ID, label: "T3 Code" },
29 { id: "material-you", label: "Material You" },
30 ...BUILT_IN_THEMES.map((theme) => ({ id: theme.id as MobileThemeId, label: theme.label })),
31];
32​
33// Closed set: every key `createMobileThemeVariables` writes. Reads of a
34// misspelled variable then fail to compile instead of yielding undefined.
35export type MobileThemeVariable = keyof ReturnType<typeof createMobileThemeVariables>;
36export type MobileThemeVariables = Readonly<Record<MobileThemeVariable, string>>;
37​
38export function normalizeMobileThemeId(value: unknown): MobileThemeId {
39 return typeof value === "string" && (MOBILE_THEME_IDS as readonly string[]).includes(value)
40 ? (value as MobileThemeId)
41 : DEFAULT_MOBILE_THEME_ID;
43​
44export function normalizeMobileThemeMode(value: unknown): MobileThemeMode {
45 return value === "light" || value === "dark" || value === "system" ? value : "system";
47​
48export function resolveMobileThemeIds(preferences: {
49 readonly themeId?: unknown;
50 readonly lightThemeId?: unknown;
51 readonly darkThemeId?: unknown;
52}): MobileThemeIds {
53 const legacyThemeId = normalizeMobileThemeId(preferences.themeId);
54 return {
55 light:
56 preferences.lightThemeId === undefined
57 ? legacyThemeId
58 : normalizeMobileThemeId(preferences.lightThemeId),
59 dark:
60 preferences.darkThemeId === undefined
61 ? legacyThemeId
62 : normalizeMobileThemeId(preferences.darkThemeId),
63 };
65​
66export function createMobileThemeSelectionPatch(
67 themeIds: MobileThemeIds,
68 activeAppearance: MobileThemeAppearance,
69 selectedAppearance: MobileThemeAppearance,
70 value: MobileThemeId,
71) {
72 const nextThemeIds: MobileThemeIds = {
73 light: selectedAppearance === "light" ? value : themeIds.light,
74 dark: selectedAppearance === "dark" ? value : themeIds.dark,
75 };
76 return {
77 lightThemeId: nextThemeIds.light,
78 darkThemeId: nextThemeIds.dark,
79 // Keep older OTA bundles on the theme for the appearance currently in use.
80 themeId: nextThemeIds[activeAppearance],
81 };
83​
84export function createMobileThemePairPatch(value: MobileThemeId) {
85 return {
86 lightThemeId: value,
87 darkThemeId: value,
88 themeId: value,
89 };
91​
92const OKLCH_PATTERN = /^oklch\(\s*([\d.]+)\s+([\d.]+)\s+(-?[\d.]+)(?:\s*\/\s*([\d.]+))?\s*\)$/;
93​
94function linearToSrgb(value: number): number {
95 const converted = value <= 0.0031308 ? 12.92 * value : 1.055 * value ** (1 / 2.4) - 0.055;
96 return Math.round(Math.min(1, Math.max(0, converted)) * 255);
98​
99/** React Native does not accept OKLCH ColorValues, so palettes cross the app boundary as sRGB. */
100export function themeColorToNativeColor(value: string): string {
101 const match = OKLCH_PATTERN.exec(value);
102 if (!match) return value;
103​
104 const lightness = Number(match[1]);
105 const chroma = Number(match[2]);
106 const hue = (Number(match[3]) * Math.PI) / 180;
107 const alpha = match[4] === undefined ? 1 : Number(match[4]);
108 const a = chroma * Math.cos(hue);
109 const b = chroma * Math.sin(hue);
110 const lPrime = lightness + 0.3963377774 * a + 0.2158037573 * b;
111 const mPrime = lightness - 0.1055613458 * a - 0.0638541728 * b;
112 const sPrime = lightness - 0.0894841775 * a - 1.291485548 * b;
113 const l = lPrime ** 3;
114 const m = mPrime ** 3;
115 const s = sPrime ** 3;
116 const red = linearToSrgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s);
117 const green = linearToSrgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s);
118 const blue = linearToSrgb(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s);
119​
120 return alpha < 1
121 ? `rgba(${red}, ${green}, ${blue}, ${Number(alpha.toFixed(4))})`
122 : `#${[red, green, blue].map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
124​
125function nativeColors(colors: ThemeColors): ThemeColors {
126 return Object.fromEntries(
127 Object.entries(colors).map(([role, color]) => [role, themeColorToNativeColor(color)]),
128 ) as ThemeColors;
130​
131function withAlpha(color: string, alpha: number): string {
132 const hex = color.startsWith("#") ? color.slice(1) : "";
133 if (hex.length !== 6) return color;
134 const [red, green, blue] = [0, 2, 4].map((offset) =>
135 Number.parseInt(hex.slice(offset, offset + 2), 16),
136 );
137 return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
139​
140function rgbChannels(color: string): readonly [number, number, number] | null {
141 const match = /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i.exec(color);
142 if (!match) return null;
143 const [, red = "0", green = "0", blue = "0"] = match;
144 return [Number.parseInt(red, 16), Number.parseInt(green, 16), Number.parseInt(blue, 16)];
146​
147/**
148 * An opaque form of a theme colour, composited over the surface behind it. Native chip drawing
149 * parses only opaque hex — an `rgba()` string falls back to a default that is nothing like the
150 * colour asked for — so a translucent role like `--color-border` has to be flattened first.
151 */
152export function flattenThemeColor(color: string, surface: string): string {
153 const match = /^rgba?\(\s*(\d+)[,\s]+(\d+)[,\s]+(\d+)(?:[,\s/]+([\d.]+))?\s*\)$/i.exec(
154 color.trim(),
155 );
156 if (!match) return color;
157 const alpha = match[4] === undefined ? 1 : Number(match[4]);
158 const behind = rgbChannels(surface) ?? [0, 0, 0];
159 const channels = [match[1], match[2], match[3]].map((channel, index) =>
160 Math.max(0, Math.min(255, Math.round(Number(channel) * alpha + behind[index]! * (1 - alpha)))),
161 );
162 return `#${channels.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
164​
165function relativeLuminance(channels: readonly [number, number, number]): number {
166 const [red, green, blue] = channels.map((channel) => {
167 const value = channel / 255;
168 return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
169 });
170 return 0.2126 * red! + 0.7152 * green! + 0.0722 * blue!;
172​
173function contrastRatio(
174 first: readonly [number, number, number],
175 second: readonly [number, number, number],
176): number {
177 const firstLuminance = relativeLuminance(first);
178 const secondLuminance = relativeLuminance(second);
179 return (
180 (Math.max(firstLuminance, secondLuminance) + 0.05) /
181 (Math.min(firstLuminance, secondLuminance) + 0.05)
182 );
184​
185/** Preserve the theme's action hue while making it readable as skill text on a message bubble. */
186function readableMessageAccent(accent: string, surface: string): string {
187 const accentChannels = rgbChannels(accent);
188 const surfaceChannels = rgbChannels(surface);
189 if (
190 !accentChannels ||
191 !surfaceChannels ||
192 contrastRatio(accentChannels, surfaceChannels) >= 4.5
193 ) {
194 return accent;
195 }
196​
197 const black = [0, 0, 0] as const;
198 const white = [255, 255, 255] as const;
199 const target =
200 contrastRatio(black, surfaceChannels) >= contrastRatio(white, surfaceChannels) ? black : white;
201 let readable: readonly [number, number, number] = target;
202 let lowerAmount = 0;
203 let upperAmount = 1;
204 for (let index = 0; index < 12; index += 1) {
205 const amount = (lowerAmount + upperAmount) / 2;
206 const candidate: readonly [number, number, number] = [
207 Math.round(accentChannels[0] + (target[0] - accentChannels[0]) * amount),
208 Math.round(accentChannels[1] + (target[1] - accentChannels[1]) * amount),
209 Math.round(accentChannels[2] + (target[2] - accentChannels[2]) * amount),
210 ];
211 if (contrastRatio(candidate, surfaceChannels) >= 4.5) {
212 readable = candidate;
213 upperAmount = amount;
214 } else {
215 lowerAmount = amount;
216 }
217 }
218 return `#${readable.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
220​
221export function themeColorWithAlpha(color: string, alpha: number): string {
222 const channels = rgbChannels(color);
223 if (channels) {
224 return `rgba(${channels[0]}, ${channels[1]}, ${channels[2]}, ${alpha})`;
225 }
226 const rgb = /^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/.exec(color);
227 return rgb ? `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, ${alpha})` : color;
229​
230export function createMobileThemeVariables(colors: ThemeColors, appearance: MobileThemeAppearance) {
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 };
316​
317export const MOBILE_THEME_VARIABLE_NAMES = Object.keys(
318 createMobileThemeVariables(T3_CHAT_THEME.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) ?? T3_CHAT_THEME;
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;
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) ?? T3_CHAT_THEME;
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 };