All files / lib onlineDetector.ts

83.33% Statements 15/18
66.66% Branches 4/6
83.33% Functions 5/6
88.23% Lines 15/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 4169x 69x 69x         69x 69x     65x   659x 659x     647x 647x 471x         69x   3632x 65x   3632x                      
export interface OnlineDetector {
E  isOnline(): boolean
  subscribe(listener: () => void): () => void
}

const listeners = new Set<() => void>()
 
if (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
}