react-query
Version:
Hooks for managing, caching and syncing asynchronous and remote data in React
108 lines (80 loc) • 2.82 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.focusManager = exports.FocusManager = void 0;
var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
var _subscribable = require("./subscribable");
var _utils = require("./utils");
var FocusManager = /*#__PURE__*/function (_Subscribable) {
(0, _inheritsLoose2.default)(FocusManager, _Subscribable);
function FocusManager() {
var _this;
_this = _Subscribable.call(this) || this;
_this.setup = function (onFocus) {
var _window;
if (!_utils.isServer && ((_window = window) == null ? void 0 : _window.addEventListener)) {
var listener = function listener() {
return onFocus();
}; // Listen to visibillitychange and focus
window.addEventListener('visibilitychange', listener, false);
window.addEventListener('focus', listener, false);
return function () {
// Be sure to unsubscribe if a new handler is set
window.removeEventListener('visibilitychange', listener);
window.removeEventListener('focus', listener);
};
}
};
return _this;
}
var _proto = FocusManager.prototype;
_proto.onSubscribe = function onSubscribe() {
if (!this.cleanup) {
this.setEventListener(this.setup);
}
};
_proto.onUnsubscribe = function onUnsubscribe() {
if (!this.hasListeners()) {
var _this$cleanup;
(_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
this.cleanup = undefined;
}
};
_proto.setEventListener = function setEventListener(setup) {
var _this$cleanup2,
_this2 = this;
this.setup = setup;
(_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
this.cleanup = setup(function (focused) {
if (typeof focused === 'boolean') {
_this2.setFocused(focused);
} else {
_this2.onFocus();
}
});
};
_proto.setFocused = function setFocused(focused) {
this.focused = focused;
if (focused) {
this.onFocus();
}
};
_proto.onFocus = function onFocus() {
this.listeners.forEach(function (listener) {
listener();
});
};
_proto.isFocused = function isFocused() {
if (typeof this.focused === 'boolean') {
return this.focused;
} // document global can be unavailable in react native
if (typeof document === 'undefined') {
return true;
}
return [undefined, 'visible', 'prerender'].includes(document.visibilityState);
};
return FocusManager;
}(_subscribable.Subscribable);
exports.FocusManager = FocusManager;
var focusManager = new FocusManager();
exports.focusManager = focusManager;