Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

onlineManager.ts

87 lines1.8 KB

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 if (!isServer && window?.addEventListener) {
18 const listener = () => onOnline()
19 // Listen to online
20 window.addEventListener('online', listener, false)
21 window.addEventListener('offline', listener, false)
22​
23 return () => {
24 // Be sure to unsubscribe if a new handler is set
25 window.removeEventListener('online', listener)
26 window.removeEventListener('offline', listener)
27 }
28 }
29 }
30 }
31​
32 protected onSubscribe(): void {
33 if (!this.cleanup) {
34 this.setEventListener(this.setup)
35 }
36 }
37​
38 protected onUnsubscribe() {
39 if (!this.hasListeners()) {
40 this.cleanup?.()
41 this.cleanup = undefined
42 }
43 }
44​
45 setEventListener(setup: SetupFn): void {
46 this.setup = setup
47 this.cleanup?.()
48 this.cleanup = setup((online?: boolean) => {
49 if (typeof online === 'boolean') {
50 this.setOnline(online)
51 } else {
52 this.onOnline()
53 }
54 })
55 }
56​
57 setOnline(online?: boolean): void {
58 this.online = online
59​
60 if (online) {
61 this.onOnline()
62 }
63 }
64​
65 onOnline(): void {
66 this.listeners.forEach(listener => {
67 listener()
68 })
69 }
70​
71 isOnline(): boolean {
72 if (typeof this.online === 'boolean') {
73 return this.online
74 }
75​
76 if (
77 typeof navigator === 'undefined' ||
78 typeof navigator.onLine === 'undefined'
79 ) {
80 return true
81 }
82​
83 return navigator.onLine
84 }
86​
87export const onlineManager = new OnlineManager()