Files
ti/static/sw.js
Henrik Jess Nielsen b640d9950c feat(pwa): offline support so the list works in-store with no net
No signal inside the store made the server-rendered app unusable. Make it
an installable PWA:
- service worker (static/sw.js) caches pages (network-first, cache fallback)
  and assets, served from root so scope is /
- offline.js: cittiFetch() queues check-off / price / qty / pick POSTs in
  localStorage when offline and replays them in order on reconnect, with an
  optimistic response and an Offline/Syncing status badge
- manifest + icon for add-to-home-screen; PWA meta tags on the in-store pages
- in-store mutations (saveToServer, pick/unpick) go through cittiFetch;
  archive/refresh/add still need net by design
- Dockerfile copies static/
Open once online first so the SW can cache; then it works offline.
2026-10-30 11:54:38 +01:00

51 lines
1.7 KiB
JavaScript

// citti service worker — offline shell + asset caching.
// Pages: network-first (fresh when online, cached copy in the store).
// Assets: cache-first. POSTs are never touched here — the page queues them.
const CACHE = 'citti-v1';
const CORE = ['/', '/tilbud', '/koeb-nu', '/offline.js', '/manifest.webmanifest', '/icon.svg'];
self.addEventListener('install', (e) => {
e.waitUntil(
caches.open(CACHE)
.then((c) => Promise.allSettled(CORE.map((u) => c.add(u))))
.then(() => self.skipWaiting())
);
});
self.addEventListener('activate', (e) => {
e.waitUntil(
caches.keys()
.then((ks) => Promise.all(ks.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
.then(() => self.clients.claim())
);
});
self.addEventListener('fetch', (e) => {
const req = e.request;
if (req.method !== 'GET') return; // POSTs go straight to network; the page queues failures
const url = new URL(req.url);
if (url.origin !== location.origin) return;
const isAsset = /\.(js|css|svg|png|jpe?g|webp|webmanifest)$/.test(url.pathname)
|| url.pathname.startsWith('/uploads/');
if (isAsset) {
e.respondWith(
caches.match(req).then((hit) => hit || fetch(req).then((r) => {
const copy = r.clone();
caches.open(CACHE).then((c) => c.put(req, copy));
return r;
}))
);
} else {
// pages (navigations): network-first, fall back to the cached copy, then to '/'
e.respondWith(
fetch(req).then((r) => {
const copy = r.clone();
caches.open(CACHE).then((c) => c.put(req, copy));
return r;
}).catch(() => caches.match(req).then((hit) => hit || caches.match('/')))
);
}
});