Skip to content

Commit c8c6deb

Browse files
refactor(mobile): shared AppState, reduce-motion and back-button helpers (pingdotgg#25011)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 0bf4d16 commit c8c6deb

10 files changed

Lines changed: 181 additions & 89 deletions

File tree

‎apps/mobile/src/components/ui/AppBar.android.tsx‎

Lines changed: 7 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,6 @@
1-
import { useCallback, useEffect, useRef, useState } from "react";
2-
import {
3-
BackHandler,
4-
Keyboard,
5-
Pressable,
6-
TextInput,
7-
type TextInputInstance,
8-
View,
9-
} from "react-native";
1+
import { useCallback, useRef, useState } from "react";
2+
import { Keyboard, Pressable, TextInput, type TextInputInstance, View } from "react-native";
3+
import { useHardwareBack } from "../../lib/backHandler";
104
import { useToolbarLayout } from "./useToolbarLayout";
115
import { NativeStackScreenOptions } from "../../native/StackHeader";
126
import { AndroidWorkspaceSidebarButton } from "../../features/layout/workspace-sidebar-toolbar";
@@ -34,14 +28,10 @@ export function AppBar(props: AppBarProps) {
3428
setSearchOpen(false);
3529
Keyboard.dismiss();
3630
}, [onSearchChange]);
37-
useEffect(() => {
38-
if (!searching || search?.mode === "inline") return;
39-
const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
40-
closeSearch();
41-
return true;
42-
});
43-
return () => subscription.remove();
44-
}, [closeSearch, searching, search?.mode]);
31+
useHardwareBack(searching && search?.mode !== "inline", () => {
32+
closeSearch();
33+
return true;
34+
});
4535
const menuView = props.menus?.map((menu) => (
4636
<Menu
4737
key={menu.title}

‎apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,11 @@ import { EnvironmentId, ThreadId, type PreviewSessionSnapshot } from "@t3tools/c
77
import { normalizePreviewUrl, previewPdfAssetUrl } from "@t3tools/shared/preview";
88
import * as Option from "effect/Option";
99
import { useCallback, useEffect, useRef, useState } from "react";
10-
import { AppState, Platform, TextInput, View } from "react-native";
10+
import { Platform, TextInput, View } from "react-native";
1111
import { useSafeAreaInsets } from "react-native-safe-area-context";
1212

1313
import { ControlPill } from "../../components/ui/ControlPill";
14+
import { useAppForeground } from "../../lib/appState";
1415
import { AppBar } from "../../components/ui/AppBar";
1516

1617
import { useThreadServerBrowserTabs } from "../../state/preview";
@@ -79,7 +80,7 @@ function BrowserPreviewScreen({
7980
const prepared = usePreparedConnection(environmentId);
8081
const httpBaseUrl = Option.isSome(prepared) ? prepared.value.httpBaseUrl : null;
8182
const focused = useIsFocused();
82-
const [foreground, setForeground] = useState(AppState.currentState !== "background");
83+
const foreground = useAppForeground();
8384
const [selectedTabId, setSelectedTabId] = useState(initialTabId);
8485
const [pictureInPicture, setPictureInPicture] = useState(NO_PICTURE_IN_PICTURE);
8586
const [streaming, setStreaming] = useState(false);
@@ -94,12 +95,6 @@ function BrowserPreviewScreen({
9495
setPictureInPicture(NO_PICTURE_IN_PICTURE);
9596
setSelectedTabId(tabId);
9697
}
97-
useEffect(() => {
98-
const subscription = AppState.addEventListener("change", (state) =>
99-
setForeground(state !== "background"),
100-
);
101-
return () => subscription.remove();
102-
}, []);
10398
useEffect(() => {
10499
if (focused && loaded && tabs.length === 0) onClose();
105100
}, [focused, loaded, tabs.length, onClose]);

‎apps/mobile/src/features/browser/ThreadBrowserFloat.tsx‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@ import type { EnvironmentId, PreviewSessionSnapshot, ThreadId } from "@t3tools/c
33
import { previewPdfAssetUrl } from "@t3tools/shared/preview";
44
import * as Option from "effect/Option";
55
import { useCallback, useEffect, useRef, useState } from "react";
6-
import { AppState, Pressable, View } from "react-native";
6+
import { Pressable, View } from "react-native";
77
import Animated, { FadeIn, FadeOut, ReduceMotion } from "react-native-reanimated";
88

99
import { SymbolView } from "../../components/ui/AppSymbol";
10+
import { useAppForeground } from "../../lib/appState";
1011
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
1112
import { browserTabTitle } from "./browserTabs";
1213
import { PreviewStreamWebView } from "./PreviewStreamWebView";
@@ -41,13 +42,7 @@ export function ThreadBrowserFloat(props: {
4142
if (opened !== undefined) setTabId(opened.tabId);
4243
}, [props.loaded, props.tabs]);
4344
const focused = useIsFocused();
44-
const [foreground, setForeground] = useState(AppState.currentState !== "background");
45-
useEffect(() => {
46-
const subscription = AppState.addEventListener("change", (state) =>
47-
setForeground(state !== "background"),
48-
);
49-
return () => subscription.remove();
50-
}, []);
45+
const foreground = useAppForeground();
5146
const tab = props.tabs.find((entry) => entry.tabId === tabId) ?? null;
5247
const onOpen = props.onOpen;
5348
const open = useCallback(() => {

‎apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsx‎

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import * as Cause from "effect/Cause";
1212
import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
1313
import * as Haptics from "expo-haptics";
1414
import { Accelerometer } from "expo-sensors";
15-
import { AppState, BackHandler, Pressable, StatusBar, View } from "react-native";
15+
import { Pressable, StatusBar, View } from "react-native";
1616
import Animated, { FadeIn, FadeOut, ReduceMotion } from "react-native-reanimated";
1717
import { useSafeAreaInsets } from "react-native-safe-area-context";
1818

@@ -27,6 +27,8 @@ import {
2727
findHeaderMenuAction,
2828
} from "../../components/ui/headerMenu.android";
2929
import type { AppBarMenuItem } from "../../components/ui/AppBar.types";
30+
import { useAppForeground } from "../../lib/appState";
31+
import { useHardwareBack } from "../../lib/backHandler";
3032
import { deriveBottomControlInsets } from "../../lib/reserved-regions";
3133
import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
3234
import { deviceEnvironment, refreshDeviceHubAccess, useDeviceHubAccess } from "../../state/device";
@@ -88,7 +90,7 @@ export function DevicePreviewScreen({
8890
const handleBounds = deriveBottomControlInsets(useNativeColumnLayoutMetrics());
8991
const { themeVariables } = useAppearancePreferences();
9092
const focused = useIsFocused();
91-
const [foreground, setForeground] = useState(AppState.currentState !== "background");
93+
const foreground = useAppForeground();
9294
const [selectedKey, setSelectedKey] = useState<string | null>(initialDeviceKey ?? null);
9395
const [inputConnected, setInputConnected] = useState(false);
9496
const [streamAttempt, setStreamAttempt] = useState(0);
@@ -107,12 +109,6 @@ export function DevicePreviewScreen({
107109
},
108110
[embedded],
109111
);
110-
useEffect(() => {
111-
const subscription = AppState.addEventListener("change", (state) =>
112-
setForeground(state !== "background"),
113-
);
114-
return () => subscription.remove();
115-
}, []);
116112
useEffect(() => {
117113
if (focused && state.data !== null && previews.length === 0) onClose();
118114
}, [focused, state.data, previews.length, onClose]);
@@ -127,14 +123,10 @@ export function DevicePreviewScreen({
127123
});
128124
return () => subscription.remove();
129125
}, [focused, foreground, embedded]);
130-
useEffect(() => {
131-
if (controlsVisible) return;
132-
const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
133-
setControlsVisible(true);
134-
return true;
135-
});
136-
return () => subscription.remove();
137-
}, [controlsVisible]);
126+
useHardwareBack(!controlsVisible, () => {
127+
setControlsVisible(true);
128+
return true;
129+
});
138130

139131
const shutDownDevice = async () => {
140132
if (!preview || shuttingDown) return;

‎apps/mobile/src/features/files/FilesHeader.tsx‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
2-
import { BackHandler, Keyboard, type TextInputInstance, View } from "react-native";
1+
import { useCallback, useRef, useState, type ReactNode } from "react";
2+
import { Keyboard, type TextInputInstance, View } from "react-native";
33

44
import {
55
AndroidHeaderIconButton,
@@ -8,6 +8,7 @@ import {
88
import { AndroidAnchoredMenu } from "../../components/ui/AndroidAnchoredMenu";
99
import { SearchField } from "../../components/ui/SearchField";
1010
import { useToolbarLayout } from "../../components/ui/useToolbarLayout";
11+
import { useHardwareBack } from "../../lib/backHandler";
1112

1213
export function FilesHeader(props: {
1314
readonly projectName: string;
@@ -28,14 +29,10 @@ export function FilesHeader(props: {
2829
Keyboard.dismiss();
2930
}, [onSearchQueryChange]);
3031

31-
useEffect(() => {
32-
if (!searching) return;
33-
const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
34-
closeSearch();
35-
return true;
36-
});
37-
return () => subscription.remove();
38-
}, [closeSearch, searching]);
32+
useHardwareBack(searching, () => {
33+
closeSearch();
34+
return true;
35+
});
3936

4037
return (
4138
<View>

‎apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { useEffect, useState } from "react";
2-
import { BackHandler, Platform, View } from "react-native";
1+
import { useState } from "react";
2+
import { Platform, View } from "react-native";
33
import { WebView } from "react-native-webview";
44
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
55

@@ -9,6 +9,7 @@ import { FilePreviewLoading } from "./FilePreviewFeedback";
99
import { LoadingStrip } from "../../components/ui/LoadingStrip";
1010
import { PdfPreview } from "../../components/PdfPreview";
1111
import { ControlPill } from "../../components/ui/ControlPill";
12+
import { useHardwareBack } from "../../lib/backHandler";
1213
import { isPdfPreviewUri } from "../../lib/pdfPreview";
1314
import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
1415

@@ -27,14 +28,10 @@ function DocumentWebPreview(props: { readonly uri: string }) {
2728
const [loadError, setLoadError] = useState<string | null>(null);
2829
const [linkedPdf, setLinkedPdf] = useState<string | null>(null);
2930

30-
useEffect(() => {
31-
if (linkedPdf === null) return;
32-
const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
33-
setLinkedPdf(null);
34-
return true;
35-
});
36-
return () => subscription.remove();
37-
}, [linkedPdf]);
31+
useHardwareBack(linkedPdf !== null, () => {
32+
setLinkedPdf(null);
33+
return true;
34+
});
3835

3936
if (isPdfPreviewUri(props.uri)) {
4037
return (

‎apps/mobile/src/features/threads/thread-work-log.tsx‎

Lines changed: 3 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,7 @@ import {
3333
type ReactNode,
3434
} from "react";
3535
import {
36-
AccessibilityInfo,
3736
Animated as NativeAnimated,
38-
AppState,
3937
type ColorValue,
4038
Easing,
4139
Pressable,
@@ -63,6 +61,7 @@ import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
6361
import { AppText as Text } from "../../components/ui/AppText";
6462
import { T3Wordmark } from "../../components/T3Wordmark";
6563
import { BrowserAppIcon } from "./BrowserAppIcon";
64+
import { useAppActive, useReduceMotionEnabled } from "../../lib/appState";
6665
import { cn } from "../../lib/cn";
6766
import { THREAD_WORK_ROW_MIN_HEIGHT, type deriveThreadWorkLogSizing } from "../../lib/layout";
6867
import {
@@ -264,8 +263,8 @@ export function ShimmeringWorkContent(props: {
264263
}) {
265264
const [availableWidth, setAvailableWidth] = useState(0);
266265
const [textWidth, setTextWidth] = useState(0);
267-
const [appIsActive, setAppIsActive] = useState(AppState.currentState === "active");
268-
const [reducedMotion, setReducedMotion] = useState(true);
266+
const appIsActive = useAppActive();
267+
const reducedMotion = useReduceMotionEnabled();
269268
const screenIsFocused = useIsFocused();
270269
const progress = useAnimatedValue(0);
271270
const gradientId = `work-shimmer-${useId().replaceAll(":", "")}`;
@@ -274,22 +273,6 @@ export function ShimmeringWorkContent(props: {
274273
(props.showIcon ? SHIMMER_ICON_AND_GAP_WIDTH : 0) + Math.ceil(textWidth),
275274
);
276275

277-
useEffect(() => {
278-
const subscription = AppState.addEventListener("change", (state) => {
279-
setAppIsActive(state === "active");
280-
});
281-
return () => subscription.remove();
282-
}, []);
283-
284-
useEffect(() => {
285-
void AccessibilityInfo.isReduceMotionEnabled().then(setReducedMotion);
286-
const subscription = AccessibilityInfo.addEventListener(
287-
"reduceMotionChanged",
288-
setReducedMotion,
289-
);
290-
return () => subscription.remove();
291-
}, []);
292-
293276
// Runs on React Native's native driver instead of Reanimated, whose
294277
// per-frame commits starve React's while commit pausing is disabled
295278
// (package.json). See docs/internals/performance-regressions.md.
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { describe, expect, it, vi } from "vite-plus/test";
2+
3+
const native = vi.hoisted(() => ({
4+
enabled: false,
5+
listeners: new Set<(enabled: boolean) => void>(),
6+
}));
7+
8+
vi.mock("react-native", () => ({
9+
AppState: { currentState: "active", addEventListener: vi.fn() },
10+
AccessibilityInfo: {
11+
addEventListener: (_event: string, listener: (enabled: boolean) => void) => {
12+
native.listeners.add(listener);
13+
return { remove: () => native.listeners.delete(listener) };
14+
},
15+
isReduceMotionEnabled: () => Promise.resolve(native.enabled),
16+
},
17+
}));
18+
19+
import { readReduceMotionEnabled, subscribeReduceMotion } from "./appState";
20+
21+
describe("reduce motion store", () => {
22+
it("reseeds from native after observation stops and restarts", async () => {
23+
native.enabled = false;
24+
const unsubscribe = subscribeReduceMotion(() => undefined);
25+
await Promise.resolve();
26+
expect(readReduceMotionEnabled()).toBe(false);
27+
unsubscribe();
28+
29+
// Changed while nobody listened: no event reaches the store.
30+
native.enabled = true;
31+
const unsubscribeAgain = subscribeReduceMotion(() => undefined);
32+
// Unknown until the reseed lands, which reads as reduced, not the stale false.
33+
expect(readReduceMotionEnabled()).toBe(true);
34+
await Promise.resolve();
35+
expect(readReduceMotionEnabled()).toBe(true);
36+
unsubscribeAgain();
37+
});
38+
39+
it("ignores a seed that resolves after the last unsubscribe", async () => {
40+
native.enabled = false;
41+
subscribeReduceMotion(() => undefined)();
42+
await Promise.resolve();
43+
expect(readReduceMotionEnabled()).toBe(true);
44+
});
45+
});

0 commit comments

Comments
 (0)