/** * Service for monitoring network status * Provides methods to check if the user is online and to register listeners for network status changes */ class NetworkService { private online: boolean = navigator.onLine private listeners: Set<(online: boolean) => void> = new Set() constructor() { // Initialize with current online status this.online = navigator.onLine // Add event listeners for online/offline events if (typeof window !== 'undefined') { window.addEventListener('online', this.handleOnline.bind(this)) window.addEventListener('offline', this.handleOffline.bind(this)) } } /** * Check if the user is currently online * @returns boolean - True if online, false if offline */ isOnline(): boolean { return this.online } /** * Add a listener for network status changes * @param listener - Function to call when network status changes * @returns Function - Function to remove the listener */ addStatusChangeListener(listener: (online: boolean) => void): () => void { this.listeners.add(listener) // Return function to remove listener return () => { this.listeners.delete(listener) } } /** * Handle online event */ private handleOnline(): void { this.online = true this.notifyListeners() } /** * Handle offline event */ private handleOffline(): void { this.online = false this.notifyListeners() } /** * Notify all listeners of network status change */ private notifyListeners(): void { for (const listener of this.listeners) { listener(this.online) } } } // Create a singleton instance export const networkService = new NetworkService()