All files / lib onlineDetector.ts

100% Statements 18/18
83.33% Branches 5/6
100% Functions 6/6
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41          13x   13x 13x 6x 6x     13x 13x       18x   288x 287x     118x 118x 118x           13x     284x 12x   284x    
export interface OnlineDetector {
  isOnline(): boolean
  subscribe(listener: () => void): () => void
}
 
const listeners = new Set<() => void>()
 
Eif (typeof window !== 'undefined') {
  const notifyAll = () => {
    for (const fn of listeners) {
      fn()
    }
  }
  window.addEventListener('online', notifyAll)
  window.addEventListener('offline', notifyAll)
}
 
export function createOnlineDetector(): OnlineDetector {
  return {
    isOnline() {
      if (typeof navigator === 'undefined') return true
      return navigator.onLine
    },
    subscribe(listener: () => void) {
      listeners.add(listener)
      return () => {
        listeners.delete(listener)
      }
    },
  }
}
 
let _instance: OnlineDetector | null = null
 
export function getOnlineDetector(): OnlineDetector {
  if (!_instance) {
    _instance = createOnlineDetector()
  }
  return _instance
}