Skip to content
TypeScript

refactor(mobile): shared AppState, reduce-motion and back-button helpers (#25011)

Julius Marmingec8c6deb6139a
diff --git a/apps/mobile/src/components/ui/AppBar.android.tsx b/apps/mobile/src/components/ui/AppBar.android.tsx
index 4132c225677..d5df66d22d6 100644
--- a/apps/mobile/src/components/ui/AppBar.android.tsx
+++ b/apps/mobile/src/components/ui/AppBar.android.tsx
@@ -1,12 +1,6 @@
-import { useCallback, useEffect, useRef, useState } from "react";
-import {
- BackHandler,
- Keyboard,
- Pressable,
- TextInput,
- type TextInputInstance,
- View,
-} from "react-native";
+import { useCallback, useRef, useState } from "react";
+import { Keyboard, Pressable, TextInput, type TextInputInstance, View } from "react-native";
+import { useHardwareBack } from "../../lib/backHandler";
import { useToolbarLayout } from "./useToolbarLayout";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { AndroidWorkspaceSidebarButton } from "../../features/layout/workspace-sidebar-toolbar";
@@ -34,14 +28,10 @@ export function AppBar(props: AppBarProps) {
setSearchOpen(false);
Keyboard.dismiss();
}, [onSearchChange]);
- useEffect(() => {
- if (!searching || search?.mode === "inline") return;
- const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
- closeSearch();
- return true;
- });
- return () => subscription.remove();
- }, [closeSearch, searching, search?.mode]);
+ useHardwareBack(searching && search?.mode !== "inline", () => {
+ closeSearch();
+ return true;
+ });
const menuView = props.menus?.map((menu) => (
<Menu
key={menu.title}
diff --git a/apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx b/apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx
index a458046ee2b..3ec1b2b9a56 100644
--- a/apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx
+++ b/apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx
@@ -7,10 +7,11 @@ import { EnvironmentId, ThreadId, type PreviewSessionSnapshot } from "@t3tools/c
import { normalizePreviewUrl, previewPdfAssetUrl } from "@t3tools/shared/preview";
import * as Option from "effect/Option";
import { useCallback, useEffect, useRef, useState } from "react";
-import { AppState, Platform, TextInput, View } from "react-native";
+import { Platform, TextInput, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { ControlPill } from "../../components/ui/ControlPill";
+import { useAppForeground } from "../../lib/appState";
import { AppBar } from "../../components/ui/AppBar";
import { useThreadServerBrowserTabs } from "../../state/preview";
@@ -79,7 +80,7 @@ function BrowserPreviewScreen({
const prepared = usePreparedConnection(environmentId);
const httpBaseUrl = Option.isSome(prepared) ? prepared.value.httpBaseUrl : null;
const focused = useIsFocused();
- const [foreground, setForeground] = useState(AppState.currentState !== "background");
+ const foreground = useAppForeground();
const [selectedTabId, setSelectedTabId] = useState(initialTabId);
const [pictureInPicture, setPictureInPicture] = useState(NO_PICTURE_IN_PICTURE);
const [streaming, setStreaming] = useState(false);
@@ -94,12 +95,6 @@ function BrowserPreviewScreen({
setPictureInPicture(NO_PICTURE_IN_PICTURE);
setSelectedTabId(tabId);
}
- useEffect(() => {
- const subscription = AppState.addEventListener("change", (state) =>
- setForeground(state !== "background"),
- );
- return () => subscription.remove();
- }, []);
useEffect(() => {
if (focused && loaded && tabs.length === 0) onClose();
}, [focused, loaded, tabs.length, onClose]);
diff --git a/apps/mobile/src/features/browser/ThreadBrowserFloat.tsx b/apps/mobile/src/features/browser/ThreadBrowserFloat.tsx
index 3cc5eb951b6..5f6a876b0d5 100644
--- a/apps/mobile/src/features/browser/ThreadBrowserFloat.tsx
+++ b/apps/mobile/src/features/browser/ThreadBrowserFloat.tsx
@@ -3,10 +3,11 @@ import type { EnvironmentId, PreviewSessionSnapshot, ThreadId } from "@t3tools/c
import { previewPdfAssetUrl } from "@t3tools/shared/preview";
import * as Option from "effect/Option";
import { useCallback, useEffect, useRef, useState } from "react";
-import { AppState, Pressable, View } from "react-native";
+import { Pressable, View } from "react-native";
import Animated, { FadeIn, FadeOut, ReduceMotion } from "react-native-reanimated";
import { SymbolView } from "../../components/ui/AppSymbol";
+import { useAppForeground } from "../../lib/appState";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import { browserTabTitle } from "./browserTabs";
import { PreviewStreamWebView } from "./PreviewStreamWebView";
@@ -41,13 +42,7 @@ export function ThreadBrowserFloat(props: {
if (opened !== undefined) setTabId(opened.tabId);
}, [props.loaded, props.tabs]);
const focused = useIsFocused();
- const [foreground, setForeground] = useState(AppState.currentState !== "background");
- useEffect(() => {
- const subscription = AppState.addEventListener("change", (state) =>
- setForeground(state !== "background"),
- );
- return () => subscription.remove();
- }, []);
+ const foreground = useAppForeground();
const tab = props.tabs.find((entry) => entry.tabId === tabId) ?? null;
const onOpen = props.onOpen;
const open = useCallback(() => {
diff --git a/apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsx b/apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsx
index 850049f111a..f42eb1c6702 100644
--- a/apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsx
+++ b/apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsx
@@ -12,7 +12,7 @@ import * as Cause from "effect/Cause";
import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
import * as Haptics from "expo-haptics";
import { Accelerometer } from "expo-sensors";
-import { AppState, BackHandler, Pressable, StatusBar, View } from "react-native";
+import { Pressable, StatusBar, View } from "react-native";
import Animated, { FadeIn, FadeOut, ReduceMotion } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -27,6 +27,8 @@ import {
findHeaderMenuAction,
} from "../../components/ui/headerMenu.android";
import type { AppBarMenuItem } from "../../components/ui/AppBar.types";
+import { useAppForeground } from "../../lib/appState";
+import { useHardwareBack } from "../../lib/backHandler";
import { deriveBottomControlInsets } from "../../lib/reserved-regions";
import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
import { deviceEnvironment, refreshDeviceHubAccess, useDeviceHubAccess } from "../../state/device";
@@ -88,7 +90,7 @@ export function DevicePreviewScreen({
const handleBounds = deriveBottomControlInsets(useNativeColumnLayoutMetrics());
const { themeVariables } = useAppearancePreferences();
const focused = useIsFocused();
- const [foreground, setForeground] = useState(AppState.currentState !== "background");
+ const foreground = useAppForeground();
const [selectedKey, setSelectedKey] = useState<string | null>(initialDeviceKey ?? null);
const [inputConnected, setInputConnected] = useState(false);
const [streamAttempt, setStreamAttempt] = useState(0);
@@ -107,12 +109,6 @@ export function DevicePreviewScreen({
},
[embedded],
);
- useEffect(() => {
- const subscription = AppState.addEventListener("change", (state) =>
- setForeground(state !== "background"),
- );
- return () => subscription.remove();
- }, []);
useEffect(() => {
if (focused && state.data !== null && previews.length === 0) onClose();
}, [focused, state.data, previews.length, onClose]);
@@ -127,14 +123,10 @@ export function DevicePreviewScreen({
});
return () => subscription.remove();
}, [focused, foreground, embedded]);
- useEffect(() => {
- if (controlsVisible) return;
- const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
- setControlsVisible(true);
- return true;
- });
- return () => subscription.remove();
- }, [controlsVisible]);
+ useHardwareBack(!controlsVisible, () => {
+ setControlsVisible(true);
+ return true;
+ });
const shutDownDevice = async () => {
if (!preview || shuttingDown) return;
diff --git a/apps/mobile/src/features/files/FilesHeader.tsx b/apps/mobile/src/features/files/FilesHeader.tsx
index f3d52c20430..1c373f78f35 100644
--- a/apps/mobile/src/features/files/FilesHeader.tsx
+++ b/apps/mobile/src/features/files/FilesHeader.tsx
@@ -1,5 +1,5 @@
-import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
-import { BackHandler, Keyboard, type TextInputInstance, View } from "react-native";
+import { useCallback, useRef, useState, type ReactNode } from "react";
+import { Keyboard, type TextInputInstance, View } from "react-native";
import {
AndroidHeaderIconButton,
@@ -8,6 +8,7 @@ import {
import { AndroidAnchoredMenu } from "../../components/ui/AndroidAnchoredMenu";
import { SearchField } from "../../components/ui/SearchField";
import { useToolbarLayout } from "../../components/ui/useToolbarLayout";
+import { useHardwareBack } from "../../lib/backHandler";
export function FilesHeader(props: {
readonly projectName: string;
@@ -28,14 +29,10 @@ export function FilesHeader(props: {
Keyboard.dismiss();
}, [onSearchQueryChange]);
- useEffect(() => {
- if (!searching) return;
- const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
- closeSearch();
- return true;
- });
- return () => subscription.remove();
- }, [closeSearch, searching]);
+ useHardwareBack(searching, () => {
+ closeSearch();
+ return true;
+ });
return (
<View>
diff --git a/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx b/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx
index 432f2eb36bd..cb0daef2610 100644
--- a/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx
+++ b/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx
@@ -1,5 +1,5 @@
-import { useEffect, useState } from "react";
-import { BackHandler, Platform, View } from "react-native";
+import { useState } from "react";
+import { Platform, View } from "react-native";
import { WebView } from "react-native-webview";
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
@@ -9,6 +9,7 @@ import { FilePreviewLoading } from "./FilePreviewFeedback";
import { LoadingStrip } from "../../components/ui/LoadingStrip";
import { PdfPreview } from "../../components/PdfPreview";
import { ControlPill } from "../../components/ui/ControlPill";
+import { useHardwareBack } from "../../lib/backHandler";
import { isPdfPreviewUri } from "../../lib/pdfPreview";
import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
@@ -27,14 +28,10 @@ function DocumentWebPreview(props: { readonly uri: string }) {
const [loadError, setLoadError] = useState<string | null>(null);
const [linkedPdf, setLinkedPdf] = useState<string | null>(null);
- useEffect(() => {
- if (linkedPdf === null) return;
- const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
- setLinkedPdf(null);
- return true;
- });
- return () => subscription.remove();
- }, [linkedPdf]);
+ useHardwareBack(linkedPdf !== null, () => {
+ setLinkedPdf(null);
+ return true;
+ });
if (isPdfPreviewUri(props.uri)) {
return (
diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx
index 6ed0240f7c0..9659abc144b 100644
--- a/apps/mobile/src/features/threads/thread-work-log.tsx
+++ b/apps/mobile/src/features/threads/thread-work-log.tsx
@@ -33,9 +33,7 @@ import {
type ReactNode,
} from "react";
import {
- AccessibilityInfo,
Animated as NativeAnimated,
- AppState,
type ColorValue,
Easing,
Pressable,
@@ -63,6 +61,7 @@ import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
import { AppText as Text } from "../../components/ui/AppText";
import { T3Wordmark } from "../../components/T3Wordmark";
import { BrowserAppIcon } from "./BrowserAppIcon";
+import { useAppActive, useReduceMotionEnabled } from "../../lib/appState";
import { cn } from "../../lib/cn";
import { THREAD_WORK_ROW_MIN_HEIGHT, type deriveThreadWorkLogSizing } from "../../lib/layout";
import {
@@ -264,8 +263,8 @@ export function ShimmeringWorkContent(props: {
}) {
const [availableWidth, setAvailableWidth] = useState(0);
const [textWidth, setTextWidth] = useState(0);
- const [appIsActive, setAppIsActive] = useState(AppState.currentState === "active");
- const [reducedMotion, setReducedMotion] = useState(true);
+ const appIsActive = useAppActive();
+ const reducedMotion = useReduceMotionEnabled();
const screenIsFocused = useIsFocused();
const progress = useAnimatedValue(0);
const gradientId = `work-shimmer-${useId().replaceAll(":", "")}`;
@@ -274,22 +273,6 @@ export function ShimmeringWorkContent(props: {
(props.showIcon ? SHIMMER_ICON_AND_GAP_WIDTH : 0) + Math.ceil(textWidth),
);
- useEffect(() => {
- const subscription = AppState.addEventListener("change", (state) => {
- setAppIsActive(state === "active");
- });
- return () => subscription.remove();
- }, []);
-
- useEffect(() => {
- void AccessibilityInfo.isReduceMotionEnabled().then(setReducedMotion);
- const subscription = AccessibilityInfo.addEventListener(
- "reduceMotionChanged",
- setReducedMotion,
- );
- return () => subscription.remove();
- }, []);
-
// Runs on React Native's native driver instead of Reanimated, whose
// per-frame commits starve React's while commit pausing is disabled
// (package.json). See docs/internals/performance-regressions.md.
diff --git a/apps/mobile/src/lib/appState.test.ts b/apps/mobile/src/lib/appState.test.ts
new file mode 100644
index 00000000000..cabaf0290ec
--- /dev/null
+++ b/apps/mobile/src/lib/appState.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it, vi } from "vite-plus/test";
+
+const native = vi.hoisted(() => ({
+ enabled: false,
+ listeners: new Set<(enabled: boolean) => void>(),
+}));
+
+vi.mock("react-native", () => ({
+ AppState: { currentState: "active", addEventListener: vi.fn() },
+ AccessibilityInfo: {
+ addEventListener: (_event: string, listener: (enabled: boolean) => void) => {
+ native.listeners.add(listener);
+ return { remove: () => native.listeners.delete(listener) };
+ },
+ isReduceMotionEnabled: () => Promise.resolve(native.enabled),
+ },
+}));
+
+import { readReduceMotionEnabled, subscribeReduceMotion } from "./appState";
+
+describe("reduce motion store", () => {
+ it("reseeds from native after observation stops and restarts", async () => {
+ native.enabled = false;
+ const unsubscribe = subscribeReduceMotion(() => undefined);
+ await Promise.resolve();
+ expect(readReduceMotionEnabled()).toBe(false);
+ unsubscribe();
+
+ // Changed while nobody listened: no event reaches the store.
+ native.enabled = true;
+ const unsubscribeAgain = subscribeReduceMotion(() => undefined);
+ // Unknown until the reseed lands, which reads as reduced, not the stale false.
+ expect(readReduceMotionEnabled()).toBe(true);
+ await Promise.resolve();
+ expect(readReduceMotionEnabled()).toBe(true);
+ unsubscribeAgain();
+ });
+
+ it("ignores a seed that resolves after the last unsubscribe", async () => {
+ native.enabled = false;
+ subscribeReduceMotion(() => undefined)();
+ await Promise.resolve();
+ expect(readReduceMotionEnabled()).toBe(true);
+ });
+});
diff --git a/apps/mobile/src/lib/appState.ts b/apps/mobile/src/lib/appState.ts
new file mode 100644
index 00000000000..7be20c8e3c0
--- /dev/null
+++ b/apps/mobile/src/lib/appState.ts
@@ -0,0 +1,79 @@
+import { useSyncExternalStore } from "react";
+import { AccessibilityInfo, AppState } from "react-native";
+
+type Listener = () => void;
+
+function subscribeAppState(onChange: Listener): () => void {
+ const subscription = AppState.addEventListener("change", () => onChange());
+ return () => subscription.remove();
+}
+
+function isAppActive(): boolean {
+ return AppState.currentState === "active";
+}
+
+export function useAppActive(): boolean {
+ return useSyncExternalStore(subscribeAppState, isAppActive);
+}
+
+function isAppForeground(): boolean {
+ return AppState.currentState !== "background";
+}
+
+/**
+ * True unless the app is backgrounded. Unlike useAppActive, the transient
+ * "inactive" state (Control Center, the app switcher, a system prompt) still
+ * counts as foreground, so live streams do not reconnect around it.
+ */
+export function useAppForeground(): boolean {
+ return useSyncExternalStore(subscribeAppState, isAppForeground);
+}
+
+// Null until the native seed resolves; read as reduced so animated consumers
+// never start motion a reduce-motion user has turned off.
+let reduceMotionEnabled: boolean | null = null;
+const reduceMotionListeners = new Set<Listener>();
+let reduceMotionSubscription: { remove: () => void } | null = null;
+
+function setReduceMotionEnabled(next: boolean) {
+ if (next === reduceMotionEnabled) return;
+ reduceMotionEnabled = next;
+ for (const listener of reduceMotionListeners) listener();
+}
+
+export function subscribeReduceMotion(onChange: Listener): () => void {
+ reduceMotionListeners.add(onChange);
+ if (reduceMotionSubscription === null) {
+ const subscription = AccessibilityInfo.addEventListener(
+ "reduceMotionChanged",
+ setReduceMotionEnabled,
+ );
+ reduceMotionSubscription = subscription;
+ // The native event only reports changes; seed the current value once per
+ // observation, and drop a seed that resolves after observation stopped.
+ void AccessibilityInfo.isReduceMotionEnabled().then(
+ (enabled) => {
+ if (reduceMotionSubscription === subscription) setReduceMotionEnabled(enabled);
+ },
+ () => undefined,
+ );
+ }
+ return () => {
+ reduceMotionListeners.delete(onChange);
+ if (reduceMotionListeners.size === 0) {
+ reduceMotionSubscription?.remove();
+ reduceMotionSubscription = null;
+ // Changes made while nobody observed were never reported, so the cached
+ // value can be stale; the next subscriber reseeds from native.
+ reduceMotionEnabled = null;
+ }
+ };
+}
+
+export function readReduceMotionEnabled(): boolean {
+ return reduceMotionEnabled ?? true;
+}
+
+export function useReduceMotionEnabled(): boolean {
+ return useSyncExternalStore(subscribeReduceMotion, readReduceMotionEnabled);
+}
diff --git a/apps/mobile/src/lib/backHandler.ts b/apps/mobile/src/lib/backHandler.ts
new file mode 100644
index 00000000000..c1005998b27
--- /dev/null
+++ b/apps/mobile/src/lib/backHandler.ts
@@ -0,0 +1,19 @@
+import { useIsFocused } from "@react-navigation/native";
+import { useEffect, useEffectEvent } from "react";
+import { BackHandler } from "react-native";
+
+/**
+ * Android hardware back while `active` and the owning screen is focused.
+ * Keyed on those alone, not `onBack`: BackHandler calls the newest listener
+ * first, so re-registering per render lets a covered screen consume Back.
+ */
+export function useHardwareBack(active: boolean, onBack: () => boolean) {
+ const focused = useIsFocused();
+ const handleBack = useEffectEvent(onBack);
+ // oxlint-disable-next-line t3code/react-effect-budget -- subscribes to BackHandler for the focused screen's lifetime
+ useEffect(() => {
+ if (!active || !focused) return;
+ const subscription = BackHandler.addEventListener("hardwareBackPress", () => handleBack());
+ return () => subscription.remove();
+ }, [active, focused]);
+}