Tracks and routes as containers of points: listed (collapsed) under them in the tree, added via a point's popup, a new note or the route planner's navigation pins, and written as course points into the FIT course
This commit is contained in:
1 parent
6aa7b34f92
commit
4265421457
10 files changed
+354
-20
No files matched your search
+89
-1
@@ -251,6 +251,9 @@ export class GpxPanelControl {
|
||||
}
|
||||
|
||||
_renderTree(node) {
|
||||
this._files = new Map();
|
||||
const index = (n) => (n.children || []).forEach((c) => (c.type === "folder" ? index(c) : this._files.set(c.path, c)));
|
||||
index(node);
|
||||
this._treeContainer.innerHTML = "";
|
||||
this._treeContainer.appendChild(this._renderChildren(node.children));
|
||||
}
|
||||
@@ -269,6 +272,8 @@ export class GpxPanelControl {
|
||||
const li = document.createElement("li");
|
||||
if (child.type === "folder") {
|
||||
li.appendChild(this._renderFolder(child));
|
||||
} else if (child.points) {
|
||||
li.appendChild(this._renderTrackWithPoints(child));
|
||||
} else {
|
||||
li.appendChild(this._renderFile(child));
|
||||
}
|
||||
@@ -278,6 +283,62 @@ export class GpxPanelControl {
|
||||
return ul;
|
||||
}
|
||||
|
||||
// A track/route holding points: collapsed by default (there can be many),
|
||||
// each point zooms to itself and can be taken out again.
|
||||
_renderTrackWithPoints(file) {
|
||||
this._openTracks ||= new Set();
|
||||
const details = document.createElement("details");
|
||||
details.className = "gpx-tree__track";
|
||||
details.open = this._openTracks.has(file.path);
|
||||
details.addEventListener("toggle", () => (details.open ? this._openTracks.add(file.path) : this._openTracks.delete(file.path)));
|
||||
const summary = document.createElement("summary");
|
||||
summary.appendChild(this._renderFile(file));
|
||||
details.appendChild(summary);
|
||||
|
||||
const ul = document.createElement("ul");
|
||||
ul.className = "gpx-tree__points";
|
||||
file.points.forEach((point) => {
|
||||
const li = document.createElement("li");
|
||||
li.className = "gpx-tree__point";
|
||||
const name = document.createElement("button");
|
||||
name.type = "button";
|
||||
name.className = "gpx-tree__point-name";
|
||||
name.textContent = point.name;
|
||||
name.addEventListener("click", () => this._goToPoint(file.path, point));
|
||||
li.appendChild(name);
|
||||
if (isLoggedIn()) li.appendChild(this._deleteButton(() => this._removePoint(file, point)));
|
||||
ul.appendChild(li);
|
||||
});
|
||||
details.appendChild(ul);
|
||||
return details;
|
||||
}
|
||||
|
||||
async _goToPoint(path, point) {
|
||||
await this.show(path);
|
||||
this._map.flyTo({ center: point.coordinates, zoom: Math.max(this._map.getZoom(), 15) });
|
||||
const feature = this._pointsByPath.get(path)?.features.find((f) => f.properties.id === point.id);
|
||||
if (feature) this._openPointPopup(path, feature, point.coordinates);
|
||||
}
|
||||
|
||||
async _removePoint(file, point) {
|
||||
if (!window.confirm(`Remove "${point.name}" from "${file.name}"?`)) return;
|
||||
const response = await fetch(`/api/library/notes?${new URLSearchParams({ path: file.path, id: point.id })}`, { method: "DELETE" });
|
||||
if (!response.ok) return window.alert("Could not remove the point.");
|
||||
await this._loadTree();
|
||||
if (this._visible.has(file.path)) await this._reloadFile(file.path);
|
||||
}
|
||||
|
||||
// A copy of the point into a shown track/route, which keeps it from
|
||||
// then on (exported with it, a course point in its FIT course).
|
||||
async _addPointTo(target, feature) {
|
||||
const { id, ...properties } = feature.properties;
|
||||
const body = new URLSearchParams({ feature: JSON.stringify({ type: "Feature", geometry: { type: "Point", coordinates: feature.geometry.coordinates }, properties }) });
|
||||
const response = await fetch(`${gpxFileUrl(target)}/points`, { method: "POST", body });
|
||||
if (!response.ok) return window.alert("Could not add the point.");
|
||||
this._renderTree((await response.json()).tree);
|
||||
await this._reloadFile(target);
|
||||
}
|
||||
|
||||
_renderFolder(folder) {
|
||||
const details = document.createElement("details");
|
||||
details.open = true;
|
||||
@@ -831,10 +892,37 @@ export class GpxPanelControl {
|
||||
addRoutePoint(feature.geometry.coordinates, feature.properties.name);
|
||||
popup.remove();
|
||||
});
|
||||
popup.getElement().querySelector(".maplibregl-popup-content").appendChild(button);
|
||||
const content = popup.getElement().querySelector(".maplibregl-popup-content");
|
||||
content.appendChild(button);
|
||||
if (isLoggedIn()) {
|
||||
// Into any track/route shown right now, or out of the one holding it.
|
||||
const holder = this._files?.get(path)?.points?.some((p) => p.id === feature.properties.id) && this._files.get(path);
|
||||
const targets = [...this._visible].filter((p) => p !== path && p.startsWith("item:") && this._files?.get(p)?.kinds?.some((k) => k === "track" || k === "route") && !this._files.get(p).layer);
|
||||
targets.forEach((target) => {
|
||||
content.appendChild(this._popupButton(`Add to "${this._files.get(target).name}"`, async () => {
|
||||
popup.remove();
|
||||
await this._addPointTo(target, feature);
|
||||
}));
|
||||
});
|
||||
if (holder) {
|
||||
content.appendChild(this._popupButton(`Remove from "${holder.name}"`, async () => {
|
||||
popup.remove();
|
||||
await this._removePoint(holder, { id: feature.properties.id, name: feature.properties.name || "Point" });
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_popupButton(label, onClick) {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "gpx-popup__route";
|
||||
button.textContent = label;
|
||||
button.addEventListener("click", onClick);
|
||||
return button;
|
||||
}
|
||||
|
||||
// Edit swaps the popup's content for a plain textarea + Save/Cancel (the
|
||||
// note's location doesn't change, just its text, so there's no need for
|
||||
// NoteSaveForm's fuller target-file picker here). Delete just confirms
|
||||
|
||||
+21
-5
@@ -130,9 +130,11 @@ export class NoteSaveForm {
|
||||
async _populateTargets() {
|
||||
const previousValue = this._target.value;
|
||||
let folders = [];
|
||||
let lines = [];
|
||||
try {
|
||||
const tree = await (await fetch("/api/library/tree")).json();
|
||||
folders = folderPaths(tree);
|
||||
lines = this._geometry?.type === "Point" ? trackNodes(tree) : [];
|
||||
} catch (err) {
|
||||
// Tree fetch failed — still usable with the top level or a new folder.
|
||||
}
|
||||
@@ -140,8 +142,11 @@ export class NoteSaveForm {
|
||||
this._target.innerHTML =
|
||||
`<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 : "";
|
||||
`<option value="${NEW_FOLDER_VALUE}">+ New folder…</option>` +
|
||||
// A point can go straight into a track/route (kept and exported with it).
|
||||
(lines.length ? `<optgroup label="Into a track / route">${lines.map(([key, label]) => `<option value="${escapeAttr(key)}">${escapeText(label)}</option>`).join("")}</optgroup>` : "");
|
||||
const values = [...this._target.options].map((o) => o.value);
|
||||
this._target.value = values.includes(previousValue) ? previousValue : "";
|
||||
this._newName.hidden = this._target.value !== NEW_FOLDER_VALUE;
|
||||
}
|
||||
|
||||
@@ -170,14 +175,16 @@ export class NoteSaveForm {
|
||||
geometry: this._geometry,
|
||||
};
|
||||
|
||||
const requestBody = new URLSearchParams({ feature: JSON.stringify(feature), folder });
|
||||
const intoLine = folder.startsWith("item:");
|
||||
const requestBody = new URLSearchParams({ feature: JSON.stringify(feature), ...(intoLine ? {} : { folder }) });
|
||||
|
||||
this._saveButton.disabled = true;
|
||||
try {
|
||||
const response = await fetch("/api/library/notes", { method: "POST", body: requestBody });
|
||||
const url = intoLine ? `/api/library/node/${encodeURIComponent(folder)}/points` : "/api/library/notes";
|
||||
const response = await fetch(url, { method: "POST", body: requestBody });
|
||||
if (!response.ok) throw new Error(`save failed: ${response.status}`);
|
||||
const { path } = await response.json();
|
||||
notifyGpxStoreChanged(path);
|
||||
notifyGpxStoreChanged(intoLine ? folder : path);
|
||||
this.close();
|
||||
this._onSaved?.();
|
||||
} catch (err) {
|
||||
@@ -276,6 +283,15 @@ function folderPaths(node) {
|
||||
return (node.children || []).filter((child) => child.type === "folder").flatMap((child) => [child.path, ...folderPaths(child)]);
|
||||
}
|
||||
|
||||
// Tracks/routes of the library as [key, "folder / name"].
|
||||
function trackNodes(node, folder = "") {
|
||||
return (node.children || []).flatMap((child) => {
|
||||
if (child.type === "folder") return trackNodes(child, child.path);
|
||||
const line = child.path.startsWith("item:") && !child.layer && child.kinds?.some((k) => k === "track" || k === "route");
|
||||
return line ? [[child.path, [folder, child.name].filter(Boolean).join(" / ")]] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function escapeAttr(value) {
|
||||
return value.replace(/&/g, "&").replace(/"/g, """);
|
||||
}
|
||||
|
||||
+55
-5
@@ -36,7 +36,7 @@ export class RoutePanelControl {
|
||||
.then((r) => r.json())
|
||||
.then((d) => d.available)
|
||||
.catch(() => false);
|
||||
this._points = []; // [{ lngLat: [lon, lat], name, marker }]
|
||||
this._points = []; // [{ lngLat: [lon, lat], name, nav, marker }]; nav: saved as a point the device shows
|
||||
this._route = null; // the last /api/route Feature
|
||||
this._request = 0; // so a slow older response can't overwrite a newer one
|
||||
this._editing = null; // { key, id, name } of a saved route being edited
|
||||
@@ -111,11 +111,13 @@ export class RoutePanelControl {
|
||||
|
||||
// --- points ---------------------------------------------------------------
|
||||
|
||||
_addPoint(lngLat, name, { quiet = false } = {}) {
|
||||
// A named place (a saved point, a search result) is shown in navigation
|
||||
// by default; a plain map click only shapes the route.
|
||||
_addPoint(lngLat, name, { quiet = false, nav = !!name && name !== "My position" } = {}) {
|
||||
const element = document.createElement("div");
|
||||
element.className = "route-marker";
|
||||
const marker = new Marker({ element, draggable: true }).setLngLat(lngLat).addTo(this._map);
|
||||
const point = { lngLat, name, marker };
|
||||
const point = { lngLat, name, nav, marker };
|
||||
marker.on("dragend", () => {
|
||||
const { lng, lat } = marker.getLngLat();
|
||||
point.lngLat = [lng, lat];
|
||||
@@ -153,7 +155,8 @@ export class RoutePanelControl {
|
||||
this._clear();
|
||||
// Back to the vehicle it was planned for, if that profile still exists.
|
||||
if (this._vehicles?.some((v) => v.id === feature.properties.vehicle?.id)) this._selectVehicle(feature.properties.vehicle.id);
|
||||
feature.properties.via.forEach((lngLat) => this._addPoint(lngLat, null, { quiet: true }));
|
||||
const named = feature.properties.via_points || [];
|
||||
feature.properties.via.forEach((lngLat, i) => this._addPoint(lngLat, named[i]?.name || null, { quiet: true, nav: !!named[i]?.nav }));
|
||||
this._editing = { key, id: feature.properties.id, name: feature.properties.name };
|
||||
this._setOpen(true);
|
||||
this._changed();
|
||||
@@ -188,6 +191,7 @@ export class RoutePanelControl {
|
||||
text.textContent = `${label} · ${point.name || `${point.lngLat[1].toFixed(5)}, ${point.lngLat[0].toFixed(5)}`}`;
|
||||
li.append(
|
||||
text,
|
||||
this._navButton(point, label),
|
||||
this._pointButton("↑", "Move up", index > 0, () => this._move(point, -1)),
|
||||
this._pointButton("↓", "Move down", index < this._points.length - 1, () => this._move(point, 1)),
|
||||
this._pointButton("×", "Remove", true, () => this._removePoint(point)),
|
||||
@@ -202,6 +206,24 @@ export class RoutePanelControl {
|
||||
this._saveButton.textContent = this._editing ? "Save changes" : "Save to library";
|
||||
}
|
||||
|
||||
// Toggles whether the point is saved into the route as a navigation
|
||||
// point (a course point on a Garmin); an unnamed one asks for a name.
|
||||
_navButton(point, label) {
|
||||
const button = this._pointButton("📍", "Show in navigation", true, () => {
|
||||
if (!point.nav && !point.name) {
|
||||
const name = window.prompt("Name shown in navigation:", label);
|
||||
if (!name?.trim()) return;
|
||||
point.name = name.trim();
|
||||
}
|
||||
point.nav = !point.nav;
|
||||
this._renderPoints();
|
||||
});
|
||||
button.classList.add("route-panel__nav");
|
||||
button.classList.toggle("active", !!point.nav);
|
||||
button.setAttribute("aria-pressed", !!point.nav);
|
||||
return button;
|
||||
}
|
||||
|
||||
_pointButton(text, title, enabled, onClick) {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
@@ -372,7 +394,14 @@ export class RoutePanelControl {
|
||||
type: "Feature",
|
||||
geometry: this._route.geometry,
|
||||
// The elevation profile too, so the library shows it like a track's.
|
||||
properties: { ...properties, ...this._profileProperties(), name: name.trim(), via: this._points.map((p) => p.lngLat), vehicle: this._vehicle },
|
||||
properties: {
|
||||
...properties,
|
||||
...this._profileProperties(),
|
||||
name: name.trim(),
|
||||
via: this._points.map((p) => p.lngLat),
|
||||
via_points: this._points.map((p) => ({ name: p.name || null, nav: !!p.nav })),
|
||||
vehicle: this._vehicle,
|
||||
},
|
||||
};
|
||||
const editing = this._editing;
|
||||
const response = await fetch(NOTES_URL, {
|
||||
@@ -393,12 +422,33 @@ export class RoutePanelControl {
|
||||
return;
|
||||
}
|
||||
const path = editing ? editing.key : (await response.json()).path;
|
||||
await this._saveNavPoints(path);
|
||||
notifyGpxStoreChanged(path);
|
||||
this._editing = { key: path, id: editing?.id ?? (await this._savedId(path)), name: name.trim() };
|
||||
this._renderPoints();
|
||||
this._summary.textContent += " · saved";
|
||||
}
|
||||
|
||||
// The route's points marked 📍 as points inside the route item (marked
|
||||
// from_route, so points added to it by hand stay untouched): missing
|
||||
// ones added, unmarked or moved ones removed.
|
||||
async _saveNavPoints(key) {
|
||||
const url = `/api/library/node/${encodeURIComponent(key)}`;
|
||||
const id = (p) => `${p.lngLat[0].toFixed(6)},${p.lngLat[1].toFixed(6)},${p.name}`;
|
||||
const { features } = await (await fetch(url)).json();
|
||||
const existing = new Map(features.filter((f) => f.geometry.type === "Point" && f.properties.from_route).map((f) => [id({ lngLat: f.geometry.coordinates, name: f.properties.name }), f]));
|
||||
const wanted = this._points.map((p, i) => ({ ...p, name: p.name || `Via ${i}` })).filter((p) => p.nav);
|
||||
const wantedIds = new Set(wanted.map(id));
|
||||
for (const [key2, f] of existing) {
|
||||
if (!wantedIds.has(key2)) await fetch(`/api/library/notes?${new URLSearchParams({ path: key, id: f.properties.id })}`, { method: "DELETE" });
|
||||
}
|
||||
for (const p of wanted) {
|
||||
if (existing.has(id(p))) continue;
|
||||
const feature = { type: "Feature", geometry: { type: "Point", coordinates: p.lngLat }, properties: { name: p.name, from_route: true } };
|
||||
await fetch(`${url}/points`, { method: "POST", body: new URLSearchParams({ feature: JSON.stringify(feature) }) });
|
||||
}
|
||||
}
|
||||
|
||||
// The id of the route just saved, so a second Save updates it instead of
|
||||
// adding another copy.
|
||||
async _savedId(key) {
|
||||
|
||||
Reference in new issue
Block a user