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

onlineManager.ts

89 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 }
33​
34 protected onSubscribe(): void {
35 if (!this.cleanup) {
36 this.setEventListener(this.setup)
37 }
38 }
39​
40 protected onUnsubscribe() {
41 if (!this.hasListeners()) {
42 this.cleanup?.()
43 this.cleanup = undefined
44 }
45 }
46​
47 setEventListener(setup: SetupFn): void {
48 this.setup = setup
49 this.cleanup?.()
50 this.cleanup = setup((online?: boolean) => {
51 if (typeof online === 'boolean') {
52 this.setOnline(online)
53 } else {
54 this.onOnline()
55 }
56 })
57 }
58​
59 setOnline(online?: boolean): void {
60 this.online = online
61​
62 if (online) {
63 this.onOnline()
64 }
65 }
66​
67 onOnline(): void {
68 this.listeners.forEach((listener) => {
69 listener()
70 })
71 }
72​
73 isOnline(): boolean {
74 if (typeof this.online === 'boolean') {
75 return this.online
76 }
77​
78 if (
79 typeof navigator === 'undefined' ||
80 typeof navigator.onLine === 'undefined'
81 ) {
82 return true
83 }
84​
85 return navigator.onLine
86 }
88​
89export const onlineManager = new OnlineManager()