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