Skip to content

Commit a89f6d7

Browse files
refactor(mobile): theme preferences reach the native runtime without a layout effect
The appearance provider mirrored the preferences atom into the native runtime (Appearance.setColorScheme, Uniwind text-scale variables) from a useLayoutEffect, and kept the Material You palettes in component state fed by an AppState listener effect. Three refs kept the provider's view of "what was applied" and "what was picked" in step with renders. The runtime now follows a derived atom (font size, theme mode, appearance) through one app-lifetime subscription installed with the other app services in App.tsx, so the native theme is applied when the preference changes rather than after the next provider commit. The palettes are a keep-alive atom that owns its AppState listeners. Theme pickers read the current selection from the registry at call time, which already includes the previous pick's optimistic write, instead of a ref copied in the layout effect. Effects: AppearancePreferencesProvider.tsx 2 -> 0 (palette listener effect, runtime layout effect). App.tsx unchanged; the splash hide stays an effect because it reacts to the provider's ready state after commit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 5d91ab1 commit a89f6d7

2 files changed

Lines changed: 128 additions & 100 deletions

File tree

‎apps/mobile/src/App.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcase
2424
import { IncomingShareProvider } from "./features/sharing/IncomingShareProvider";
2525
import {
2626
AppearancePreferencesProvider,
27+
installAppearanceRuntime,
2728
useAppearancePreferences,
2829
} from "./features/settings/appearance/AppearancePreferencesProvider";
2930
import { RootStack } from "./Stack";
@@ -107,6 +108,7 @@ const appServiceDisposers = [
107108
threadRefsAtom: environmentThreadShells.threadRefsAtom,
108109
shellStateAtom: environmentShell.stateAtom,
109110
}),
111+
installAppearanceRuntime(),
110112
installSubscriptionUsageRefresh(),
111113
installPermissionUpdateNotice(),
112114
installThreadOutboxDelivery(),

‎apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx‎

Lines changed: 126 additions & 100 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,8 @@
1-
import {
2-
createContext,
3-
startTransition,
4-
use,
5-
useCallback,
6-
useEffect,
7-
useState,
8-
useLayoutEffect,
9-
useMemo,
10-
useRef,
11-
type ReactNode,
12-
} from "react";
1+
import { createContext, startTransition, use, useCallback, useMemo, type ReactNode } from "react";
132
import { AppState, Appearance, Platform, useColorScheme } from "react-native";
143

154
import { useAtomSet, useAtomValue } from "@effect/atom-react";
16-
import { AsyncResult } from "effect/reactivity";
5+
import { Atom, AsyncResult } from "effect/reactivity";
176

187
import { ScopedTheme, ScopedVariables, Uniwind } from "uniwind";
198

