diff --git a/VERSION b/VERSION index 1fdcf1c..fb9a769 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1228 \ No newline at end of file +1233 \ No newline at end of file diff --git a/backend/static/css/components.css b/backend/static/css/components.css index 5b2a7dd..ce50752 100644 --- a/backend/static/css/components.css +++ b/backend/static/css/components.css @@ -7307,12 +7307,26 @@ svg.empty-state-icon { pointer-events: none; letter-spacing: 0.01em; } -/* Eingeklappt (5s nach Offline-Gang, boot.js): schmale Icon-Leiste statt 2-Zeilen-Banner — - das volle Banner verdeckte die Karten-Steuerung oben (Gerätetest iOS 2026-06-06). */ +/* Eingeklappt (5s nach Offline-Gang, boot.js): kleines pulsierendes Icon LINKS unterhalb + der Karten-Zoom-Regler (+/−) — rechts verdeckte es die Legenden-Chips, die volle Leiste + davor Nav-Elemente (Gerätetests René 2026-06-07/08). */ #offline-banner.collapsed { - padding: calc(env(safe-area-inset-top, 0px) + 2px) 16px 2px; + top: calc(env(safe-area-inset-top, 0px) + 110px); + left: 10px; + right: auto; + width: 32px; + height: 32px; + padding: 0; + border-radius: 50%; + box-shadow: 0 2px 10px rgba(0,0,0,.35); + animation: by-offline-pulse 2s ease-in-out infinite; +} +#offline-banner.collapsed #offline-banner-text { display: none; } +#offline-banner.collapsed #offline-queue-badge { display: none !important; } +@keyframes by-offline-pulse { + 0%, 100% { opacity: 0.55; transform: scale(1); } + 50% { opacity: 1; transform: scale(1.1); } } -#offline-banner.collapsed #offline-banner-text { display: none; } /* ------------------------------------------------------------ STREAK-WIDGET (Welcome-Seite) diff --git a/backend/static/index.html b/backend/static/index.html index ab2e972..3b4a4bc 100644 --- a/backend/static/index.html +++ b/backend/static/index.html @@ -86,14 +86,14 @@ Ban Yaro - + - - - - - + + + + + @@ -612,11 +612,11 @@ - - - - - + + + + + @@ -626,7 +626,7 @@ - + diff --git a/backend/static/js/app.js b/backend/static/js/app.js index 468016a..513603f 100644 --- a/backend/static/js/app.js +++ b/backend/static/js/app.js @@ -3,7 +3,7 @@ Router, State-Management, Navigation, Initialisierung. ============================================================ */ -const APP_VER = '1228'; // ← bei jedem Deploy mit Frontend-Änderungen erhöhen +const APP_VER = '1233'; // ← bei jedem Deploy mit Frontend-Änderungen erhöhen const APP_VERSION = '1.6.0'; // ← semantische Version, wird bei make release gesetzt window.APP_VER = APP_VER; // global verfügbar für andere Module (z.B. offline-indicator) window.APP_VERSION = APP_VERSION; diff --git a/backend/static/js/map-offline.js b/backend/static/js/map-offline.js index 127c286..6d481a0 100644 --- a/backend/static/js/map-offline.js +++ b/backend/static/js/map-offline.js @@ -37,6 +37,7 @@ window.MapOffline = (function () { } var _get = function (k) { return _req(STORE, 'readonly', function (os) { return os.get(k); }); }; var _put = function (k, v) { return _req(STORE, 'readwrite', function (os) { os.put(v, k); }); }; + var _del = function (k) { return _req(STORE, 'readwrite', function (os) { os.delete(k); }); }; var _count = function () { return _req(STORE, 'readonly', function (os) { return os.count(); }); }; var _metaGet = function (k) { return _req(META, 'readonly', function (os) { return os.get(k); }); }; var _metaPut = function (k, v) { return _req(META, 'readwrite', function (os) { os.put(v, k); }); }; @@ -127,17 +128,25 @@ window.MapOffline = (function () { 'restaurant', 'bank', 'giftkoeder', 'kotbeutel', 'gefahr', 'parkplatz', 'treffpunkt', 'sonstiges', 'hotel']; - // Frische Liste mit Bestand mergen (per id) — eine zweite Region (Urlaubsort) darf die erste - // nicht löschen. Liefert die Anzahl frischer Einträge. - function _mergeStore(key, fresh) { - if (!fresh || !fresh.length) return Promise.resolve(0); + // Frische Liste mit Bestand mergen (per id) — eine zweite Region (Urlaubsort) darf die + // erste nicht löschen. WICHTIG für Warnungen (René 2026-06-08): Die Server-Antwort ist + // für die geladene Bbox AUTORITATIV — Bestands-Einträge INNERHALB der Bbox, die nicht + // mehr geliefert werden (aufgehobener Giftköder, gefundener Hund, wegen Meldungen + // ausgeblendeter Marker), werden ENTFERNT. fresh == null (Fetch fehlgeschlagen) merged + // NIE — sonst würde ein Offline-Refresh den Bestand wegputzen. + function _mergeStore(key, fresh, bbox) { + if (fresh == null) return Promise.resolve(0); return _get(key).then(function (old) { - var merged = fresh; - if (old && old.length) { - var seen = {}; - fresh.forEach(function (p) { seen[p.id] = true; }); - merged = fresh.concat(old.filter(function (p) { return !seen[p.id]; })); - } + var seen = {}; + fresh.forEach(function (p) { seen[p.id] = true; }); + var keep = (old || []).filter(function (p) { + if (seen[p.id]) return false; + if (bbox && p.lat >= bbox.south && p.lat <= bbox.north && + p.lon >= bbox.west && p.lon <= bbox.east) return false; // in Bbox, nicht mehr da → weg + return true; + }); + var merged = fresh.concat(keep); + if (!merged.length && !(old && old.length)) return 0; return _put(key, merged).then(function () { return fresh.length; }); }); } @@ -149,31 +158,53 @@ window.MapOffline = (function () { south: bbox.south, west: bbox.west, north: bbox.north, east: bbox.east }); return fetch('/api/osm/pois?' + params) .then(function (r) { return r.ok ? r.json() : null; }) - .then(function (fresh) { return _mergeStore('p/' + type, fresh); }) + .then(function (fresh) { return _mergeStore('p/' + type, fresh, bbox); }) .then(function (n) { total += n; }) .catch(function () {}); }); // Sicherheitsdaten MÜSSEN offline da sein (René 2026-06-07): Giftköder-Alarme // (/api/poison, Radius in m) + vermisste Hunde (/api/lost, Radius in km) — beide anonym. + // Fetch-Radius ×√2: der Kreis muss die Bbox-ECKEN abdecken, sonst räumt der + // Bbox-Replace in _mergeStore dort fälschlich Bestand weg. var midLat = (bbox.south + bbox.north) / 2, midLon = (bbox.west + bbox.east) / 2; var radiusKm = Math.max( (bbox.north - bbox.south) * 111 / 2, (bbox.east - bbox.west) * 111 * Math.cos(midLat * Math.PI / 180) / 2, 1); - jobs.push(fetch('/api/poison?lat=' + midLat + '&lon=' + midLon + '&radius=' + Math.round(radiusKm * 1000)) + jobs.push(fetch('/api/poison?lat=' + midLat + '&lon=' + midLon + '&radius=' + Math.round(radiusKm * 1415)) .then(function (r) { return r.ok ? r.json() : null; }) - .then(function (fresh) { return _mergeStore('p/_poison', fresh); }) + .then(function (fresh) { return _mergeStore('p/_poison', fresh, bbox); }) .then(function (n) { total += n; }) .catch(function () {})); - jobs.push(fetch('/api/lost?lat=' + midLat + '&lon=' + midLon + '&radius_km=' + Math.ceil(radiusKm)) + jobs.push(fetch('/api/lost?lat=' + midLat + '&lon=' + midLon + '&radius_km=' + Math.ceil(radiusKm * 1.42)) .then(function (r) { return r.ok ? r.json() : null; }) - .then(function (fresh) { return _mergeStore('p/_lost', fresh); }) + .then(function (fresh) { return _mergeStore('p/_lost', fresh, bbox); }) .then(function (n) { total += n; }) .catch(function () {})); return Promise.all(jobs).then(function () { return total; }); } + // Warnungen aktuell halten (René 2026-06-08: Giftköder können aufgehoben, Hunde gefunden + // sein): max. alle 24 h den 50-km-Umkreis der Position frisch laden — der Bbox-Replace + // in _mergeStore räumt Aufgehobenes weg. Bbox (~35 km Halbseite) liegt IM Fetch-Kreis. + function _refreshAlerts(lat, lon) { + return _metaGet('alertsTs').then(function (ts) { + if (ts && Date.now() - ts < 86400000) return; + var bb = { south: lat - 0.31, north: lat + 0.31, west: lon - 0.47, east: lon + 0.47 }; + return Promise.all([ + fetch('/api/poison?lat=' + lat + '&lon=' + lon + '&radius=50000') + .then(function (r) { return r.ok ? r.json() : null; }) + .then(function (f) { return _mergeStore('p/_poison', f, bb); }) + .catch(function () {}), + fetch('/api/lost?lat=' + lat + '&lon=' + lon + '&radius_km=50') + .then(function (r) { return r.ok ? r.json() : null; }) + .then(function (f) { return _mergeStore('p/_lost', f, bb); }) + .catch(function () {}), + ]).then(function () { return _metaPut('alertsTs', Date.now()); }); + }).catch(function () {}); + } + // Gespeicherte Sicherheits-Alarme ('poison' | 'lost') im Bbox-Ausschnitt — Offline-Fallback. function alerts(kind, bbox) { return _get('p/_' + kind).then(function (list) { @@ -216,9 +247,12 @@ window.MapOffline = (function () { } // Gespeichertes Gebiet in der Regions-Liste verbuchen ('region' = letztes, Back-Compat). + // Gleicher Typ + Name (z.B. Korridor derselben Route erneut geladen) ersetzt den Alt-Eintrag. function _addRegion(region) { return _metaGet('regions').then(function (list) { - list = list || []; + list = (list || []).filter(function (r) { + return !(region.name && r.type === region.type && r.name === region.name); + }); list.push(region); if (list.length > 30) list = list.slice(-30); return _metaPut('regions', list); @@ -234,6 +268,7 @@ window.MapOffline = (function () { function downloadAround(lat, lon, opts) { if (typeof opts === 'number') opts = {}; // alte Signatur (lat, lon, radiusKm) → Default-Budget opts = opts || {}; + _persistStorage(); var budget = (opts.budgetMB || 5) * 1048576; var maxKm = opts.maxRadiusKm || 25; var cx = _x(lon, MAXZOOM), cy = _y(lat, MAXZOOM); @@ -290,9 +325,10 @@ window.MapOffline = (function () { .then(function (gb) { state.bytes += gb; return _cachePois(_bboxAround(lat, lon, radiusKm)); }) .then(function (pc) { poiCount = pc; - return _addRegion({ lat: lat, lon: lon, radiusKm: radiusKm, tiles: state.stored, - bytes: state.bytes, pois: poiCount, savedAt: Date.now() }); + return _addRegion({ type: opts.type || 'gebiet', lat: lat, lon: lon, radiusKm: radiusKm, + tiles: state.stored, bytes: state.bytes, pois: poiCount, savedAt: Date.now() }); }) + .then(function () { return _bumpTotal(state.bytes); }) .then(function () { return { tiles: state.stored, bytes: state.bytes, pois: poiCount, radiusKm: radiusKm }; }); } @@ -301,7 +337,117 @@ window.MapOffline = (function () { // wird nie hochgeladen. Signal = echte Tile-Fetch-Fehler bei aktivem GPS // (NICHT navigator.onLine — das lügt bei Captive-Portal/Schwachempfang). var _gps = null, _lastZoneNote = 0; - function setGps(pos) { _gps = pos; } // {lat,lon} während aktiver Aufzeichnung, sonst null + + // ---- Speicher-Cap (Soft-Guard für die AUTOMATISCHEN Pfade) ------------------- + // Manuelle Downloads bleiben immer möglich; Vorausladen + Funkloch-Autofill stoppen + // über dem Cap. totalBytes wird bei jedem Download mitgezählt; clear() setzt zurück. + var CAP_MB = 250; + function _bumpTotal(bytes) { + if (!bytes) return Promise.resolve(); + return _metaGet('totalBytes') + .then(function (t) { return _metaPut('totalBytes', Math.max(0, (t || 0) + bytes)); }) + .catch(function () {}); + } + function _overCap() { + return _metaGet('totalBytes') + .then(function (t) { return (t || 0) > CAP_MB * 1048576; }) + .catch(function () { return false; }); + } + + // Persistenten Speicher anfragen (best-effort, idempotent) — härtet IndexedDB gegen + // Eviction bei Speicherdruck. Safari/iOS ignoriert es teils, schadet aber nicht. + function _persistStorage() { + if (_persistStorage._done) return; + _persistStorage._done = true; + try { + if (navigator.storage && navigator.storage.persist) navigator.storage.persist().catch(function () {}); + } catch (e) {} + } + + // {lat,lon} während aktiver Aufzeichnung, sonst null. Nebeneffekte (Runde 3): + // 1. ROLLENDES VORAUSLADEN — solange Empfang da ist, alle ~400 m die fehlenden Kacheln + // um die aktuelle Position still mitnehmen. EPHEMER: Hatte die Runde KEIN Funkloch, + // wird das Vorausgeladene am Ende wieder gelöscht — gespeichert bleibt nur, was + // wegen fehlenden Netzes nötig ist + manuell Hinzugefügtes (Modell René 2026-06-08). + // 2. NETZ-PROBE — erkennt Funklöcher auch in BEREITS GESPEICHERTEN Gebieten (dort + // kommen Kacheln aus IndexedDB → kein Remote-Miss als Signal). + var _lastPre = null, _preActive = false; + var _preKeys = [], _preBytes = 0, _recHadDeadzone = false; + function setGps(pos) { + if (!pos) { // Aufzeichnung beendet + _gps = null; _lastPre = null; + _prunePrefetch(); + return; + } + _gps = pos; + _probeNet(pos); + if (_preActive || !navigator.onLine) return; + if (_lastPre && _distKm(_lastPre.lat, _lastPre.lon, pos.lat, pos.lon) < 0.4) return; + _preActive = true; + var p = { lat: pos.lat, lon: pos.lon }; + _overCap().then(function (over) { + if (over) return; + return _prefetchRing(p.lat, p.lon, 2).then(function () { _lastPre = p; }); + }).catch(function () {}) + .then(function () { _preActive = false; }); + } + + // Aktive Netz-Probe (alle ~2 Min bei Aufzeichnung): kleiner Request mit Timeout. + // Fehlschlag = Funkloch an dieser Position — unabhängig davon, ob die Kacheln + // hier längst lokal liegen. (navigator.onLine lügt bei Schwachempfang.) + var _lastProbe = 0; + function _probeNet(pos) { + var now = Date.now(); + if (now - _lastProbe < 120000) return; + _lastProbe = now; + var p = { lat: pos.lat, lon: pos.lon }; + var ctrl = (typeof AbortController !== 'undefined') ? new AbortController() : null; + var timer = ctrl && setTimeout(function () { try { ctrl.abort(); } catch (e) {} }, 6000); + fetch('/api/version', { cache: 'no-store', signal: ctrl ? ctrl.signal : undefined }) + .then(function (r) { if (!r.ok) throw new Error('probe ' + r.status); }) + .catch(function () { + _recHadDeadzone = true; + markDeadZone(p.lat, p.lon); + }) + .then(function () { if (timer) clearTimeout(timer); }); + } + + // Vorausgeladenes wieder entfernen, wenn die Runde KEIN Funkloch hatte. + function _prunePrefetch() { + var keys = _preKeys, bytes = _preBytes, had = _recHadDeadzone; + _preKeys = []; _preBytes = 0; _recHadDeadzone = false; + if (had || !keys.length) return Promise.resolve(); + var chain = Promise.resolve(); + keys.forEach(function (k) { chain = chain.then(function () { return _del(k).catch(function () {}); }); }); + return chain.then(function () { return _bumpTotal(-bytes); }); + } + + // z14-Kacheln ±n um lat/lon (+ Eltern z10–13) — NUR fehlende, still, ohne Region-Eintrag. + function _prefetchRing(lat, lon, n) { + var cx = _x(lon, MAXZOOM), cy = _y(lat, MAXZOOM), seen = {}, list = []; + for (var x = cx - n; x <= cx + n; x++) for (var y = cy - n; y <= cy + n; y++) { + list.push([MAXZOOM, x, y]); + for (var pz = 13; pz >= 10; pz--) { + var px = x >> (MAXZOOM - pz), py = y >> (MAXZOOM - pz), k = pz + '/' + px + '/' + py; + if (!seen[k]) { seen[k] = 1; list.push([pz, px, py]); } + } + } + var missing = [], chain = Promise.resolve(); + list.forEach(function (t) { + chain = chain.then(function () { + return _get(t[0] + '/' + t[1] + '/' + t[2]).then(function (hit) { if (!hit) missing.push(t); }); + }); + }); + var state = { done: 0, bytes: 0, stored: 0 }; + return chain + .then(function () { return missing.length ? _fetchTiles(missing, state, null) : null; }) + .then(function () { + // Nur NEU gespeicherte Keys fürs Prune merken — Bestand bleibt unangetastet. + missing.forEach(function (t) { _preKeys.push(t[0] + '/' + t[1] + '/' + t[2]); }); + _preBytes += state.bytes; + return _bumpTotal(state.bytes); + }); + } function _distKm(aLat, aLon, bLat, bLon) { var dLat = (bLat - aLat) * 111, dLon = (bLon - aLon) * 111 * Math.cos(aLat * Math.PI / 180); @@ -310,12 +456,22 @@ window.MapOffline = (function () { function _noteRemoteMiss() { if (!_gps) return; + _recHadDeadzone = true; // Vorausgeladenes dieser Runde behalten var now = Date.now(); if (now - _lastZoneNote < 120000) return; // max. 1 Eintrag / 2 Min _lastZoneNote = now; markDeadZone(_gps.lat, _gps.lon); } + // Zone manuell „ent-funklochen" (✕ im Offline-Modal): wird nicht mehr automatisch + // geladen; bereits geladene Kacheln bleiben bis „Alles löschen"/Eviction. + function removeDeadZone(ts) { + return _metaGet('deadzones').then(function (zones) { + zones = (zones || []).filter(function (z) { return z.ts !== ts; }); + return _metaPut('deadzones', zones).then(function () { return zones.length; }); + }); + } + // Funkloch merken (Dedupe: keine zweite Zone im Umkreis von 2 km, Cap 50). function markDeadZone(lat, lon) { return _metaGet('deadzones').then(function (zones) { @@ -327,28 +483,64 @@ window.MapOffline = (function () { }).catch(function () {}); } - // Offene Funkloch-Zonen budget-getrieben nachladen (nur online sinnvoll). - // Dort wo Netz verfügbar ist, braucht man keine Offline-Karten — gespeichert - // wird gezielt da, wo es ausfiel. Liefert die Anzahl gefüllter Zonen. + // Funkloch-Zonen nachladen (nur online sinnvoll). Dort wo Netz verfügbar ist, braucht + // man keine Offline-Karten — gespeichert wird gezielt da, wo es ausfiel. + // opts {lat, lon, maxKm:50}: mit Position werden nur Zonen im Umkreis betrachtet + // (Speicher minimal halten) und nächstgelegene zuerst geladen. Gefüllte Zonen werden + // VERIFIZIERT (Zentrums-Kachel noch da?) — fängt „Alles löschen" und iOS-Eviction ab: + // die Gebiete kommen beim nächsten Start automatisch wieder (Modell René 2026-06-08). + // Liefert die Anzahl (neu) gefüllter Zonen. var _autofillActive = false; - function autoFillDeadZones() { + function autoFillDeadZones(opts) { + opts = opts || {}; + var maxKm = opts.maxKm || 50; if (_autofillActive || !navigator.onLine) return Promise.resolve(0); _autofillActive = true; - var filled = 0; - return _metaGet('deadzones').then(function (zones) { - zones = zones || []; - var open = zones.filter(function (z) { return !z.filled; }); - if (!open.length) return 0; - var chain = Promise.resolve(); - open.forEach(function (z) { - chain = chain.then(function () { - return downloadAround(z.lat, z.lon, { budgetMB: 5 }).then(function (res) { - if (res.bytes > 0) { z.filled = true; filled++; } - }).catch(function () {}); + var filled = 0, all = null; + return _overCap().then(function (over) { + if (over) return null; // Speicher-Cap erreicht → kein automatisches Nachladen mehr + return _metaGet('deadzones'); + }).then(function (zones) { + if (zones === null) return 0; // expliziter Cap-Abbruch (s.o.) + zones = zones || []; // keine Zonen → trotzdem Warnungs-Refresh unten + all = zones; + var cand = opts.lat == null ? zones.slice() : zones.filter(function (z) { + return _distKm(z.lat, z.lon, opts.lat, opts.lon) <= maxKm; + }); + if (!cand.length) { + // Keine Zonen in der Nähe — Warnungen trotzdem frisch halten (24-h-Takt). + if (opts.lat != null) return _refreshAlerts(opts.lat, opts.lon).then(function () { return 0; }); + return 0; + } + // Verify: als gefüllt markierte Zonen ohne lokale Zentrums-Kachel wieder öffnen. + var verify = Promise.resolve(); + cand.forEach(function (z) { + verify = verify.then(function () { + if (!z.filled) return; + return _get(MAXZOOM + '/' + _x(z.lon, MAXZOOM) + '/' + _y(z.lat, MAXZOOM)) + .then(function (hit) { if (!hit) z.filled = false; }); }); }); - return chain.then(function () { return _metaPut('deadzones', zones); }) - .then(function () { return filled; }); + return verify.then(function () { + var open = cand.filter(function (z) { return !z.filled; }); + if (opts.lat != null) open.sort(function (a, b) { + return _distKm(a.lat, a.lon, opts.lat, opts.lon) - _distKm(b.lat, b.lon, opts.lat, opts.lon); + }); + var chain = Promise.resolve(); + open.forEach(function (z) { + chain = chain.then(function () { + return downloadAround(z.lat, z.lon, { budgetMB: 5, type: 'funkloch' }).then(function (res) { + if (res.bytes > 0) { z.filled = true; filled++; } + }).catch(function () {}); + }); + }); + return chain.then(function () { return _metaPut('deadzones', all); }) + .then(function () { + // Warnungen im Umkreis frisch halten (24-h-Takt, Bbox-Replace). + if (opts.lat != null) return _refreshAlerts(opts.lat, opts.lon); + }) + .then(function () { return filled; }); + }); }).then(function (n) { _autofillActive = false; return n; }, function () { _autofillActive = false; return 0; }); } @@ -360,6 +552,7 @@ window.MapOffline = (function () { function downloadCorridor(track, opts) { opts = opts || {}; if (!track || track.length < 2) return Promise.reject(new Error('Kein GPS-Track')); + _persistStorage(); var buffer = opts.bufferKm || 1, cap = (opts.capMB || 50) * 1048576; var seen = {}, list = []; var push = function (z, x, y) { @@ -403,51 +596,166 @@ window.MapOffline = (function () { return _addRegion({ type: 'korridor', name: opts.name || null, lat: track[0].lat, lon: track[0].lon, tiles: state.stored, bytes: state.bytes, pois: poiCount, savedAt: Date.now() }); }) + .then(function () { return _bumpTotal(state.bytes); }) + .then(function () { return { tiles: state.stored, bytes: state.bytes, pois: poiCount, capped: state.bytes >= cap }; }); + } + + // Gespeicherte Routen offline nutzbar halten (René 2026-06-08): beim Start die Korridore + // der eigenen Routen in Positionsnähe sicherstellen — Stichproben-Kacheln prüfen, bei + // Lücken Korridor (neu) laden. Deckt „Alles löschen" + Eviction ab; preview_track + // (~40 Punkte) reicht, der ±1-km-Puffer schluckt die Vereinfachung. Automatischer Pfad → Cap. + var _ensureActive = false; + function ensureRouteCorridors(routes, opts) { + opts = opts || {}; + var maxKm = opts.maxKm || 50; + if (_ensureActive || !navigator.onLine) return Promise.resolve(0); + _ensureActive = true; + var done = 0; + return _overCap().then(function (over) { + if (over) return 0; + var cand = (routes || []).filter(function (r) { + var t = r.preview_track || r.gps_track; + if (!t || t.length < 2) return false; + if (opts.lat == null) return true; + return _distKm(t[0].lat, t[0].lon, opts.lat, opts.lon) <= maxKm; + }); + var chain = Promise.resolve(); + cand.forEach(function (r) { + chain = chain.then(function () { + var t = r.preview_track || r.gps_track; + var idxs = [0, Math.floor(t.length / 4), Math.floor(t.length / 2), + Math.floor(3 * t.length / 4), t.length - 1]; + var missing = false, v = Promise.resolve(); + idxs.forEach(function (i) { + v = v.then(function () { + if (missing) return; + var p = t[i]; + return _get(MAXZOOM + '/' + _x(p.lon, MAXZOOM) + '/' + _y(p.lat, MAXZOOM)) + .then(function (hit) { if (!hit) missing = true; }); + }); + }); + return v.then(function () { + if (!missing) return; + return downloadCorridor(t, { bufferKm: 1, name: r.name || ('route-' + r.id) }) + .then(function (res) { if (res.bytes > 0) done++; }) + .catch(function () {}); + }); + }); + }); + return chain.then(function () { return done; }); + }).then(function (n) { _ensureActive = false; return n; }, + function () { _ensureActive = false; return 0; }); + } + + // ---- Bereichsauswahl: sichtbaren Karten-Ausschnitt komplett speichern --------- + // bbox = {south,west,north,east} (z.B. aktueller Viewport). Zu-groß-Schutz über + // Kachelzahl, Abbruch-Cap über capMB. opts {capMB:40, name, onProgress({bytes,done,total})}. + function downloadBbox(bbox, opts) { + opts = opts || {}; + _persistStorage(); + var cap = (opts.capMB || 40) * 1048576; + var seen = {}, list = []; + var push = function (z, x, y) { + if (x < 0 || y < 0 || x >= Math.pow(2, z) || y >= Math.pow(2, z)) return; + var k = z + '/' + x + '/' + y; + if (!seen[k]) { seen[k] = 1; list.push([z, x, y]); } + }; + for (var z = 0; z <= MAXZOOM; z++) { + var x0 = _x(bbox.west, z), x1 = _x(bbox.east, z), y0 = _y(bbox.north, z), y1 = _y(bbox.south, z); + if (z === MAXZOOM && (x1 - x0 + 1) * (y1 - y0 + 1) > 4000) { + return Promise.reject(new Error('Bereich zu groß — bitte weiter reinzoomen.')); + } + for (var x = x0; x <= x1; x++) for (var y = y0; y <= y1; y++) push(z, x, y); + } + var state = { done: 0, bytes: 0, stored: 0 }, total = list.length, poiCount = 0; + function chunkLoop(idx) { + if (idx >= list.length || state.bytes >= cap) return Promise.resolve(); + return _fetchTiles(list.slice(idx, idx + 64), state, function () { + if (opts.onProgress) opts.onProgress({ bytes: state.bytes, done: state.done, total: total }); + }).then(function () { return chunkLoop(idx + 64); }); + } + var midLat = (bbox.south + bbox.north) / 2, midLon = (bbox.west + bbox.east) / 2; + return chunkLoop(0) + .then(function () { return _cacheGlyphs(); }) + .then(function (gb) { state.bytes += gb; return _cachePois(bbox); }) + .then(function (pc) { + poiCount = pc; + return _addRegion({ type: 'ausschnitt', name: opts.name || null, lat: midLat, lon: midLon, + tiles: state.stored, bytes: state.bytes, pois: poiCount, savedAt: Date.now() }); + }) + .then(function () { return _bumpTotal(state.bytes); }) .then(function () { return { tiles: state.stored, bytes: state.bytes, pois: poiCount, capped: state.bytes >= cap }; }); } // ---- Coverage-Layer ---------------------------------------------------------- - // GeoJSON der gespeicherten z14-Kacheln — zeigt auf der Karte, welche Bereiche offline da sind. + // GeoJSON der gespeicherten z14-Kacheln — zeigt auf der Karte, welche Bereiche offline + // da sind. properties.kind: 'funkloch' (Kachel liegt in einer Funkloch-Region, wird + // anders eingefärbt — Wunsch René 2026-06-08) oder 'manuell'. function _tile2lat(y, z) { var m = Math.PI - 2 * Math.PI * y / Math.pow(2, z); return 180 / Math.PI * Math.atan(0.5 * (Math.exp(m) - Math.exp(-m))); } function coverage() { var re = new RegExp('^' + MAXZOOM + '/(\\d+)/(\\d+)$'); - return _req(STORE, 'readonly', function (os) { return os.getAllKeys(); }).then(function (keys) { - var feats = []; - (keys || []).forEach(function (k) { - var m = re.exec(k); - if (!m) return; - var x = +m[1], y = +m[2], n2 = Math.pow(2, MAXZOOM); - var west = x / n2 * 360 - 180, east = (x + 1) / n2 * 360 - 180; - var north = _tile2lat(y, MAXZOOM), south = _tile2lat(y + 1, MAXZOOM); - feats.push({ type: 'Feature', properties: {}, geometry: { type: 'Polygon', - coordinates: [[[west, south], [east, south], [east, north], [west, north], [west, south]]] } }); + return _metaGet('regions').then(function (regions) { + var fz = (regions || []).filter(function (r) { return r.type === 'funkloch'; }); + return _req(STORE, 'readonly', function (os) { return os.getAllKeys(); }).then(function (keys) { + var feats = []; + (keys || []).forEach(function (k) { + var m = re.exec(k); + if (!m) return; + var x = +m[1], y = +m[2], n2 = Math.pow(2, MAXZOOM); + var west = x / n2 * 360 - 180, east = (x + 1) / n2 * 360 - 180; + var north = _tile2lat(y, MAXZOOM), south = _tile2lat(y + 1, MAXZOOM); + var cLat = (north + south) / 2, cLon = (west + east) / 2; + var isFz = fz.some(function (r) { + return _distKm(r.lat, r.lon, cLat, cLon) <= (r.radiusKm || 5) + 0.8; + }); + feats.push({ type: 'Feature', properties: { kind: isFz ? 'funkloch' : 'manuell' }, + geometry: { type: 'Polygon', + coordinates: [[[west, south], [east, south], [east, north], [west, north], [west, south]]] } }); + }); + return { type: 'FeatureCollection', features: feats }; }); - return { type: 'FeatureCollection', features: feats }; }); } function stats() { return _count().then(function (count) { return _metaGet('regions').then(function (regions) { - return _metaGet('region').then(function (meta) { - return { count: count, meta: meta || null, regions: regions || [] }; + return _metaGet('totalBytes').then(function (totalBytes) { + return _metaGet('deadzones').then(function (deadzones) { + return _metaGet('region').then(function (meta) { + return { count: count, meta: meta || null, regions: regions || [], + totalBytes: totalBytes || 0, deadzones: deadzones || [] }; + }); + }); }); }); }); } function hasRegion() { return stats().then(function (s) { return s.count > 0; }).catch(function () { return false; }); } + // „Alles löschen" entfernt Kacheln/Marker/Regionen — das FUNKLOCH-GEDÄCHTNIS bleibt + // (Quelle der Wahrheit, Modell René 2026-06-08): Zonen werden auf filled:false gesetzt + // und beim nächsten Online-Start in Positionsnähe automatisch neu geladen. function clear() { return _req(STORE, 'readwrite', function (os) { os.clear(); }) - .then(function () { return _req(META, 'readwrite', function (os) { os.clear(); }); }); + .then(function () { return _metaGet('deadzones'); }) + .then(function (zones) { + return _req(META, 'readwrite', function (os) { os.clear(); }).then(function () { + if (zones && zones.length) { + zones.forEach(function (z) { z.filled = false; }); + return _metaPut('deadzones', zones); + } + }); + }); } return { registerProtocol: registerProtocol, downloadAround: downloadAround, downloadCorridor: downloadCorridor, + downloadBbox: downloadBbox, ensureRouteCorridors: ensureRouteCorridors, tile: tile, glyph: glyph, pois: pois, alerts: alerts, coverage: coverage, - setGps: setGps, markDeadZone: markDeadZone, autoFillDeadZones: autoFillDeadZones, + setGps: setGps, markDeadZone: markDeadZone, removeDeadZone: removeDeadZone, autoFillDeadZones: autoFillDeadZones, stats: stats, hasRegion: hasRegion, clear: clear, MAXZOOM: MAXZOOM, }; })(); diff --git a/backend/static/js/offline-indicator.js b/backend/static/js/offline-indicator.js index cb6bf6e..be73fe1 100644 --- a/backend/static/js/offline-indicator.js +++ b/backend/static/js/offline-indicator.js @@ -25,9 +25,11 @@ window.OfflineIndicator = (() => { function _offlineTilesMode() { try { return !!(window.BY && BY.offlineTiles()); } catch (e) { return false; } } - // Ist eine Offline-Region (Vektorkacheln) in IndexedDB gespeichert? (ohne MapOffline zu laden) - // WICHTIG: dasselbe Schema/Version wie map-offline.js anlegen — sonst legt ein versionsloses open() - // die DB leer an und MapOffline kann seine Stores nicht mehr erstellen. + // Offline-Ready (Pfote Segment 5) — ohne MapOffline/GL-Stack zu laden. + // Semantik (Modell René 2026-06-08): Gibt es bekannte FUNKLOCH-Zonen, zählt deren + // Füllstand (alle gefüllt = grün); ohne bekannte Zonen wie bisher: irgendein Gebiet da. + // WICHTIG: dasselbe Schema/Version wie map-offline.js anlegen — sonst legt ein versionsloses + // open() die DB leer an und MapOffline kann seine Stores nicht mehr erstellen. function _offlineRegionStored() { return new Promise(res => { try { @@ -39,10 +41,18 @@ window.OfflineIndicator = (() => { }; r.onsuccess = () => { const db = r.result; - if (!db.objectStoreNames.contains('tiles')) { db.close(); return res(false); } - const cnt = db.transaction('tiles', 'readonly').objectStore('tiles').count(); - cnt.onsuccess = () => { res(cnt.result > 0); db.close(); }; - cnt.onerror = () => { res(false); db.close(); }; + if (!db.objectStoreNames.contains('tiles') || !db.objectStoreNames.contains('meta')) { + db.close(); return res(false); + } + const mz = db.transaction('meta', 'readonly').objectStore('meta').get('deadzones'); + mz.onsuccess = () => { + const zones = mz.result || []; + if (zones.length) { res(zones.every(z => z.filled)); db.close(); return; } + const cnt = db.transaction('tiles', 'readonly').objectStore('tiles').count(); + cnt.onsuccess = () => { res(cnt.result > 0); db.close(); }; + cnt.onerror = () => { res(false); db.close(); }; + }; + mz.onerror = () => { res(false); db.close(); }; }; r.onerror = () => res(false); } catch (e) { res(false); } @@ -224,9 +234,10 @@ window.OfflineIndicator = (() => { } catch (e) { console.warn('Offline-Region-Download fehlgeschlagen:', e); } } - // Gibt es offene (ungefüllte) Funkloch-Zonen? — direkt aus IndexedDB, OHNE den - // GL-Stack zu laden (gleiches Schema/Version wie map-offline.js, s. Warnung oben). - function _openDeadZonesStored() { + // Gibt es überhaupt Funkloch-Zonen? — direkt aus IndexedDB, OHNE den GL-Stack zu + // laden. Auch GEFÜLLTE zählen: der Start-Check verifiziert deren Kacheln (nach + // „Alles löschen"/Eviction werden sie automatisch neu geladen, Modell René 2026-06-08). + function _anyDeadZonesStored() { return new Promise(res => { try { const r = indexedDB.open('by-offline-tiles', 1); @@ -239,7 +250,7 @@ window.OfflineIndicator = (() => { const db = r.result; if (!db.objectStoreNames.contains('meta')) { db.close(); return res(false); } const rq = db.transaction('meta', 'readonly').objectStore('meta').get('deadzones'); - rq.onsuccess = () => { res((rq.result || []).some(z => !z.filled)); db.close(); }; + rq.onsuccess = () => { res((rq.result || []).length > 0); db.close(); }; rq.onerror = () => { res(false); db.close(); }; }; r.onerror = () => res(false); @@ -247,8 +258,64 @@ window.OfflineIndicator = (() => { }); } - // Funkloch-Zonen automatisch füllen, sobald Netz da ist — das Gerät lernt selbst, - // wo Offline-Karten nötig sind (dort wo Netz ist, braucht es keine). + // Letzte bekannte Position: GPS nur wenn Permission schon erteilt (kein Popup), + // sonst localStorage-Stand (gesetzt von wetter.js u.a.). + async function _lastKnownPos() { + try { + if (navigator.permissions && navigator.geolocation) { + const perm = await navigator.permissions.query({ name: 'geolocation' }); + if (perm.state === 'granted') { + const pos = await new Promise(res => + navigator.geolocation.getCurrentPosition(p => res(p), () => res(null), { timeout: 5000 })); + if (pos) return { lat: pos.coords.latitude, lon: pos.coords.longitude }; + } + } + } catch {} + try { + const raw = localStorage.getItem(LS_LAST_POS); + if (raw) { const p = JSON.parse(raw); if (p?.lat != null) return { lat: p.lat, lon: p.lon }; } + } catch {} + return null; + } + + // Flugmodus/Netzverlust bei OFFENER App = klares Funkloch-Signal (René 2026-06-08): + // aktuelle Position direkt als Zone merken — raw in IndexedDB, denn der GL-Stack ist + // offline evtl. nicht ladbar. Dedupe 2 km wie MapOffline.markDeadZone; Cap 50. + function _markDeadZoneRaw(lat, lon) { + try { + const r = indexedDB.open('by-offline-tiles', 1); + r.onupgradeneeded = () => { + const d = r.result; + if (!d.objectStoreNames.contains('tiles')) d.createObjectStore('tiles'); + if (!d.objectStoreNames.contains('meta')) d.createObjectStore('meta'); + }; + r.onsuccess = () => { + const db = r.result; + if (!db.objectStoreNames.contains('meta')) { db.close(); return; } + const store = db.transaction('meta', 'readwrite').objectStore('meta'); + const rq = store.get('deadzones'); + rq.onsuccess = () => { + let zones = rq.result || []; + const near = zones.some(z => { + const dLat = (z.lat - lat) * 111, dLon = (z.lon - lon) * 111 * Math.cos(lat * Math.PI / 180); + return Math.sqrt(dLat * dLat + dLon * dLon) < 2; + }); + if (!near) { + zones.push({ lat, lon, ts: Date.now(), filled: false }); + if (zones.length > 50) zones = zones.slice(-50); + store.put(zones, 'deadzones'); + } + db.close(); + }; + rq.onerror = () => db.close(); + }; + } catch (e) {} + } + + // Start-Check (auch bei Netz-Rückkehr): Funkloch-Zonen UND Routen-Korridore in + // Positionsnähe (50 km) füllen/verifizieren — das Gerät hält selbst aktuell, was + // offline nötig ist (René 2026-06-08: gespeicherte Routen müssen offline nutzbar + // bleiben, auch nach „Alles löschen"/Eviction). Ferne Gebiete kommen, wenn man dort ist. let _autoFillTimer = null; function _scheduleAutoFill(delayMs) { if (!_offlineTilesMode()) return; @@ -256,11 +323,21 @@ window.OfflineIndicator = (() => { _autoFillTimer = setTimeout(async () => { if (!navigator.onLine) return; try { - if (!(await _openDeadZonesStored())) return; // nichts zu tun → GL-Stack nicht laden + const hasZones = await _anyDeadZonesStored(); + let routes = []; + try { routes = (await API.routes.list()) || []; } catch {} + routes = routes.filter(r => (r.preview_track || []).length >= 2); + if (!hasZones && !routes.length) return; // nichts zu tun → GL-Stack nicht laden + const pos = await _lastKnownPos(); + const o = pos ? { lat: pos.lat, lon: pos.lon } : {}; await UI.loadMapLibreUI(); - const n = await window.MapOffline?.autoFillDeadZones?.(); - if (n) { - UI.toast?.info(`${n} Funkloch-${n === 1 ? 'Gebiet' : 'Gebiete'} automatisch offline gespeichert.`); + const n = await window.MapOffline?.autoFillDeadZones?.(o) || 0; + const k = routes.length ? (await window.MapOffline?.ensureRouteCorridors?.(routes, o) || 0) : 0; + if (n || k) { + const parts = []; + if (n) parts.push(`${n} Funkloch-${n === 1 ? 'Gebiet' : 'Gebiete'}`); + if (k) parts.push(`${k} Routen-${k === 1 ? 'Korridor' : 'Korridore'}`); + UI.toast?.info(`${parts.join(' + ')} automatisch offline gespeichert.`); refresh(); } } catch (e) {} @@ -417,9 +494,9 @@ window.OfflineIndicator = (() => { function init() { refresh(); _prefetchPages(); - // OSM-Raster-Prefetch nur für die Leaflet-Karte — die GL-Karte (byt://-Vektorkacheln) - // nutzt das Raster nicht. Komplett-Entfernung wenn Flag dauerhaft AN (OFFLINE_MAPS_PLAN.md). - if (!_offlineTilesMode()) _prefetchTiles(); + // Automatischer OSM-Raster-Prefetch ENTFERNT (2026-06-07): Flag ist auf allen deployten + // Hosts AN, die GL-Karte nutzt das Raster nicht. _prefetchTiles bleibt nur noch für den + // manuellen „Fehlende nachladen"-Pfad im Leaflet-Modus (localhost / by_map_gl=0). _prefetchData(); _bindLongPress(); @@ -438,6 +515,13 @@ window.OfflineIndicator = (() => { // Funkloch-Zonen nachladen: verzögert beim Start + sobald die Verbindung zurückkommt. _scheduleAutoFill(30_000); window.addEventListener('online', () => _scheduleAutoFill(8_000)); + // Flugmodus/Netzverlust bei offener App → Standort als Funkloch-Zone merken + // (wird beim nächsten Online-Sein automatisch geladen und künftig aktuell gehalten). + window.addEventListener('offline', async () => { + if (!_offlineTilesMode()) return; + const pos = await _lastKnownPos(); + if (pos) _markDeadZoneRaw(pos.lat, pos.lon); + }); _checkStorageQuota(); // beim Init prüfen setInterval(() => { _prefetchData(); refresh(); _checkStorageQuota(); }, 60_000); } diff --git a/backend/static/js/pages/map.js b/backend/static/js/pages/map.js index e62f653..213713f 100644 --- a/backend/static/js/pages/map.js +++ b/backend/static/js/pages/map.js @@ -2190,6 +2190,34 @@ window.Page_map = (() => { } } + // Bereichsauswahl: den SICHTBAREN Karten-Ausschnitt komplett speichern (z.B. fürs + // Urlaubsziel: hinzoomen/-schieben, speichern). Cap 40 MB, Zu-groß-Schutz in MapOffline. + async function _downloadViewport() { + if (!_map || !window.MapOffline) return; + const btn = document.getElementById('map-offline-btn'); + if (btn?.classList.contains('loading')) return; + const p = _mapPaddedBounds(0.02); + btn?.classList.add('loading'); + _setOsmStatus('Offline: 0 MB…'); + try { + const res = await MapOffline.downloadBbox( + { south: p.south, west: p.west, north: p.north, east: p.east }, + { capMB: 40, onProgress: pr => { + _setOsmStatus(`Offline: ${(pr.bytes / 1048576).toFixed(1)} MB (${Math.round(pr.done / pr.total * 100)} %)…`); + } }); + _setOsmStatus(''); + UI.toast.success(`Ausschnitt offline gespeichert — ${res.pois || 0} Marker, ${(res.bytes / 1048576).toFixed(1)} MB.` + + `${res.capped ? ' (40-MB-Limit erreicht)' : ''}`); + window.OfflineIndicator?.refresh(); + if (_covOn) _setCoverage(true); + } catch (e) { + _setOsmStatus(''); + UI.toast.error(e?.message?.includes('zu groß') ? e.message : 'Offline-Download fehlgeschlagen — bitte erneut versuchen.'); + } finally { + btn?.classList.remove('loading'); + } + } + // ---------------------------------------------------------- // Offline-Bereiche-Layer (gespeicherte z14-Kacheln) + Verwaltungs-Modal // ---------------------------------------------------------- @@ -2207,14 +2235,16 @@ window.Page_map = (() => { } const gj = await MapOffline.coverage().catch(() => null); if (!gj || !gj.features.length) { UI.toast.info('Noch keine Offline-Bereiche gespeichert.'); return false; } + // Funkloch-Gebiete orange, manuell gespeicherte blau (Wunsch René 2026-06-08). + const covColor = ['match', ['get', 'kind'], 'funkloch', '#f59e0b', '#3b82f6']; if (_map.getSource('by-off-cov')) { _map.getSource('by-off-cov').setData(gj); } else { _map.addSource('by-off-cov', { type: 'geojson', data: gj }); _map.addLayer({ id: 'by-off-cov', type: 'fill', source: 'by-off-cov', - paint: { 'fill-color': '#3b82f6', 'fill-opacity': 0.15 } }); + paint: { 'fill-color': covColor, 'fill-opacity': 0.15 } }); _map.addLayer({ id: 'by-off-cov-line', type: 'line', source: 'by-off-cov', - paint: { 'line-color': '#3b82f6', 'line-opacity': 0.35, 'line-width': 0.5 } }); + paint: { 'line-color': covColor, 'line-opacity': 0.35, 'line-width': 0.5 } }); } _covOn = true; return true; @@ -2226,7 +2256,7 @@ window.Page_map = (() => { let s = { regions: [] }; try { s = await MapOffline.stats(); } catch (e) {} const regions = s.regions || []; - const totalBytes = regions.reduce((a, r) => a + (r.bytes || 0), 0); + const totalBytes = s.totalBytes || regions.reduce((a, r) => a + (r.bytes || 0), 0); const totalPois = regions.reduce((a, r) => a + (r.pois || 0), 0); UI.modal.open({ title: '🗺️ Offline-Karten', @@ -2238,13 +2268,38 @@ window.Page_map = (() => {

