Open History to see the last commit
1import { Subscribable } from './subscribable'
2import { isServer } from './utils'
3β
4type SetupFn = (
5 setOnline: (online?: boolean) => void,
6) => (() => void) | undefined
7β
8export class OnlineManager extends Subscribable {
9 private online?: boolean
10 private cleanup?: () => void
11β
12 private setup: SetupFn
13β
14 constructor() {
15 super()
16 this.setup = (onOnline) => {
17 // addEventListener does not exist in React Native, but window does
18 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
19 if (!isServer && window.addEventListener) {
20 const listener = () => onOnline()
21 // Listen to online
22 window.addEventListener('online', listener, false)
23 window.addEventListener('offline', listener, false)
24β
25 return () => {
26 // Be sure to unsubscribe if a new handler is set
27 window.removeEventListener('online', listener)
28 window.removeEventListener('offline', listener)
29 }
30 }
31 }
32 }
33β
34 protected onSubscribe(): void {
35 if (!this.cleanup) {
36 this.setEventListener(this.setup)
37 }
38 }
39β
40 protected onUnsubscribe() {
41 if (!this.hasListeners()) {
42 this.cleanup?.()
43 this.cleanup = undefined
44 }
45 }
46β
47 setEventListener(setup: SetupFn): void {
48 this.setup = setup
49 this.cleanup?.()
50 this.cleanup = setup((online?: boolean) => {
51 if (typeof online === 'boolean') {
52 this.setOnline(online)
53 } else {
54 this.onOnline()
55 }
56 })
57 }
58β
59 setOnline(online?: boolean): void {
60 this.online = online
61β
62 if (online) {
63 this.onOnline()
64 }
65 }
66β
67 onOnline(): void {
68 this.listeners.forEach((listener) => {
69 listener()
70 })
71 }
72β
73 isOnline(): boolean {
74 if (typeof this.online === 'boolean') {
75 return this.online
76 }
77β
78 if (
79 typeof navigator === 'undefined' ||
80 typeof navigator.onLine === 'undefined'
81 ) {
82 return true
83 }
84β
85 return navigator.onLine
86 }
87}
88β
89export const onlineManager = new OnlineManager()