Compare commits

..

3 Commits

Author SHA1 Message Date
92fa8df574 Merge pull request 'worktree-citti-arkiver-tur' (#5) from worktree-citti-arkiver-tur into main
All checks were successful
Build and Deploy citti / build-and-deploy (push) Successful in 1m57s
Reviewed-on: #5
2026-10-30 12:00:31 +01:00
Henrik Jess Nielsen
66031345d2 feat(pwa): installable — PNG icons + beforeinstallprompt button
Chrome's install prompt needs 192 and 512 PNG icons (SVG-only often isn't
enough, especially on Android). Add them and reference them in the manifest
(any + maskable). offline.js captures beforeinstallprompt and shows an
'Installér app' button that triggers the native prompt, and clears it on
appinstalled. Bump SW cache to v2 so the new manifest/icons take effect.
2026-10-30 11:58:46 +01:00
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
11 changed files with 242 additions and 3 deletions

View File

@@ -26,6 +26,7 @@ RUN pip install --no-cache-dir -r requirements.txt
COPY app.py . COPY app.py .
COPY templates/ templates/ COPY templates/ templates/
COPY static/ static/
ENV DATA_DIR=/app/instance \ ENV DATA_DIR=/app/instance \
PORT=9756 \ PORT=9756 \

30
app.py
View File

@@ -646,6 +646,36 @@ def health():
return jsonify({'status': 'healthy', 'service': 'citti'}) 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']) @app.route('/api/category', methods=['POST'])
def add_category(): def add_category():
d = request.json d = request.json

BIN
static/icon-192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

BIN
static/icon-512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

9
static/icon.svg Normal file
View File

@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
<rect width="512" height="512" rx="96" fill="#c84b2f"/>
<g fill="none" stroke="#fff" stroke-width="26" stroke-linecap="round" stroke-linejoin="round">
<path d="M120 150h40l40 190h170l34-130H190"/>
<circle cx="214" cy="386" r="22" fill="#fff" stroke="none"/>
<circle cx="360" cy="386" r="22" fill="#fff" stroke="none"/>
</g>
<text x="256" y="250" font-family="DM Sans, Arial, sans-serif" font-size="150" font-weight="700" fill="#fff" text-anchor="middle">C</text>
</svg>

After

Width:  |  Height:  |  Size: 578 B

View File

@@ -0,0 +1,17 @@
{
"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": "/static/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" },
{ "src": "/static/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" },
{ "src": "/static/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" },
{ "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" }
]
}

110
static/offline.js Normal file
View File

@@ -0,0 +1,110 @@
// 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'; }
}
// ---- Install ("Add to home screen") prompt ----
var deferredPrompt = null;
function showInstall() {
if (!document.body) { document.addEventListener('DOMContentLoaded', showInstall); return; }
var b = document.getElementById('citti-install');
if (!b) {
b = document.createElement('button');
b.id = 'citti-install';
b.type = 'button';
b.textContent = '⬇ Installér app';
b.style.cssText = 'position:fixed;left:14px;bottom:14px;z-index:9999;padding:9px 15px;'
+ 'border:none;border-radius:20px;background:#1a1814;color:#fff;cursor:pointer;'
+ 'font:600 13px/1 system-ui,-apple-system,sans-serif;box-shadow:0 2px 10px rgba(0,0,0,.25)';
b.addEventListener('click', function () {
if (!deferredPrompt) return;
deferredPrompt.prompt();
deferredPrompt.userChoice.finally(function () { deferredPrompt = null; b.remove(); });
});
document.body.appendChild(b);
}
}
window.addEventListener('beforeinstallprompt', function (e) {
e.preventDefault(); // keep the event so we can trigger it from our button
deferredPrompt = e;
showInstall();
});
window.addEventListener('appinstalled', function () {
deferredPrompt = null;
var b = document.getElementById('citti-install');
if (b) b.remove();
});
window.addEventListener('online', function () { render(); flush(); });
window.addEventListener('offline', render);
if (document.readyState !== 'loading') { render(); flush(); }
else document.addEventListener('DOMContentLoaded', function () { render(); flush(); });
})();

