Skip to content
TypeScript

refactor(mobile): theme preferences reach the native runtime without a layout effect (#25767)

Julius Marmingebea2e9d62fdc
diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx
index acb6287e3a3..3ade5d940fd 100644
--- a/apps/mobile/src/App.tsx
+++ b/apps/mobile/src/App.tsx
@@ -24,6 +24,7 @@ import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcase
import { IncomingShareProvider } from "./features/sharing/IncomingShareProvider";
import {
AppearancePreferencesProvider,
+ installAppearanceRuntime,
useAppearancePreferences,
} from "./features/settings/appearance/AppearancePreferencesProvider";
import { RootStack } from "./Stack";
@@ -107,6 +108,7 @@ const appServiceDisposers = [
threadRefsAtom: environmentThreadShells.threadRefsAtom,
shellStateAtom: environmentShell.stateAtom,
}),
+ installAppearanceRuntime(),
installSubscriptionUsageRefresh(),
installPermissionUpdateNotice(),
installThreadOutboxDelivery(),
diff --git a/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx b/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx
index a7b2807d782..bdde057dd23 100644
--- a/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx
+++ b/apps/mobile/src/features/settings/appearance/AppearancePreferencesProvider.tsx
@@ -1,19 +1,8 @@
-import {
- createContext,
- startTransition,
- use,
- useCallback,
- useEffect,
- useState,
- useLayoutEffect,
- useMemo,
- useRef,
- type ReactNode,
-} from "react";
+import { createContext, startTransition, use, useCallback, useMemo, type ReactNode } from "react";
import { AppState, Appearance, Platform, useColorScheme } from "react-native";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
-import { AsyncResult } from "effect/reactivity";
+import { Atom, AsyncResult } from "effect/reactivity";
import { ScopedTheme, ScopedVariables, Uniwind } from "uniwind";
@@ -22,9 +11,14 @@ import {
resolveAppearancePreferences,
type ResolvedAppearance,
} from "../../../lib/appearancePreferences";
+import { appAtomRegistry } from "../../../state/atom-registry";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../../state/preferences";
import type { Preferences } from "../../../persistence/mobile-preferences";
-import { isSystemColorsAvailable, readSystemColorPalettes } from "../../../lib/materialYouPalette";
+import {
+ isSystemColorsAvailable,
+ readSystemColorPalettes,
+ type MaterialYouPalettes,
+} from "../../../lib/materialYouPalette";
import { materialYouPaletteToMobileThemeVariables } from "../../../lib/materialYouTheme";
import { getMobileThemeRuntimeVariables } from "../../../lib/mobileThemeVariables";
import type { MobileThemeVariables } from "../../../lib/mobileTheme";
@@ -74,6 +68,115 @@ interface AppearancePreferencesContextValue {
const AppearancePreferencesContext = createContext<AppearancePreferencesContextValue | null>(null);
+function storedPreferencesOf<E>(result: AsyncResult.AsyncResult<Preferences, E>) {
+ return AsyncResult.isSuccess(result) ? result.value : null;
+}
+
+/**
+ * Material You palettes follow the system wallpaper, which can change while the
+ * app is in the background.
+ */
+const systemColorPalettesAtom = Atom.make((get): MaterialYouPalettes | null => {
+ const initial = readSystemColorPalettes();
+ if (!isSystemColorsAvailable) return initial;
+ let current = initial;
+ const refresh = () => {
+ const next = readSystemColorPalettes();
+ if (JSON.stringify(current) === JSON.stringify(next)) return;
+ current = next;
+ get.setSelf(next);
+ };
+ const subscription = AppState.addEventListener("change", (state) => {
+ if (state === "active") refresh();
+ });
+ const focusSubscription = AppState.addEventListener("focus", refresh);
+ get.addFinalizer(() => {
+ subscription.remove();
+ focusSubscription.remove();
+ });
+ return initial;
+}).pipe(Atom.withLabel("mobile:system-color-palettes"));
+
+function resolveThemeVariablesByAppearance(
+ themeIds: MobileThemeIds,
+ palettes: MaterialYouPalettes | null,
+): Readonly<Record<MobileThemeAppearance, MobileThemeVariables>> {
+ const resolve = (appearance: MobileThemeAppearance) => {
+ const base = getMobileThemeRuntimeVariables(themeIds[appearance], appearance, Platform.OS);
+ return themeIds[appearance] === "material-you" && palettes
+ ? materialYouPaletteToMobileThemeVariables(palettes[appearance], appearance, base)
+ : base;
+ };
+ return { light: resolve("light"), dark: resolve("dark") };
+}
+
+/** The appearance whose theme is on screen, read from the native scheme. */
+function resolveThemeAppearance(stored: Preferences | null): MobileThemeAppearance {
+ const themeMode = normalizeMobileThemeMode(stored?.themeMode);
+ if (themeMode !== "system") return themeMode;
+ return Appearance.getColorScheme() === "dark" ? "dark" : "light";
+}
+
+function runtimeStateFor(stored: Preferences | null): MobileThemeRuntimeState {
+ return {
+ baseFontSize: resolveAppearancePreferences(stored).baseFontSize,
+ themeMode: normalizeMobileThemeMode(stored?.themeMode),
+ themeAppearance: resolveThemeAppearance(stored),
+ };
+}
+
+const themeRuntimeStateAtom = Atom.make((get) =>
+ runtimeStateFor(storedPreferencesOf(get(mobilePreferencesAtom))),
+).pipe(
+ Atom.withEquality(
+ (left: MobileThemeRuntimeState, right: MobileThemeRuntimeState) =>
+ left.baseFontSize === right.baseFontSize &&
+ left.themeMode === right.themeMode &&
+ left.themeAppearance === right.themeAppearance,
+ ),
+);
+
+// Native appearance and Uniwind text variables are process-global, so the
+// last applied state is too. Setters apply ahead of the preference write so the
+// first frame after a change already uses it; the atom subscription then sees
+// no difference.
+let appliedRuntimeState: MobileThemeRuntimeState | null = null;
+
+function applyThemeRuntime(next: MobileThemeRuntimeState) {
+ for (const operation of createMobileThemeRuntimeOperations(appliedRuntimeState, next)) {
+ if (operation.kind === "update-text-variables") {
+ Uniwind.updateCSSVariables(operation.themeName, operation.variables);
+ continue;
+ }
+ if (operation.kind === "set-appearance-mode") {
+ Appearance.setColorScheme(
+ operation.themeMode === "system" ? "unspecified" : operation.appearance,
+ );
+ }
+ }
+ appliedRuntimeState = next;
+}
+
+function currentRuntimeState() {
+ return appliedRuntimeState ?? appAtomRegistry.get(themeRuntimeStateAtom);
+}
+
+/**
+ * App-lifetime: applies theme preferences to the native runtime and holds the
+ * system palette listeners. Holding them here instead of `keepAlive` lets the
+ * fast-refresh disposer release the replaced module's AppState listeners.
+ */
+export function installAppearanceRuntime(): () => void {
+ const unsubscribeRuntime = appAtomRegistry.subscribe(themeRuntimeStateAtom, applyThemeRuntime, {
+ immediate: true,
+ });
+ const releasePalettes = appAtomRegistry.mount(systemColorPalettesAtom);
+ return () => {
+ unsubscribeRuntime();
+ releasePalettes();
+ };
+}
+
export function AppearancePreferencesProvider(props: { readonly children: ReactNode }) {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
@@ -94,37 +197,11 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN
);
const themeId = themeIds[themeAppearance];
const systemColorsActive = themeId === "material-you" && isSystemColorsAvailable;
- const [systemColorPalettes, setSystemColorPalettes] = useState(readSystemColorPalettes);
- useEffect(() => {
- if (!isSystemColorsAvailable) return;
- const refresh = () => {
- const next = readSystemColorPalettes();
- setSystemColorPalettes((previous) =>
- JSON.stringify(previous) === JSON.stringify(next) ? previous : next,
- );
- };
- const subscription = AppState.addEventListener("change", (state) => {
- if (state === "active") refresh();
- });
- const focusSubscription = AppState.addEventListener("focus", refresh);
- return () => {
- subscription.remove();
- focusSubscription.remove();
- };
- }, []);
- const themeVariablesByAppearance = useMemo(() => {
- const resolve = (appearance: MobileThemeAppearance) => {
- const base = getMobileThemeRuntimeVariables(themeIds[appearance], appearance, Platform.OS);
- return themeIds[appearance] === "material-you" && systemColorPalettes
- ? materialYouPaletteToMobileThemeVariables(
- systemColorPalettes[appearance],
- appearance,
- base,
- )
- : base;
- };
- return { light: resolve("light"), dark: resolve("dark") };
- }, [themeIds, systemColorPalettes]);
+ const systemColorPalettes = useAtomValue(systemColorPalettesAtom);
+ const themeVariablesByAppearance = resolveThemeVariablesByAppearance(
+ themeIds,
+ systemColorPalettes,
+ );
const themeVariables = themeVariablesByAppearance[themeAppearance];
const activeThemeName = getMobileUniwindThemeName(themeId, themeAppearance);
const { baseFontSize, codeFontSize, codeWordBreak, terminalFontSize } = preferences;
@@ -133,38 +210,6 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN
[baseFontSize, codeFontSize, codeWordBreak, terminalFontSize],
);
const isReady = AsyncResult.isSuccess(preferencesResult);
- const runtimeState = useMemo<MobileThemeRuntimeState>(
- () => ({
- baseFontSize,
- themeAppearance,
- themeMode,
- }),
- [baseFontSize, themeAppearance, themeMode],
- );
- const appliedRuntimeStateRef = useRef<MobileThemeRuntimeState | null>(null);
- const selectedThemeIdsRef = useRef(themeIds);
-
- const applyThemeRuntime = useCallback((next: MobileThemeRuntimeState) => {
- const operations = createMobileThemeRuntimeOperations(appliedRuntimeStateRef.current, next);
- for (const operation of operations) {
- if (operation.kind === "update-text-variables") {
- Uniwind.updateCSSVariables(operation.themeName, operation.variables);
- continue;
- }
- if (operation.kind === "set-appearance-mode") {
- Appearance.setColorScheme(
- operation.themeMode === "system" ? "unspecified" : operation.appearance,
- );
- }
- }
- appliedRuntimeStateRef.current = next;
- }, []);
-
- const syncThemeRuntime = useCallback(
- (next: MobileThemeRuntimeState) => applyThemeRuntime(next),
- [applyThemeRuntime],
- );
-
const updatePreferences = useCallback(
(patch: Partial<Preferences>) => {
startTransition(() => savePreferences(patch));
@@ -179,37 +224,30 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN
[savePreferences],
);
- useLayoutEffect(() => {
- selectedThemeIdsRef.current = themeIds;
- syncThemeRuntime(runtimeState);
- }, [runtimeState, syncThemeRuntime, themeIds]);
-
const setThemeIdForAppearance = useCallback(
(appearance: MobileThemeAppearance, value: MobileThemeId) => {
- const patch = createMobileThemeSelectionPatch(
- selectedThemeIdsRef.current,
- themeAppearance,
- appearance,
- value,
+ // Read at call time: a second pick before the next render must build on
+ // the first one's optimistic write.
+ const selected = resolveMobileThemeIds(
+ storedPreferencesOf(appAtomRegistry.get(mobilePreferencesAtom)) ?? {},
+ );
+ updateThemePreferences(
+ createMobileThemeSelectionPatch(selected, themeAppearance, appearance, value),
);
- selectedThemeIdsRef.current = resolveMobileThemeIds(patch);
- updateThemePreferences(patch);
},
[themeAppearance, updateThemePreferences],
);
const setThemeIdForBothAppearances = useCallback(
(value: MobileThemeId) => {
- const patch = createMobileThemePairPatch(value);
- selectedThemeIdsRef.current = resolveMobileThemeIds(patch);
- updateThemePreferences(patch);
+ updateThemePreferences(createMobileThemePairPatch(value));
},
[updateThemePreferences],
);
const setThemeMode = useCallback(
(value: MobileThemeMode) => {
- const current = appliedRuntimeStateRef.current ?? runtimeState;
+ const current = currentRuntimeState();
// Clear forced appearance before publishing System so useColorScheme batches the system palette into the preference commit.
if (value === "system") {
@@ -223,23 +261,22 @@ export function AppearancePreferencesProvider(props: { readonly children: ReactN
themeMode: value,
};
- updateThemePreferences({ themeMode: value });
if (value === "system") {
- appliedRuntimeStateRef.current = next;
+ appliedRuntimeState = next;
} else {
- syncThemeRuntime(next);
+ applyThemeRuntime(next);
}
+ updateThemePreferences({ themeMode: value });
},
- [runtimeState, syncThemeRuntime, updateThemePreferences],
+ [updateThemePreferences],
);
const setBaseFontSize = useCallback(
(value: number) => {
- const current = appliedRuntimeStateRef.current ?? runtimeState;
- syncThemeRuntime({ ...current, baseFontSize: value });
+ applyThemeRuntime({ ...currentRuntimeState(), baseFontSize: value });
updatePreferences({ baseFontSize: value });
},
- [runtimeState, syncThemeRuntime, updatePreferences],
+ [updatePreferences],
);
const setTerminalFontSize = useCallback(