Offline-Karten Runde 5: Geraetetest-Feedback (Indikator, Flugmodus-Signal, Ent-Funklochen, Warnungs-Aktualitaet, Routen-Start-Check)
- Indikator links unter die Zoom-Regler (rechts verdeckte Legenden-Chips) - Flugmodus bei offener App -> Position raw als Funkloch-Zone (offline-Event) - Ent-Funklochen: Zonen-Liste im Offline-Modal mit X (removeDeadZone) - Warnungs-Aktualitaet: _mergeStore Bbox-Replace (aufgehobene Giftkoeder/ gefundene Hunde verschwinden; Fetch-Kreis deckt Bbox via sqrt2 ab; fresh=null merged nie) + 24h-Refresh im 50km-Umkreis beim Start - Routen offline nutzbar halten: ensureRouteCorridors beim Start-Check (Stichproben-Verify, Re-Download aus preview_track, Region-Dedupe) - Stub-Tests ins Repo: tests/js/ (r1/r3/r4/r5, alle gruen) Bump v1231
This commit is contained in:
parent
53bc27faa3
commit
6c313aca05
15 changed files with 606 additions and 52 deletions
2
VERSION
2
VERSION
|
|
@ -1 +1 @@
|
|||
1230
|
||||
1231
|
||||
|
|
@ -7307,14 +7307,13 @@ svg.empty-state-icon {
|
|||
pointer-events: none;
|
||||
letter-spacing: 0.01em;
|
||||
}
|
||||
/* Eingeklappt (5s nach Offline-Gang, boot.js): kleines pulsierendes Icon oben rechts —
|
||||
die Leiste über die volle Breite verdeckte Nav-Elemente (z.B. „← Zurück" in der
|
||||
Routennavigation, Gerätetest 2026-06-07). Sitzt UNTERHALB der Kopfzeilen-Höhe,
|
||||
damit es Buttons (Zentrieren, Legende) nie überlagert. */
|
||||
/* 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 {
|
||||
top: calc(env(safe-area-inset-top, 0px) + 54px);
|
||||
left: auto;
|
||||
right: 8px;
|
||||
top: calc(env(safe-area-inset-top, 0px) + 110px);
|
||||
left: 10px;
|
||||
right: auto;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
padding: 0;
|
||||
|
|
|
|||
|
|
@ -86,14 +86,14 @@
|
|||
<title>Ban Yaro</title>
|
||||
|
||||
<!-- Theme + theme-color Statusleiste vor CSS setzen -->
|
||||
<script src="/js/boot-early.js?v=1230"></script>
|
||||
<script src="/js/boot-early.js?v=1231"></script>
|
||||
|
||||
<!-- CSS: Reihenfolge ist wichtig — ?v= zwingt Browser zur Neuladung -->
|
||||
<link rel="stylesheet" href="/css/design-system.css?v=1230">
|
||||
<link rel="stylesheet" href="/css/layout.css?v=1230">
|
||||
<link rel="stylesheet" href="/css/components.css?v=1230">
|
||||
<link rel="stylesheet" href="/css/utilities.css?v=1230">
|
||||
<link rel="stylesheet" href="/css/lists.css?v=1230">
|
||||
<link rel="stylesheet" href="/css/design-system.css?v=1231">
|
||||
<link rel="stylesheet" href="/css/layout.css?v=1231">
|
||||
<link rel="stylesheet" href="/css/components.css?v=1231">
|
||||
<link rel="stylesheet" href="/css/utilities.css?v=1231">
|
||||
<link rel="stylesheet" href="/css/lists.css?v=1231">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
|
|
@ -612,11 +612,11 @@
|
|||
<div id="modal-container"></div>
|
||||
|
||||
<!-- JS: Reihenfolge ist wichtig — erst Basis, dann Features -->
|
||||
<script src="/js/api.js?v=1230"></script>
|
||||
<script src="/js/ui.js?v=1230"></script>
|
||||
<script src="/js/app.js?v=1230"></script>
|
||||
<script src="/js/worlds.js?v=1230"></script>
|
||||
<script src="/js/offline-indicator.js?v=1230"></script>
|
||||
<script src="/js/api.js?v=1231"></script>
|
||||
<script src="/js/ui.js?v=1231"></script>
|
||||
<script src="/js/app.js?v=1231"></script>
|
||||
<script src="/js/worlds.js?v=1231"></script>
|
||||
<script src="/js/offline-indicator.js?v=1231"></script>
|
||||
|
||||
<!-- Feature-Seiten werden lazy geladen -->
|
||||
|
||||
|
|
@ -626,7 +626,7 @@
|
|||
|
||||
|
||||
<!-- Boot: Offline-Banner + SW-Registration (extrahiert für CSP) -->
|
||||
<script src="/js/boot.js?v=1230"></script>
|
||||
<script src="/js/boot.js?v=1231"></script>
|
||||
|
||||
|
||||
</body>
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
Router, State-Management, Navigation, Initialisierung.
|
||||
============================================================ */
|
||||
|
||||
const APP_VER = '1230'; // ← bei jedem Deploy mit Frontend-Änderungen erhöhen
|
||||
const APP_VER = '1231'; // ← 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;
|
||||
|
|
|
|||
|
|
@ -128,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; });
|
||||
});
|
||||
}
|
||||
|
|
@ -150,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) {
|
||||
|
|
@ -217,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);
|
||||
|
|
@ -430,6 +463,15 @@ window.MapOffline = (function () {
|
|||
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) {
|
||||
|
|
@ -459,12 +501,17 @@ window.MapOffline = (function () {
|
|||
if (over) return null; // Speicher-Cap erreicht → kein automatisches Nachladen mehr
|
||||
return _metaGet('deadzones');
|
||||
}).then(function (zones) {
|
||||
if (zones === null || zones === undefined) return 0;
|
||||
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) return 0;
|
||||
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) {
|
||||
|
|
@ -488,6 +535,10 @@ window.MapOffline = (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; },
|
||||
|
|
@ -549,6 +600,53 @@ window.MapOffline = (function () {
|
|||
.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})}.
|
||||
|
|
@ -626,8 +724,11 @@ window.MapOffline = (function () {
|
|||
return _count().then(function (count) {
|
||||
return _metaGet('regions').then(function (regions) {
|
||||
return _metaGet('totalBytes').then(function (totalBytes) {
|
||||
return _metaGet('region').then(function (meta) {
|
||||
return { count: count, meta: meta || null, regions: regions || [], totalBytes: totalBytes || 0 };
|
||||
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 || [] };
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -652,8 +753,9 @@ window.MapOffline = (function () {
|
|||
|
||||
return {
|
||||
registerProtocol: registerProtocol, downloadAround: downloadAround, downloadCorridor: downloadCorridor,
|
||||
downloadBbox: downloadBbox, tile: tile, glyph: glyph, pois: pois, alerts: alerts, coverage: coverage,
|
||||
setGps: setGps, markDeadZone: markDeadZone, autoFillDeadZones: autoFillDeadZones,
|
||||
downloadBbox: downloadBbox, ensureRouteCorridors: ensureRouteCorridors,
|
||||
tile: tile, glyph: glyph, pois: pois, alerts: alerts, coverage: coverage,
|
||||
setGps: setGps, markDeadZone: markDeadZone, removeDeadZone: removeDeadZone, autoFillDeadZones: autoFillDeadZones,
|
||||
stats: stats, hasRegion: hasRegion, clear: clear, MAXZOOM: MAXZOOM,
|
||||
};
|
||||
})();
|
||||
|
|
|
|||
|
|
@ -278,9 +278,44 @@ window.OfflineIndicator = (() => {
|
|||
return null;
|
||||
}
|
||||
|
||||
// Funkloch-Zonen automatisch füllen/verifizieren, sobald Netz da ist — das Gerät lernt
|
||||
// selbst, wo Offline-Karten nötig sind. Mit Position werden nur Zonen im Umkreis
|
||||
// (50 km) geladen → Speicher bleibt minimal, ferne Zonen kommen, wenn man dort ist.
|
||||
// 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;
|
||||
|
|
@ -288,12 +323,21 @@ window.OfflineIndicator = (() => {
|
|||
_autoFillTimer = setTimeout(async () => {
|
||||
if (!navigator.onLine) return;
|
||||
try {
|
||||
if (!(await _anyDeadZonesStored())) 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?.(pos ? { lat: pos.lat, lon: pos.lon } : {});
|
||||
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) {}
|
||||
|
|
@ -471,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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2276,11 +2276,30 @@ window.Page_map = (() => {
|
|||
</p>
|
||||
${regions.length ? `<button class="btn btn-secondary" id="off-clear" style="color:var(--c-danger)">${UI.icon('trash')} Alles löschen</button>` : ''}
|
||||
</div>
|
||||
${(s.deadzones || []).length ? `
|
||||
<div style="margin-top:var(--space-3)">
|
||||
<div style="font-size:var(--text-xs);font-weight:600;color:var(--c-text-secondary);margin-bottom:2px">
|
||||
Funkloch-Gebiete (${s.deadzones.length}) — werden automatisch aktuell gehalten</div>
|
||||
${s.deadzones.map(z => `
|
||||
<div class="off-zone-row" style="display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:var(--text-xs);padding:4px 0;border-top:1px solid var(--c-border)">
|
||||
<span style="color:var(--c-text-secondary)">📡 ${new Date(z.ts).toLocaleDateString('de-DE')} · ${z.lat.toFixed(3)}, ${z.lon.toFixed(3)} · ${z.filled ? 'geladen' : 'ausstehend'}</span>
|
||||
<button type="button" class="btn btn-secondary off-zone-del" data-ts="${z.ts}"
|
||||
title="Nicht mehr automatisch laden" style="padding:1px 8px;font-size:var(--text-xs)">✕</button>
|
||||
</div>`).join('')}
|
||||
</div>` : ''}
|
||||
`,
|
||||
footer: `<button class="btn btn-secondary" data-modal-close style="width:100%">Schließen</button>`,
|
||||
});
|
||||
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;
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<script src="/js/landing-init.js?v=1230"></script>
|
||||
<script src="/js/landing-init.js?v=1231"></script>
|
||||
<title>Ban Yaro — Die Hunde-App für Deutschland, Österreich & Schweiz</title>
|
||||
<meta name="description" content="Ban Yaro: Die kostenlose All-in-One Hunde-App für DACH. Tagebuch, Giftköder-Alarm, Training mit KI, Forum, Wurfbörse, Stammbaum, Inzucht-Check — DSGVO-konform, offline-fähig, ohne App Store.">
|
||||
<meta name="keywords" content="Hunde App, Hunde Community, Wurfbörse, Züchter, Welpen kaufen, Stammbaum Hund, Inzuchtkoeffizient, Hundezucht, Impfpass Hund, Giftköder Alarm, Gassi Community, Hundetraining App, Hunde Forum, Hunde KI, Hundefilm Datenbank, Welpen Marktplatz">
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
============================================================ */
|
||||
|
||||
// ← EINZIGE Stelle für die Version — STATIC_ASSETS und CACHE_VERSION leiten sich ab
|
||||
const VER = '1230';
|
||||
const VER = '1231';
|
||||
const CACHE_VERSION = `by-v${VER}`;
|
||||
const CACHE_STATIC = `${CACHE_VERSION}-static`;
|
||||
const CACHE_TILES = 'ban-yaro-tiles-v1'; // bleibt über SW-Updates erhalten
|
||||
|
|
|
|||
|
|
@ -103,6 +103,22 @@ die Kacheln sind jederzeit neu ableitbarer Cache.
|
|||
- **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).
|
||||
|
|
|
|||
15
tests/js/README.md
Normal file
15
tests/js/README.md
Normal file
|
|
@ -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.
|
||||
82
tests/js/test-map-offline-r1.js
Normal file
82
tests/js/test-map-offline-r1.js
Normal file
|
|
@ -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); });
|
||||
78
tests/js/test-map-offline-r3.js
Normal file
78
tests/js/test-map-offline-r3.js
Normal file
|
|
@ -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); });
|
||||
99
tests/js/test-map-offline-r4.js
Normal file
99
tests/js/test-map-offline-r4.js
Normal file
|
|
@ -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); });
|
||||
93
tests/js/test-map-offline-r5.js
Normal file
93
tests/js/test-map-offline-r5.js
Normal file
|
|
@ -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); });
|
||||
Loading…
Add table
Add a link
Reference in a new issue