All files / src sw.ts

0% Statements 0/25
0% Branches 0/16
0% Functions 0/6
0% Lines 0/23

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 42 43 44 45 46 47 48 49 50 51 52 53                                                                                                         
/// <reference lib="WebWorker" />
import { cleanupOutdatedCaches, precacheAndRoute } from 'workbox-precaching'
 
declare const self: ServiceWorkerGlobalScope
 
cleanupOutdatedCaches()
precacheAndRoute(self.__WB_MANIFEST)
 
self.skipWaiting()
self.addEventListener('activate', (event) => {
  event.waitUntil((self as unknown as { clients: { claim(): Promise<void> } }).clients.claim())
})
 
self.addEventListener('push', (event: PushEvent) => {
  const data = event.data?.json() ?? {}
  const title: string = data.title ?? 'ListMe'
  const body: string = data.body ?? ''
  const url: string = data.url ?? '/'
 
  event.waitUntil(
    self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clients) => {
      // App is visible in a tab — the WS in-app toast already handles it
      const appVisible = (clients as WindowClient[]).some(c => c.visibilityState === 'visible')
      if (appVisible) return
      return self.registration.showNotification(title, {
        body,
        icon: '/pwa-192x192.png',
        badge: '/pwa-64x64.png',
        tag: 'listme-' + (data.url ?? 'general'),
        renotify: true,
        data: { url },
      } as NotificationOptions)
    }),
  )
})
 
self.addEventListener('notificationclick', (event: NotificationEvent) => {
  event.notification.close()
  const url: string = (event.notification.data as { url?: string })?.url ?? '/'
 
  event.waitUntil(
    self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
      for (const client of clientList) {
        if ('focus' in client) {
          client.navigate(url)
          return client.focus()
        }
      }
      return self.clients.openWindow(url)
    }),
  )
})