Route panel: points from search, GPS and library points, reordering, editing a saved route

This commit is contained in:
randy committed 2026-11-13 22:37:49 +01:00
1 parent 3146478c23
commit abde7fe5f9
10 files changed
+214 -25

No files matched your search

+25 -1
View File
@@ -11,7 +11,7 @@ import {
POI_ICONS,
PARK4NIGHT_TAGS,
} from "/js/icons.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen, onGpxStoreChanged, notifyGpxStoreChanged } from "/js/panels.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen, onGpxStoreChanged, notifyGpxStoreChanged, addRoutePoint, editRoute } from "/js/panels.js";
import { formatActivityType } from "/js/track_profile.js";
import { isLoggedIn } from "/js/auth.js";
@@ -366,6 +366,7 @@ export class GpxPanelControl {
{ label: "Color…", run: () => this._pickColor(file) },
file.color && { label: "Default color", run: () => this._patchNode(file.path, { color: "" }) },
file.layer && { label: "Split into items", run: () => this._splitLayer(file) },
(file.kinds || []).includes("route") && { label: "Edit route", run: () => this._editRoute(file) },
]);
}
@@ -757,6 +758,17 @@ export class GpxPanelControl {
.setHTML(popupHtml(feature.properties, { editable }))
.addTo(this._map);
if (editable) this._wireNoteActions(popup, path, feature);
if (feature.geometry.type === "Point") {
const button = document.createElement("button");
button.type = "button";
button.className = "gpx-popup__route";
button.textContent = "Add to route";
button.addEventListener("click", () => {
addRoutePoint(feature.geometry.coordinates, feature.properties.name);
popup.remove();
});
popup.getElement().querySelector(".maplibregl-popup-content").appendChild(button);
}
}
// Edit swaps the popup's content for a plain textarea + Save/Cancel (the
@@ -1123,6 +1135,18 @@ export class GpxPanelControl {
}
}
// A route saved from the route panel keeps its points (properties.via);
// one without them (an imported GPX route) can't be re-routed.
async _editRoute(file) {
const { features } = await (await fetch(gpxFileUrl(file.path))).json();
const route = features.find((f) => f.geometry.type === "LineString" && Array.isArray(f.properties.via));
if (!route) {
window.alert("This route has no saved route points, so it can't be edited.");
return;
}
editRoute(file.path, route);
}
async _splitLayer(file) {
if (!window.confirm(`Split "${file.name}" into separate points and tracks? This can't be undone.`)) return;
+1 -1
View File
@@ -585,7 +585,7 @@ if (isLoggedIn()) new PluginsControl(map).mount(sidebar);
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Offline hub"></div>`);
layerToggle.mount(sidebar);
layerToggle.setActive("online");
new RoutePanelControl(map).mount(sidebar);
new RoutePanelControl(map, gnssControl).mount(sidebar);
new OfflineDataControl().mount(sidebar);
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Navigation"></div>`);
+22
View File
@@ -31,3 +31,25 @@ export function notifyGpxStoreChanged(path) {
export function onGpxStoreChanged(callback) {
document.addEventListener(STORE_CHANGED_EVENT, (event) => callback(event.detail));
}
// Anything with a location (a search result, a library point) hands it to
// the route panel (route.js) the same decoupled way.
const ROUTE_POINT_EVENT = "route-point";
const ROUTE_EDIT_EVENT = "route-edit";
export function addRoutePoint(lngLat, name) {
document.dispatchEvent(new CustomEvent(ROUTE_POINT_EVENT, { detail: { lngLat, name } }));
}
export function onRoutePoint(callback) {
document.addEventListener(ROUTE_POINT_EVENT, (event) => callback(event.detail));
}
// A saved route (its library node key and feature) back into the panel.
export function editRoute(key, feature) {
document.dispatchEvent(new CustomEvent(ROUTE_EDIT_EVENT, { detail: { key, feature } }));
}
export function onRouteEdit(callback) {
document.addEventListener(ROUTE_EDIT_EVENT, (event) => callback(event.detail));
}
+92 -19
View File
@@ -1,6 +1,6 @@
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { ROUTE_ICON } from "/js/icons.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen, notifyGpxStoreChanged } from "/js/panels.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen, notifyGpxStoreChanged, onRoutePoint, onRouteEdit } from "/js/panels.js";
import { isLoggedIn } from "/js/auth.js";
const ROUTE_URL = "/api/route";
@@ -15,11 +15,19 @@ const SAVE_FOLDER = "Routes";
// them comes from POST /api/route (Valhalla, for the stored vehicle). The
// route stays drawn after the panel closes, until Clear.
export class RoutePanelControl {
constructor(map) {
constructor(map, gnssControl) {
this._map = map;
this._points = []; // [{ lngLat: [lon, lat], marker }]
this._gnss = gnssControl;
this._points = []; // [{ lngLat: [lon, lat], name, marker }]
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
onRoutePoint(({ lngLat, name }) => {
this._setOpen(true);
this._addPoint(lngLat, name);
});
onRouteEdit(({ key, feature }) => this._edit(key, feature));
map.on("click", (event) => {
if (this._panel.hidden || event.originalEvent.altKey) return;
@@ -47,6 +55,8 @@ export class RoutePanelControl {
this._changed();
});
this._panel.querySelector('[data-action="clear"]').addEventListener("click", () => this._clear());
this._panel.querySelector('[data-action="position"]').addEventListener("click", () => this._addPosition());
this._editingNote = this._panel.querySelector(".route-panel__editing");
this._saveButton.addEventListener("click", () => this._save());
this._setupVehicle();
@@ -67,17 +77,49 @@ export class RoutePanelControl {
// --- points ---------------------------------------------------------------
_addPoint(lngLat) {
_addPoint(lngLat, name, { quiet = false } = {}) {
const element = document.createElement("div");
element.className = "route-marker";
const marker = new Marker({ element, draggable: true }).setLngLat(lngLat).addTo(this._map);
const point = { lngLat, marker };
const point = { lngLat, name, marker };
marker.on("dragend", () => {
const { lng, lat } = marker.getLngLat();
point.lngLat = [lng, lat];
point.name = null; // no longer that place
this._changed();
});
this._points.push(point);
if (!quiet) this._changed();
}
// The GNSS fix when there is one, else the browser's own position.
_addPosition() {
const fix = this._gnss?.getPosition();
if (fix) {
this._addPoint([fix.lng, fix.lat], "My position");
return;
}
navigator.geolocation.getCurrentPosition(
(position) => this._addPoint([position.coords.longitude, position.coords.latitude], "My position"),
() => window.alert("Could not determine your location."),
{ enableHighAccuracy: true },
);
}
_move(point, step) {
const index = this._points.indexOf(point);
const other = index + step;
if (other < 0 || other >= this._points.length) return;
[this._points[index], this._points[other]] = [this._points[other], this._points[index]];
this._changed();
}
// A saved route's points back in the panel; Save then updates that item.
_edit(key, feature) {
this._clear();
feature.properties.via.forEach((lngLat) => this._addPoint(lngLat, null, { quiet: true }));
this._editing = { key, id: feature.properties.id, name: feature.properties.name };
this._setOpen(true);
this._changed();
}
@@ -90,6 +132,7 @@ export class RoutePanelControl {
_clear() {
this._points.forEach((p) => p.marker.remove());
this._points = [];
this._editing = null;
this._changed();
}
@@ -105,16 +148,31 @@ export class RoutePanelControl {
point.marker.getElement().textContent = index === 0 ? "S" : index === this._points.length - 1 ? "E" : String(index);
const li = document.createElement("li");
const text = document.createElement("span");
text.textContent = `${label} · ${point.lngLat[1].toFixed(5)}, ${point.lngLat[0].toFixed(5)}`;
const remove = document.createElement("button");
remove.type = "button";
remove.className = "route-panel__remove";
remove.title = "Remove";
remove.textContent = "×";
remove.addEventListener("click", () => this._removePoint(point));
li.append(text, remove);
text.className = "route-panel__point";
text.textContent = `${label} · ${point.name || `${point.lngLat[1].toFixed(5)}, ${point.lngLat[0].toFixed(5)}`}`;
li.append(
text,
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)),
);
this._list.appendChild(li);
});
this._editingNote.hidden = !this._editing;
if (this._editing) this._editingNote.textContent = `Editing "${this._editing.name}"`;
this._saveButton.textContent = this._editing ? "Save changes" : "Save to library";
}
_pointButton(text, title, enabled, onClick) {
const button = document.createElement("button");
button.type = "button";
button.className = "route-panel__remove";
button.title = title;
button.setAttribute("aria-label", title);
button.textContent = text;
button.disabled = !enabled;
button.addEventListener("click", onClick);
return button;
}
// --- route ----------------------------------------------------------------
@@ -193,9 +251,10 @@ export class RoutePanelControl {
}
// A route item in the library ("Routes" folder), keeping its points and
// vehicle so it can be routed again later.
// vehicle so it can be routed again later; an edited one is updated in
// place.
async _save() {
const name = window.prompt("Route name:", `Route ${new Date().toLocaleDateString()}`);
const name = window.prompt("Route name:", this._editing?.name || `Route ${new Date().toLocaleDateString()}`);
if (!name || !name.trim()) return;
const { maneuvers, ...properties } = this._route.properties;
@@ -204,10 +263,15 @@ export class RoutePanelControl {
geometry: this._route.geometry,
properties: { ...properties, name: name.trim(), via: this._points.map((p) => p.lngLat), vehicle: this._vehicle },
};
const editing = this._editing;
const response = await fetch(NOTES_URL, {
method: "POST",
method: editing ? "PUT" : "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ feature: JSON.stringify(feature), folder: SAVE_FOLDER }),
body: new URLSearchParams(
editing
? { feature: JSON.stringify(feature), path: editing.key, id: editing.id }
: { feature: JSON.stringify(feature), folder: SAVE_FOLDER },
),
});
if (response.status === 401) {
window.location.href = "/login";
@@ -217,9 +281,18 @@ export class RoutePanelControl {
window.alert("Could not save the route.");
return;
}
const { path } = await response.json();
const path = editing ? editing.key : (await response.json()).path;
notifyGpxStoreChanged(path);
this._summary.textContent += ` · saved to "${SAVE_FOLDER}"`;
this._editing = { key: path, id: editing?.id ?? (await this._savedId(path)), name: name.trim() };
this._renderPoints();
this._summary.textContent += " · saved";
}
// The id of the route just saved, so a second Save updates it instead of
// adding another copy.
async _savedId(key) {
const { features } = await (await fetch(`/api/library/node/${encodeURIComponent(key)}`)).json();
return features.find((f) => f.geometry.type === "LineString")?.properties.id;
}
// --- vehicle --------------------------------------------------------------
+9
View File
@@ -1,6 +1,7 @@
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { SEARCH_ICON } from "/js/icons.js";
import { escapeHtml } from "/js/gpx.js";
import { addRoutePoint } from "/js/panels.js";
const NOMINATIM_API = "https://nominatim.openstreetmap.org/search";
// "lat, lng" / "lat lng" decimal degrees — the same plain-text shape the
@@ -208,6 +209,7 @@ export class SearchControl {
result.status
? `<li class="search-panel__status">${escapeHtml(result.status)}</li>`
: `<li class="search-panel__result" data-index="${i}">
${result.lat != null || result.bbox ? `<button type="button" class="search-panel__route" title="Add to route" aria-label="Add to route">+</button>` : ""}
${escapeHtml(result.name)}
<span class="search-panel__where">${escapeHtml(
[result.where, result.distanceKm != null && formatKm(result.distanceKm)].filter(Boolean).join(" · "),
@@ -215,6 +217,13 @@ export class SearchControl {
</li>`,
)
.join("") + tail;
this._resultsEl.querySelectorAll(".search-panel__route").forEach((button) => {
button.addEventListener("click", (event) => {
event.stopPropagation();
const { lat, lng, bbox, name } = this._results[Number(button.closest("li").dataset.index)];
addRoutePoint(lat != null ? [lng, lat] : [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2], name);
});
});
this._resultsEl.querySelectorAll(".search-panel__result").forEach((el) => {
el.addEventListener("click", () => {
const result = this._results[Number(el.dataset.index)];