@@ -22,9 +11,14 @@ import {
2211
resolveAppearancePreferences,
2312
type ResolvedAppearance,
2413
} from "../../../lib/appearancePreferences";
14+
import { appAtomRegistry } from "../../../state/atom-registry";
2515
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../../state/preferences";
2616
import type { Preferences } from "../../../persistence/mobile-preferences";
27-
import { isSystemColorsAvailable, readSystemColorPalettes } from "../../../lib/materialYouPalette";
17+
import {
18+
isSystemColorsAvailable,
19+
readSystemColorPalettes,
20+
type MaterialYouPalettes,
21+
} from "../../../lib/materialYouPalette";
2822
import { materialYouPaletteToMobileThemeVariables } from "../../../lib/materialYouTheme";
2923
import { getMobileThemeRuntimeVariables } from "../../../lib/mobileThemeVariables";
3024
import type { MobileThemeVariables } from "../../../lib/mobileTheme";
@@ -74,6 +68,104 @@ interface AppearancePreferencesContextValue {
7468

7569
const AppearancePreferencesContext = createContext<AppearancePreferencesContextValue | null>(null);
7670

71+
function storedPreferencesOf<E>(result: AsyncResult.AsyncResult<Preferences, E>) {
72+
return AsyncResult.isSuccess(result) ? result.value : null;
73+
}
74+
75+
/**
76+
* Material You palettes follow the system wallpaper, which can change while the
77+
* app is in the background.
78+
*/
79+
const systemColorPalettesAtom = Atom.make((get): MaterialYouPalettes | null => {
80+
const initial = readSystemColorPalettes();
81+
if (!isSystemColorsAvailable) return initial;
82+
let current = initial;
83+
const refresh = () => {
84+
const next = readSystemColorPalettes();
85+
if (JSON.stringify(current) === JSON.stringify(next)) return;
86+
current = next;
87+
get.setSelf(next);
88+
};
89+
const subscription = AppState.addEventListener("change", (state) => {
90+
if (state === "active") refresh();
91+
});
92+
const focusSubscription = AppState.addEventListener("focus", refresh);
93+
get.addFinalizer(() => {
94+
subscription.remove();
95+
focusSubscription.remove();
96+
});
97+
return initial;
98+
}).pipe(Atom.keepAlive, Atom.withLabel("mobile:system-color-palettes"));
99+
100+
function resolveThemeVariablesByAppearance(
101+
themeIds: MobileThemeIds,
102+
palettes: MaterialYouPalettes | null,
103+
): Readonly<Record<MobileThemeAppearance, MobileThemeVariables>> {
104+
const resolve = (appearance: MobileThemeAppearance) => {
105+
const base = getMobileThemeRuntimeVariables(themeIds[appearance], appearance, Platform.OS);
106+
return themeIds[appearance] === "material-you" && palettes
107+
? materialYouPaletteToMobileThemeVariables(palettes[appearance], appearance, base)
108+
: base;
109+
};
110+
return { light: resolve("light"), dark: resolve("dark") };
111+
}
112+
113+
/** The appearance whose theme is on screen, read from the native scheme. */
114+
function resolveThemeAppearance(stored: Preferences | null): MobileThemeAppearance {
115+
const themeMode = normalizeMobileThemeMode(stored?.themeMode);
116+
if (themeMode !== "system") return themeMode;
117+
return Appearance.getColorScheme() === "dark" ? "dark" : "light";
118+
}
119+
120+
function runtimeStateFor(stored: Preferences | null): MobileThemeRuntimeState {
121+
return {
122+
baseFontSize: resolveAppearancePreferences(stored).baseFontSize,
123+
themeMode: normalizeMobileThemeMode(stored?.themeMode),
124+
themeAppearance: resolveThemeAppearance(stored),
125+
};
126+
}
127+
128+
const themeRuntimeStateAtom = Atom.make((get) =>
129+
runtimeStateFor(storedPreferencesOf(get(mobilePreferencesAtom))),
130+
).pipe(
131+
Atom.withEquality(
132+
(left: MobileThemeRuntimeState, right: MobileThemeRuntimeState) =>
133+
left.baseFontSize === right.baseFontSize &&
134+
left.themeMode === right.themeMode &&
135+
left.themeAppearance === right.themeAppearance,
136+
),
137+
);
138+
139+
// Native appearance and Uniwind text variables are process-global, so the
140+
// last applied state is too. Setters apply ahead of the preference write so the
141+
// first frame after a change already uses it; the atom subscription then sees
142+
// no difference.
143+
let appliedRuntimeState: MobileThemeRuntimeState | null = null;
144+
145+
function applyThemeRuntime(next: MobileThemeRuntimeState) {
146+
for (const operation of createMobileThemeRuntimeOperations(appliedRuntimeState, next)) {
147+
if (operation.kind === "update-text-variables") {
148+
Uniwind.updateCSSVariables(operation.themeName, operation.variables);
149+
continue;
150+
}
151+
if (operation.kind === "set-appearance-mode") {
152+
Appearance.setColorScheme(
153+
operation.themeMode === "system" ? "unspecified" : operation.appearance,
154+
);
155+
}
156+
}
157+
appliedRuntimeState = next;
158+
}
159+
160+
function currentRuntimeState() {
161+
return appliedRuntimeState ?? appAtomRegistry.get(themeRuntimeStateAtom);
162+
}
163+
164+
/** App-lifetime: applies theme preferences to the native runtime. */
165+
export function installAppearanceRuntime(): () => void {
166+
return appAtomRegistry.subscribe(themeRuntimeStateAtom, applyThemeRuntime, { immediate: true });
167+
}
168+
77169
export function AppearancePreferencesProvider(props: { readonly children: ReactNode }) {
78170
const preferencesResult = useAtomValue(mobilePreferencesAtom);
79171
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
@@ -94,37 +186,11 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN
94186
);
95187
const themeId = themeIds[themeAppearance];
96188
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]);
189+
const systemColorPalettes = useAtomValue(systemColorPalettesAtom);
190+
const themeVariablesByAppearance = resolveThemeVariablesByAppearance(
191+
themeIds,
192+
systemColorPalettes,
193+
);
128194
const themeVariables = themeVariablesByAppearance[themeAppearance];
129195
const activeThemeName = getMobileUniwindThemeName(themeId, themeAppearance);
130196
const { baseFontSize, codeFontSize, codeWordBreak, terminalFontSize } = preferences;
@@ -133,38 +199,6 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN
133199
[baseFontSize, codeFontSize, codeWordBreak, terminalFontSize],
134200
);
135201
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-
168202
const updatePreferences = useCallback(
169203
(patch: Partial<Preferences>) => {
170204
startTransition(() => savePreferences(patch));
@@ -179,37 +213,30 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN
179213
[savePreferences],
180214
);
181215

182-
useLayoutEffect(() => {
183-
selectedThemeIdsRef.current = themeIds;
184-
syncThemeRuntime(runtimeState);
185-
}, [runtimeState, syncThemeRuntime, themeIds]);
186-
187216
const setThemeIdForAppearance = useCallback(
188217
(appearance: MobileThemeAppearance, value: MobileThemeId) => {
189-
const patch = createMobileThemeSelectionPatch(
190-
selectedThemeIdsRef.current,
191-
themeAppearance,
192-
appearance,
193-
value,
218+
// Read at call time: a second pick before the next render must build on
219+
// the first one's optimistic write.
220+
const selected = resolveMobileThemeIds(
221+
storedPreferencesOf(appAtomRegistry.get(mobilePreferencesAtom)) ?? {},
222+
);
223+
updateThemePreferences(
224+
createMobileThemeSelectionPatch(selected, themeAppearance, appearance, value),
194225
);
195-
selectedThemeIdsRef.current = resolveMobileThemeIds(patch);
196-
updateThemePreferences(patch);
197226
},
198227
[themeAppearance, updateThemePreferences],
199228
);
200229

201230
const setThemeIdForBothAppearances = useCallback(
202231
(value: MobileThemeId) => {
203-
const patch = createMobileThemePairPatch(value);
204-
selectedThemeIdsRef.current = resolveMobileThemeIds(patch);
205-
updateThemePreferences(patch);
232+
updateThemePreferences(createMobileThemePairPatch(value));
206233
},
207234
[updateThemePreferences],
208235
);
209236

210237
const setThemeMode = useCallback(
211238
(value: MobileThemeMode) => {
212-
const current = appliedRuntimeStateRef.current ?? runtimeState;
239+
const current = currentRuntimeState();
213240

214241
// Clear forced appearance before publishing System so useColorScheme batches the system palette into the preference commit.
215242
if (value === "system") {
@@ -223,23 +250,22 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN
223250
themeMode: value,
224251
};
225252

226-
updateThemePreferences({ themeMode: value });
227253
if (value === "system") {
228-
appliedRuntimeStateRef.current = next;
254+
appliedRuntimeState = next;
229255
} else {
230-
syncThemeRuntime(next);
256+
applyThemeRuntime(next);
231257
}
258+
updateThemePreferences({ themeMode: value });
232259
},
233-
[runtimeState, syncThemeRuntime, updateThemePreferences],
260+
[updateThemePreferences],
234261
);
235262

236263
const setBaseFontSize = useCallback(
237264
(value: number) => {
238-
const current = appliedRuntimeStateRef.current ?? runtimeState;
239-
syncThemeRuntime({ ...current, baseFontSize: value });
265+
applyThemeRuntime({ ...currentRuntimeState(), baseFontSize: value });
240266
updatePreferences({ baseFontSize: value });
241267
},
242-
[runtimeState, syncThemeRuntime, updatePreferences],
268+
[updatePreferences],
243269
);
244270

245271
const setTerminalFontSize = useCallback(

0 commit comments

Comments
 (0)