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

AppearancePreferencesProvider.tsx

336 lines11.2 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 a forced native appearance before publishing System. The
215 // resulting useColorScheme notification still sees the previous forced
216 // preference, so React batches the actual system palette into the one
217 // urgent preference commit below.
218 if (value === "system") {
219 Appearance.setColorScheme("unspecified");
220 }
221 const nextAppearance =
222 value === "system" ? (Appearance.getColorScheme() === "dark" ? "dark" : "light") : value;
223 const next = {
224 ...current,
225 themeAppearance: nextAppearance,
226 themeMode: value,
227 };
228​
229 updateThemePreferences({ themeMode: value });
230 if (value === "system") {
231 appliedRuntimeStateRef.current = next;
232 } else {
233 syncThemeRuntime(next);
234 }
235 },
236 [runtimeState, syncThemeRuntime, updateThemePreferences],
237 );
238​
239 const setBaseFontSize = useCallback(
240 (value: number) => {
241 const current = appliedRuntimeStateRef.current ?? runtimeState;
242 syncThemeRuntime({ ...current, baseFontSize: value });
243 updatePreferences({ baseFontSize: value });
244 },
245 [runtimeState, syncThemeRuntime, updatePreferences],
246 );
247​
248 const setTerminalFontSize = useCallback(
249 (value: number | null) => {
250 updatePreferences({ terminalFontSize: value });
251 },
252 [updatePreferences],
253 );
254​
255 const setCodeFontSize = useCallback(
256 (value: number | null) => {
257 updatePreferences({ codeFontSize: value });
258 },
259 [updatePreferences],
260 );
261​
262 const setCodeWordBreak = useCallback(
263 (value: boolean) => {
264 updatePreferences({ codeWordBreak: value });
265 },
266 [updatePreferences],
267 );
268​
269 const mathRenderingEnabled = storedPreferences?.mathRenderingEnabled === true;
270 const setMathRenderingEnabled = useCallback(
271 (value: boolean) => updatePreferences({ mathRenderingEnabled: value }),
272 [updatePreferences],
273 );
274​
275 const value = useMemo(
276 (): AppearancePreferencesContextValue => ({
277 appearance,
278 themeId,
279 themeIds,
280 themeMode,
281 themeAppearance,
282 systemColorsAvailable: isSystemColorsAvailable,
283 systemColorsActive,
284 themeVariables,
285 themeVariablesByAppearance,
286 systemColorPalettes,
287 isReady,
288 setThemeIdForAppearance,
289 setThemeIdForBothAppearances,
290 setThemeMode,
291 setBaseFontSize,
292 setTerminalFontSize,
293 setCodeFontSize,
294 setCodeWordBreak,
295 mathRenderingEnabled,
296 setMathRenderingEnabled,
297 }),
298 [
299 appearance,
300 themeId,
301 themeIds,
302 themeMode,
303 themeAppearance,
304 systemColorsActive,
305 themeVariables,
306 themeVariablesByAppearance,
307 systemColorPalettes,
308 isReady,
309 setThemeIdForAppearance,
310 setThemeIdForBothAppearances,
311 setThemeMode,
312 setBaseFontSize,
313 setTerminalFontSize,
314 setCodeFontSize,
315 setCodeWordBreak,
316 mathRenderingEnabled,
317 setMathRenderingEnabled,
318 ],
319 );
320​
321 return (
322 <AppearancePreferencesContext.Provider value={value}>
323 <ScopedTheme theme={activeThemeName}>
324 <ScopedVariables variables={themeVariables}>{props.children}</ScopedVariables>
325 </ScopedTheme>
326 </AppearancePreferencesContext.Provider>
327 );
329​
330export function useAppearancePreferences(): AppearancePreferencesContextValue {
331 const context = use(AppearancePreferencesContext);
332 if (!context) {
333 throw new Error("useAppearancePreferences must be used within AppearancePreferencesProvider");
334 }
335 return context;