258 lines
9.1 KiB
JavaScript
258 lines
9.1 KiB
JavaScript
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 { 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) {
|
||
this._map = map;
|
||
this._points = []; // [{ lngLat: [lon, lat], marker }]
|
||
this._route = null; // the last /api/route Feature
|
||
this._request = 0; // so a slow older response can't overwrite a newer one
|
||
|
||
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 = `<button type="button" class="sidebar-icon" title="Route" aria-label="Route">${ROUTE_ICON}</button>`;
|
||
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._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) {
|
||
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 };
|
||
marker.on("dragend", () => {
|
||
const { lng, lat } = marker.getLngLat();
|
||
point.lngLat = [lng, lat];
|
||
this._changed();
|
||
});
|
||
this._points.push(point);
|
||
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._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.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);
|
||
this._list.appendChild(li);
|
||
});
|
||
}
|
||
|
||
// --- 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.
|
||
async _save() {
|
||
const name = window.prompt("Route 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 response = await fetch(NOTES_URL, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||
body: new URLSearchParams({ 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 } = await response.json();
|
||
notifyGpxStoreChanged(path);
|
||
this._summary.textContent += ` · saved to "${SAVE_FOLDER}"`;
|
||
}
|
||
|
||
// --- 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`;
|
||
}
|