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

onlineManager.ts

75 lines1.7 KB

1import { Subscribable } from './subscribable'
2import { isServer } from './utils'
3​
4class OnlineManager extends Subscribable {
5 private online?: boolean
6 private removeEventListener?: () => void
7​
8 protected onSubscribe(): void {
9 if (!this.removeEventListener) {
10 this.setDefaultEventListener()
11 }
12 }
13​
14 setEventListener(
15 setup: (setOnline: () => void) => (online?: boolean) => void
16 ): void {
17 if (this.removeEventListener) {
18 this.removeEventListener()
19 }
20 this.removeEventListener = setup((online?: boolean) => {
21 if (typeof online === 'boolean') {
22 this.setOnline(online)
23 } else {
24 this.onOnline()
25 }
26 })
27 }
28​
29 setOnline(online?: boolean): void {
30 this.online = online
31​
32 if (online) {
33 this.onOnline()
34 }
35 }
36​
37 onOnline(): void {
38 this.listeners.forEach(listener => {
39 listener()
40 })
41 }
42​
43 isOnline(): boolean {
44 if (typeof this.online === 'boolean') {
45 return this.online
46 }
47​
48 if (
49 typeof navigator === 'undefined' ||
50 typeof navigator.onLine === 'undefined'
51 ) {
52 return true
53 }
54​
55 return navigator.onLine
56 }
57​
58 private setDefaultEventListener() {
59 if (!isServer && window?.addEventListener) {
60 this.setEventListener(onOnline => {
61 // Listen to online
62 window.addEventListener('online', onOnline, false)
63 window.addEventListener('offline', onOnline, false)
64​
65 return () => {
66 // Be sure to unsubscribe if a new handler is set
67 window.removeEventListener('online', onOnline)
68 window.removeEventListener('offline', onOnline)
69 }
70 })
71 }
72 }
74​
75export const onlineManager = new OnlineManager()