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

OnlineDetector.ts

98 lines2.1 KB

1import type { OnlineDetector } from '../types'
2​
3/**
4 * Web-based online detector that uses browser APIs.
5 * Listens for:
6 * - `window.online` event for network connectivity changes
7 * - `document.visibilitychange` event for tab/window focus changes
8 */
9export class WebOnlineDetector implements OnlineDetector {
10 private listeners: Set<() => void> = new Set()
11 private isListening = false
12​
13 constructor() {
14 this.startListening()
15 }
16​
17 private startListening(): void {
18 if (this.isListening) {
19 return
20 }
21​
22 this.isListening = true
23​
24 if (typeof window !== `undefined`) {
25 window.addEventListener(`online`, this.handleOnline)
26 document.addEventListener(`visibilitychange`, this.handleVisibilityChange)
27 }
28 }
29​
30 private stopListening(): void {
31 if (!this.isListening) {
32 return
33 }
34​
35 this.isListening = false
36​
37 if (typeof window !== `undefined`) {
38 window.removeEventListener(`online`, this.handleOnline)
39 document.removeEventListener(
40 `visibilitychange`,
41 this.handleVisibilityChange,
42 )
43 }
44 }
45​
46 private handleOnline = (): void => {
47 this.notifyListeners()
48 }
49​
50 private handleVisibilityChange = (): void => {
51 if (document.visibilityState === `visible`) {
52 this.notifyListeners()
53 }
54 }
55​
56 private notifyListeners(): void {
57 for (const listener of this.listeners) {
58 try {
59 listener()
60 } catch (error) {
61 console.warn(`OnlineDetector listener error:`, error)
62 }
63 }
64 }
65​
66 subscribe(callback: () => void): () => void {
67 this.listeners.add(callback)
68​
69 return () => {
70 this.listeners.delete(callback)
71​
72 if (this.listeners.size === 0) {
73 this.stopListening()
74 }
75 }
76 }
77​
78 notifyOnline(): void {
79 this.notifyListeners()
80 }
81​
82 isOnline(): boolean {
83 if (typeof navigator !== `undefined`) {
84 return navigator.onLine
85 }
86 return true
87 }
88​
89 dispose(): void {
90 this.stopListening()
91 this.listeners.clear()
92 }
94​
95/**
96 * @deprecated Use `WebOnlineDetector` instead. This alias is kept for backwards compatibility.
97 */
98export const DefaultOnlineDetector = WebOnlineDetector