import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs"; import { ROUTE_ICON } from "/js/icons.js"; import { notifySidePanelOpen, onlyOneSidePanelOpen, notifyGpxStoreChanged, onRoutePoint, onRouteEdit } from "/js/panels.js"; import { isLoggedIn } from "/js/auth.js"; const ROUTE_URL = "/api/route"; const VEHICLE_URL = "/api/vehicle"; const NOTES_URL = "/api/library/notes"; const SOURCE = "route"; const COLOR = "#1d6fdc"; const SAVE_FOLDER = "Routes"; // Offline routing (docs/routing-design.adoc): while the panel is open, a // map click adds a point, markers drag to move, and the route through // 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, gnssControl) { this._map = map; 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; this._addPoint([event.lngLat.lng, event.lngLat.lat]); }); // setStyle() (base map switch) drops custom sources. map.on("style.load", () => this._draw()); } mount(sidebar) { this._container = document.createElement("div"); this._container.className = "sidebar-item"; this._container.innerHTML = ``; this._icon = this._container.querySelector(".sidebar-icon"); this._icon.addEventListener("click", () => this._togglePanel()); this._panel = document.getElementById("route-panel"); this._panel.querySelector(".basemap-panel__close").addEventListener("click", () => this._togglePanel(false)); this._list = this._panel.querySelector(".route-panel__points"); this._summary = this._panel.querySelector(".route-panel__summary"); this._directions = this._panel.querySelector(".route-panel__directions"); this._saveButton = this._panel.querySelector('[data-action="save"]'); this._panel.querySelector('[data-action="reverse"]').addEventListener("click", () => { this._points.reverse(); 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(); onlyOneSidePanelOpen(this._panel, () => this._setOpen(false)); sidebar.appendChild(this._container); } _togglePanel(force) { this._setOpen(force === undefined ? this._panel.hidden : force); } _setOpen(open) { this._panel.hidden = !open; this._icon.classList.toggle("active", open); this._map.getCanvas().style.cursor = open ? "crosshair" : ""; if (open) notifySidePanelOpen(this._panel); } // --- points --------------------------------------------------------------- _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, 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(); } _removePoint(point) { point.marker.remove(); this._points = this._points.filter((p) => p !== point); this._changed(); } _clear() { this._points.forEach((p) => p.marker.remove()); this._points = []; this._editing = null; this._changed(); } _changed() { this._renderPoints(); this._fetchRoute(); } _renderPoints() { this._list.innerHTML = ""; this._points.forEach((point, index) => { const label = index === 0 ? "Start" : index === this._points.length - 1 ? "End" : `Via ${index}`; 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.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 ---------------------------------------------------------------- async _fetchRoute() { const request = ++this._request; this._route = null; if (this._points.length < 2) { this._showResult(null, ""); return; } this._showResult(null, "Routing…"); let data; let error; try { const response = await fetch(ROUTE_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ locations: this._points.map((p) => p.lngLat) }), }); data = await response.json().catch(() => ({})); if (!response.ok) error = data.error || `routing failed (${response.status})`; } catch (err) { error = err.message; } if (request !== this._request) return; this._route = error ? null : data; this._showResult(this._route, error ? `No route: ${error}` : ""); } _showResult(route, message) { this._draw(); this._saveButton.hidden = !route || !isLoggedIn(); this._directions.hidden = !route; if (!route) { this._summary.textContent = message; return; } const { distance_km: km, time_s: seconds, maneuvers } = route.properties; this._summary.textContent = `${km.toFixed(1)} km · ${formatDuration(seconds)}`; const list = this._directions.querySelector("ol"); list.innerHTML = ""; maneuvers.forEach(({ text, km: length }) => { const li = document.createElement("li"); li.textContent = length > 0 ? `${text} (${length.toFixed(1)} km)` : text; list.appendChild(li); }); } _draw() { const data = { type: "FeatureCollection", features: this._route ? [this._route] : [] }; const source = this._map.getSource(SOURCE); if (source) { source.setData(data); return; } if (!this._map.isStyleLoaded()) return; // style.load draws it this._map.addSource(SOURCE, { type: "geojson", data }); this._map.addLayer({ id: `${SOURCE}-casing`, type: "line", source: SOURCE, layout: { "line-cap": "round", "line-join": "round" }, paint: { "line-color": "#fff", "line-width": 8 }, }); this._map.addLayer({ id: `${SOURCE}-line`, type: "line", source: SOURCE, layout: { "line-cap": "round", "line-join": "round" }, paint: { "line-color": COLOR, "line-width": 5 }, }); } // A route item in the library ("Routes" folder), keeping its points and // vehicle so it can be routed again later; an edited one is updated in // place. async _save() { const name = window.prompt("Route name:", this._editing?.name || `Route ${new Date().toLocaleDateString()}`); if (!name || !name.trim()) return; const { maneuvers, ...properties } = this._route.properties; const feature = { type: "Feature", 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: editing ? "PUT" : "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, 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"; return; } if (!response.ok) { window.alert("Could not save the route."); return; } const path = editing ? editing.key : (await response.json()).path; notifyGpxStoreChanged(path); 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 -------------------------------------------------------------- // Readable by anyone, saved only when logged in; a change re-routes. async _setupVehicle() { const inputs = [...this._panel.querySelectorAll(".route-panel__vehicle input")]; try { this._vehicle = await (await fetch(VEHICLE_URL)).json(); } catch { return; } inputs.forEach((input) => { input.value = this._vehicle[input.name]; input.disabled = !isLoggedIn(); input.addEventListener("change", async () => { const body = new URLSearchParams(inputs.map((i) => [i.name, i.value])); const response = await fetch(VEHICLE_URL, { method: "PUT", body }); const data = await response.json().catch(() => ({})); if (!response.ok) { window.alert(data.error || "Could not save the vehicle."); input.value = this._vehicle[input.name]; return; } this._vehicle = data; this._fetchRoute(); }); }); } } function formatDuration(seconds) { const minutes = Math.round(seconds / 60); return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h ${minutes % 60} min`; }