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

AppearancePreferencesProvider.tsx

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