+ +

+ manuell gespeichert  ·  + Funkloch (automatisch) +

${regions.length ? `` : ''}
+ ${(s.deadzones || []).length ? ` +
+
+ Funkloch-Gebiete (${s.deadzones.length}) — werden automatisch aktuell gehalten
+ ${s.deadzones.map(z => ` +
+ 📡 ${new Date(z.ts).toLocaleDateString('de-DE')} · ${z.lat.toFixed(3)}, ${z.lon.toFixed(3)} · ${z.filled ? 'geladen' : 'ausstehend'} + +
`).join('')} +
` : ''} `, footer: ``, }); document.getElementById('off-dl')?.addEventListener('click', () => { UI.modal.close(); _downloadVectorRegion(); }); + document.getElementById('off-bbox')?.addEventListener('click', () => { UI.modal.close(); _downloadViewport(); }); + // Ent-Funklochen: Zone aus dem Gedächtnis nehmen (✕) — lädt nicht mehr automatisch. + document.querySelectorAll('.off-zone-del').forEach(b => b.addEventListener('click', async e => { + const ts = Number(e.currentTarget.dataset.ts); + e.currentTarget.closest('.off-zone-row')?.remove(); + await MapOffline.removeDeadZone(ts).catch(() => {}); + UI.toast.success('Funkloch-Gebiet entfernt — wird nicht mehr automatisch geladen.'); + window.OfflineIndicator?.refresh(); + })); document.getElementById('off-cov')?.addEventListener('click', async () => { UI.modal.close(); await _setCoverage(!_covOn); }); document.getElementById('off-clear')?.addEventListener('click', async e => { const btn = e.currentTarget; @@ -2256,7 +2311,7 @@ window.Page_map = (() => { await MapOffline.clear().catch(() => {}); _setCoverage(false); UI.modal.close(); - UI.toast.success('Offline-Karten gelöscht.'); + UI.toast.success('Offline-Karten gelöscht. Bekannte Funkloch-Gebiete werden beim nächsten Start automatisch neu geladen.'); window.OfflineIndicator?.refresh(); }); } diff --git a/backend/static/js/pages/routes.js b/backend/static/js/pages/routes.js index 68729c7..220496d 100644 --- a/backend/static/js/pages/routes.js +++ b/backend/static/js/pages/routes.js @@ -2488,7 +2488,8 @@ window.Page_routes = (() => { else { gl.addSource('rd-off-cov', { type: 'geojson', data: gj }); gl.addLayer({ id: 'rd-off-cov', type: 'fill', source: 'rd-off-cov', - paint: { 'fill-color': '#3b82f6', 'fill-opacity': 0.15 } }); + paint: { 'fill-color': ['match', ['get', 'kind'], 'funkloch', '#f59e0b', '#3b82f6'], + 'fill-opacity': 0.15 } }); } } } catch (e) {} diff --git a/backend/static/landing.html b/backend/static/landing.html index c662fdf..31aadcf 100644 --- a/backend/static/landing.html +++ b/backend/static/landing.html @@ -4,7 +4,7 @@ - + Ban Yaro — Die Hunde-App für Deutschland, Österreich & Schweiz diff --git a/backend/static/sw.js b/backend/static/sw.js index c0390b0..e514ca9 100644 --- a/backend/static/sw.js +++ b/backend/static/sw.js @@ -4,7 +4,7 @@ ============================================================ */ // ← EINZIGE Stelle für die Version — STATIC_ASSETS und CACHE_VERSION leiten sich ab -const VER = '1228'; +const VER = '1233'; const CACHE_VERSION = `by-v${VER}`; const CACHE_STATIC = `${CACHE_VERSION}-static`; const CACHE_TILES = 'ban-yaro-tiles-v1'; // bleibt über SW-Updates erhalten @@ -23,6 +23,15 @@ const PRIORITY_PAGES = [ '/js/pages/routes.js', '/js/pages/poison.js', '/js/pages/lost.js', + // GL-Karten-Stack: ohne diese Dateien ist die Karte offline TOT, obwohl + // Kacheln/Marker in IndexedDB liegen (Gerätetest 2026-06-08). + '/js/vendor/maplibre-gl.js', + '/js/vendor/maplibre-gl.css', + '/js/vendor/pmtiles.js', + '/js/map-gl-style.js', + '/js/map-offline.js', + '/js/map-gl-markers.js', + '/js/map-gl-mini.js', ]; // index.html wird NICHT pre-gecacht (immer Network-First) @@ -236,9 +245,36 @@ self.addEventListener('install', event => { // ---------------------------------------------------------- // ACTIVATE — alte Caches aufräumen (CACHE_TILES + CACHE_API behalten) // ---------------------------------------------------------- +// Carry-Over VOR dem Löschen: Einträge der alten Static-Caches in den neuen übernehmen, +// die dort noch fehlen. Sonst reißt ein Versions-Update ein Offline-Loch — alte Caches +// weg, neuer erst teilweise befüllt (Hintergrund-Precache) → Karte offline tot, obwohl +// die Pfote „ready" zeigt (Gerätetest 2026-06-08). Network-First ersetzt die übernommenen +// Einträge online sukzessive durch frische. +async function _migrateStaticCaches() { + const names = (await caches.keys()).filter(k => /^by-v\d+-static$/.test(k) && k !== CACHE_STATIC); + if (!names.length) return; + const fresh = await caches.open(CACHE_STATIC); + const have = new Set((await fresh.keys()).map(r => r.url.split('?')[0])); + for (const name of names) { + const oldCache = await caches.open(name); + for (const req of await oldCache.keys()) { + const bare = req.url.split('?')[0]; + if (have.has(bare)) continue; // neue Version schon vorhanden + const resp = await oldCache.match(req); + if (resp) { + // Unter NACKTEM Key (ohne ?v=) ablegen: der Online-Refresh (PRIORITY_PAGES / + // Network-First) überschreibt genau diesen Key — keine Versions-Duplikate. + try { await fresh.put(bare, resp); have.add(bare); } catch (e) {} + } + } + } +} + self.addEventListener('activate', event => { event.waitUntil( - caches.keys() + _migrateStaticCaches() + .catch(() => {}) + .then(() => caches.keys()) .then(keys => Promise.all( keys .filter(k => k !== CACHE_STATIC && k !== CACHE_TILES && k !== CACHE_API) @@ -362,56 +398,77 @@ self.addEventListener('fetch', event => { return; } - // CSS, Core-JS + Seiten-Module: Network-First mit ignoreSearch-Fallback für Offline + // CSS, Core-JS + Seiten-Module: Network-First — aber nach 2,5 s ohne Antwort kommt der + // CACHE (stale-while-revalidate): bei schwachem Empfang blieb die App sonst SEHR LANGE + // weiß, weil der Fetch nicht fehlschlägt, sondern tröpfelt (Gerätetest 2026-06-08). + // Das Netz-Ergebnis aktualisiert den Cache im Hintergrund weiter; echte Versions-Updates + // zieht der Update-Mechanismus (x-app-version + controllerchange) ohnehin separat. if (url.pathname.startsWith('/css/') || url.pathname.startsWith('/js/pages/') || url.pathname.startsWith('/js/app.js') || url.pathname.startsWith('/js/ui.js') || url.pathname.startsWith('/js/api.js') || url.pathname.startsWith('/js/worlds.js')) { - event.respondWith( - fetch(event.request) - .then(response => { - if (response.ok) { - const clone = response.clone(); - caches.open(CACHE_STATIC).then(c => c.put(event.request, clone)); - } - return response; - }) - .catch(() => caches.match(event.request, { ignoreSearch: true }) - .then(cached => cached || new Response('', { status: 503 }))) - ); - return; - } - - // Navigation (index.html): immer Network-First - if (event.request.mode === 'navigate') { - event.respondWith( - fetch(event.request) - .then(response => { + event.respondWith((async () => { + const network = fetch(event.request).then(response => { + if (response.ok) { const clone = response.clone(); caches.open(CACHE_STATIC).then(c => c.put(event.request, clone)); - return response; - }) - .catch(() => caches.match('/')) - ); + } + return response; + }); + const winner = await Promise.race([ + network.catch(() => null), + new Promise(res => setTimeout(() => res(null), 2500)), + ]); + if (winner) return winner; + const cached = await caches.match(event.request, { ignoreSearch: true }); + if (cached) { network.catch(() => {}); return cached; } // Netz läuft im Hintergrund weiter + return network.catch(() => new Response('', { status: 503 })); + })()); return; } - // Statische Assets: Cache-First - event.respondWith( - caches.match(event.request) - .then(cached => cached || fetch(event.request) - .then(response => { - if (response.ok && event.request.method === 'GET') { - const clone = response.clone(); - caches.open(CACHE_STATIC).then(c => c.put(event.request, clone)); - } - return response; - }) - ) - .catch(() => { - if (event.request.mode === 'navigate') return caches.match('/'); - return new Response('', { status: 503 }); - }) - ); + // Navigation (index.html): Network-First, nach 2,5 s ohne Antwort die gecachte Shell + // (gleicher Schwachempfang-Schutz wie oben; Offline-Fallback bleibt caches.match('/')). + if (event.request.mode === 'navigate') { + event.respondWith((async () => { + const network = fetch(event.request).then(response => { + const clone = response.clone(); + caches.open(CACHE_STATIC).then(c => c.put(event.request, clone)); + return response; + }); + const winner = await Promise.race([ + network.catch(() => null), + new Promise(res => setTimeout(() => res(null), 2500)), + ]); + if (winner) return winner; + const cached = await caches.match('/'); + if (cached) { network.catch(() => {}); return cached; } + return network.catch(() => caches.match('/')); + })()); + return; + } + + // Statische Assets: Cache-First. Für eigene /js/ + /css/ zusätzlich ignoreSearch- + // Fallback — Lazy-Loads hängen ?v=APP_VER an, Carry-Over-Einträge tragen aber den + // alten ?v= bzw. gar keinen (PRIORITY_PAGES). Online ersetzt der Fetch sie frisch. + event.respondWith((async () => { + let cached = await caches.match(event.request); + if (!cached && url.origin === self.location.origin && + (url.pathname.startsWith('/js/') || url.pathname.startsWith('/css/'))) { + cached = await caches.match(event.request, { ignoreSearch: true }); + } + if (cached) return cached; + try { + const response = await fetch(event.request); + if (response.ok && event.request.method === 'GET') { + const clone = response.clone(); + caches.open(CACHE_STATIC).then(c => c.put(event.request, clone)).catch(() => {}); + } + return response; + } catch (e) { + if (event.request.mode === 'navigate') return caches.match('/'); + return new Response('', { status: 503 }); + } + })()); }); // ---------------------------------------------------------- diff --git a/docs/OFFLINE_MAPS_PLAN.md b/docs/OFFLINE_MAPS_PLAN.md index c440341..74bbe06 100644 --- a/docs/OFFLINE_MAPS_PLAN.md +++ b/docs/OFFLINE_MAPS_PLAN.md @@ -67,17 +67,63 @@ nach bestandenen Gerätetests Runde 1+2). localhost = Leaflet/AUS. bestanden) — er lag im bereits gespeicherten Gebiet. Nach dem Speichern werden die gespeicherten Bereiche jetzt blau auf der Routen-Detailkarte eingeblendet (`_detailMap._gl`). -**🔲 Offen (Runde 3):** -- **Gerätetest Runde 2** (Budget-Download, Funkloch-Lernen auf echter Gassi-Runde, Korridor, - Coverage-Layer) → dann Prod-Freigabe-Entscheidung (BY.offlineTiles-Default erweitern analog `by_map_gl`). -- **Rollendes Vorausladen beim Aufzeichnen** (fortlaufend um die aktuelle Position cachen, solange - Empfang da — deckt den Weg schon beim ersten Mal ab; Akku-/Datensparsamkeit beachten). -- **Bereichsauswahl** (Karten-Ausschnitt/Rechteck als Download-Gebiet) — Korridor deckt den - Hauptfall ab, Rest nach Bedarf. -- **Speicher-Cap + LRU** über alles (alte Gebiete fliegen automatisch raus) + optional - `navigator.storage.persist()`. -- Alten OSM-Raster-Prefetch (`offline-indicator.js _prefetchTiles` + `map.js _cacheTiles`) komplett - entfernen, wenn Flag dauerhaft AN (auch Prod). +**✅ Runde 3 (2026-06-07):** +- **Offline-Indikator = pulsierendes Icon** oben rechts (32 px, unterhalb der Kopfzeilen-Höhe) statt + Banner über die volle Breite — verdeckte Nav-Elemente, z.B. „← Zurück" in der Routennavigation + (Gerätetest René). Vollbanner weiterhin 5 s beim Offline-Gang, dann Icon. +- **Rollendes Vorausladen beim Aufzeichnen:** `setGps()` lädt alle ~400 m still die FEHLENDEN + z14±2-Kacheln (+Eltern) um die Position, solange online — deckt Weg + Anfahrt schon beim ERSTEN + Besuch ab (das Funkloch-Gedächtnis greift erst ab dem 2.). Kein Region-Eintrag, kein UI. +- **Bereichsauswahl light:** Modal-Button „Sichtbaren Ausschnitt speichern" → `downloadBbox(viewport, + {capMB:40})` mit Zu-groß-Schutz (>4000 z14-Kacheln → „bitte reinzoomen"). +- **Speicher-Cap 250 MB (Soft-Guard):** `totalBytes`-Zähler in Meta; AUTOMATISCHE Pfade (Vorausladen, + Funkloch-Autofill) stoppen über dem Cap, manuelle bleiben; `navigator.storage.persist()` best-effort. + Echte LRU-Eviction bewusst vertagt (Kacheln werden regionsübergreifend geteilt → Eviction braucht + Refcounting; bei ~8 MB/Gebiet kein Druck). +- **Auto-OSM-Raster-Prefetch entfernt** (offline-indicator init); `_prefetchTiles`/`_cacheTiles` + bleiben nur für den manuellen Leaflet-Pfad (localhost / by_map_gl=0). +- Logik per Node-Stub-Tests verifiziert (Bbox, Zu-groß, Cap, Prefetch-Throttle, persist). + Achtung Node 21+: eingebautes `navigator`-Global schluckt `global.navigator=`-Stubs — + `Object.defineProperty(globalThis, 'navigator', …)` verwenden. + +**✅ Runde 4 — Minimal-Speicher-Modell (2026-06-08, Modell René):** +Prinzip: Gespeichert bleibt NUR, was wegen Funklöchern nötig ist + manuell Hinzugefügtes +(jeweils mit allen Markern + Warnungen). Das Funkloch-Gedächtnis ist die QUELLE DER WAHRHEIT, +die Kacheln sind jederzeit neu ableitbarer Cache. +- **Ephemeres Vorausladen:** Rolling-Prefetch-Kacheln werden bei Aufzeichnungsende GELÖSCHT, + wenn die Runde kein Funkloch hatte (nur neu gespeicherte Keys; Bestand unangetastet). +- **Netz-Probe bei Aufzeichnung** (alle ~2 Min, /api/version, 6-s-Timeout): erkennt Funklöcher + auch in BEREITS GESPEICHERTEN Gebieten — dort kommen Kacheln aus IndexedDB, es gibt keinen + Remote-Miss als Signal (Lücke von René gefunden). +- **clear() behält das Funkloch-Gedächtnis** (Zonen → filled:false): Beim nächsten Online-Start + werden Funkloch-Gebiete automatisch neu geladen, auch wenn man alles gelöscht hat. +- **Start-Check mit Position:** autoFillDeadZones({lat,lon,maxKm:50}) — nur Zonen im Umkreis + (Speicher minimal), nächstgelegene zuerst; VERIFIZIERT gefüllte Zonen (Zentrums-Kachel da?) + → fängt Löschen + iOS-Eviction ab. Pfote-Segment 5 = „alle bekannten Funkloch-Zonen gefüllt". +- **Coverage-Layer zweifarbig:** Funkloch-Gebiete ORANGE (#f59e0b), manuelle BLAU (#3b82f6); + Legende im Offline-Modal; Regionen tragen type 'funkloch'/'gebiet'/'korridor'/'ausschnitt'. + +**✅ Runde 5 — Gerätetest-Feedback (2026-06-08):** +- **Indikator links unter die Zoom-Regler** (+/−): rechts verdeckte er die Legenden-Chips. +- **Flugmodus bei offener App = Funkloch-Signal:** `offline`-Event → Position raw als Zone in + IndexedDB (GL-Stack offline evtl. nicht ladbar) → wird künftig automatisch geladen. +- **Ent-Funklochen:** Zonen-Liste im Offline-Modal (Datum/Koordinaten/Status) mit ✕ → + `removeDeadZone(ts)`; Kacheln bleiben bis „Alles löschen". +- **Warnungs-Aktualität (Frage René):** `_mergeStore` mit **Bbox-Replace** — die Server-Antwort + ist für die geladene Bbox autoritativ, aufgehobene Giftköder/gefundene Hunde fliegen raus + (Fetch-Kreis ⊇ Bbox via ×√2; fresh=null merged nie → Offline-Fetch putzt nichts weg). + Zusätzlich **24-h-Refresh** der Warnungen im 50-km-Umkreis beim Start-Check. +- **Routen-Korridore im Start-Check:** `ensureRouteCorridors(routes)` — eigene Routen in + Positionsnähe per Stichproben-Kacheln verifizieren, bei Lücken Korridor aus `preview_track` + (40 Punkte, ±1-km-Puffer schluckt die Vereinfachung) neu laden. Gespeicherte Routen bleiben + offline nutzbar, auch nach „Alles löschen"/Eviction. Region-Dedupe per Typ+Name. +- Stub-Tests jetzt im Repo: `tests/js/test-map-offline-r*.js` (s. tests/js/README.md). + +**🔲 Offen (Backlog):** +- Echte LRU-Eviction (Refcounting/Region-Zuordnung der Kacheln), wenn Nutzer real ans Cap kommen. +- Rechteck-Zeichnen als präzisere Bereichsauswahl (Viewport-Variante deckt den Hauptfall ab). +- POIs auch beim rollenden Vorausladen (aktuell nur Kacheln; Giftköder kommen aus dem + localStorage-Fallback der letzten Online-Position). ## Ziel GL-Vektorkarten offline-tauglich machen — Kernszenario **Gassi/Wandern im Funkloch**. diff --git a/tests/js/README.md b/tests/js/README.md new file mode 100644 index 0000000..e428ae5 --- /dev/null +++ b/tests/js/README.md @@ -0,0 +1,15 @@ +# JS-Logik-Tests (Node, ohne Browser) + +Stub-Tests für `backend/static/js/map-offline.js` (IndexedDB/pmtiles/fetch gemockt): + +``` +for f in tests/js/test-map-offline*.js; do node "$f" backend/static/js/map-offline.js; done +``` + +- r1: Budget-Download, Korridor, Coverage, Deadzone-Dedupe +- r3: downloadBbox, Zu-groß-Schutz, totalBytes, Prefetch-Throttle, Cap-Guard, persist() +- r4: Minimal-Speicher-Modell (Prune, Netz-Probe, clear behält Zonen, Nähe/Verify, Färbung) +- r5: Bbox-Replace (aufgehobene Warnungen), 24h-Alert-Refresh, removeDeadZone, ensureRouteCorridors + +⚠️ Node 21+: eingebautes `navigator`-Global — Stubs via `Object.defineProperty(globalThis, 'navigator', …)`, +ein einfaches `global.navigator =` wird still verschluckt. diff --git a/tests/js/test-map-offline-r1.js b/tests/js/test-map-offline-r1.js new file mode 100644 index 0000000..85d01d5 --- /dev/null +++ b/tests/js/test-map-offline-r1.js @@ -0,0 +1,82 @@ +// Isolierter Logik-Test für map-offline.js (IndexedDB/pmtiles/fetch gestubbt) +const fs = require('fs'); + +const stores = { tiles: new Map(), meta: new Map() }; +function mkReq(result) { return { result }; } +global.indexedDB = { + open() { + const req = {}; + setTimeout(() => { + const db = { + objectStoreNames: { contains: n => !!stores[n] }, + transaction(name) { + const os = { + get: k => mkReq(stores[name].get(k)), + put: (v, k) => { stores[name].set(k, v); return mkReq(undefined); }, + count: () => mkReq(stores[name].size), + getAllKeys: () => mkReq([...stores[name].keys()]), + }; + const tx = { objectStore: () => os }; + setTimeout(() => tx.oncomplete && tx.oncomplete()); + return tx; + }, + close() {}, + }; + req.result = db; + req.onsuccess && req.onsuccess(); + }); + return req; + }, +}; +global.window = {}; +Object.defineProperty(globalThis, 'navigator', { value: { onLine: true }, configurable: true }); +global.pmtiles = { PMTiles: class { getZxy() { return Promise.resolve({ data: new Uint8Array(100).buffer }); } } }; +global.MapGLStyle = { tilesUrl: () => 'http://test/dach.pmtiles' }; +global.fetch = (url) => Promise.resolve({ + ok: true, + arrayBuffer: () => Promise.resolve(new Uint8Array(50).buffer), + json: () => Promise.resolve(url.includes('giftkoeder') ? [{ id: 1, lat: 48.08, lon: 11.97 }] : []), +}); + +eval(fs.readFileSync(process.argv[2], 'utf8')); +const MO = global.window.MapOffline; + +(async () => { + // 1. Budget-Download: winziges Budget → muss nach wenigen Ringen stoppen + const r1 = await MO.downloadAround(48.07, 11.96, { budgetMB: 0.01, maxRadiusKm: 10 }); + console.log('downloadAround:', JSON.stringify(r1)); + if (!(r1.tiles > 0 && r1.bytes >= 10240)) throw new Error('Budget-Download speichert nichts'); + + // 2. Korridor + const track = [{ lat: 48.07, lon: 11.96 }, { lat: 48.08, lon: 11.99 }, { lat: 48.09, lon: 12.02 }]; + const r2 = await MO.downloadCorridor(track, { bufferKm: 1, name: 'Test' }); + console.log('downloadCorridor:', JSON.stringify(r2)); + if (!(r2.tiles > 0)) throw new Error('Korridor speichert keine Kacheln'); + + // 3. Coverage muss die z14-Kacheln aus 1+2 enthalten + const gj = await MO.coverage(); + const z14 = [...stores.tiles.keys()].filter(k => /^14\//.test(k)).length; + console.log('coverage-Features:', gj.features.length, '— z14-Keys im Store:', z14); + if (gj.features.length !== z14) throw new Error('Coverage != gespeicherte z14-Kacheln'); + if (!gj.features.length) throw new Error('Coverage leer'); + + // 4. Geometrie-Plausibilität: Feature in Track-Nähe? + const c = gj.features[0].geometry.coordinates[0][0]; + console.log('Beispiel-Ecke:', c); + if (Math.abs(c[1] - 48.08) > 0.3 || Math.abs(c[0] - 11.99) > 0.5) throw new Error('Coverage-Polygon liegt falsch'); + + // 5. Regions-Meta + const s = await MO.stats(); + console.log('regions:', JSON.stringify(s.regions.map(r => ({ type: r.type || 'gebiet', tiles: r.tiles })))); + if (s.regions.length !== 2) throw new Error('Regions-Liste unvollständig'); + + // 6. Funkloch: markDeadZone + Dedupe + await MO.markDeadZone(48.5, 12.5); + await MO.markDeadZone(48.5005, 12.5005); // < 2 km → Dedupe + await MO.markDeadZone(48.8, 12.9); + const zones = stores.meta.get('deadzones'); + console.log('deadzones:', zones.length); + if (zones.length !== 2) throw new Error('Deadzone-Dedupe kaputt'); + + console.log('\nALLE TESTS BESTANDEN'); +})().catch(e => { console.error('FEHLER:', e.message); process.exit(1); }); diff --git a/tests/js/test-map-offline-r3.js b/tests/js/test-map-offline-r3.js new file mode 100644 index 0000000..8f0f865 --- /dev/null +++ b/tests/js/test-map-offline-r3.js @@ -0,0 +1,78 @@ +// Runde-3-Tests: downloadBbox, rollendes Vorausladen (setGps), Cap +const fs = require('fs'); +const stores = { tiles: new Map(), meta: new Map() }; +function mkReq(result) { return { result }; } +global.indexedDB = { open() { + const req = {}; + setTimeout(() => { + const db = { + objectStoreNames: { contains: n => !!stores[n] }, + transaction(name) { + const os = { + get: k => mkReq(stores[name].get(k)), + put: (v, k) => { stores[name].set(k, v); return mkReq(undefined); }, + count: () => mkReq(stores[name].size), + getAllKeys: () => mkReq([...stores[name].keys()]), + }; + const tx = { objectStore: () => os }; + setTimeout(() => tx.oncomplete && tx.oncomplete()); + return tx; + }, + close() {}, + }; + req.result = db; req.onsuccess && req.onsuccess(); + }); + return req; +} }; +global.window = {}; +let persistCalled = 0; +Object.defineProperty(globalThis, 'navigator', { value: { onLine: true, storage: { persist: () => { persistCalled++; return Promise.resolve(true); } } }, configurable: true }); +global.pmtiles = { PMTiles: class { getZxy() { return Promise.resolve({ data: new Uint8Array(100).buffer }); } } }; +global.MapGLStyle = { tilesUrl: () => 'http://test/dach.pmtiles' }; +global.fetch = () => Promise.resolve({ ok: true, arrayBuffer: () => Promise.resolve(new Uint8Array(50).buffer), json: () => Promise.resolve([]) }); +eval(fs.readFileSync(process.argv[2], 'utf8')); +const MO = global.window.MapOffline; + +(async () => { + // 1. downloadBbox: kleiner Ausschnitt + const r1 = await MO.downloadBbox({ south: 48.06, west: 11.94, north: 48.09, east: 11.99 }, { capMB: 40 }); + console.log('downloadBbox:', JSON.stringify(r1)); + if (!(r1.tiles > 0)) throw new Error('Bbox-Download leer'); + if (!persistCalled) throw new Error('storage.persist() nicht aufgerufen'); + + // 2. Zu-groß-Schutz + let threw = false; + await MO.downloadBbox({ south: 40, west: 0, north: 55, east: 20 }, {}).catch(e => { threw = /zu groß/.test(e.message); }); + console.log('Zu-groß-Schutz:', threw); + if (!threw) throw new Error('Zu-groß-Schutz fehlt'); + + // 3. totalBytes-Zähler + stats + const s = await MO.stats(); + console.log('totalBytes:', s.totalBytes); + if (!(s.totalBytes > 0)) throw new Error('totalBytes nicht gezählt'); + + // 4. Rollendes Vorausladen: setGps zweimal — erst > 400m Distanz lädt neu + const before = stores.tiles.size; + MO.setGps({ lat: 47.50, lon: 11.50 }); + await new Promise(r => setTimeout(r, 300)); + const afterFirst = stores.tiles.size; + console.log('Prefetch nach 1. setGps:', afterFirst - before, 'neue Keys'); + if (afterFirst <= before) throw new Error('Rollendes Vorausladen lädt nichts'); + MO.setGps({ lat: 47.5001, lon: 11.5001 }); // < 400 m → kein neuer Load + await new Promise(r => setTimeout(r, 200)); + if (stores.tiles.size !== afterFirst) throw new Error('Distanz-Throttle greift nicht'); + MO.setGps({ lat: 47.51, lon: 11.52 }); // > 400 m → neuer Ring + await new Promise(r => setTimeout(r, 300)); + console.log('Prefetch nach Bewegung:', stores.tiles.size - afterFirst, 'neue Keys'); + if (stores.tiles.size <= afterFirst) throw new Error('Vorausladen nach Bewegung fehlt'); + + // 5. Cap stoppt Vorausladen + stores.meta.set('totalBytes', 300 * 1048576); + const capBefore = stores.tiles.size; + MO.setGps({ lat: 47.60, lon: 11.60 }); + await new Promise(r => setTimeout(r, 300)); + if (stores.tiles.size !== capBefore) throw new Error('Cap stoppt Vorausladen nicht'); + console.log('Cap-Guard: ok'); + + console.log('\nALLE RUNDE-3-TESTS BESTANDEN'); +})().catch(e => { console.error('FEHLER:', e.message); process.exit(1); }); diff --git a/tests/js/test-map-offline-r4.js b/tests/js/test-map-offline-r4.js new file mode 100644 index 0000000..ef833d3 --- /dev/null +++ b/tests/js/test-map-offline-r4.js @@ -0,0 +1,99 @@ +// Runde-4-Tests: Minimal-Speicher-Modell (Prune, clear-behält-Zonen, Verify, Probe, Färbung) +const fs = require('fs'); +const stores = { tiles: new Map(), meta: new Map() }; +function mkReq(result) { return { result }; } +global.indexedDB = { open() { + const req = {}; + setTimeout(() => { + const db = { + objectStoreNames: { contains: n => !!stores[n] }, + transaction(name) { + const os = { + get: k => mkReq(stores[name].get(k)), + put: (v, k) => { stores[name].set(k, v); return mkReq(undefined); }, + delete: k => { stores[name].delete(k); return mkReq(undefined); }, + clear: () => { stores[name].clear(); return mkReq(undefined); }, + count: () => mkReq(stores[name].size), + getAllKeys: () => mkReq([...stores[name].keys()]), + }; + const tx = { objectStore: () => os }; + setTimeout(() => tx.oncomplete && tx.oncomplete()); + return tx; + }, + close() {}, + }; + req.result = db; req.onsuccess && req.onsuccess(); + }); + return req; +} }; +global.window = {}; +Object.defineProperty(globalThis, 'navigator', { value: { onLine: true, storage: { persist: () => Promise.resolve(true) } }, configurable: true }); +let tileFails = false; +global.pmtiles = { PMTiles: class { getZxy() { return tileFails ? Promise.reject(new Error('offline')) : Promise.resolve({ data: new Uint8Array(100).buffer }); } } }; +global.MapGLStyle = { tilesUrl: () => 'http://t/d.pmtiles' }; +let apiFails = false; +global.fetch = (url) => apiFails + ? Promise.reject(new Error('offline')) + : Promise.resolve({ ok: true, arrayBuffer: () => Promise.resolve(new Uint8Array(50).buffer), json: () => Promise.resolve([]) }); +eval(fs.readFileSync(process.argv[2], 'utf8')); +const MO = global.window.MapOffline; +const sleep = ms => new Promise(r => setTimeout(r, ms)); + +(async () => { + // 1. Ephemeres Vorausladen: Runde OHNE Funkloch → Prefetch wird gelöscht + MO.setGps({ lat: 47.5, lon: 11.5 }); + await sleep(300); + const afterPre = stores.tiles.size; + if (!(afterPre > 0)) throw new Error('Prefetch lief nicht'); + MO.setGps(null); + await sleep(300); + console.log('Prune ohne Funkloch:', afterPre, '→', stores.tiles.size); + if (stores.tiles.size !== 0) throw new Error('Prefetch nicht gepruned'); + + // 2. Runde MIT Funkloch (Netz-Probe schlägt fehl) → Prefetch bleibt + Zone gemerkt + MO.setGps({ lat: 47.5, lon: 11.5 }); + await sleep(300); + tileFails = true; // Funkloch: Tile-Remote-Miss bei aktivem GPS + MO.setGps({ lat: 47.6, lon: 11.6 }); + await MO.tile(14, 1, 1); // nicht gespeichert + remote weg -> _noteRemoteMiss + await sleep(300); + tileFails = false; + MO.setGps(null); + await sleep(300); + const zones1 = stores.meta.get('deadzones') || []; + console.log('Nach Funkloch-Runde: tiles=', stores.tiles.size, 'zones=', zones1.length); + if (!(stores.tiles.size > 0)) throw new Error('Prefetch trotz Funkloch gepruned'); + if (!(zones1.length >= 1)) throw new Error('Netz-Probe hat Funkloch nicht gemerkt'); + + // 3. clear() behält Zonen (filled=false) + stores.meta.get('deadzones').forEach(z => z.filled = true); + stores.meta.set('deadzones', stores.meta.get('deadzones')); + await MO.clear(); + const zones2 = stores.meta.get('deadzones') || []; + console.log('Nach clear(): tiles=', stores.tiles.size, 'zones=', zones2.length, 'filled=', zones2.filter(z => z.filled).length); + if (stores.tiles.size !== 0) throw new Error('clear löscht Kacheln nicht'); + if (!zones2.length || zones2.some(z => z.filled)) throw new Error('clear behält/reset Zonen nicht'); + + // 4. autoFill mit Position: nahe Zone gefüllt (type funkloch), ferne (>50km) bleibt offen + await MO.markDeadZone(49.9, 13.9); // ~270 km entfernt + const n = await MO.autoFillDeadZones({ lat: 47.6, lon: 11.62 }); + const zones3 = stores.meta.get('deadzones'); + const near = zones3.find(z => Math.abs(z.lat - 47.6) < 0.2); + const far = zones3.find(z => z.lat === 49.9); + console.log('autoFill nahe:', n, 'gefüllt; fern offen:', !far.filled); + if (!near.filled || far.filled) throw new Error('Nähe-Filter kaputt'); + + // 5. Verify: gefüllte Zone, Kacheln weg → wird beim nächsten autoFill neu geladen + stores.tiles.clear(); + const n2 = await MO.autoFillDeadZones({ lat: 47.6, lon: 11.62 }); + console.log('Re-Fill nach Kachel-Verlust:', n2); + if (n2 < 1) throw new Error('Coverage-Verify lädt nicht nach'); + + // 6. Coverage-Färbung: funkloch-Kacheln markiert + const gj = await MO.coverage(); + const fz = gj.features.filter(f => f.properties.kind === 'funkloch').length; + console.log('Coverage:', gj.features.length, 'Features, davon funkloch:', fz); + if (!(fz > 0)) throw new Error('Funkloch-Kacheln nicht markiert'); + + console.log('\nALLE RUNDE-4-TESTS BESTANDEN'); +})().catch(e => { console.error('FEHLER:', e.message); process.exit(1); }); diff --git a/tests/js/test-map-offline-r5.js b/tests/js/test-map-offline-r5.js new file mode 100644 index 0000000..2ad1381 --- /dev/null +++ b/tests/js/test-map-offline-r5.js @@ -0,0 +1,93 @@ +// Runde-5-Tests: Bbox-Replace, 24h-Refresh, removeDeadZone, ensureRouteCorridors +const fs = require('fs'); +const stores = { tiles: new Map(), meta: new Map() }; +function mkReq(result) { return { result }; } +global.indexedDB = { open() { + const req = {}; + setTimeout(() => { + const db = { + objectStoreNames: { contains: n => !!stores[n] }, + transaction(name) { + const os = { + get: k => mkReq(stores[name].get(k)), + put: (v, k) => { stores[name].set(k, v); return mkReq(undefined); }, + delete: k => { stores[name].delete(k); return mkReq(undefined); }, + clear: () => { stores[name].clear(); return mkReq(undefined); }, + count: () => mkReq(stores[name].size), + getAllKeys: () => mkReq([...stores[name].keys()]), + }; + const tx = { objectStore: () => os }; + setTimeout(() => tx.oncomplete && tx.oncomplete()); + return tx; + }, + close() {}, + }; + req.result = db; req.onsuccess && req.onsuccess(); + }); + return req; +} }; +global.window = {}; +Object.defineProperty(globalThis, 'navigator', { value: { onLine: true, storage: { persist: () => Promise.resolve(true) } }, configurable: true }); +global.pmtiles = { PMTiles: class { getZxy() { return Promise.resolve({ data: new Uint8Array(100).buffer }); } } }; +global.MapGLStyle = { tilesUrl: () => 'http://t/d.pmtiles' }; +// Giftköder-Szenario: 1. Laden liefert Alarm 1+2, 2. Laden nur noch Alarm 1 (Alarm 2 aufgehoben) +let poisonRound = 0; +global.fetch = (url) => { + if (url.includes('/api/poison')) { + poisonRound++; + const data = poisonRound === 1 + ? [{ id: 1, lat: 48.07, lon: 11.96 }, { id: 2, lat: 48.075, lon: 11.965 }] + : [{ id: 1, lat: 48.07, lon: 11.96 }]; + return Promise.resolve({ ok: true, json: () => Promise.resolve(data), arrayBuffer: () => Promise.resolve(new Uint8Array(0).buffer) }); + } + return Promise.resolve({ ok: true, arrayBuffer: () => Promise.resolve(new Uint8Array(50).buffer), json: () => Promise.resolve([]) }); +}; +eval(fs.readFileSync(process.argv[2], 'utf8')); +const MO = global.window.MapOffline; + +(async () => { + // 1. Bbox-Replace: aufgehobener Giftköder verschwindet beim Re-Download + await MO.downloadAround(48.07, 11.96, { budgetMB: 0.005 }); + let p = stores.tiles.get('p/_poison'); + console.log('Nach 1. Download Giftköder:', p.map(x => x.id)); + if (p.length !== 2) throw new Error('Erster Snapshot falsch'); + await MO.downloadAround(48.07, 11.96, { budgetMB: 0.005 }); + p = stores.tiles.get('p/_poison'); + console.log('Nach 2. Download (Alarm 2 aufgehoben):', p.map(x => x.id)); + if (p.length !== 1 || p[0].id !== 1) throw new Error('Bbox-Replace räumt aufgehobenen Alarm nicht weg'); + + // 2. 24h-Refresh: alertsTs alt → autoFill refresht auch ohne offene Zonen + stores.meta.set('alertsTs', Date.now() - 2 * 86400000); + const before = poisonRound; + await MO.autoFillDeadZones({ lat: 48.07, lon: 11.96 }); + console.log('Alert-Refresh gefeuert:', poisonRound > before, '— alertsTs erneuert:', Date.now() - stores.meta.get('alertsTs') < 5000); + if (poisonRound <= before) throw new Error('24h-Refresh feuert nicht'); + const ts1 = stores.meta.get('alertsTs'); + await MO.autoFillDeadZones({ lat: 48.07, lon: 11.96 }); + if (stores.meta.get('alertsTs') !== ts1) throw new Error('Refresh-Throttle (24h) greift nicht'); + + // 3. removeDeadZone + await MO.markDeadZone(48.5, 12.5); + const z = stores.meta.get('deadzones')[0]; + await MO.removeDeadZone(z.ts); + console.log('removeDeadZone:', stores.meta.get('deadzones').length === 0); + if (stores.meta.get('deadzones').length !== 0) throw new Error('removeDeadZone kaputt'); + + // 4. ensureRouteCorridors: fehlende Route wird geladen, vorhandene nicht doppelt + const route = { id: 7, name: 'Weiher-Runde', preview_track: [ + { lat: 48.20, lon: 12.10 }, { lat: 48.21, lon: 12.12 }, { lat: 48.22, lon: 12.14 }] }; + const k1 = await MO.ensureRouteCorridors([route], { lat: 48.20, lon: 12.10 }); + const k2 = await MO.ensureRouteCorridors([route], { lat: 48.20, lon: 12.10 }); + console.log('ensureRouteCorridors: 1. Lauf geladen:', k1, '— 2. Lauf (abgedeckt):', k2); + if (k1 !== 1 || k2 !== 0) throw new Error('Korridor-Ensure kaputt'); + // ferne Route (>50km) wird ignoriert + const far = { id: 8, name: 'Fernroute', preview_track: [{ lat: 50.5, lon: 9.5 }, { lat: 50.6, lon: 9.6 }] }; + const k3 = await MO.ensureRouteCorridors([far], { lat: 48.20, lon: 12.10 }); + if (k3 !== 0) throw new Error('Nähe-Filter für Routen kaputt'); + // Region-Dedupe: 'korridor'+Name nur einmal in der Liste + const kr = stores.meta.get('regions').filter(r => r.name === 'Weiher-Runde'); + console.log('Korridor-Region dedupe:', kr.length === 1); + if (kr.length !== 1) throw new Error('_addRegion-Dedupe kaputt'); + + console.log('\nALLE RUNDE-5-TESTS BESTANDEN'); +})().catch(e => { console.error('FEHLER:', e.message); process.exit(1); });