123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- import { Subscribable } from './subscribable.esm.js';
- import { isServer } from './utils.esm.js';
- const onlineEvents = ['online', 'offline'];
- class OnlineManager extends Subscribable {
- constructor() {
- super();
- this.setup = onOnline => {
- // addEventListener does not exist in React Native, but window does
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
- if (!isServer && window.addEventListener) {
- const listener = () => onOnline(); // Listen to online
- onlineEvents.forEach(event => {
- window.addEventListener(event, listener, false);
- });
- return () => {
- // Be sure to unsubscribe if a new handler is set
- onlineEvents.forEach(event => {
- window.removeEventListener(event, listener);
- });
- };
- }
- return;
- };
- }
- onSubscribe() {
- if (!this.cleanup) {
- this.setEventListener(this.setup);
- }
- }
- onUnsubscribe() {
- if (!this.hasListeners()) {
- var _this$cleanup;
- (_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
- this.cleanup = undefined;
- }
- }
- setEventListener(setup) {
- var _this$cleanup2;
- this.setup = setup;
- (_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
- this.cleanup = setup(online => {
- if (typeof online === 'boolean') {
- this.setOnline(online);
- } else {
- this.onOnline();
- }
- });
- }
- setOnline(online) {
- const changed = this.online !== online;
- if (changed) {
- this.online = online;
- this.onOnline();
- }
- }
- onOnline() {
- this.listeners.forEach(({
- listener
- }) => {
- listener();
- });
- }
- isOnline() {
- if (typeof this.online === 'boolean') {
- return this.online;
- }
- if (typeof navigator === 'undefined' || typeof navigator.onLine === 'undefined') {
- return true;
- }
- return navigator.onLine;
- }
- }
- const onlineManager = new OnlineManager();
- export { OnlineManager, onlineManager };
- //# sourceMappingURL=onlineManager.esm.js.map
|