/** * A new version of the app waits until the person asks for it. * * A new worker that took over at once served its files to the screens already open, and an open screen that then * opened a page it had not loaded yet got that page's file of the new version - next to the main file of the old * one. So a new worker waits: the open screens keep their version, the person is told a new one is ready, and the * screen that asks moves to it and reloads. The browser checks for a new worker only when a page is opened, and a * screen kept open for days opens none, so the check is also made when the screen comes back into view and every * hour. */ export const UPDATE_CHECK_MS = 60 * 60 * 1000 /** The message a waiting worker takes over on (sw-src). */ export const SKIP_WAITING = 'SKIP_WAITING' export interface UpdateWatch { /** Calls the listener when a new version waits - at once if one waits already. */ onWaiting(listener: () => void): () => void /** Moves this screen to the waiting version and reloads it. */ apply(): void } export function watchForUpdate( container: { controller: unknown; addEventListener(type: string, listener: () => void): void }, registration: { waiting: any installing: any update(): Promise addEventListener(type: string, listener: () => void): void }, { reload = () => window.location.reload(), doc = document as { visibilityState: string; addEventListener(type: string, listener: () => void): void }, every = UPDATE_CHECK_MS, repeat = (work: () => void, ms: number) => setInterval(work, ms) as unknown } = {} ): UpdateWatch { const listeners = new Set<() => void>() let waits = false let asked = false /* A worker installed while another controls this screen is a new version; the first worker of all is none. */ const installed = (worker: any) => { if (worker.state !== 'installed' || !container.controller) return waits = true listeners.forEach(listener => listener()) } const follow = (worker: any) => { if (!worker) return installed(worker) worker.addEventListener('statechange', () => installed(worker)) } follow(registration.waiting) follow(registration.installing) registration.addEventListener('updatefound', () => follow(registration.installing)) /* Only the screen that asked reloads - another screen open may hold an unsaved form. */ container.addEventListener('controllerchange', () => asked && reload()) const check = () => registration.update().catch(() => {}) doc.addEventListener('visibilitychange', () => doc.visibilityState === 'visible' && check()) repeat(check, every) return { onWaiting(listener) { listeners.add(listener) if (waits) listener() return () => listeners.delete(listener) }, apply() { /* Another screen may have moved to it already - then this one only reloads. */ if (!registration.waiting) return reload() asked = true registration.waiting.postMessage({ type: SKIP_WAITING }) } } }