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

onlineManager.ts

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