Installable PWA with a share target; design for an item-based library
CI / check (push) Successful in 18s
CI / deploy (push) Successful in 13s

Android's share sheet (OsmAnd, Locus, mapy.com, ...) can now send
GPX/FIT/GeoJSON/ZIP files to the installed app: the service worker parks
them and the page offers to import them into a Tracks & Points folder,
waiting through a login if needed. Manifest, app icon, a server-side
fallback for /share-target.

docs/library-design.adoc proposes replacing the file-based GpxStore with
folders and items (stable ids, timestamps, tombstones, a change feed) as
the base for syncing with OsmAnd and Locus.
This commit is contained in:
randy committed 2026-11-12 13:42:04 +01:00
1 parent e2461f794c
commit 25b87b94fe
14 files changed
+637 -5

No files matched your search

+57
View File
@@ -99,6 +99,63 @@ html, body {
color: #fff;
}
/* Files shared to the installed app (share_import.js), waiting to be
imported. */
.share-import {
position: fixed;
bottom: 16px;
left: 50%;
transform: translateX(-50%);
z-index: 40;
width: 320px;
max-width: calc(100vw - 32px);
box-sizing: border-box;
padding: 12px;
background: #1a1a1a;
color: #ddd;
border-radius: 6px;
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.35);
font-size: 13px;
}
.share-import__files {
margin: 6px 0;
padding-left: 18px;
max-height: 120px;
overflow-y: auto;
overflow-wrap: anywhere;
}
.share-import__folder {
display: flex;
align-items: center;
gap: 8px;
}
.share-import__folder input {
flex: 1;
min-width: 0;
padding: 4px 6px;
font: inherit;
}
.share-import__actions {
display: flex;
justify-content: flex-end;
align-items: center;
gap: 12px;
margin-top: 10px;
}
.share-import__actions a {
color: #8fb8ff;
}
.share-import__status {
margin: 8px 0 0;
color: #f2a29a;
}
/* Horizon-style sun & moon chart, dropped down from the topbar's sun
readout (sun.js sunChartHtml). */
.sun-chart {
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

+9
View File
@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<!-- Full-bleed background so the same file works as a maskable icon;
the artwork stays inside the central 80% safe zone. -->
<rect width="512" height="512" fill="#1a1a1a"/>
<path d="M120 380 C 170 330, 200 400, 250 350 S 330 300, 300 250" fill="none" stroke="#f2b632"
stroke-width="18" stroke-linecap="round" stroke-dasharray="2 34"/>
<path d="M330 110 a 70 70 0 0 1 70 70 c 0 52 -70 128 -70 128 s -70 -76 -70 -128 a 70 70 0 0 1 70 -70 z" fill="#fff"/>
<circle cx="330" cy="180" r="26" fill="#1a1a1a"/>
</svg>

After

Width:  |  Height:  |  Size: 599 B

+17 -3
View File
@@ -957,10 +957,11 @@ export class GpxPanelControl {
// file already in this app's own shape (e.g. a previous /api/gpx/file
// response, saved and re-uploaded) can skip GPX/FIT entirely.
const files = [...fileList].filter((file) => /\.(gpx|fit|geojson|zip)$/i.test(file.name));
if (files.length === 0) return;
if (files.length === 0) return [];
let tree = null;
let failed = 0;
const uploaded = [];
for (const [index, file] of files.entries()) {
this._setStatus(files.length === 1 ? "Uploading…" : `Uploading ${index + 1} of ${files.length}…`);
@@ -978,10 +979,12 @@ export class GpxPanelControl {
const xhr = await uploadFile(formData, () => this._setStatus("Converting…"));
if (xhr.status === 401) {
window.location.href = "/login";
return;
return uploaded;
}
if (xhr.status < 200 || xhr.status >= 300) throw new Error("upload failed");
({ tree } = JSON.parse(xhr.responseText));
let paths;
({ tree, paths } = JSON.parse(xhr.responseText));
uploaded.push(...paths);
} catch (err) {
failed += 1;
}
@@ -989,6 +992,17 @@ export class GpxPanelControl {
if (tree) this._renderTree(tree);
this._setStatus(failed > 0 ? `${failed} of ${files.length} uploads failed.` : "Uploaded.");
return uploaded;
}
// Files shared to the installed app (share_import.js): uploaded like a
// drop onto the tree, then shown on the map straight away — whoever
// shared a track from OsmAnd/Locus wants to see it, not hunt for it.
async importFiles(files, folder) {
this._togglePanel(true);
const paths = await this._uploadFiles(files, folder);
await Promise.all(paths.map((path) => this.show(path)));
return paths;
}
async _deleteFile(path) {
+2
View File
@@ -21,6 +21,7 @@ import { formatCoords, formatSunInfo, sunChartHtml } from "/js/sun.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen } from "/js/panels.js";
import { isLoggedIn } from "/js/auth.js";
import { DebugControl } from "/js/debug.js";
import { offerSharedFiles } from "/js/share_import.js";
import HomeButton from "/vendor/npmap-home-button/home-button.esm.js";
import OverviewMap from "/vendor/npmap-overview/overview.esm.js";
import * as maplibregl from "/vendor/maplibre-gl/maplibre-gl.mjs";
@@ -570,6 +571,7 @@ const gpxPanel = new GpxPanelControl(map, profilePanel);
gpxPanel.mount(sidebar);
const overlaysControl = new OverlaysControl(map);
overlaysControl.mount(sidebar);
offerSharedFiles(gpxPanel);
searchControl.setLayerOpeners({
layers: (path, result) => gpxPanel.showFeature(path, result.bbox.slice(0, 2)),
hiking_trails: (code) => overlaysControl.showHikingTrailsCountry(code),
+120
View File
@@ -0,0 +1,120 @@
import { isLoggedIn } from "/js/auth.js";
import { escapeHtml } from "/js/gpx.js";
// Files shared to the installed app from Android's share sheet (OsmAnd,
// Locus, mapy.com, a file manager, ...): public/sw.js parks them in this
// cache and opens the app; this offers to import them into a folder of
// Tracks & Points. Checked on every page load, not just right after a
// share, so a share made while logged out is still waiting after login.
const SHARED_CACHE = "shared-files";
const KNOWN_EXTENSION = /\.(gpx|fit|geojson|zip)$/i;
// Some apps share a bare name ("Track 12") — the upload only accepts
// these extensions, so one is added from the file's type.
const EXTENSION_BY_TYPE = {
"application/gpx+xml": ".gpx",
"application/xml": ".gpx",
"text/xml": ".gpx",
"application/geo+json": ".geojson",
"application/json": ".geojson",
"application/zip": ".zip",
"application/vnd.ant.fit": ".fit",
};
const DEFAULT_FOLDER = "Shared";
export async function offerSharedFiles(gpxPanel) {
if (new URLSearchParams(window.location.search).has("shared")) window.history.replaceState(null, "", "/");
if (!("caches" in window)) return;
let cache;
let requests;
try {
cache = await caches.open(SHARED_CACHE);
requests = await cache.keys();
} catch {
return; // storage blocked — nothing to offer
}
if (requests.length === 0) return;
const files = await Promise.all(
requests.map(async (request) => {
const response = await cache.match(request);
const blob = await response.blob();
return new File([blob], withExtension(decodeURIComponent(response.headers.get("x-filename") || "shared"), blob.type), {
type: blob.type,
});
}),
);
const discard = () => Promise.all(requests.map((request) => cache.delete(request)));
const card = document.createElement("div");
card.className = "share-import";
card.innerHTML = `
<strong>Shared to MapTool</strong>
<ul class="share-import__files">${files.map((file) => `<li>${escapeHtml(file.name)}</li>`).join("")}</ul>
${
isLoggedIn()
? `<label class="share-import__folder">Folder
<input type="text" value="${DEFAULT_FOLDER}" list="share-import-folders">
<datalist id="share-import-folders"></datalist>
</label>
<div class="share-import__actions">
<button type="button" data-action="import">Import</button>
<button type="button" data-action="discard">Discard</button>
</div>`
: `<p>Log in to import — they'll wait here until then.</p>
<div class="share-import__actions">
<a href="/login">Log in</a>
<button type="button" data-action="discard">Discard</button>
</div>`
}
<p class="share-import__status" hidden></p>
`;
document.body.appendChild(card);
card.querySelector('[data-action="discard"]').addEventListener("click", async () => {
await discard();
card.remove();
});
const importButton = card.querySelector('[data-action="import"]');
if (!importButton) return;
fillFolderSuggestions(card.querySelector("datalist"));
importButton.addEventListener("click", async () => {
const folder = card.querySelector(".share-import__folder input").value.trim();
card.querySelectorAll("button").forEach((button) => (button.disabled = true));
const paths = await gpxPanel.importFiles(files, folder);
if (paths.length > 0) {
await discard();
card.remove();
return;
}
// Nothing made it in (wrong file type, server error) — keep them
// parked so another try or a discard is still possible.
const status = card.querySelector(".share-import__status");
status.hidden = false;
status.textContent = "Import failed — only GPX, FIT, GeoJSON and ZIP files can be imported.";
card.querySelectorAll("button").forEach((button) => (button.disabled = false));
});
}
function withExtension(name, type) {
return KNOWN_EXTENSION.test(name) ? name : `${name}${EXTENSION_BY_TYPE[type] || ".gpx"}`;
}
async function fillFolderSuggestions(datalist) {
try {
const tree = await (await fetch("/api/gpx/tree")).json();
const folders = [];
const walk = (node) =>
(node.children || []).forEach((child) => {
if (child.type !== "folder") return;
folders.push(child.path);
walk(child);
});
walk(tree);
datalist.innerHTML = folders.map((path) => `<option value="${escapeHtml(path)}">`).join("");
} catch {
// suggestions only — typing a folder name still works
}
}
+35
View File
@@ -0,0 +1,35 @@
{
"name": "MapTool",
"short_name": "MapTool",
"description": "Offline maps, tracks and points for the van",
"start_url": "/",
"scope": "/",
"display": "standalone",
"background_color": "#1a1a1a",
"theme_color": "#1a1a1a",
"icons": [
{ "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png" },
{ "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
],
"share_target": {
"action": "/share-target",
"method": "POST",
"enctype": "multipart/form-data",
"params": {
"files": [
{
"name": "file",
"accept": [
"application/gpx+xml", ".gpx",
"application/geo+json", "application/json", ".geojson",
"application/zip", ".zip",
".fit", "application/vnd.ant.fit",
"application/xml", "text/xml",
"application/octet-stream"
]
}
]
}
}
}
+40 -2
View File
@@ -1,11 +1,16 @@
// Caches RainViewer radar tile images so the last-seen frames stay visible
// once the network is actually gone — nothing else here. No app-shell
// once the network is actually gone, and receives files shared to the
// installed app (manifest.webmanifest's share_target, below). No app-shell
// precaching: the app itself is served by the same local server that's
// already the offline resource in the van, so there's no "app unreachable
// but should still work" scenario to solve, unlike the radar tiles (a
// third-party CDN).
const CACHE_VERSION = "v1";
const RADAR_CACHE = `radar-tiles-${CACHE_VERSION}`;
// Files shared to the app wait here until the page imports them (see
// public/js/share_import.js) — not versioned, so a SW update can't drop a
// file someone shared but hasn't imported yet.
const SHARED_CACHE = "shared-files";
// ponytail: a rough cap, not real LRU/expiry — trims oldest-by-insertion via
// Cache API iteration order (stable in practice, not spec-guaranteed).
@@ -25,13 +30,17 @@ self.addEventListener("activate", (event) => {
event.waitUntil(
caches
.keys()
.then((keys) => Promise.all(keys.filter((key) => key !== RADAR_CACHE).map((key) => caches.delete(key))))
.then((keys) => Promise.all(keys.filter((key) => key !== RADAR_CACHE && key !== SHARED_CACHE).map((key) => caches.delete(key))))
.then(() => self.clients.claim()),
);
});
self.addEventListener("fetch", (event) => {
const url = new URL(event.request.url);
if (event.request.method === "POST" && url.origin === self.location.origin && url.pathname === "/share-target") {
event.respondWith(receiveSharedFiles(event.request));
return;
}
if (!isRadarTile(url)) return;
event.respondWith(networkFallingBackToCache(event.request));
@@ -61,3 +70,32 @@ async function trimRadarCache(cache) {
if (keys.length <= MAX_RADAR_TILES) return;
await Promise.all(keys.slice(0, keys.length - MAX_RADAR_TILES).map((key) => cache.delete(key)));
}
// Android's share sheet (OsmAnd, Locus, mapy.com, a file manager, ...)
// POSTs the files here. They're parked in SHARED_CACHE rather than
// uploaded straight away: the page does that with a normal same-origin
// request (session cookie, login redirect, folder choice) — see
// share_import.js.
async function receiveSharedFiles(request) {
try {
const form = await request.formData();
const cache = await caches.open(SHARED_CACHE);
const stamp = Date.now();
await Promise.all(
form
.getAll("file")
.filter((file) => file instanceof File)
.map((file, i) =>
cache.put(
`/shared-files/${stamp}-${i}`,
new Response(file, {
headers: { "content-type": file.type || "application/octet-stream", "x-filename": encodeURIComponent(file.name || "shared") },
}),
),
),
);
} catch {
// fall through to the app anyway — nothing parked just means nothing to offer
}
return Response.redirect("/?shared=1", 303);
}