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

AppearancePreferencesProvider.tsx

333 lines11.1 KB

1import {
2 createContext,
3 startTransition,
4 use,
5 useCallback,
6 useEffect,
7 useState,
8 useLayoutEffect,
9 useMemo,
10 useRef,
11 type ReactNode,
12} from "react";
13import { AppState, Appearance, Platform, useColorScheme } from "react-native";
14​
15import { useAtomSet, useAtomValue } from "@effect/atom-react";
16import { AsyncResult } from "effect/reactivity";
17​
18import { ScopedTheme, ScopedVariables, Uniwind } from "uniwind";
19​
20import {
21 resolveAppearance,
22 resolveAppearancePreferences,
23 type ResolvedAppearance,
24} from "../../../lib/appearancePreferences";
25import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../../state/preferences";
26import type { Preferences } from "../../../persistence/mobile-preferences";
27import { isSystemColorsAvailable, readSystemColorPalettes } 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 themeAppearance: MobileThemeAppearance;
53 readonly systemColorsAvailable: boolean;
54 readonly systemColorsActive: boolean;
55 readonly themeVariables: MobileThemeVariables;
56 readonly themeVariablesByAppearance: Readonly<
57 Record<MobileThemeAppearance, MobileThemeVariables>
58 >;
59 readonly systemColorPalettes: ReturnType<typeof readSystemColorPalettes>;
60 readonly isReady: boolean;
61 readonly setThemeIdForAppearance: (
62 appearance: MobileThemeAppearance,
63 value: MobileThemeId,
64 ) => void;
65 readonly setThemeIdForBothAppearances: (value: MobileThemeId) => void;
66 readonly setThemeMode: (value: MobileThemeMode) => void;
67 readonly setBaseFontSize: (value: number) => void;
68 readonly setTerminalFontSize: (value: number | null) => void;
69 readonly setCodeFontSize: (value: number | null) => void;
70 readonly setCodeWordBreak: (value: boolean) => void;
71 readonly mathRenderingEnabled: boolean;
72 readonly setMathRenderingEnabled: (value: boolean) => void;
74​
75const AppearancePreferencesContext = createContext<AppearancePreferencesContextValue | null>(null);
76​
77export function AppearancePreferencesProvider(props: { readonly children: ReactNode }) {
78 const preferencesResult = useAtomValue(mobilePreferencesAtom);
79 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
80 const systemColorScheme = useColorScheme() === "dark" ? "dark" : "light";
81 const storedPreferences = AsyncResult.isSuccess(preferencesResult)
82 ? preferencesResult.value
83 : null;
84 const preferences = useMemo(
85 () => resolveAppearancePreferences(storedPreferences),
86 [storedPreferences],
87 );
88 const themeMode = normalizeMobileThemeMode(storedPreferences?.themeMode);
89 const themeAppearance = themeMode === "system" ? systemColorScheme : themeMode;
90 const resolvedThemeIds = resolveMobileThemeIds(storedPreferences ?? {});
91 const themeIds = useMemo<MobileThemeIds>(
92 () => ({ light: resolvedThemeIds.light, dark: resolvedThemeIds.dark }),
93 [resolvedThemeIds.dark, resolvedThemeIds.light],
94 );
95 const themeId = themeIds[themeAppearance];
96 const systemColorsActive = themeId === "material-you" && isSystemColorsAvailable;
97 const [systemColorPalettes, setSystemColorPalettes] = useState(readSystemColorPalettes);
98 useEffect(() => {
99 if (!isSystemColorsAvailable) return;
100 const refresh = () => {
101 const next = readSystemColorPalettes();
102 setSystemColorPalettes((previous) =>
103 JSON.stringify(previous) === JSON.stringify(next) ? previous : next,
104 );
105 };
106 const subscription = AppState.addEventListener("change", (state) => {
107 if (state === "active") refresh();
108 });
109 const focusSubscription = AppState.addEventListener("focus", refresh);
110 return () => {
111 subscription.remove();
112 focusSubscription.remove();
113 };
114 }, []);
115 const themeVariablesByAppearance = useMemo(() => {
116 const resolve = (appearance: MobileThemeAppearance) => {
117 const base = getMobileThemeRuntimeVariables(themeIds[appearance], appearance, Platform.OS);
118 return themeIds[appearance] === "material-you" && systemColorPalettes
119 ? materialYouPaletteToMobileThemeVariables(
120 systemColorPalettes[appearance],
121 appearance,
122 base,
123 )
124 : base;
125 };
126 return { light: resolve("light"), dark: resolve("dark") };
127 }, [themeIds, systemColorPalettes]);
128 const themeVariables = themeVariablesByAppearance[themeAppearance];
129 const activeThemeName = getMobileUniwindThemeName(themeId, themeAppearance);
130 const { baseFontSize, codeFontSize, codeWordBreak, terminalFontSize } = preferences;
131 const appearance = useMemo(
132 () => resolveAppearance({ baseFontSize, codeFontSize, codeWordBreak, terminalFontSize }),
133 [baseFontSize, codeFontSize, codeWordBreak, terminalFontSize],
134 );
135 const isReady = AsyncResult.isSuccess(preferencesResult);
136 const runtimeState = useMemo<MobileThemeRuntimeState>(
137 () => ({
138 baseFontSize,
139 themeAppearance,
140 themeMode,
141 }),
142 [baseFontSize, themeAppearance, themeMode],
143 );
144 const appliedRuntimeStateRef = useRef<MobileThemeRuntimeState | null>(null);
145 const selectedThemeIdsRef = useRef(themeIds);
146​
147 const applyThemeRuntime = useCallback((next: MobileThemeRuntimeState) => {
148 const operations = createMobileThemeRuntimeOperations(appliedRuntimeStateRef.current, next);
149 for (const operation of operations) {
150 if (operation.kind === "update-text-variables") {
151 Uniwind.updateCSSVariables(operation.themeName, operation.variables);
152 continue;
153 }
154 if (operation.kind === "set-appearance-mode") {
155 Appearance.setColorScheme(
156 operation.themeMode === "system" ? "unspecified" : operation.appearance,
157 );
158 }
159 }
160 appliedRuntimeStateRef.current = next;
161 }, []);
162​
163 const syncThemeRuntime = useCallback(
164 (next: MobileThemeRuntimeState) => applyThemeRuntime(next),
165 [applyThemeRuntime],
166 );
167​
168 const updatePreferences = useCallback(
169 (patch: Partial<Preferences>) => {
170 startTransition(() => savePreferences(patch));
171 },
172 [savePreferences],
173 );
174​
175 const updateThemePreferences = useCallback(
176 (patch: Partial<Preferences>) => {
177 savePreferences(patch);
178 },
179 [savePreferences],
180 );
181​
182 useLayoutEffect(() => {
183 selectedThemeIdsRef.current = themeIds;
184 syncThemeRuntime(runtimeState);
185 }, [runtimeState, syncThemeRuntime, themeIds]);
186​
187 const setThemeIdForAppearance = useCallback(
188 (appearance: MobileThemeAppearance, value: MobileThemeId) => {
189 const patch = createMobileThemeSelectionPatch(
190 selectedThemeIdsRef.current,
191 themeAppearance,
192 appearance,
193 value,
194 );
195 selectedThemeIdsRef.current = resolveMobileThemeIds(patch);
196 updateThemePreferences(patch);
197 },
198 [themeAppearance, updateThemePreferences],
199 );
200​
201 const setThemeIdForBothAppearances = useCallback(
202 (value: MobileThemeId) => {
203 const patch = createMobileThemePairPatch(value);
204 selectedThemeIdsRef.current = resolveMobileThemeIds(patch);
205 updateThemePreferences(patch);
206 },
207 [updateThemePreferences],
208 );
209​
210 const setThemeMode = useCallback(
211 (value: MobileThemeMode) => {
212 const current = appliedRuntimeStateRef.current ?? runtimeState;
213​
214 // Clear forced appearance before publishing System so useColorScheme batches the system palette into the preference commit.
215 if (value === "system") {
216 Appearance.setColorScheme("unspecified");
217 }
218 const nextAppearance =
219 value === "system" ? (Appearance.getColorScheme() === "dark" ? "dark" : "light") : value;
220 const next = {
221 ...current,
222 themeAppearance: nextAppearance,
223 themeMode: value,
224 };
225​
226 updateThemePreferences({ themeMode: value });
227 if (value === "system") {
228 appliedRuntimeStateRef.current = next;
229 } else {
230 syncThemeRuntime(next);
231 }
232 },
233 [runtimeState, syncThemeRuntime, updateThemePreferences],
234 );
235​
236 const setBaseFontSize = useCallback(
237 (value: number) => {
238 const current = appliedRuntimeStateRef.current ?? runtimeState;
239 syncThemeRuntime({ ...current, baseFontSize: value });
240 updatePreferences({ baseFontSize: value });
241 },
242 [runtimeState, syncThemeRuntime, updatePreferences],
243 );
244​
245 const setTerminalFontSize = useCallback(
246 (value: number | null) => {
247 updatePreferences({ terminalFontSize: value });
248 },
249 [updatePreferences],
250 );
251​
252 const setCodeFontSize = useCallback(
253 (value: number | null) => {
254 updatePreferences({ codeFontSize: value });
255 },
256 [updatePreferences],
257 );
258​
259 const setCodeWordBreak = useCallback(
260 (value: boolean) => {
261 updatePreferences({ codeWordBreak: value });
262 },
263 [updatePreferences],
264 );
265​
266 const mathRenderingEnabled = storedPreferences?.mathRenderingEnabled === true;
267 const setMathRenderingEnabled = useCallback(
268 (value: boolean) => updatePreferences({ mathRenderingEnabled: value }),
269 [updatePreferences],
270 );
271​
272 const value = useMemo(
273 (): AppearancePreferencesContextValue => ({
274 appearance,
275 themeId,
276 themeIds,
277 themeMode,
278 themeAppearance,
279 systemColorsAvailable: isSystemColorsAvailable,
280 systemColorsActive,
281 themeVariables,
282 themeVariablesByAppearance,
283 systemColorPalettes,
284 isReady,
285 setThemeIdForAppearance,
286 setThemeIdForBothAppearances,
287 setThemeMode,
288 setBaseFontSize,
289 setTerminalFontSize,
290 setCodeFontSize,
291 setCodeWordBreak,
292 mathRenderingEnabled,
293 setMathRenderingEnabled,
294 }),
295 [
296 appearance,
297 themeId,
298 themeIds,
299 themeMode,
300 themeAppearance,
301 systemColorsActive,
302 themeVariables,
303 themeVariablesByAppearance,
304 systemColorPalettes,
305 isReady,
306 setThemeIdForAppearance,
307 setThemeIdForBothAppearances,
308 setThemeMode,
309 setBaseFontSize,
310 setTerminalFontSize,
311 setCodeFontSize,
312 setCodeWordBreak,
313 mathRenderingEnabled,
314 setMathRenderingEnabled,
315 ],
316 );
317​
318 return (
319 <AppearancePreferencesContext.Provider value={value}>
320 <ScopedTheme theme={activeThemeName}>
321 <ScopedVariables variables={themeVariables}>{props.children}</ScopedVariables>
322 </ScopedTheme>
323 </AppearancePreferencesContext.Provider>
324 );
326​
327export function useAppearancePreferences(): AppearancePreferencesContextValue {
328 const context = use(AppearancePreferencesContext);
329 if (!context) {
330 throw new Error("useAppearancePreferences must be used within AppearancePreferencesProvider");
331 }
332 return context;