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

appState.ts

79 lines2.7 KB

1import { useSyncExternalStore } from "react";
2import { AccessibilityInfo, AppState } from "react-native";
3​
4type Listener = () => void;
5​
6function subscribeAppState(onChange: Listener): () => void {
7 const subscription = AppState.addEventListener("change", () => onChange());
8 return () => subscription.remove();
9}
10​
11function isAppActive(): boolean {
12 return AppState.currentState === "active";
14​
15export function useAppActive(): boolean {
16 return useSyncExternalStore(subscribeAppState, isAppActive);
18​
19function isAppForeground(): boolean {
20 return AppState.currentState !== "background";
22​
23/**
24 * True unless the app is backgrounded. Unlike useAppActive, the transient
25 * "inactive" state (Control Center, the app switcher, a system prompt) still
26 * counts as foreground, so live streams do not reconnect around it.
27 */
28export function useAppForeground(): boolean {
29 return useSyncExternalStore(subscribeAppState, isAppForeground);
31​
32// Null until the native seed resolves; read as reduced so animated consumers
33// never start motion a reduce-motion user has turned off.
34let reduceMotionEnabled: boolean | null = null;
35const reduceMotionListeners = new Set<Listener>();
36let reduceMotionSubscription: { remove: () => void } | null = null;
37​
38function setReduceMotionEnabled(next: boolean) {
39 if (next === reduceMotionEnabled) return;
40 reduceMotionEnabled = next;
41 for (const listener of reduceMotionListeners) listener();
43​
44export function subscribeReduceMotion(onChange: Listener): () => void {
45 reduceMotionListeners.add(onChange);
46 if (reduceMotionSubscription === null) {
47 const subscription = AccessibilityInfo.addEventListener(
48 "reduceMotionChanged",
49 setReduceMotionEnabled,
50 );
51 reduceMotionSubscription = subscription;
52 // The native event only reports changes; seed the current value once per
53 // observation, and drop a seed that resolves after observation stopped.
54 void AccessibilityInfo.isReduceMotionEnabled().then(
55 (enabled) => {
56 if (reduceMotionSubscription === subscription) setReduceMotionEnabled(enabled);
57 },
58 () => undefined,
59 );
60 }
61 return () => {
62 reduceMotionListeners.delete(onChange);
63 if (reduceMotionListeners.size === 0) {
64 reduceMotionSubscription?.remove();
65 reduceMotionSubscription = null;
66 // Changes made while nobody observed were never reported, so the cached
67 // value can be stale; the next subscriber reseeds from native.
68 reduceMotionEnabled = null;
69 }
70 };
72​
73export function readReduceMotionEnabled(): boolean {
74 return reduceMotionEnabled ?? true;
76​
77export function useReduceMotionEnabled(): boolean {
78 return useSyncExternalStore(subscribeReduceMotion, readReduceMotionEnabled);