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