All files / lib onlineDetector.ts

91.66% Statements 33/36
75% Branches 9/12
91.66% Functions 11/12
92.59% Lines 25/27

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 4149x 49x 49x     13x   49x 49x 6x 6x 48x   412x 412x     410x 410x 283x 288x 287x     118x 118x 2172x 48x   2172x     13x     284x 12x   284x    
export interface OnlineDetector {
E  isOnline(): boolean
  subscribe(listener: () => void): () => void
}

const listeners = new Set<() => void>()
 
Eif (typeof window !== 'undefined') {
  const notifyAll = () => {
    for (const fn of listeners) {
      fn()
    }
  }
  wIindow.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
}