UNPKG

react-native-unit-components

Version:

Unit React Native components

61 lines (55 loc) 2.36 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useIsBackFromLongBackground = void 0; var _react = require("react"); var _reactNative = require("react-native"); /* eslint-disable @typescript-eslint/no-explicit-any */ const getIsAppActive = currentAppState => { return currentAppState !== 'background' && currentAppState !== 'inactive'; }; const BACKGROUND_THRESHOLD = 30000; // 30 seconds in milliseconds /* * This hook is used to check if the app is in the background for a long period of time. * If yes - returns true and trigger closing the bottomsheet. * If no - returns false and keep the bottomsheet open. * * Returns false unless background time is more than 30 seconds. */ const useIsBackFromLongBackground = () => { const appState = (0, _react.useRef)(_reactNative.AppState.currentState); const [isLongBackgroundTime, setIsLongBackgroundTime] = (0, _react.useState)(false); const backgroundTimestamp = (0, _react.useRef)(null); const activeTimestamp = (0, _react.useRef)(null); (0, _react.useEffect)(() => { const subscription = _reactNative.AppState.addEventListener('change', nextAppState => { const nextAppStateActive = getIsAppActive(nextAppState); const currentAppStateActive = getIsAppActive(appState.current); if (!nextAppStateActive && currentAppStateActive) { // Set background timestamp when first entering background backgroundTimestamp.current = Date.now(); activeTimestamp.current = null; } else if (nextAppStateActive && !currentAppStateActive) { // Set active timestamp when coming back from background activeTimestamp.current = Date.now(); // Check if time difference is more than threshold if (activeTimestamp.current - (backgroundTimestamp.current ?? 0) > BACKGROUND_THRESHOLD) { setIsLongBackgroundTime(true); } else { setIsLongBackgroundTime(false); } // Reset timestamps for next cycle backgroundTimestamp.current = null; activeTimestamp.current = null; } appState.current = nextAppState; }); return () => { subscription.remove(); }; }, []); return isLongBackgroundTime; }; exports.useIsBackFromLongBackground = useIsBackFromLongBackground; //# sourceMappingURL=useAppStateListener.js.map