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

mobileTheme.ts

329 lines13.0 KB

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;
40​
41export function normalizeMobileThemeMode(value: unknown): MobileThemeMode {
42 return value === "light" || value === "dark" || value === "system" ? value : "system";
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 };
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 };
80​
81export function createMobileThemePairPatch(value: MobileThemeId) {
82 return {
83 lightThemeId: value,
84 darkThemeId: value,
85 themeId: value,
86 };
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);
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("")}`;
121​
122function nativeColors(colors: ThemeColors): ThemeColors {
123 return Object.fromEntries(
124 Object.entries(colors).map(([role, color]) => [role, themeColorToNativeColor(color)]),
125 ) as ThemeColors;
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})`;
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;
143​
144function relativeLuminance(channels: readonly [number, number, number]): number {
145 const [red, green, blue] = channels.map((channel) => {
146 const value = channel / 255;
147 return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
148 });
149 return 0.2126 * red! + 0.7152 * green! + 0.0722 * blue!;
151​
152function contrastRatio(
153 first: readonly [number, number, number],
154 second: readonly [number, number, number],
155): number {
156 const firstLuminance = relativeLuminance(first);
157 const secondLuminance = relativeLuminance(second);
158 return (
159 (Math.max(firstLuminance, secondLuminance) + 0.05) /
160 (Math.min(firstLuminance, secondLuminance) + 0.05)
161 );
163​
164/** Preserve the theme's action hue while making it readable as skill text on a message bubble. */
165function readableMessageAccent(accent: string, surface: string): string {
166 const accentChannels = rgbChannels(accent);
167 const surfaceChannels = rgbChannels(surface);
168 if (
169 !accentChannels ||
170 !surfaceChannels ||
171 contrastRatio(accentChannels, surfaceChannels) >= 4.5
172 ) {
173 return accent;
174 }
175​
176 const black = [0, 0, 0] as const;
177 const white = [255, 255, 255] as const;
178 const target =
179 contrastRatio(black, surfaceChannels) >= contrastRatio(white, surfaceChannels) ? black : white;
180 let readable: readonly [number, number, number] = target;
181 let lowerAmount = 0;
182 let upperAmount = 1;
183 for (let index = 0; index < 12; index += 1) {
184 const amount = (lowerAmount + upperAmount) / 2;
185 const candidate: readonly [number, number, number] = [
186 Math.round(accentChannels[0] + (target[0] - accentChannels[0]) * amount),
187 Math.round(accentChannels[1] + (target[1] - accentChannels[1]) * amount),
188 Math.round(accentChannels[2] + (target[2] - accentChannels[2]) * amount),
189 ];
190 if (contrastRatio(candidate, surfaceChannels) >= 4.5) {
191 readable = candidate;
192 upperAmount = amount;
193 } else {
194 lowerAmount = amount;
195 }
196 }
197 return `#${readable.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
199​
200export function themeColorWithAlpha(color: string, alpha: number): string {
201 const hex = /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i.exec(color);
202 if (hex) {
203 return `rgba(${Number.parseInt(hex[1], 16)}, ${Number.parseInt(hex[2], 16)}, ${Number.parseInt(hex[3], 16)}, ${alpha})`;
204 }
205 const rgb = /^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/.exec(color);
206 return rgb ? `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, ${alpha})` : color;
208​
209export function createMobileThemeVariables(
210 colors: ThemeColors,
211 appearance: MobileThemeAppearance,
212): MobileThemeVariables {
213 const c = nativeColors(colors);
214 return {
215 "--color-screen": c.canvas,
216 "--color-sheet": withAlpha(c.chrome, 0.98),
217 "--color-sheet-solid": c.chrome,
218 "--color-card": c.surfaceRaised,
219 "--color-card-alt": c.surface,
220 "--color-card-translucent": withAlpha(c.surfaceRaised, 0.8),
221 "--color-thread-canvas": c.surface,
222 "--color-thread-selected": c.surfaceRaised,
223 "--color-thread-selected-foreground": c.text,
224 "--color-thread-selected-foreground-muted": c.textMuted,
225 "--color-composer-panel": themeColorWithAlpha(c.surface, appearance === "dark" ? 0.92 : 0.88),
226 "--color-composer-surface": themeColorWithAlpha(
227 c.surfaceRaised,
228 appearance === "dark" ? 0.9 : 0.94,
229 ),
230 "--color-composer-border": themeColorWithAlpha(c.border, appearance === "dark" ? 0.46 : 0.54),
231 "--color-foreground": c.text,
232 "--color-foreground-secondary": c.textMuted,
233 "--color-foreground-muted": c.mutedForeground,
234 "--color-foreground-tertiary": c.secondaryLabel,
235 "--color-border": c.border,
236 "--color-border-subtle": withAlpha(c.border, 0.7),
237 "--color-separator": withAlpha(c.border, 0.55),
238 "--color-subtle": c.muted,
239 "--color-subtle-strong": c.secondary,
240 "--color-inline-skill-background": c.accentSurface,
241 "--color-inline-skill-border": withAlpha(c.accent, 0.42),
242 "--color-inline-skill-foreground": c.accentSurfaceForeground,
243 "--color-primary": c.accent,
244 "--color-primary-foreground": c.accentForeground,
245 "--color-primary-shadow": "#000000",
246 "--color-secondary": c.secondary,
247 "--color-secondary-foreground": c.secondaryForeground,
248 "--color-secondary-border": c.border,
249 "--color-switch-active-track": c.accent,
250 "--color-switch-active-thumb": c.accentForeground,
251 "--color-switch-inactive-track": c.secondary,
252 "--color-switch-inactive-thumb": c.mutedForeground,
253 "--color-warning": c.warningSurface,
254 "--color-warning-border": withAlpha(c.warning, 0.32),
255 "--color-warning-foreground": c.warningForeground,
256 "--color-danger": c.errorSurface,
257 "--color-danger-border": withAlpha(c.error, 0.32),
258 "--color-danger-foreground": c.errorForeground,
259 "--color-input": c.surfaceRaised,
260 "--color-input-border": c.input,
261 "--color-sidebar-search": c.sidebarControlSurface,
262 "--color-placeholder": c.placeholder,
263 "--color-icon": c.text,
264 "--color-icon-muted": c.iconMuted,
265 "--color-icon-subtle": c.secondaryLabel,
266 "--color-header": withAlpha(c.toolbar, 0.97),
267 "--color-header-border": c.toolbarBorder,
268 "--color-glass-surface": withAlpha(c.surfaceOverlay, 0.74),
269 "--color-glass-tint": withAlpha(c.surfaceOverlay, 0.22),
270 "--color-status-bar": c.canvas,
271 "--color-md-body": c.text,
272 "--color-md-strong": c.toolbarForeground,
273 "--color-md-link": c.accent,
274 "--color-md-blockquote-border": c.border,
275 "--color-md-blockquote-bg": c.muted,
276 "--color-md-code-bg": c.codeBackground,
277 "--color-md-code-text": c.codeForeground,
278 "--color-md-user-code-bg": withAlpha(c.messageForeground, 0.18),
279 "--color-md-user-code-text": c.messageForeground,
280 "--color-md-user-fence-bg": withAlpha("#000000", appearance === "dark" ? 0.28 : 0.16),
281 "--color-md-user-fence-text": c.messageForeground,
282 "--color-md-hr": c.border,
283 "--color-user-bubble": c.messageSurface,
284 "--color-user-bubble-foreground": c.messageForeground,
285 "--color-user-bubble-foreground-muted": withAlpha(c.messageForeground, 0.78),
286 "--color-user-bubble-skill-foreground": readableMessageAccent(
287 c.messageAction,
288 c.messageSurface,
289 ),
290 "--color-backdrop": withAlpha("#000000", appearance === "dark" ? 0.48 : 0.22),
291 "--color-drawer": withAlpha(c.sidebar, 0.99),
292 "--color-drawer-shadow": withAlpha("#000000", appearance === "dark" ? 0.32 : 0.12),
293 "--color-dot-separator": withAlpha(c.textMuted, 0.35),
294 "--color-wordmark": c.text,
295 "--color-chevron": withAlpha(c.textMuted, 0.42),
296 };
298​
299export const MOBILE_THEME_VARIABLE_NAMES = Object.keys(
300 createMobileThemeVariables(BUILT_IN_THEMES[0].colors, "light"),
301) as ReadonlyArray<MobileThemeVariable>;
302​
303export function getMobileThemeVariables(
304 themeId: BuiltInThemeId,
305 appearance: MobileThemeAppearance,
306 overrides: Partial<MobileThemeVariables> | null = null,
307): MobileThemeVariables {
308 const theme = BUILT_IN_THEMES.find((candidate) => candidate.id === themeId) ?? BUILT_IN_THEMES[0];
309 const colors = getThemeColorsForAppearance(theme, appearance) ?? theme.colors;
310 const baseVariables = createMobileThemeVariables(colors, appearance);
311​
312 // The complete base record guarantees that optional overrides cannot leave a token undefined.
313 return overrides ? ({ ...baseVariables, ...overrides } as MobileThemeVariables) : baseVariables;
315​
316export function getMobileThemePreviewColors(
317 themeId: MobileThemeId,
318 appearance: MobileThemeAppearance,
319): ThemePreviewColors {
320 if (themeId === DEFAULT_MOBILE_THEME_ID || themeId === "material-you")
321 return STANDARD_THEME_PREVIEW_COLORS[appearance];
322 const theme = BUILT_IN_THEMES.find((candidate) => candidate.id === themeId) ?? BUILT_IN_THEMES[0];
323 const colors = getThemeColorsForAppearance(theme, appearance) ?? theme.colors;
324 return {
325 canvas: themeColorToNativeColor(colors.canvas),
326 accent: themeColorToNativeColor(colors.accent),
327 messageAction: themeColorToNativeColor(colors.messageAction),
328 };