mirror of
https://github.com/zoriya/react-native-web.git
synced 2026-06-10 21:12:08 +00:00
bcdeda5dab
Fixes dozens of Flow errors; adds type annotations; marks more files for Flow type checking. Fixes a bug in 'AppState'. 15 Flow errors remaining. Several React Native files are still not type checked (e.g., PanResponder, Touchables) Ref #465
70 lines
1.8 KiB
JavaScript
70 lines
1.8 KiB
JavaScript
/**
|
|
* @flow
|
|
*/
|
|
|
|
import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment';
|
|
import findIndex from 'array-find-index';
|
|
import invariant from 'fbjs/lib/invariant';
|
|
|
|
const EVENT_TYPES = ['change'];
|
|
const VISIBILITY_CHANGE_EVENT = 'visibilitychange';
|
|
|
|
const AppStates = {
|
|
BACKGROUND: 'background',
|
|
ACTIVE: 'active'
|
|
};
|
|
|
|
const listeners = [];
|
|
|
|
class AppState {
|
|
static isAvailable = ExecutionEnvironment.canUseDOM && document.visibilityState;
|
|
|
|
static get currentState() {
|
|
if (!AppState.isAvailable) {
|
|
return AppStates.ACTIVE;
|
|
}
|
|
|
|
switch (document.visibilityState) {
|
|
case 'hidden':
|
|
case 'prerender':
|
|
case 'unloaded':
|
|
return AppStates.BACKGROUND;
|
|
default:
|
|
return AppStates.ACTIVE;
|
|
}
|
|
}
|
|
|
|
static addEventListener(type: string, handler: Function) {
|
|
if (AppState.isAvailable) {
|
|
invariant(
|
|
EVENT_TYPES.indexOf(type) !== -1,
|
|
'Trying to subscribe to unknown event: "%s"',
|
|
type
|
|
);
|
|
const callback = () => handler(AppState.currentState);
|
|
listeners.push([handler, callback]);
|
|
document.addEventListener(VISIBILITY_CHANGE_EVENT, callback, false);
|
|
}
|
|
}
|
|
|
|
static removeEventListener(type: string, handler: Function) {
|
|
if (AppState.isAvailable) {
|
|
invariant(
|
|
EVENT_TYPES.indexOf(type) !== -1,
|
|
'Trying to remove listener for unknown event: "%s"',
|
|
type
|
|
);
|
|
const listenerIndex = findIndex(listeners, pair => pair[0] === handler);
|
|
invariant(
|
|
listenerIndex !== -1,
|
|
'Trying to remove AppState listener for unregistered handler'
|
|
);
|
|
const callback = listeners[listenerIndex][1];
|
|
document.removeEventListener(VISIBILITY_CHANGE_EVENT, callback, false);
|
|
listeners.splice(listenerIndex, 1);
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = AppState;
|