garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /web/src/sw.js

raw

// The hub page's service worker: it shows what needs the person when the hub
// wakes this browser (push.rs). The push carries nothing; what waits is asked
// of the hub with the person's own login, so the push service never sees it.
// Plain JavaScript, served as it is from the page's root (its scope is all of it).

self.addEventListener('install', () => self.skipWaiting())
self.addEventListener('activate', (e) => e.waitUntil(self.clients.claim()))

self.addEventListener('push', (e) => {
    e.waitUntil(
        (async () => {
            let needs = []
            try {
                const r = await fetch('/v1/push/needs', {credentials: 'same-origin'})
                if (r.ok) needs = await r.json()
            } catch {
                // Offline, or the login lapsed: still say something waits.
            }
            const first = needs[0]
            const title = needs.length > 1 ? `${needs.length} things need you` : first ? first.title : 'Something needs you'
            const body = needs.length > 1 ? needs.slice(0, 3).map((n) => n.title).join(' · ') : first ? first.body : 'Open Midas to see what.'
            await self.registration.showNotification(title, {
                body,
                tag: 'midas-needs',
                renotify: true,
                icon: '/icon-192.png',
                data: {url: first ? first.url : '/'},
            })
        })(),
    )
})

self.addEventListener('notificationclick', (e) => {
    e.notification.close()
    const url = (e.notification.data && e.notification.data.url) || '/'
    e.waitUntil(
        (async () => {
            const open = await self.clients.matchAll({type: 'window', includeUncontrolled: true})
            for (const w of open) {
                if ('focus' in w) {
                    await w.navigate(url)
                    return w.focus()
                }
            }
            return self.clients.openWindow(url)
        })(),
    )
})