Files
react-native-web/src/apis/AppState/index.js
T
Nicolas Gallagher bcdeda5dab [fix] Flow type checking and annotations
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
2017-05-27 10:44:33 -07:00

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;