Library phase 1: SQLite item library with folders, migration of old files as layers, import split into items

This commit is contained in:
randy committed 2026-11-13 09:03:22 +01:00
1 parent 4216211a20
commit ad8b72c3d3
16 files changed
+897 -499

No files matched your search

+32 -46
View File
@@ -6,7 +6,6 @@ import {
WAYPOINT_ICON,
TRACK_ICON,
ROUTE_ICON,
PENDING_ICON,
DOWNLOAD_ICON,
MAP_MARKER_ICON,
POI_ICONS,
@@ -16,10 +15,10 @@ import { notifySidePanelOpen, onlyOneSidePanelOpen, onGpxStoreChanged, notifyGpx
import { formatActivityType } from "/js/track_profile.js";
import { isLoggedIn } from "/js/auth.js";
const TREE_URL = "/api/gpx/tree";
const UPLOAD_URL = "/api/gpx";
const FOLDER_URL = "/api/gpx/folder";
const MOVE_URL = "/api/gpx/move";
const TREE_URL = "/api/library/tree";
const UPLOAD_URL = "/api/library/import";
const FOLDER_URL = "/api/library/folder";
const MOVE_URL = "/api/library/move";
const TRACK_COLOR = "#e63946";
const POI_ICON_KEYS = Object.keys(POI_ICONS);
const POI_ICON_IMAGE_SIZE = 48; // rasterized once at this size, rendered much smaller by icon-size below
@@ -303,26 +302,19 @@ export class GpxPanelControl {
checkbox.checked = this._visible.has(file.path);
checkbox.dataset.path = file.path;
checkbox.addEventListener("change", () => this._toggleFile(file.path, checkbox.checked, checkbox));
// Just the real, as-uploaded name — it used to grow a ".geojson" suffix
// once cached (matching the real "<path>.geojson" cache file on disk),
// back when the name doubled as a GeoJSON-only download link and the
// suffix explained what clicking it would get you. Now that downloading
// is the download button's job (see below), that suffix was just
// confusing: the file is still named "ride.gpx", not "ride.gpx.geojson".
const loggedIn = isLoggedIn();
const name = document.createElement("span");
name.className = "gpx-tree__file-name";
name.textContent = file.name;
label.appendChild(checkbox);
(file.kinds || []).forEach((kind) => label.appendChild(this._kindIcon(kind)));
if (!file.cached) label.appendChild(this._pendingIcon());
label.appendChild(name);
row.appendChild(label);
// Delete/download require login (app.rb); shown only once logged in
// rather than shown-but-failing-on-click.
if (loggedIn) {
row.appendChild(this._downloadButton(file));
row.appendChild(this._deleteButton(() => this._deleteFile(file.path)));
row.appendChild(this._deleteButton(() => this._deleteFile(file)));
}
return row;
@@ -344,14 +336,6 @@ export class GpxPanelControl {
return icon;
}
_pendingIcon() {
const icon = document.createElement("span");
icon.className = "gpx-tree__kind-icon";
icon.innerHTML = PENDING_ICON;
icon.title = "Not yet converted — dropped straight into data/gpx/, not uploaded through the app";
return icon;
}
// One button, one obvious place for both download kinds — clicking it
// opens a small menu (Original / GeoJSON) instead of splitting them
// across two differently-shaped click targets (the file name used to be
@@ -373,9 +357,10 @@ export class GpxPanelControl {
const menu = document.createElement("div");
menu.className = "gpx-tree__download-menu";
menu.hidden = true;
const geojsonName = file.cached && !file.name.toLowerCase().endsWith(".geojson") ? `${file.name}.geojson` : file.name;
menu.appendChild(this._downloadMenuItem("Original file", `${gpxFileUrl(file.path)}?download=original`, file.name));
menu.appendChild(this._downloadMenuItem("GeoJSON", `${gpxFileUrl(file.path)}?download=geojson`, geojsonName));
// A folder's loose points have no single file they came from.
if (file.original) menu.appendChild(this._downloadMenuItem("Original file", `${gpxFileUrl(file.path)}?download=original`, file.name));
const geojsonUrl = `${gpxFileUrl(file.path)}?${new URLSearchParams({ download: "geojson", name: file.name })}`;
menu.appendChild(this._downloadMenuItem("GeoJSON", geojsonUrl, `${file.name}.geojson`));
// stopPropagation so this click doesn't immediately reach the
// document-level listener (mount()) that closes whichever menu is
@@ -764,7 +749,7 @@ export class GpxPanelControl {
element.querySelector(".gpx-popup__delete")?.addEventListener("click", async () => {
if (!window.confirm("Delete this note?")) return;
try {
const response = await fetch(`/api/gpx/notes?${new URLSearchParams({ path, id })}`, { method: "DELETE" });
const response = await fetch(`/api/library/notes?${new URLSearchParams({ path, id })}`, { method: "DELETE" });
if (!response.ok) throw new Error(`delete failed: ${response.status}`);
popup.remove();
notifyGpxStoreChanged();
@@ -803,7 +788,7 @@ export class GpxPanelControl {
const updated = { ...feature, properties };
try {
const body = new URLSearchParams({ path, id, feature: JSON.stringify(updated) });
const response = await fetch("/api/gpx/notes", { method: "PUT", body });
const response = await fetch("/api/library/notes", { method: "PUT", body });
if (!response.ok) throw new Error(`save failed: ${response.status}`);
popup.remove();
notifyGpxStoreChanged();
@@ -952,10 +937,8 @@ export class GpxPanelControl {
async _uploadFiles(fileList, folder) {
// .zip: Garmin's bulk/FIT export format — the server expands it into
// its .gpx/.fit/.geojson entries, so it's accepted here even though the
// tree never shows a .zip itself. .geojson needs no server-side
// conversion (GpxStore#geojson serves it as-is) — accepted here so a
// 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.
// tree never shows a .zip itself. .geojson: e.g. a node's GeoJSON
// download, re-imported.
const files = [...fileList].filter((file) => /\.(gpx|fit|geojson|zip)$/i.test(file.name));
if (files.length === 0) return [];
@@ -1005,8 +988,8 @@ export class GpxPanelControl {
return paths;
}
async _deleteFile(path) {
if (!window.confirm(`Delete "${path}"?`)) return;
async _deleteFile({ path, name }) {
if (!window.confirm(`Delete "${name}"?`)) return;
const response = await fetch(gpxFileUrl(path), { method: "DELETE" });
if (redirectIfUnauthorized(response)) return;
@@ -1023,37 +1006,35 @@ export class GpxPanelControl {
async _deleteFolder(path) {
if (!window.confirm(`Delete "${path}" and everything in it?`)) return;
const response = await fetch(`/api/gpx/folder/${path.split("/").map(encodeURIComponent).join("/")}`, {
const response = await fetch(`/api/library/folder/${path.split("/").map(encodeURIComponent).join("/")}`, {
method: "DELETE",
});
if (redirectIfUnauthorized(response)) return;
if (!response.ok) return;
const prefix = `${path}/`;
[...this._visible].forEach((visiblePath) => {
if (visiblePath === path || visiblePath.startsWith(prefix)) {
this._visible.delete(visiblePath);
this._removeLayers(visiblePath);
}
});
// Node keys don't carry their folder's path — whatever's no longer in
// the tree was in the deleted folder.
const { tree } = await response.json();
const remaining = new Set(nodeKeys(tree));
[...this._visible].forEach((key) => {
if (remaining.has(key)) return;
this._visible.delete(key);
this._removeLayers(key);
});
this._renderTree(tree);
}
async _moveFile(from, toFolder) {
if (from === toFolder) return;
const response = await fetch(MOVE_URL, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: `from=${encodeURIComponent(from)}&to_folder=${encodeURIComponent(toFolder)}`,
body: `key=${encodeURIComponent(from)}&to_folder=${encodeURIComponent(toFolder)}`,
});
if (redirectIfUnauthorized(response)) return;
if (!response.ok) return;
const { path: newPath, tree } = await response.json();
if (this._visible.has(from)) {
if (this._visible.has(from) && newPath !== from) {
this._visible.delete(from);
this._removeLayers(from);
this._visible.add(newPath);
@@ -1138,8 +1119,13 @@ function pointsSourceId(path) {
return `gpx-${path}-points`;
}
// path: a node key from the tree ("item:<id>" / "points:<folder id>").
function gpxFileUrl(path) {
return `/api/gpx/file/${path.split("/").map(encodeURIComponent).join("/")}`;
return `/api/library/node/${encodeURIComponent(path)}`;
}
function nodeKeys(node) {
return (node.children || []).flatMap((child) => (child.type === "folder" ? nodeKeys(child) : [child.path]));
}
// properties come straight from an uploaded GPX file — untrusted input —
+1 -1
View File
@@ -456,7 +456,7 @@ map.addControl(new ZoomLevelControl(), "top-left");
const pitchToggle = new PitchToggleControl();
map.addControl(pitchToggle, "top-left");
map.addControl(new MeasureControl(), "top-left");
// Writing a note needs a login (POST /api/gpx/notes) — no point adding a
// Writing a note needs a login (POST /api/library/notes) — no point adding a
// button that can only ever end in a 401 for a logged-out viewer, same
// "hide the write-only affordance" story as GpxPanelControl's own
// upload/new-folder buttons.
+20 -26
View File
@@ -28,7 +28,7 @@ const ICON_LABELS = {
shop_convenience: "Convenience store",
};
const NEW_LAYER_VALUE = "__new__";
const NEW_FOLDER_VALUE = "__new__";
// Every hand-drawn note (from here or measure.js's "Save as note") gets one
// of these — the only stable way to find a specific feature again for
@@ -68,7 +68,7 @@ export class NoteSaveForm {
</div>
<textarea class="notes-panel__body" rows="3" placeholder="Details (optional) — **bold**, *italic*, links"></textarea>
<select class="notes-panel__target"></select>
<input type="text" class="notes-panel__new-name" placeholder="Layer name" hidden>
<input type="text" class="notes-panel__new-name" placeholder="Folder name" hidden>
<div class="notes-panel__actions">
<button type="button" class="notes-panel__save">Save</button>
<button type="button" class="notes-panel__cancel">Cancel</button>
@@ -92,7 +92,7 @@ export class NoteSaveForm {
});
});
this._target.addEventListener("change", () => {
this._newName.hidden = this._target.value !== NEW_LAYER_VALUE;
this._newName.hidden = this._target.value !== NEW_FOLDER_VALUE;
if (!this._newName.hidden) this._newName.focus();
});
this._saveButton.addEventListener("click", () => this._save());
@@ -129,20 +129,20 @@ export class NoteSaveForm {
async _populateTargets() {
const previousValue = this._target.value;
let files = [];
let folders = [];
try {
const tree = await (await fetch("/api/gpx/tree")).json();
files = geojsonFiles(tree);
const tree = await (await fetch("/api/library/tree")).json();
folders = folderPaths(tree);
} catch (err) {
// Tree fetch failed — target select just falls back to "new layer"
// only, still usable.
// Tree fetch failed — still usable with the top level or a new folder.
}
this._target.innerHTML =
files.map((file) => `<option value="${escapeAttr(file.path)}">${escapeText(file.path)}</option>`).join("") +
`<option value="${NEW_LAYER_VALUE}">+ New layer…</option>`;
this._target.value = files.some((file) => file.path === previousValue) ? previousValue : NEW_LAYER_VALUE;
this._newName.hidden = this._target.value !== NEW_LAYER_VALUE;
`<option value="">Top level</option>` +
folders.map((path) => `<option value="${escapeAttr(path)}">${escapeText(path)}</option>`).join("") +
`<option value="${NEW_FOLDER_VALUE}">+ New folder…</option>`;
this._target.value = folders.includes(previousValue) || previousValue === NEW_FOLDER_VALUE ? previousValue : "";
this._newName.hidden = this._target.value !== NEW_FOLDER_VALUE;
}
async _save() {
@@ -150,9 +150,9 @@ export class NoteSaveForm {
const details = this._body.value.trim();
if (!title || !this._geometry) return;
const isNewLayer = this._target.value === NEW_LAYER_VALUE;
const name = isNewLayer ? this._newName.value.trim() : "";
if (isNewLayer && !name) {
const isNewFolder = this._target.value === NEW_FOLDER_VALUE;
const folder = isNewFolder ? this._newName.value.trim() : this._target.value;
if (isNewFolder && !folder) {
this._newName.focus();
return;
}
@@ -170,13 +170,11 @@ export class NoteSaveForm {
geometry: this._geometry,
};
const requestBody = new URLSearchParams({ feature: JSON.stringify(feature) });
if (isNewLayer) requestBody.set("name", name);
else requestBody.set("path", this._target.value);
const requestBody = new URLSearchParams({ feature: JSON.stringify(feature), folder });
this._saveButton.disabled = true;
try {
const response = await fetch("/api/gpx/notes", { method: "POST", body: requestBody });
const response = await fetch("/api/library/notes", { method: "POST", body: requestBody });
if (!response.ok) throw new Error(`save failed: ${response.status}`);
const { path } = await response.json();
notifyGpxStoreChanged(path);
@@ -191,7 +189,7 @@ export class NoteSaveForm {
}
// A quick "pin it with a note" tool — click the map, write a short note,
// pick which .geojson "layer" file it joins (or start a new one). Point
// pick which folder it goes into (or start a new one). Point
// only: for a distance/area shape, draw it with the Measure tool and use
// its own "Save as note" button instead of duplicating that click-to-place
// UX here — see measure.js.
@@ -274,12 +272,8 @@ export class NotesControl {
}
}
function geojsonFiles(node, results = []) {
if (node.type === "file" && node.path.toLowerCase().endsWith(".geojson")) {
results.push({ path: node.path });
}
(node.children || []).forEach((child) => geojsonFiles(child, results));
return results;
function folderPaths(node) {
return (node.children || []).filter((child) => child.type === "folder").flatMap((child) => [child.path, ...folderPaths(child)]);
}
function escapeAttr(value) {
+1 -1
View File
@@ -104,7 +104,7 @@ function withExtension(name, type) {
async function fillFolderSuggestions(datalist) {
try {
const tree = await (await fetch("/api/gpx/tree")).json();
const tree = await (await fetch("/api/library/tree")).json();
const folders = [];
const walk = (node) =>
(node.children || []).forEach((child) => {