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

onlineManager.ts

96 lines2.1 KB

1import { Subscribable } from './subscribable'
2import { isServer } from './utils'
3​
4type SetupFn = (
5 setOnline: (online?: boolean) => void,
6) => (() => void) | undefined
7​
8const onlineEvents = ['online', 'offline'] as const
9​
10export class OnlineManager extends Subscribable {
11 private online?: boolean
12 private cleanup?: () => void
13​
14 private setup: SetupFn
15​
16 constructor() {
17 super()
18 this.setup = (onOnline) => {
19 // addEventListener does not exist in React Native, but window does
20 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
21 if (!isServer && window.addEventListener) {
22 const listener = () => onOnline()
23 // Listen to online
24 onlineEvents.forEach((event) => {
25 window.addEventListener(event, listener, false)
26 })
27​
28 return () => {
29 // Be sure to unsubscribe if a new handler is set
30 onlineEvents.forEach((event) => {
31 window.removeEventListener(event, listener)
32 })
33 }
34 }
35​
36 return
37 }
38 }
39​
40 protected onSubscribe(): void {
41 if (!this.cleanup) {
42 this.setEventListener(this.setup)
43 }
44 }
45​
46 protected onUnsubscribe() {
47 if (!this.hasListeners()) {
48 this.cleanup?.()
49 this.cleanup = undefined
50 }
51 }
52​
53 setEventListener(setup: SetupFn): void {
54 this.setup = setup
55 this.cleanup?.()
56 this.cleanup = setup((online?: boolean) => {
57 if (typeof online === 'boolean') {
58 this.setOnline(online)
59 } else {
60 this.onOnline()
61 }
62 })
63 }
64​
65 setOnline(online?: boolean): void {
66 const changed = this.online !== online
67​
68 if (changed) {
69 this.online = online
70 this.onOnline()
71 }
72 }
73​
74 onOnline(): void {
75 this.listeners.forEach(({ listener }) => {
76 listener()
77 })
78 }
79​
80 isOnline(): boolean {
81 if (typeof this.online === 'boolean') {
82 return this.online
83 }
84​
85 if (
86 typeof navigator === 'undefined' ||
87 typeof navigator.onLine === 'undefined'
88 ) {
89 return true
90 }
91​
92 return navigator.onLine
93 }
95​
96export const onlineManager = new OnlineManager()