baldav/frontend/js/tilecache.js
4aiman 184b86b18c Tile import, road map, orientation lock, CSP fix, tile error handling
- Tile import: pack_tiles.js (PNG→SQLite), Rust import_tiles + download_file
  commands, JS importFromSqlite, UI in settings (file + router download)
- Road map: road_points table with 2m dedup, rebuild_roads + get_road_points
  Rust commands (bypass Tauri SQL plugin 28K row limit), bike=blue walk=brown
- Orientation lock button (A/L) on recording map, hysteresis 65/35 degrees
- CSP fix: tile URL a.tile.openstreetmap.org (matches *.tile CSP pattern)
- Tile errors: done(null, tile) instead of Error to prevent crash cascade
- GPS placeholder: only show when state=waiting_gps (not on screen re-enter)
- ureq body size: use into_reader() to bypass 10MB limit for tile downloads
2026-06-26 16:41:14 +03:00

209 lines
6.3 KiB
JavaScript

// Offline tile cache — download OSM tiles to IndexedDB, serve locally
// Exposes window.TileCache
const TileCache = {};
const DB_NAME = "baldav_tiles";
const STORE = "tiles";
let _db = null;
function openDB() {
if (_db) return Promise.resolve(_db);
return new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, 1);
req.onupgradeneeded = () => req.result.createObjectStore(STORE);
req.onsuccess = () => { _db = req.result; resolve(_db); };
req.onerror = () => reject(req.error);
});
}
function putTile(key, blob) {
return openDB().then(db => new Promise((resolve, reject) => {
const tx = db.transaction(STORE, "readwrite");
tx.objectStore(STORE).put(blob, key);
tx.oncomplete = resolve;
tx.onerror = () => reject(tx.error);
}));
}
function getTile(key) {
return openDB().then(db => new Promise((resolve, reject) => {
const tx = db.transaction(STORE, "readonly");
const req = tx.objectStore(STORE).get(key);
req.onsuccess = () => resolve(req.result || null);
req.onerror = () => reject(req.error);
}));
}
// Count cached tiles
TileCache.count = async function() {
const db = await openDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE, "readonly");
const req = tx.objectStore(STORE).count();
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
};
// Clear all cached tiles
TileCache.clear = async function() {
const db = await openDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE, "readwrite");
tx.objectStore(STORE).clear();
tx.oncomplete = resolve;
tx.onerror = () => reject(tx.error);
});
};
// Calculate tile coordinates for a bounding box at a given zoom
function getTileRange(bounds, zoom) {
const n = Math.pow(2, zoom);
const toTile = (lat, lon) => ({
x: Math.floor((lon + 180) / 360 * n),
y: Math.floor((1 - Math.log(Math.tan(lat * Math.PI / 180) + 1 / Math.cos(lat * Math.PI / 180)) / Math.PI) / 2 * n),
});
const sw = toTile(bounds.getSouth(), bounds.getWest());
const ne = toTile(bounds.getNorth(), bounds.getEast());
return {
xMin: Math.min(sw.x, ne.x), xMax: Math.max(sw.x, ne.x),
yMin: Math.min(sw.y, ne.y), yMax: Math.max(sw.y, ne.y),
};
}
// Count tiles needed for area + zoom range
TileCache.countTilesForArea = function(bounds, zoomMin, zoomMax) {
let total = 0;
for (let z = zoomMin; z <= zoomMax; z++) {
const r = getTileRange(bounds, z);
total += (r.xMax - r.xMin + 1) * (r.yMax - r.yMin + 1);
}
return total;
};
// Download tiles for current map bounds
// onProgress(downloaded, total) callback
TileCache.downloadArea = async function(bounds, zoomMin, zoomMax, onProgress) {
const tiles = [];
for (let z = zoomMin; z <= zoomMax; z++) {
const r = getTileRange(bounds, z);
for (let x = r.xMin; x <= r.xMax; x++) {
for (let y = r.yMin; y <= r.yMax; y++) {
tiles.push({ z, x, y });
}
}
}
let done = 0;
const PARALLEL = 12;
async function downloadOne(tile) {
const key = `${tile.z}/${tile.x}/${tile.y}`;
// Skip if already cached
const existing = await getTile(key);
if (existing) { done++; if (onProgress) onProgress(done, tiles.length); return; }
const url = `https://a.tile.openstreetmap.org/${key}.png`;
try {
const resp = await fetch(url);
if (resp.ok) {
const blob = await resp.blob();
await putTile(key, blob);
}
} catch { /* skip failed tiles */ }
done++;
if (onProgress) onProgress(done, tiles.length);
}
// Process in parallel batches
for (let i = 0; i < tiles.length; i += PARALLEL) {
const batch = tiles.slice(i, i + PARALLEL);
await Promise.all(batch.map(downloadOne));
}
return done;
};
// Custom Leaflet TileLayer that checks IndexedDB first
TileCache.createLayer = function() {
return L.TileLayer.extend({
createTile: function(coords, done) {
const tile = document.createElement("img");
const key = `${coords.z}/${coords.x}/${coords.y}`;
getTile(key).then(blob => {
if (blob) {
tile.src = URL.createObjectURL(blob);
done(null, tile);
} else if (TileCache.offlineMode) {
// Offline: show empty tile
done(null, tile);
} else {
// Fetch from network
tile.crossOrigin = "";
tile.src = `https://a.tile.openstreetmap.org/${key}.png`;
tile.onload = () => {
fetch(tile.src).then(r => r.blob()).then(b => putTile(key, b)).catch(() => {});
done(null, tile);
};
tile.onerror = () => done(null, tile);
}
}).catch(() => {
if (TileCache.offlineMode) { done(null, tile); return; }
tile.src = `https://a.tile.openstreetmap.org/${key}.png`;
tile.onload = () => done(null, tile);
tile.onerror = () => done(null, tile);
});
return tile;
}
});
};
// Offline mode — when true, tiles only served from cache, never fetched from network
TileCache.offlineMode = false;
TileCache.setOfflineMode = function(val) {
TileCache.offlineMode = !!val;
localStorage.setItem("baldav_offline_maps", val ? "1" : "0");
};
TileCache.loadOfflineMode = function() {
TileCache.offlineMode = localStorage.getItem("baldav_offline_maps") === "1";
};
TileCache.loadOfflineMode();
// Import tiles from a SQLite file (packed by tools/pack_tiles.js) into IndexedDB
// path: filesystem path to the .db file
// onProgress(done, total): callback
TileCache.importFromSqlite = async function(path, onProgress) {
const invoke = window.__TAURI__.core.invoke;
const BATCH = 100;
let offset = 0;
let total = 0;
let imported = 0;
while (true) {
const raw = await invoke("import_tiles", { path, offset, batchSize: BATCH });
const resp = JSON.parse(raw);
total = resp.total;
for (const [key, b64] of resp.tiles) {
const binary = atob(b64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
await putTile(key, new Blob([bytes], { type: "image/png" }));
imported++;
}
if (onProgress) onProgress(imported, total);
if (!resp.has_more) break;
offset += BATCH;
}
return imported;
};
window.TileCache = TileCache;
console.log("[tilecache.js] window.TileCache ready, offline:", TileCache.offlineMode);