44 lines
1.9 KiB
JavaScript
44 lines
1.9 KiB
JavaScript
const CACHE = 'life-os-shell-v1.15.0';
|
|
const SHELL = [
|
|
'/', '/index.html', '/manifest.webmanifest', '/life-os-icon.svg'
|
|
];
|
|
|
|
self.addEventListener('install', event => {
|
|
event.waitUntil(caches.open(CACHE).then(cache => cache.addAll(SHELL)).then(() => self.skipWaiting()));
|
|
});
|
|
|
|
self.addEventListener('activate', event => {
|
|
event.waitUntil(caches.keys().then(keys => Promise.all(keys.filter(key => key.startsWith('life-os-shell-') && key !== CACHE).map(key => caches.delete(key)))).then(() => self.clients.claim()));
|
|
});
|
|
|
|
self.addEventListener('fetch', event => {
|
|
const request = event.request;
|
|
if (request.method !== 'GET' || new URL(request.url).origin !== self.location.origin) return;
|
|
const url = new URL(request.url);
|
|
if (url.pathname.startsWith('/api/')) return;
|
|
if (request.mode === 'navigate') {
|
|
event.respondWith(fetch(request).then(response => {
|
|
const copy = response.clone();
|
|
caches.open(CACHE).then(cache => cache.put('/index.html', copy));
|
|
return response;
|
|
}).catch(() => caches.match('/index.html')));
|
|
return;
|
|
}
|
|
event.respondWith(caches.match(request).then(cached => cached || fetch(request).then(response => {
|
|
if (response.ok) caches.open(CACHE).then(cache => cache.put(request, response.clone()));
|
|
return response;
|
|
})));
|
|
});
|
|
|
|
self.addEventListener('notificationclick', event => {
|
|
event.notification.close();
|
|
const app = ['today', 'tasks', 'system'].includes(event.notification.data?.app) ? event.notification.data.app : 'system';
|
|
event.waitUntil(self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then(async clients => {
|
|
const existing = clients.find(client => new URL(client.url).origin === self.location.origin);
|
|
if (existing) {
|
|
await existing.focus();
|
|
existing.postMessage({ type: 'lifeos-open-app', app });
|
|
} else await self.clients.openWindow('/?app=' + encodeURIComponent(app));
|
|
}));
|
|
});
|