The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 369 lines 13.2 KB
Raw
1 import { createContext, startTransition, use, useMemo, type ReactNode } from "react";
2 import { AppState, Appearance, Platform, useColorScheme } from "react-native";
3
4 import { manufacturer } from "expo-device";
5 import {
6 resolveAndroidNavigationStyle,
7 type AndroidNavigationStyle,
8 } from "../../../lib/androidNavigationStyle";
9
10 import { useAtomValue } from "@effect/atom-react";
11 import { Atom, AsyncResult } from "effect/reactivity";
12
13 import { ScopedTheme, ScopedVariables, Uniwind } from "uniwind";
14
15 import {
16 resolveAppearance,
17 resolveAppearancePreferences,
18 type ResolvedAppearance,
19 } from "../../../lib/appearancePreferences";
20 import { appAtomRegistry } from "../../../state/atom-registry";
21 import { mobilePreferencesAtom, saveMobilePreferences } from "../../../state/preferences";
22 import { useAtomCommand } from "../../../state/use-atom-command";
23 import type { Preferences } from "../../../persistence/mobile-preferences";
24 import {
25 isSystemColorsAvailable,
26 readSystemColorPalettes,
27 type MaterialYouPalettes,
28 } from "../../../lib/materialYouPalette";
29 import { materialYouPaletteToMobileThemeVariables } from "../../../lib/materialYouTheme";
30 import { getMobileThemeRuntimeVariables } from "../../../lib/mobileThemeVariables";
31 import type { MobileThemeVariables } from "../../../lib/mobileTheme";
32 import {
33 createMobileThemePairPatch,
34 createMobileThemeSelectionPatch,
35 normalizeMobileThemeMode,
36 resolveMobileThemeIds,
37 type MobileThemeAppearance,
38 type MobileThemeId,
39 type MobileThemeIds,
40 type MobileThemeMode,
41 } from "../../../lib/mobileTheme";
42 import {
43 createMobileThemeRuntimeOperations,
44 getMobileUniwindThemeName,
45 type MobileThemeRuntimeState,
46 } from "../../../lib/mobileThemeRuntime";
47
48 interface AppearancePreferencesContextValue {
49 readonly appearance: ResolvedAppearance;
50 readonly themeId: MobileThemeId;
51 readonly themeIds: MobileThemeIds;
52 readonly themeMode: MobileThemeMode;
53 readonly androidNavigationStyle: AndroidNavigationStyle;
54 readonly setAndroidNavigationStyle: (value: AndroidNavigationStyle) => void;
55 readonly themeAppearance: MobileThemeAppearance;
56 readonly systemColorsAvailable: boolean;
57 readonly systemColorsActive: boolean;
58 readonly themeVariables: MobileThemeVariables;
59 readonly themeVariablesByAppearance: Readonly<
60 Record<MobileThemeAppearance, MobileThemeVariables>
61 >;
62 readonly systemColorPalettes: ReturnType<typeof readSystemColorPalettes>;
63 readonly isReady: boolean;
64 readonly setThemeIdForAppearance: (
65 appearance: MobileThemeAppearance,
66 value: MobileThemeId,
67 ) => void;
68 readonly setThemeIdForBothAppearances: (value: MobileThemeId) => void;
69 readonly setThemeMode: (value: MobileThemeMode) => void;
70 readonly setBaseFontSize: (value: number) => void;
71 readonly setTerminalFontSize: (value: number | null) => void;
72 readonly setCodeFontSize: (value: number | null) => void;
73 readonly setCodeWordBreak: (value: boolean) => void;
74 readonly mathRenderingEnabled: boolean;
75 readonly setMathRenderingEnabled: (value: boolean) => void;
76 }
77
78 const AppearancePreferencesContext = createContext<AppearancePreferencesContextValue | null>(null);
79
80 function storedPreferencesOf<E>(result: AsyncResult.AsyncResult<Preferences, E>) {
81 return AsyncResult.isSuccess(result) ? result.value : null;
82 }
83
84 /**
85 * Material You palettes follow the system wallpaper, which can change while the
86 * app is in the background.
87 */
88 const systemColorPalettesAtom = Atom.make((get): MaterialYouPalettes | null => {
89 const initial = readSystemColorPalettes();
90 if (!isSystemColorsAvailable) return initial;
91 let current = initial;
92 const refresh = () => {
93 const next = readSystemColorPalettes();
94 if (JSON.stringify(current) === JSON.stringify(next)) return;
95 current = next;
96 get.setSelf(next);
97 };
98 const subscription = AppState.addEventListener("change", (state) => {
99 if (state === "active") refresh();
100 });
101 const focusSubscription = AppState.addEventListener("focus", refresh);
102 get.addFinalizer(() => {
103 subscription.remove();
104 focusSubscription.remove();
105 });
106 return initial;
107 }).pipe(Atom.withLabel("mobile:system-color-palettes"));
108
109 function resolveThemeVariablesByAppearance(
110 themeIds: MobileThemeIds,
111 palettes: MaterialYouPalettes | null,
112 ): Readonly<Record<MobileThemeAppearance, MobileThemeVariables>> {
113 const resolve = (appearance: MobileThemeAppearance) => {
114 const base = getMobileThemeRuntimeVariables(themeIds[appearance], appearance, Platform.OS);
115 return themeIds[appearance] === "material-you" && palettes
116 ? materialYouPaletteToMobileThemeVariables(palettes[appearance], appearance, base)
117 : base;
118 };
119 return { light: resolve("light"), dark: resolve("dark") };
120 }
121
122 /** The appearance whose theme is on screen, read from the native scheme. */
123 export function resolveThemeAppearance(stored: Preferences | null): MobileThemeAppearance {
124 const themeMode = normalizeMobileThemeMode(stored?.themeMode);
125 if (themeMode !== "system") return themeMode;
126 return Appearance.getColorScheme() === "dark" ? "dark" : "light";
127 }
128
129 function runtimeStateFor(stored: Preferences | null): MobileThemeRuntimeState {
130 return {
131 baseFontSize: resolveAppearancePreferences(stored).baseFontSize,
132 themeMode: normalizeMobileThemeMode(stored?.themeMode),
133 themeAppearance: resolveThemeAppearance(stored),
134 };
135 }
136
137 const themeRuntimeStateAtom = Atom.make((get) =>
138 runtimeStateFor(storedPreferencesOf(get(mobilePreferencesAtom))),
139 ).pipe(
140 Atom.withEquality(
141 (left: MobileThemeRuntimeState, right: MobileThemeRuntimeState) =>
142 left.baseFontSize === right.baseFontSize &&
143 left.themeMode === right.themeMode &&
144 left.themeAppearance === right.themeAppearance,
145 ),
146 );
147
148 // Native appearance and Uniwind text variables are process-global, so the
149 // last applied state is too. Setters apply ahead of the preference write so the
150 // first frame after a change already uses it; the atom subscription then sees
151 // no difference.
152 let appliedRuntimeState: MobileThemeRuntimeState | null = null;
153
154 function applyThemeRuntime(next: MobileThemeRuntimeState) {
155 for (const operation of createMobileThemeRuntimeOperations(appliedRuntimeState, next)) {
156 if (operation.kind === "update-text-variables") {
157 Uniwind.updateCSSVariables(operation.themeName, operation.variables);
158 continue;
159 }
160 if (operation.kind === "set-appearance-mode") {
161 Appearance.setColorScheme(
162 operation.themeMode === "system" ? "unspecified" : operation.appearance,
163 );
164 }
165 }
166 appliedRuntimeState = next;
167 }
168
169 function currentRuntimeState() {
170 return appliedRuntimeState ?? appAtomRegistry.get(themeRuntimeStateAtom);
171 }
172
173 /**
174 * App-lifetime: applies theme preferences to the native runtime and holds the
175 * system palette listeners. Holding them here instead of `keepAlive` lets the
176 * fast-refresh disposer release the replaced module's AppState listeners.
177 */
178 export function installAppearanceRuntime(): () => void {
179 const unsubscribeRuntime = appAtomRegistry.subscribe(themeRuntimeStateAtom, applyThemeRuntime, {
180 immediate: true,
181 });
182 const releasePalettes = appAtomRegistry.mount(systemColorPalettesAtom);
183 return () => {
184 unsubscribeRuntime();
185 releasePalettes();
186 };
187 }
188
189 export function AppearancePreferencesProvider(props: { readonly children: ReactNode }) {
190 const preferencesResult = useAtomValue(mobilePreferencesAtom);
191 const savePreferences = useAtomCommand(saveMobilePreferences);
192 const systemColorScheme = useColorScheme() === "dark" ? "dark" : "light";
193 const storedPreferences = AsyncResult.isSuccess(preferencesResult)
194 ? preferencesResult.value
195 : null;
196 const preferences = useMemo(
197 () => resolveAppearancePreferences(storedPreferences),
198 [storedPreferences],
199 );
200 const androidNavigationStyle = resolveAndroidNavigationStyle(
201 storedPreferences?.androidNavigationStyle,
202 manufacturer,
203 process.env.EXPO_PUBLIC_T3_FLOATING_TABS === "1",
204 );
205 const themeMode = normalizeMobileThemeMode(storedPreferences?.themeMode);
206 const themeAppearance = themeMode === "system" ? systemColorScheme : themeMode;
207 const resolvedThemeIds = resolveMobileThemeIds(storedPreferences ?? {});
208 const themeIds = useMemo<MobileThemeIds>(
209 () => ({ light: resolvedThemeIds.light, dark: resolvedThemeIds.dark }),
210 [resolvedThemeIds.dark, resolvedThemeIds.light],
211 );
212 const themeId = themeIds[themeAppearance];
213 const systemColorsActive = themeId === "material-you" && isSystemColorsAvailable;
214 const systemColorPalettes = useAtomValue(systemColorPalettesAtom);
215 const themeVariablesByAppearance = resolveThemeVariablesByAppearance(
216 themeIds,
217 systemColorPalettes,
218 );
219 const themeVariables = themeVariablesByAppearance[themeAppearance];
220 const activeThemeName = getMobileUniwindThemeName(themeId, themeAppearance);
221 const { baseFontSize, codeFontSize, codeWordBreak, terminalFontSize } = preferences;
222 const appearance = useMemo(
223 () => resolveAppearance({ baseFontSize, codeFontSize, codeWordBreak, terminalFontSize }),
224 [baseFontSize, codeFontSize, codeWordBreak, terminalFontSize],
225 );
226 const isReady = AsyncResult.isSuccess(preferencesResult);
227 const updatePreferences = (patch: Partial<Preferences>) => {
228 startTransition(() => {
229 void savePreferences(patch);
230 });
231 };
232
233 const updateThemePreferences = (patch: Partial<Preferences>) => {
234 void savePreferences(patch);
235 };
236
237 const setThemeIdForAppearance = (appearance: MobileThemeAppearance, value: MobileThemeId) => {
238 // Read at call time: a second pick before the next render must build on
239 // the first one's optimistic write.
240 const selected = resolveMobileThemeIds(
241 storedPreferencesOf(appAtomRegistry.get(mobilePreferencesAtom)) ?? {},
242 );
243 updateThemePreferences(
244 createMobileThemeSelectionPatch(selected, themeAppearance, appearance, value),
245 );
246 };
247
248 const setThemeIdForBothAppearances = (value: MobileThemeId) => {
249 updateThemePreferences(createMobileThemePairPatch(value));
250 };
251
252 const setThemeMode = (value: MobileThemeMode) => {
253 const current = currentRuntimeState();
254
255 // Clear forced appearance before publishing System so useColorScheme batches the system palette into the preference commit.
256 if (value === "system") {
257 Appearance.setColorScheme("unspecified");
258 }
259 const nextAppearance =
260 value === "system" ? (Appearance.getColorScheme() === "dark" ? "dark" : "light") : value;
261 const next = {
262 ...current,
263 themeAppearance: nextAppearance,
264 themeMode: value,
265 };
266
267 if (value === "system") {
268 appliedRuntimeState = next;
269 } else {
270 applyThemeRuntime(next);
271 }
272 updateThemePreferences({ themeMode: value });
273 };
274
275 const setAndroidNavigationStyle = (value: AndroidNavigationStyle) =>
276 updatePreferences({ androidNavigationStyle: value });
277
278 const setBaseFontSize = (value: number) => {
279 applyThemeRuntime({ ...currentRuntimeState(), baseFontSize: value });
280 updatePreferences({ baseFontSize: value });
281 };
282
283 const setTerminalFontSize = (value: number | null) => {
284 updatePreferences({ terminalFontSize: value });
285 };
286
287 const setCodeFontSize = (value: number | null) => {
288 updatePreferences({ codeFontSize: value });
289 };
290
291 const setCodeWordBreak = (value: boolean) => {
292 updatePreferences({ codeWordBreak: value });
293 };
294
295 const mathRenderingEnabled = storedPreferences?.mathRenderingEnabled === true;
296 const setMathRenderingEnabled = (value: boolean) =>
297 updatePreferences({ mathRenderingEnabled: value });
298
299 const value = useMemo(
300 (): AppearancePreferencesContextValue => ({
301 appearance,
302 themeId,
303 themeIds,
304 themeMode,
305 androidNavigationStyle,
306 setAndroidNavigationStyle,
307 themeAppearance,
308 systemColorsAvailable: isSystemColorsAvailable,
309 systemColorsActive,
310 themeVariables,
311 themeVariablesByAppearance,
312 systemColorPalettes,
313 isReady,
314 setThemeIdForAppearance,
315 setThemeIdForBothAppearances,
316 setThemeMode,
317 setBaseFontSize,
318 setTerminalFontSize,
319 setCodeFontSize,
320 setCodeWordBreak,
321 mathRenderingEnabled,
322 setMathRenderingEnabled,
323 }),
324 [
325 appearance,
326 themeId,
327 themeIds,
328 themeMode,
329 androidNavigationStyle,
330 setAndroidNavigationStyle,
331 themeAppearance,
332 systemColorsActive,
333 themeVariables,
334 themeVariablesByAppearance,
335 systemColorPalettes,
336 isReady,
337 setThemeIdForAppearance,
338 setThemeIdForBothAppearances,
339 setThemeMode,
340 setBaseFontSize,
341 setTerminalFontSize,
342 setCodeFontSize,
343 setCodeWordBreak,
344 mathRenderingEnabled,
345 setMathRenderingEnabled,
346 ],
347 );
348
349 return (
350 <AppearancePreferencesContext.Provider value={value}>
351 <ScopedTheme theme={activeThemeName}>
352 <ScopedVariables variables={themeVariables}>{props.children}</ScopedVariables>
353 </ScopedTheme>
354 </AppearancePreferencesContext.Provider>
355 );
356 }
357
358 export function useAppearancePreferences(): AppearancePreferencesContextValue {
359 const context = use(AppearancePreferencesContext);
360 if (!context) {
361 throw new Error("useAppearancePreferences must be used within AppearancePreferencesProvider");
362 }
363 return context;
364 }
365
366 export function useAndroidFloatingTabs() {
367 const { androidNavigationStyle } = useAppearancePreferences();
368 return Platform.OS === "android" && androidNavigationStyle === "one-ui";
369 }