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