diff --git a/Dockerfile b/Dockerfile index 8da08c5..a63daa2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -26,6 +26,7 @@ RUN pip install --no-cache-dir -r requirements.txt COPY app.py . COPY templates/ templates/ +COPY static/ static/ ENV DATA_DIR=/app/instance \ PORT=9756 \ diff --git a/app.py b/app.py index 2e59c86..414792f 100644 --- a/app.py +++ b/app.py @@ -646,6 +646,36 @@ def health(): return jsonify({'status': 'healthy', 'service': 'citti'}) +# --- PWA / offline: served from root so the service worker scope is '/' ------- + +@app.route('/sw.js') +def service_worker(): + resp = send_from_directory(app.static_folder, 'sw.js') + resp.headers['Service-Worker-Allowed'] = '/' + resp.headers['Cache-Control'] = 'no-cache' + resp.headers['Content-Type'] = 'application/javascript' + return resp + + +@app.route('/offline.js') +def offline_js(): + resp = send_from_directory(app.static_folder, 'offline.js') + resp.headers['Content-Type'] = 'application/javascript' + return resp + + +@app.route('/manifest.webmanifest') +def manifest(): + resp = send_from_directory(app.static_folder, 'manifest.webmanifest') + resp.headers['Content-Type'] = 'application/manifest+json' + return resp + + +@app.route('/icon.svg') +def icon(): + return send_from_directory(app.static_folder, 'icon.svg') + + @app.route('/api/category', methods=['POST']) def add_category(): d = request.json diff --git a/static/icon.svg b/static/icon.svg new file mode 100644 index 0000000..0ff6faa --- /dev/null +++ b/static/icon.svg @@ -0,0 +1,9 @@ + diff --git a/static/manifest.webmanifest b/static/manifest.webmanifest new file mode 100644 index 0000000..1a4b1fd --- /dev/null +++ b/static/manifest.webmanifest @@ -0,0 +1,14 @@ +{ + "name": "Citti Indkøbsseddel", + "short_name": "Citti", + "description": "Indkøbsseddel og Lübeck-tilbud — virker offline i butikken.", + "start_url": "/", + "scope": "/", + "display": "standalone", + "orientation": "portrait", + "background_color": "#f5f2ed", + "theme_color": "#c84b2f", + "icons": [ + { "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any maskable" } + ] +} diff --git a/static/offline.js b/static/offline.js new file mode 100644 index 0000000..0b0154d --- /dev/null +++ b/static/offline.js @@ -0,0 +1,78 @@ +// citti offline support: register the SW, and make mutations survive no-net. +// window.cittiFetch(url, opts) tries the network; if it fails (offline), it +// queues the POST in localStorage, resolves optimistically, and replays the +// queue in order when the connection returns. +(function () { + if ('serviceWorker' in navigator) { + navigator.serviceWorker.register('/sw.js').catch(function (e) { + console.warn('[citti] SW registration failed', e); + }); + } + + var QKEY = 'citti_queue_v1'; + function getQ() { try { return JSON.parse(localStorage.getItem(QKEY) || '[]'); } catch (e) { return []; } } + function setQ(q) { try { localStorage.setItem(QKEY, JSON.stringify(q)); } catch (e) {} } + + window.cittiFetch = function (url, opts) { + opts = opts || {}; + var method = (opts.method || 'GET').toUpperCase(); + return fetch(url, opts).then(function (r) { + if (!r.ok) throw new Error('status ' + r.status); + return r; + }).catch(function () { + if (method !== 'GET') { + var q = getQ(); + q.push({ + url: url, method: method, + headers: opts.headers || {}, + body: typeof opts.body === 'string' ? opts.body : null + }); + setQ(q); + render(); + } + // optimistic: let the UI proceed as if saved + return new Response(JSON.stringify({ ok: true, queued: true }), + { status: 200, headers: { 'Content-Type': 'application/json' } }); + }); + }; + + var flushing = false; + function flush() { + if (flushing || !navigator.onLine) { render(); return; } + var q = getQ(); + if (!q.length) { render(); return; } + flushing = true; + var next = q[0]; + fetch(next.url, { method: next.method, headers: next.headers, body: next.body }) + .then(function (r) { + if (!r.ok) throw new Error('status ' + r.status); + var qq = getQ(); qq.shift(); setQ(qq); + flushing = false; render(); + if (getQ().length) flush(); + }) + .catch(function () { flushing = false; render(); }); + } + + function render() { + var n = getQ().length; + var el = document.getElementById('citti-sync'); + if (!el) { + el = document.createElement('div'); + el.id = 'citti-sync'; + el.style.cssText = 'position:fixed;left:50%;transform:translateX(-50%);bottom:14px;z-index:9999;' + + 'padding:8px 16px;border-radius:20px;font:600 13px/1 system-ui,-apple-system,sans-serif;' + + 'color:#fff;box-shadow:0 2px 10px rgba(0,0,0,.25);transition:opacity .3s;pointer-events:none'; + document.body.appendChild(el); + } + var offline = !navigator.onLine; + if (offline && n) { el.textContent = '📴 Offline · ' + n + ' gemmes når du er online'; el.style.background = '#92580a'; el.style.opacity = '1'; } + else if (offline) { el.textContent = '📴 Offline'; el.style.background = '#5a5550'; el.style.opacity = '1'; } + else if (n) { el.textContent = '↻ Synkroniserer ' + n + '…'; el.style.background = '#2d6a4f'; el.style.opacity = '1'; } + else { el.style.opacity = '0'; } + } + + window.addEventListener('online', function () { render(); flush(); }); + window.addEventListener('offline', render); + if (document.readyState !== 'loading') { render(); flush(); } + else document.addEventListener('DOMContentLoaded', function () { render(); flush(); }); +})(); diff --git a/static/sw.js b/static/sw.js new file mode 100644 index 0000000..af7d60e --- /dev/null +++ b/static/sw.js @@ -0,0 +1,50 @@ +// 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('/'))) + ); + } +}); diff --git a/templates/index.html b/templates/index.html index 788d29b..0bca1c8 100644 --- a/templates/index.html +++ b/templates/index.html @@ -3,6 +3,13 @@
+ + + + + + +