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

AppearancePreferencesProvider.tsx

277 lines9.1 KB

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