Open History to see the last commit
1import {
2 createContext,
3 startTransition,
4 use,
5 useCallback,
6 useLayoutEffect,
7 useMemo,
8 useRef,
9 type ReactNode,
10} from "react";
11import { Appearance, useColorScheme } from "react-native";
12
13import { useAtomSet, useAtomValue } from "@effect/atom-react";
14import { AsyncResult } from "effect/unstable/reactivity";
15
16import { ScopedTheme, Uniwind } from "uniwind";
17
18import {
19 resolveAppearance,
20 resolveAppearancePreferences,
21 type ResolvedAppearance,
22} from "../../../lib/appearancePreferences";
23import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../../state/preferences";
24import type { Preferences } from "../../../persistence/mobile-preferences";
25import {
26 createMobileThemePairPatch,
27 createMobileThemeSelectionPatch,
28 normalizeMobileThemeMode,
29 resolveMobileThemeIds,
30 type MobileThemeAppearance,
31 type MobileThemeId,
32 type MobileThemeIds,
33 type MobileThemeMode,
34} from "../../../lib/mobileTheme";
35import {
36 createMobileThemeRuntimeOperations,
37 getMobileUniwindThemeName,
38 type MobileThemeRuntimeState,
39} from "../../../lib/mobileThemeRuntime";
40
41interface AppearancePreferencesContextValue {
42 /** Effective values with base-size derivation applied. Use this for rendering. */
43 readonly appearance: ResolvedAppearance;
44 readonly themeId: MobileThemeId;
45 readonly themeIds: MobileThemeIds;
46 readonly themeMode: MobileThemeMode;
47 readonly themeAppearance: MobileThemeAppearance;
48 readonly isReady: boolean;
49 readonly setThemeIdForAppearance: (
50 appearance: MobileThemeAppearance,
51 value: MobileThemeId,
52 ) => void;
53 readonly setThemeIdForBothAppearances: (value: MobileThemeId) => void;
54 readonly setThemeMode: (value: MobileThemeMode) => void;
55 readonly setBaseFontSize: (value: number) => void;
56 /** Pass null to clear the override and follow the base font size. */
57 readonly setTerminalFontSize: (value: number | null) => void;
58 /** Pass null to clear the override and follow the base font size. */
59 readonly setCodeFontSize: (value: number | null) => void;
60 readonly setCodeWordBreak: (value: boolean) => void;
61}
62
63const AppearancePreferencesContext = createContext<AppearancePreferencesContextValue | null>(null);
64
65export function AppearancePreferencesProvider(props: { readonly children: ReactNode }) {
66 const preferencesResult = useAtomValue(mobilePreferencesAtom);
67 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
68 const systemColorScheme = useColorScheme() === "dark" ? "dark" : "light";
69 const storedPreferences = AsyncResult.isSuccess(preferencesResult)
70 ? preferencesResult.value
71 : null;
72 const preferences = useMemo(
73 () => resolveAppearancePreferences(storedPreferences),
74 [storedPreferences],
75 );
76 const themeMode = normalizeMobileThemeMode(storedPreferences?.themeMode);
77 const themeAppearance = themeMode === "system" ? systemColorScheme : themeMode;
78 const resolvedThemeIds = resolveMobileThemeIds(storedPreferences ?? {});
79 const themeIds = useMemo<MobileThemeIds>(
80 () => ({ light: resolvedThemeIds.light, dark: resolvedThemeIds.dark }),
81 [resolvedThemeIds.dark, resolvedThemeIds.light],
82 );
83 const themeId = themeIds[themeAppearance];
84 const activeThemeName = getMobileUniwindThemeName(themeId, themeAppearance);
85 const { baseFontSize, codeFontSize, codeWordBreak, terminalFontSize } = preferences;
86 const appearance = useMemo(
87 () => resolveAppearance({ baseFontSize, codeFontSize, codeWordBreak, terminalFontSize }),
88 [baseFontSize, codeFontSize, codeWordBreak, terminalFontSize],
89 );
90 // Preference patches are optimistic. Keep controls interactive while a save is
91 // in flight so rapid theme choices can supersede one another immediately.
92 const isReady = AsyncResult.isSuccess(preferencesResult);
93 const runtimeState = useMemo<MobileThemeRuntimeState>(
94 () => ({
95 baseFontSize,
96 themeAppearance,
97 themeMode,
98 }),
99 [baseFontSize, themeAppearance, themeMode],
100 );
101 const appliedRuntimeStateRef = useRef<MobileThemeRuntimeState | null>(null);
102 const selectedThemeIdsRef = useRef(themeIds);
103
104 const applyThemeRuntime = useCallback((next: MobileThemeRuntimeState) => {
105 const operations = createMobileThemeRuntimeOperations(appliedRuntimeStateRef.current, next);
106 for (const operation of operations) {
107 if (operation.kind === "update-text-variables") {
108 Uniwind.updateCSSVariables(operation.themeName, operation.variables);
109 continue;
110 }
111 if (operation.kind === "set-appearance-mode") {
112 Appearance.setColorScheme(
113 operation.themeMode === "system" ? "unspecified" : operation.appearance,
114 );
115 }
116 }
117 appliedRuntimeStateRef.current = next;
118 }, []);
119
120 const syncThemeRuntime = useCallback(
121 (next: MobileThemeRuntimeState) => applyThemeRuntime(next),
122 [applyThemeRuntime],
123 );
124
125 const updatePreferences = useCallback(
126 (patch: Partial<Preferences>) => {
127 startTransition(() => savePreferences(patch));
128 },
129 [savePreferences],
130 );
131
132 const updateThemePreferences = useCallback(
133 (patch: Partial<Preferences>) => {
134 // Theme selection owns the visible root ScopedTheme value. Keep its
135 // optimistic atom update urgent so the first frame after a press is the
136 // complete new palette rather than a deferred transition render.
137 savePreferences(patch);
138 },
139 [savePreferences],
140 );
141
142 useLayoutEffect(() => {
143 selectedThemeIdsRef.current = themeIds;
144 syncThemeRuntime(runtimeState);
145 }, [runtimeState, syncThemeRuntime, themeIds]);
146
147 const setThemeIdForAppearance = useCallback(
148 (appearance: MobileThemeAppearance, value: MobileThemeId) => {
149 const patch = createMobileThemeSelectionPatch(
150 selectedThemeIdsRef.current,
151 themeAppearance,
152 appearance,
153 value,
154 );
155 selectedThemeIdsRef.current = resolveMobileThemeIds(patch);
156 updateThemePreferences(patch);
157 },
158 [themeAppearance, updateThemePreferences],
159 );
160
161 const setThemeIdForBothAppearances = useCallback(
162 (value: MobileThemeId) => {
163 const patch = createMobileThemePairPatch(value);
164 selectedThemeIdsRef.current = resolveMobileThemeIds(patch);
165 updateThemePreferences(patch);
166 },
167 [updateThemePreferences],
168 );
169
170 const setThemeMode = useCallback(
171 (value: MobileThemeMode) => {
172 const current = appliedRuntimeStateRef.current ?? runtimeState;
173
174 // Clear a forced native appearance before publishing System. The
175 // resulting useColorScheme notification still sees the previous forced
176 // preference, so React batches the actual system palette into the one
177 // urgent preference commit below.
178 if (value === "system") {
179 Appearance.setColorScheme("unspecified");
180 }
181 const nextAppearance =
182 value === "system" ? (Appearance.getColorScheme() === "dark" ? "dark" : "light") : value;
183 const next = {
184 ...current,
185 themeAppearance: nextAppearance,
186 themeMode: value,
187 };
188
189 updateThemePreferences({ themeMode: value });
190 if (value === "system") {
191 appliedRuntimeStateRef.current = next;
192 } else {
193 syncThemeRuntime(next);
194 }
195 },
196 [runtimeState, syncThemeRuntime, updateThemePreferences],
197 );
198
199 const setBaseFontSize = useCallback(
200 (value: number) => {
201 const current = appliedRuntimeStateRef.current ?? runtimeState;
202 syncThemeRuntime({ ...current, baseFontSize: value });
203 updatePreferences({ baseFontSize: value });
204 },
205 [runtimeState, syncThemeRuntime, updatePreferences],
206 );
207
208 const setTerminalFontSize = useCallback(
209 (value: number | null) => {
210 updatePreferences({ terminalFontSize: value });
211 },
212 [updatePreferences],
213 );
214
215 const setCodeFontSize = useCallback(
216 (value: number | null) => {
217 updatePreferences({ codeFontSize: value });
218 },
219 [updatePreferences],
220 );
221
222 const setCodeWordBreak = useCallback(
223 (value: boolean) => {
224 updatePreferences({ codeWordBreak: value });
225 },
226 [updatePreferences],
227 );
228
229 const value = useMemo(
230 (): AppearancePreferencesContextValue => ({
231 appearance,
232 themeId,
233 themeIds,
234 themeMode,
235 themeAppearance,
236 isReady,
237 setThemeIdForAppearance,
238 setThemeIdForBothAppearances,
239 setThemeMode,
240 setBaseFontSize,
241 setTerminalFontSize,
242 setCodeFontSize,
243 setCodeWordBreak,
244 }),
245 [
246 appearance,
247 themeId,
248 themeIds,
249 themeMode,
250 themeAppearance,
251 isReady,
252 setThemeIdForAppearance,
253 setThemeIdForBothAppearances,
254 setThemeMode,
255 setBaseFontSize,
256 setTerminalFontSize,
257 setCodeFontSize,
258 setCodeWordBreak,
259 ],
260 );
261
262 return (
263 <AppearancePreferencesContext.Provider value={value}>
264 <ScopedTheme theme={activeThemeName}>{props.children}</ScopedTheme>
265 </AppearancePreferencesContext.Provider>
266 );
267}
268
269export function useAppearancePreferences(): AppearancePreferencesContextValue {
270 const context = use(AppearancePreferencesContext);
271 if (!context) {
272 throw new Error("useAppearancePreferences must be used within AppearancePreferencesProvider");
273 }
274 return context;
275}