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

AppearancePreferencesProvider.tsx

350 lines12.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/unstable/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 /** Effective values with base-size derivation applied. Use this for rendering. */
49 readonly appearance: ResolvedAppearance;
50 readonly themeId: MobileThemeId;
51 readonly themeIds: MobileThemeIds;
52 readonly themeMode: MobileThemeMode;
53 readonly themeAppearance: MobileThemeAppearance;
54 readonly materialYouStyleLayoutEnabled: boolean;
55 readonly materialYouStyleLayoutActive: boolean;
56 readonly setMaterialYouStyleLayoutEnabled: (value: boolean) => void;
57 readonly systemColorsAvailable: boolean;
58 readonly systemColorsActive: boolean;
59 readonly themeVariables: MobileThemeVariables;
60 readonly themeVariablesByAppearance: Readonly<
61 Record<MobileThemeAppearance, MobileThemeVariables>
62 >;
63 readonly systemColorPalettes: ReturnType<typeof readSystemColorPalettes>;
64 readonly isReady: boolean;
65 readonly setThemeIdForAppearance: (
66 appearance: MobileThemeAppearance,
67 value: MobileThemeId,
68 ) => void;
69 readonly setThemeIdForBothAppearances: (value: MobileThemeId) => void;
70 readonly setThemeMode: (value: MobileThemeMode) => void;
71 readonly setBaseFontSize: (value: number) => void;
72 /** Pass null to clear the override and follow the base font size. */
73 readonly setTerminalFontSize: (value: number | null) => void;
74 /** Pass null to clear the override and follow the base font size. */
75 readonly setCodeFontSize: (value: number | null) => void;
76 readonly setCodeWordBreak: (value: boolean) => void;
78​
79const AppearancePreferencesContext = createContext<AppearancePreferencesContextValue | null>(null);
80​
81export function AppearancePreferencesProvider(props: { readonly children: ReactNode }) {
82 const preferencesResult = useAtomValue(mobilePreferencesAtom);
83 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
84 const systemColorScheme = useColorScheme() === "dark" ? "dark" : "light";
85 const storedPreferences = AsyncResult.isSuccess(preferencesResult)
86 ? preferencesResult.value
87 : null;
88 const preferences = useMemo(
89 () => resolveAppearancePreferences(storedPreferences),
90 [storedPreferences],
91 );
92 const themeMode = normalizeMobileThemeMode(storedPreferences?.themeMode);
93 const themeAppearance = themeMode === "system" ? systemColorScheme : themeMode;
94 const resolvedThemeIds = resolveMobileThemeIds(storedPreferences ?? {});
95 const themeIds = useMemo<MobileThemeIds>(
96 () => ({ light: resolvedThemeIds.light, dark: resolvedThemeIds.dark }),
97 [resolvedThemeIds.dark, resolvedThemeIds.light],
98 );
99 const themeId = themeIds[themeAppearance];
100 const materialYouStyleLayoutEnabled = storedPreferences?.materialYouStyleLayoutEnabled ?? false;
101 const materialYouStyleLayoutActive = Platform.OS === "android" && materialYouStyleLayoutEnabled;
102 const systemColorsActive = themeId === "material-you" && isSystemColorsAvailable;
103 const [systemColorPalettes, setSystemColorPalettes] = useState(readSystemColorPalettes);
104 useEffect(() => {
105 if (!isSystemColorsAvailable) return;
106 const refresh = () => {
107 const next = readSystemColorPalettes();
108 setSystemColorPalettes((previous) =>
109 JSON.stringify(previous) === JSON.stringify(next) ? previous : next,
110 );
111 };
112 const subscription = AppState.addEventListener("change", (state) => {
113 if (state === "active") refresh();
114 });
115 const focusSubscription = AppState.addEventListener("focus", refresh);
116 return () => {
117 subscription.remove();
118 focusSubscription.remove();
119 };
120 }, []);
121 const themeVariablesByAppearance = useMemo(() => {
122 const resolve = (appearance: MobileThemeAppearance) => {
123 const base = getMobileThemeRuntimeVariables(themeIds[appearance], appearance);
124 return themeIds[appearance] === "material-you" && systemColorPalettes
125 ? materialYouPaletteToMobileThemeVariables(
126 systemColorPalettes[appearance],
127 appearance,
128 base,
129 )
130 : base;
131 };
132 return { light: resolve("light"), dark: resolve("dark") };
133 }, [themeIds, systemColorPalettes]);
134 const themeVariables = themeVariablesByAppearance[themeAppearance];
135 const activeThemeName = getMobileUniwindThemeName(themeId, themeAppearance);
136 const { baseFontSize, codeFontSize, codeWordBreak, terminalFontSize } = preferences;
137 const appearance = useMemo(
138 () => resolveAppearance({ baseFontSize, codeFontSize, codeWordBreak, terminalFontSize }),
139 [baseFontSize, codeFontSize, codeWordBreak, terminalFontSize],
140 );
141 // Preference patches are optimistic. Keep controls interactive while a save is
142 // in flight so rapid theme choices can supersede one another immediately.
143 const isReady = AsyncResult.isSuccess(preferencesResult);
144 const runtimeState = useMemo<MobileThemeRuntimeState>(
145 () => ({
146 baseFontSize,
147 themeAppearance,
148 themeMode,
149 }),
150 [baseFontSize, themeAppearance, themeMode],
151 );
152 const appliedRuntimeStateRef = useRef<MobileThemeRuntimeState | null>(null);
153 const selectedThemeIdsRef = useRef(themeIds);
154​
155 const applyThemeRuntime = useCallback((next: MobileThemeRuntimeState) => {
156 const operations = createMobileThemeRuntimeOperations(appliedRuntimeStateRef.current, next);
157 for (const operation of operations) {
158 if (operation.kind === "update-text-variables") {
159 Uniwind.updateCSSVariables(operation.themeName, operation.variables);
160 continue;
161 }
162 if (operation.kind === "set-appearance-mode") {
163 Appearance.setColorScheme(
164 operation.themeMode === "system" ? "unspecified" : operation.appearance,
165 );
166 }
167 }
168 appliedRuntimeStateRef.current = next;
169 }, []);
170​
171 const syncThemeRuntime = useCallback(
172 (next: MobileThemeRuntimeState) => applyThemeRuntime(next),
173 [applyThemeRuntime],
174 );
175​
176 const updatePreferences = useCallback(
177 (patch: Partial<Preferences>) => {
178 startTransition(() => savePreferences(patch));
179 },
180 [savePreferences],
181 );
182​
183 const updateThemePreferences = useCallback(
184 (patch: Partial<Preferences>) => {
185 // Theme selection owns the visible root ScopedTheme value. Keep its
186 // optimistic atom update urgent so the first frame after a press is the
187 // complete new palette rather than a deferred transition render.
188 savePreferences(patch);
189 },
190 [savePreferences],
191 );
192​
193 useLayoutEffect(() => {
194 selectedThemeIdsRef.current = themeIds;
195 syncThemeRuntime(runtimeState);
196 }, [runtimeState, syncThemeRuntime, themeIds]);
197​
198 const setThemeIdForAppearance = useCallback(
199 (appearance: MobileThemeAppearance, value: MobileThemeId) => {
200 const patch = createMobileThemeSelectionPatch(
201 selectedThemeIdsRef.current,
202 themeAppearance,
203 appearance,
204 value,
205 );
206 selectedThemeIdsRef.current = resolveMobileThemeIds(patch);
207 updateThemePreferences(patch);
208 },
209 [themeAppearance, updateThemePreferences],
210 );
211​
212 const setThemeIdForBothAppearances = useCallback(
213 (value: MobileThemeId) => {
214 const patch = createMobileThemePairPatch(value);
215 selectedThemeIdsRef.current = resolveMobileThemeIds(patch);
216 updateThemePreferences(patch);
217 },
218 [updateThemePreferences],
219 );
220​
221 const setThemeMode = useCallback(
222 (value: MobileThemeMode) => {
223 const current = appliedRuntimeStateRef.current ?? runtimeState;
224​
225 // Clear a forced native appearance before publishing System. The
226 // resulting useColorScheme notification still sees the previous forced
227 // preference, so React batches the actual system palette into the one
228 // urgent preference commit below.
229 if (value === "system") {
230 Appearance.setColorScheme("unspecified");
231 }
232 const nextAppearance =
233 value === "system" ? (Appearance.getColorScheme() === "dark" ? "dark" : "light") : value;
234 const next = {
235 ...current,
236 themeAppearance: nextAppearance,
237 themeMode: value,
238 };
239​
240 updateThemePreferences({ themeMode: value });
241 if (value === "system") {
242 appliedRuntimeStateRef.current = next;
243 } else {
244 syncThemeRuntime(next);
245 }
246 },
247 [runtimeState, syncThemeRuntime, updateThemePreferences],
248 );
249​
250 const setMaterialYouStyleLayoutEnabled = useCallback(
251 (value: boolean) => {
252 updatePreferences({ materialYouStyleLayoutEnabled: value });
253 },
254 [updatePreferences],
255 );
256​
257 const setBaseFontSize = useCallback(
258 (value: number) => {
259 const current = appliedRuntimeStateRef.current ?? runtimeState;
260 syncThemeRuntime({ ...current, baseFontSize: value });
261 updatePreferences({ baseFontSize: value });
262 },
263 [runtimeState, syncThemeRuntime, updatePreferences],
264 );
265​
266 const setTerminalFontSize = useCallback(
267 (value: number | null) => {
268 updatePreferences({ terminalFontSize: value });
269 },
270 [updatePreferences],
271 );
272​
273 const setCodeFontSize = useCallback(
274 (value: number | null) => {
275 updatePreferences({ codeFontSize: value });
276 },
277 [updatePreferences],
278 );
279​
280 const setCodeWordBreak = useCallback(
281 (value: boolean) => {
282 updatePreferences({ codeWordBreak: value });
283 },
284 [updatePreferences],
285 );
286​
287 const value = useMemo(
288 (): AppearancePreferencesContextValue => ({
289 appearance,
290 themeId,
291 themeIds,
292 themeMode,
293 themeAppearance,
294 systemColorsAvailable: isSystemColorsAvailable,
295 systemColorsActive,
296 materialYouStyleLayoutEnabled,
297 materialYouStyleLayoutActive,
298 setMaterialYouStyleLayoutEnabled,
299 themeVariables,
300 themeVariablesByAppearance,
301 systemColorPalettes,
302 isReady,
303 setThemeIdForAppearance,
304 setThemeIdForBothAppearances,
305 setThemeMode,
306 setBaseFontSize,
307 setTerminalFontSize,
308 setCodeFontSize,
309 setCodeWordBreak,
310 }),
311 [
312 appearance,
313 themeId,
314 themeIds,
315 themeMode,
316 themeAppearance,
317 systemColorsActive,
318 materialYouStyleLayoutEnabled,
319 materialYouStyleLayoutActive,
320 setMaterialYouStyleLayoutEnabled,
321 themeVariables,
322 themeVariablesByAppearance,
323 systemColorPalettes,
324 isReady,
325 setThemeIdForAppearance,
326 setThemeIdForBothAppearances,
327 setThemeMode,
328 setBaseFontSize,
329 setTerminalFontSize,
330 setCodeFontSize,
331 setCodeWordBreak,
332 ],
333 );
334​
335 return (
336 <AppearancePreferencesContext.Provider value={value}>
337 <ScopedTheme theme={activeThemeName}>
338 <ScopedVariables variables={themeVariables}>{props.children}</ScopedVariables>
339 </ScopedTheme>
340 </AppearancePreferencesContext.Provider>
341 );
343​
344export function useAppearancePreferences(): AppearancePreferencesContextValue {
345 const context = use(AppearancePreferencesContext);
346 if (!context) {
347 throw new Error("useAppearancePreferences must be used within AppearancePreferencesProvider");
348 }
349 return context;