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

onlineManager.ts

76 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: (online?: boolean) => void) => () => 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 const listener = () => onOnline()
62 // Listen to online
63 window.addEventListener('online', listener, false)
64 window.addEventListener('offline', listener, false)
65​
66 return () => {
67 // Be sure to unsubscribe if a new handler is set
68 window.removeEventListener('online', listener)
69 window.removeEventListener('offline', listener)
70 }
71 })
72 }
73 }
75​
76export const onlineManager = new OnlineManager()