| 1 | import { writable } from 'svelte/store'; |
| 2 | import { mayAutoReload } from './engine-build'; |
| 3 | |
| 4 | const ENGINE_RELOAD_GUARD = 'malice-engine-reload'; |
| 5 | |
| 6 | export const engineStale = writable(false); |
| 7 | export const engineRecovered = writable(0); |
| 8 | |
| 9 | let release: () => Promise<void> = () => Promise.resolve(); |
| 10 | |
| 11 | export function setEngineRelease(fn: () => Promise<void>): void { |
| 12 | release = fn; |
| 13 | } |
| 14 | |
| 15 | export function releaseEngine(): Promise<void> { |
| 16 | return release(); |
| 17 | } |
| 18 | |
| 19 | function reloadWhenHidden(): void { |
| 20 | if (document.visibilityState !== 'hidden') return; |
| 21 | const last = Number(sessionStorage.getItem(ENGINE_RELOAD_GUARD)) || null; |
| 22 | const now = Date.now(); |
| 23 | if (!mayAutoReload(now, last)) return; |
| 24 | sessionStorage.setItem(ENGINE_RELOAD_GUARD, String(now)); |
| 25 | void releaseEngine().then(() => window.location.reload()); |
| 26 | } |
| 27 | |
| 28 | /** |
| 29 | * Tabs in a handover leave the reload to the service worker activation. A hidden tab reloading |
| 30 | * ahead of it lands on the new build under the old service worker and gets reloaded again. |
| 31 | */ |
| 32 | export function markEngineStale(autoReload = true): void { |
| 33 | engineStale.set(true); |
| 34 | if (!autoReload) return; |
| 35 | document.addEventListener('visibilitychange', reloadWhenHidden); |
| 36 | reloadWhenHidden(); |
| 37 | } |