51
static/sw.js Normal file
View File

@@ -0,0 +1,51 @@
// 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-v2';
const CORE = ['/', '/tilbud', '/koeb-nu', '/offline.js', '/manifest.webmanifest',
'/icon.svg', '/static/icon-192.png', '/static/icon-512.png'];
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('/')))
);
}
});

View File

@@ -3,6 +3,13 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#c84b2f">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="Citti">
<link rel="manifest" href="/manifest.webmanifest">
<link rel="apple-touch-icon" href="/icon.svg">
<link rel="icon" href="/icon.svg">
<script src="/offline.js" defer></script>
<title>Citti Indkøbsseddel — Uge 23-25</title> <title>Citti Indkøbsseddel — Uge 23-25</title>
<link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=DM+Sans:wght@300;400;500;600&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=DM+Sans:wght@300;400;500;600&display=swap" rel="stylesheet">
<style> <style>
@@ -502,7 +509,7 @@ function saveToServer(key, price, checked) {
const row = document.querySelector(`.item-row[data-key="${key}"]`); const row = document.querySelector(`.item-row[data-key="${key}"]`);
const qtyInput = row ? row.querySelector('.item-qty input') : null; const qtyInput = row ? row.querySelector('.item-qty input') : null;
const qty = qtyInput ? qtyInput.value.trim() || null : null; const qty = qtyInput ? qtyInput.value.trim() || null : null;
fetch('/api/price', { (window.cittiFetch || fetch)('/api/price', {
method: 'POST', method: 'POST',
headers: {'Content-Type':'application/json'}, headers: {'Content-Type':'application/json'},
body: JSON.stringify({key, price, checked, qty}) body: JSON.stringify({key, price, checked, qty})
@@ -680,7 +687,7 @@ function toggleOffer(cb) {
} }
async function removeOffer(id) { async function removeOffer(id) {
await fetch('/api/offers/pick', { await (window.cittiFetch || fetch)('/api/offers/pick', {
method: 'POST', method: 'POST',
headers: {'Content-Type':'application/json'}, headers: {'Content-Type':'application/json'},
body: JSON.stringify({id, picked: false}) body: JSON.stringify({id, picked: false})

View File

@@ -3,6 +3,13 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#c84b2f">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="Citti">
<link rel="manifest" href="/manifest.webmanifest">
<link rel="apple-touch-icon" href="/icon.svg">
<link rel="icon" href="/icon.svg">
<script src="/offline.js" defer></script>
<title>Citti · Køb nu</title> <title>Citti · Køb nu</title>
<link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=DM+Sans:wght@300;400;500;600&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=DM+Sans:wght@300;400;500;600&display=swap" rel="stylesheet">
<style> <style>

View File

@@ -3,6 +3,13 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#c84b2f">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="Citti">
<link rel="manifest" href="/manifest.webmanifest">
<link rel="apple-touch-icon" href="/icon.svg">
<link rel="icon" href="/icon.svg">
<script src="/offline.js" defer></script>
<title>Citti Tilbud — Lübeck</title> <title>Citti Tilbud — Lübeck</title>
<link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=DM+Sans:wght@300;400;500;600&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=DM+Sans:wght@300;400;500;600&display=swap" rel="stylesheet">
<style> <style>
@@ -119,7 +126,7 @@ async function togglePick(cb, id) {
pickCount += picked ? 1 : -1; pickCount += picked ? 1 : -1;
document.getElementById('pick-count').textContent = pickCount + ' på seddel'; document.getElementById('pick-count').textContent = pickCount + ' på seddel';
try { try {
await fetch('/api/offers/pick', { await (window.cittiFetch || fetch)('/api/offers/pick', {
method: 'POST', method: 'POST',
headers: {'Content-Type':'application/json'}, headers: {'Content-Type':'application/json'},
body: JSON.stringify({id, picked}) body: JSON.stringify({id, picked})