Planning (the Design canvas' Plan and GridToday, ideas from azedler/roadplanner): a stop's type as its NPS pictogram (marker and list), notes on the trip, its days and stops, + on a leg inserts the next point there; a parking spot per stop (P marker, the route goes there, the walk shown); a link pasted into the search becomes a place (/api/link: the URL's coordinates, else the page's geo meta / JSON-LD / a map link; public addresses only, logged in), added on the leg it lengthens least; avoids for the trip (+ ferries, unpaved) or a day (routed in pieces, joined); Check and Costs folds in the Route panel (no leave time, long days, arriving after sunset, long walks, missing vignettes; fuel from km × consumption × price, stop costs / paid, the budget); Today in drive mode's Menu (stops left, tonight, sunset, Open-Meteo weather, the day's notes, Skip next, Tomorrow). Plugins along the trip's route (Maptool::Corridor, a corridor width; Overpass around:) and plugin settings saved server-side; p4n via a host Firefox's cookies (docs/deployment.adoc). The recording's days (cut where the car stood ≥ 4 h, or by hand) and their export (days, a piece A–B, the whole trip; GPX with times). Track replay in the GNSS simulator. Step advance 5 m past a maneuver. The level gauge (drive mode, from Terrain): lift per wheel to the ramps' steps from roll, pitch, wheelbase and track
CI / check (push) Successful in 23s
CI / deploy (push) Successful in 18s

This commit is contained in:
randy committed 2026-12-03 23:34:25 +01:00
1 parent 5e31dfaba9
commit 87d7bd2463
36 files changed
+2047 -123

No files matched your search

+302 -29
View File
@@ -1,10 +1,11 @@
import { Marker, Popup } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { ROUTE_ICON, REVERSE_ICON, CLEAR_ICON } from "/js/icons.js";
import { ROUTE_ICON, REVERSE_ICON, CLEAR_ICON, NPS_SYMBOLS } from "/js/icons.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen, notifyGpxStoreChanged, onRoutePoint, onRouteEdit, notifyRouteChanged, onReroute, onRouteProgress, notifyVehicle } from "/js/panels.js";
import { isLoggedIn } from "/js/auth.js";
import { SPEED_LIMITS, isHeavy, motorwayPayment } from "/js/speed_limits.js";
import { wirePreview } from "/js/preview.js";
import { elevationAt } from "/js/dem.js";
import { getTimes } from "/vendor/suncalc/suncalc.js";
const ROUTE_URL = "/api/route";
// Logged in, the panel edits this server's shared trip (lib/maptool/trip.rb)
@@ -26,10 +27,32 @@ const profileMeta = (v) =>
? [v.height && `${v.height} m`, v.weight && `${v.weight} t`].filter(Boolean).join(" · ")
: [v.speed && `${v.speed} km/h`, v.sac && `up to T${v.sac}`].filter(Boolean).join(" · ");
const AVOID_KEY = "maptool.routeAvoid";
const DAY_COLORS = ["#a21caf", "#1d6fdc", "#c2410c", "#2a9d8f", "#b45309"];
export const DAY_COLORS = ["#a21caf", "#1d6fdc", "#c2410c", "#2a9d8f", "#b45309"];
const clock = (ms) => new Date(ms).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
const escapeText = (text) => String(text).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
const NOTES_URL = "/api/library/notes";
// A stop's type: the NPS pictogram shown on its marker and in the list (the
// Design canvas' Plan). The key is the symbol's name, as a library point's icon.
export const STOP_TYPES = {
"point-of-interest": "Sight",
"food-service": "Food",
"coffee": "Break",
"parking": "Parking",
"gas-station": "Fuel",
"vehicle-ferry": "Ferry",
"campground": "Campsite",
"campsite": "Wild night",
"mechanic": "Service",
"residential-building": "Home",
};
// What a stop keeps in the shared trip (the marker and editing state stay here).
const stopData = ({ lngLat, name, nav, passed, night, stay, note, type, day_note, park, avoid, cost, paid }) => ({ lngLat, name, nav, passed, night, stay, note, type, day_note, park, avoid, cost, paid });
// what a route can avoid (Routing.costing), the trip's and a day's own
const AVOIDS = { tolls: "Tolls", highways: "Motorways", ferries: "Ferries", unpaved: "Unpaved" };
const WALK_SOURCE = "route-walks";
const MAX_DAY_DRIVING_S = 8 * 3600; // the Check: a longer day is a warning
const MAX_WALK_M = 1500;
const SOURCE = "route";
const COLOR = "#1d6fdc";
const SAVE_FOLDER = "Routes";
@@ -77,16 +100,38 @@ export class RoutePanelControl {
});
onRoutePoint(({ lngLat, name }) => {
this._setOpen(true);
// with no + picked: on the leg it lengthens least, not past the end
if (this._insertAt == null && this._points.length >= 2) {
let best = Infinity;
for (let i = 1; i < this._points.length; i++) {
if (this._points[i].passed) continue;
const [a, b] = [this._points[i - 1].lngLat, this._points[i].lngLat];
const detour = distanceM(a, lngLat) + distanceM(lngLat, b) - distanceM(a, b);
if (detour < best) [best, this._insertAt] = [detour, i];
}
const end = this._points.at(-1).lngLat;
if (distanceM(end, lngLat) < best) this._insertAt = null; // further on: a new end
}
this._addPoint(lngLat, name);
});
onRouteEdit(({ key, feature }) => this._edit(key, feature));
map.on("click", (event) => {
if (this._panel.hidden || event.originalEvent.altKey) return;
if (this._parkFor) {
// the stop's parking spot picked: the route goes there now
this._parkFor.park = { lngLat: [event.lngLat.lng, event.lngLat.lat] };
this._parkFor = null;
this._changed();
return;
}
this._addPoint([event.lngLat.lng, event.lngLat.lat]);
});
// setStyle() (base map switch) drops custom sources.
map.on("style.load", () => this._draw());
map.on("style.load", () => {
this._draw();
this._drawParking();
});
}
mount(sidebar) {
@@ -116,8 +161,8 @@ export class RoutePanelControl {
for (const [action, icon] of Object.entries(icons)) this._panel.querySelector(`[data-action="${action}"]`).insertAdjacentHTML("afterbegin", icon);
this._setupSavedPoints();
this._editingNote = this._panel.querySelector(".route-panel__editing");
this._itinerary = { name: null, start: null, day_start: null };
this._tripInputs = [...this._panel.querySelectorAll(".route-panel__trip input")];
this._itinerary = { name: null, start: null, day_start: null, note: null, budget: null, fuel_price: null };
this._tripInputs = [...this._panel.querySelectorAll(".route-panel__trip input, .route-panel__trip textarea")];
this._tripInputs.forEach((input) => input.addEventListener("change", () => {
this._itinerary[input.name] = input.value.trim() || null;
this._itineraryChanged();
@@ -173,7 +218,7 @@ export class RoutePanelControl {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
points: this._points.map(({ lngLat, name, nav, passed, night, stay, note }) => ({ lngLat, name, nav, passed, night, stay, note })),
points: this._points.map(stopData),
vehicle: this._vehicleId,
avoid: this._avoid,
editing: this._editing,
@@ -197,12 +242,12 @@ export class RoutePanelControl {
const first = this._version < 0;
this._version = trip.version;
if (fromElsewhere) {
const before = this._points.map(({ lngLat, name, nav, passed, night, stay, note }) => ({ lngLat, name, nav, passed, night, stay, note }));
const before = this._points.map(stopData);
const beforeItinerary = { ...this._itinerary };
this._points.forEach((p) => p.marker.remove());
this._points = [];
trip.points.forEach((p) => this._addPoint(p.lngLat, p.name, { quiet: true, nav: !!p.nav, passed: !!p.passed, night: p.night, stay: p.stay, note: p.note }));
this._itinerary = { name: trip.name || null, start: trip.start || null, day_start: trip.day_start || null };
trip.points.forEach((p) => this._addPoint(p.lngLat, p.name, { ...p, quiet: true, nav: !!p.nav, passed: !!p.passed }));
this._itinerary = { name: trip.name || null, start: trip.start || null, day_start: trip.day_start || null, note: trip.note || null, budget: trip.budget ?? null, fuel_price: trip.fuel_price ?? null };
this._tripInputs.forEach((input) => (input.value = this._itinerary[input.name] || ""));
if (!first) this._showRemoteChange(before, beforeItinerary); // the first load isn't another screen's change
this._editing = trip.editing;
@@ -233,11 +278,11 @@ export class RoutePanelControl {
// 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", passed = false, night, stay, note } = {}) {
_addPoint(lngLat, name, { quiet = false, nav = !!name && name !== "My position", passed = false, night, stay, note, type, day_note, park, avoid, cost, paid } = {}) {
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, nav, marker, night: night || undefined, stay: stay || undefined, note: note || undefined };
const point = { lngLat, name, nav, marker, night: night || undefined, stay: stay || undefined, note: note || undefined, type: type || undefined, day_note: day_note || undefined, park: park || undefined, avoid: avoid || undefined, cost: cost ?? undefined, paid: paid ?? undefined };
this._setPassed(point, passed);
marker.on("dragend", () => {
const { lng, lat } = marker.getLngLat();
@@ -245,7 +290,9 @@ export class RoutePanelControl {
point.name = null; // no longer that place
this._changed();
});
this._points.push(point);
if (!quiet && this._insertAt != null && this._insertAt < this._points.length) this._points.splice(this._insertAt, 0, point);
else this._points.push(point);
if (!quiet) this._insertAt = null;
if (!quiet) this._changed();
}
@@ -293,6 +340,19 @@ export class RoutePanelControl {
leg: this._leg(i), passed: p.passed, behind: this._behind(i) }));
}
// For the driving mode's Today (drive_menus.js): every stop with its plan
// (planned arrive / leave in ms, the day), the leg to it, behind the car or
// not; the trip's itinerary and the Check's items.
plan() {
const schedule = this._schedule();
return {
stops: this._points.map((p, i) => ({ ...stopData(p), ...schedule[i], index: i, leg: this._leg(i), behind: this._behind(i) })),
days: (schedule.at(-1)?.day ?? 0) + 1,
itinerary: { ...this._itinerary },
check: this._check(schedule),
};
}
togglePassed(index) {
const point = this._points[index];
if (!point) return;
@@ -439,7 +499,7 @@ export class RoutePanelControl {
const now = this._points;
const keys = new Set(before.map(key));
const added = now.find((p) => !keys.has(key(p)));
const changed = added || now.find((p, i) => JSON.stringify([p.name, p.night, p.stay, p.note]) !== JSON.stringify([before[i]?.name, before[i]?.night, before[i]?.stay, before[i]?.note]));
const changed = added || now.find((p, i) => JSON.stringify(stopData(p)) !== JSON.stringify(before[i]));
const removed = now.length < before.length;
if (!changed && !removed && JSON.stringify(beforeItinerary) === JSON.stringify(this._itinerary)) return;
const at = (changed || now[0] || before[0])?.lngLat;
@@ -454,7 +514,7 @@ export class RoutePanelControl {
this._remotePopup.remove();
this._points.forEach((p) => p.marker.remove());
this._points = [];
before.forEach((p) => this._addPoint(p.lngLat, p.name, { quiet: true, nav: !!p.nav, passed: !!p.passed, night: p.night, stay: p.stay, note: p.note }));
before.forEach((p) => this._addPoint(p.lngLat, p.name, { ...p, quiet: true, nav: !!p.nav, passed: !!p.passed }));
this._itinerary = { ...beforeItinerary };
this._tripInputs.forEach((input) => (input.value = this._itinerary[input.name] || ""));
this._changed();
@@ -472,16 +532,28 @@ export class RoutePanelControl {
const schedule = this._schedule();
const days = schedule.at(-1)?.day ?? 0;
this._points.forEach((point, index) => {
if (days > 0 && (index === 0 || this._points[index - 1].night)) this._list.appendChild(this._dayHeader(schedule[index].day, index, schedule));
if (days > 0 && (index === 0 || this._points[index - 1].night)) this._dayHeader(schedule[index].day, index, schedule);
const letter = String.fromCharCode(65 + (index % 26));
const role = index === 0 ? "Start" : index === last ? "End" : `Via ${index}`;
point.marker.getElement().textContent = letter;
const icon = NPS_SYMBOLS[point.type];
if (icon) point.marker.getElement().innerHTML = icon;
else point.marker.getElement().textContent = letter;
const leg = this._leg(index);
if (leg) {
this._list.appendChild(Object.assign(document.createElement("li"), {
className: "route-panel__leg",
textContent: `${leg.km.toFixed(1)} km${leg.s != null ? ` · ${formatDuration(leg.s)}` : ""}`,
}));
if (index > 0) {
// + inserts the next point added (map click, search, saved point, my position) here
const row = Object.assign(document.createElement("li"), { className: "route-panel__leg" });
const inserting = this._insertAt === index;
row.append(
Object.assign(document.createElement("span"), {
textContent: inserting ? "Click the map, search or pick a saved point" : leg ? `${leg.km.toFixed(1)} km${leg.s != null ? ` · ${formatDuration(leg.s)}` : ""}` : "",
}),
this._pointButton(inserting ? "×" : "+", inserting ? "Cancel" : "Insert a stop here", true, () => {
this._insertAt = inserting ? null : index;
this._renderPoints();
}),
);
row.classList.toggle("route-panel__leg--insert", inserting);
this._list.appendChild(row);
}
const li = document.createElement("li");
li.className = "route-panel__stop";
@@ -503,7 +575,8 @@ export class RoutePanelControl {
this._points.splice(index, 0, ...this._points.splice(from, 1));
this._changed();
});
const badge = Object.assign(document.createElement("span"), { className: "route-panel__badge", textContent: letter });
const badge = Object.assign(document.createElement("span"), { className: "route-panel__badge", textContent: letter, title: STOP_TYPES[point.type] || "" });
if (icon) badge.innerHTML = icon;
badge.classList.toggle("route-panel__badge--end", index === last && last > 0);
const text = document.createElement("span");
text.className = "route-panel__point";
@@ -514,13 +587,17 @@ export class RoutePanelControl {
const { arrive, leave } = schedule[index];
const time = Object.assign(document.createElement("span"), { className: "route-panel__time",
textContent: [arrive, point.night ? null : leave].filter((t) => t != null).map(clock).join("–") });
if (point.park) {
text.appendChild(Object.assign(document.createElement("span"), { className: "route-panel__park",
textContent: `${point.park.name || "Parking"} · ${walk(point)} walk` }));
}
if (point.note) text.appendChild(Object.assign(document.createElement("span"), { className: "route-panel__note", textContent: point.note }));
const night = this._pointButton("☾", "Night stop: the day ends here", index > 0 && index < last, () => {
point.night = point.night ? undefined : true;
this._itineraryChanged();
});
night.classList.toggle("route-panel__on", !!point.night);
const edit = this._pointButton("✎", "Stay and note", true, () => {
const edit = this._pointButton("✎", "Type, stay and note", true, () => {
point.editingNote = !point.editingNote;
this._renderPoints();
});
@@ -531,6 +608,9 @@ export class RoutePanelControl {
this._list.appendChild(li);
if (point.editingNote) this._list.appendChild(this._noteEditor(point));
});
this._drawParking();
this._renderCheck(schedule);
this._renderCosts();
this._stopListeners?.forEach((callback) => callback());
this._editingNote.hidden = !this._editing;
if (this._editing) this._editingNote.textContent = `Editing "${this._editing.name}"`;
@@ -575,7 +655,96 @@ export class RoutePanelControl {
return button;
}
// A day's header: its date (from when it leaves), km and driving time.
// Is the trip ready: [{ level: "bad" | "warn" | "info", what, index }]
// (index: the stop it's about, or null), the worst first, then by day.
_check(schedule) {
const out = [];
const last = this._points.length - 1;
if (last < 1) return out;
const days = (schedule.at(-1)?.day ?? 0) + 1;
const dayName = (d) => (days > 1 ? `Day ${d + 1}: ` : "");
if (!this._itinerary.start) out.push({ level: "info", what: "No leave time: the planned times are unknown", index: null, day: 0 });
// driving per day
const driving = new Array(days).fill(0);
this._points.forEach((_, i) => { if (i > 0) driving[schedule[i - 1].day] += this._leg(i)?.s || 0; });
driving.forEach((s, d) => { if (s > MAX_DAY_DRIVING_S) out.push({ level: "warn", what: `${dayName(d)}${formatDuration(s)} driving`, index: null, day: d }); });
this._points.forEach((p, i) => {
const name = p.name || `Stop ${String.fromCharCode(65 + (i % 26))}`;
const { arrive, day } = schedule[i];
// a night spot reached after dark
if ((p.night || i === last) && arrive != null && !p.passed) {
const sunset = getTimes(new Date(arrive), p.lngLat[1], p.lngLat[0]).sunset;
if (!Number.isNaN(sunset?.getTime()) && arrive > sunset.getTime()) {
out.push({ level: "warn", what: `${dayName(day)}${name}: arriving ${clock(arrive)}, after sunset (${clock(sunset.getTime())})`, index: i, day });
}
}
if (p.park && distanceM(p.park.lngLat, p.lngLat) * 1.25 > MAX_WALK_M) out.push({ level: "info", what: `${name}: ${walk(p)} from the parking`, index: i, day });
});
// motorways in a country the profile has no vignette / toll unit for
for (const { code, motorway_km: motorway } of this._route?.properties.countries || []) {
const pay = motorwayPayment(code, this._vehicle);
if (pay.how && motorway > 0 && !pay.has) {
out.push({ level: "warn", what: `${code}: ${motorway.toFixed(0)} km of motorway, ${pay.until ? `the ${pay.how} ended ${pay.until}` : `no ${pay.how} in the profile`}`, index: null, day: 0 });
}
}
const rank = { bad: 0, warn: 1, info: 2 };
return out.sort((a, b) => rank[a.level] - rank[b.level] || a.day - b.day);
}
_renderCheck(schedule) {
const fold = this._panel.querySelector(".route-panel__check");
const items = this._check(schedule);
fold.hidden = this._points.length < 2;
const count = (level) => items.filter((x) => x.level === level).length;
fold.querySelector(".route-panel__fold-meta").textContent =
items.length ? [[count("bad"), "✗"], [count("warn"), "!"], [count("info"), "i"]].filter(([n]) => n).map(([n, m]) => `${n} ${m}`).join(" · ") : "ready ✓";
fold.classList.toggle("route-panel__check--warn", count("bad") + count("warn") > 0);
fold.querySelector("ul").replaceChildren(...items.map(({ level, what, index }) => {
const li = Object.assign(document.createElement("li"), { className: `route-panel__check-${level}` });
li.append(Object.assign(document.createElement("span"), { textContent: what }));
if (index != null) {
li.appendChild(this._pointButton("⌖", "Show it", true, () => this._map.easeTo({ center: this._points[index].lngLat, zoom: Math.max(this._map.getZoom(), 13) })));
}
return li;
}));
}
// Planned (the fuel from the route's km × the profile's consumption × the
// trip's fuel price, each stop's costs) vs paid, against the budget.
_renderCosts() {
const fold = this._panel.querySelector(".route-panel__costs");
fold.hidden = this._points.length < 2;
const euro = (n) => `${n.toFixed(n < 100 ? 2 : 0)} €`;
const rows = [];
const km = this._route?.properties.distance_km;
const uses = this._vehicle?.consumption;
const price = Number(this._itinerary.fuel_price) || 0;
let planned = 0;
if (km && uses && price) {
const fuel = (km * uses * price) / 100;
planned += fuel;
rows.push(["Fuel", `${km.toFixed(0)} km × ${uses} /100 km × ${price} €`, `≈ ${euro(fuel)}`]);
} else if (km) {
rows.push(["Fuel", uses ? "set the fuel price above" : "set the consumption in the profile", "–"]);
}
let paid = 0;
this._points.forEach((p, i) => {
if (p.cost == null && p.paid == null) return;
planned += p.cost || 0;
paid += p.paid || 0;
rows.push([p.name || `Stop ${String.fromCharCode(65 + (i % 26))}`, p.paid != null ? `paid ${euro(p.paid)}` : "planned", p.cost != null ? euro(p.cost) : "–"]);
});
const budget = Number(this._itinerary.budget) || 0;
fold.querySelector(".route-panel__fold-meta").textContent = [planned && `≈ ${euro(planned)} planned`, paid && `${euro(paid)} paid`, budget && `${euro(budget - Math.max(planned, paid))} left`].filter(Boolean).join(" · ");
fold.querySelector("ul").replaceChildren(...rows.map(([what, how, amount]) => {
const li = document.createElement("li");
li.append(...[what, how, amount].map((textContent) => Object.assign(document.createElement("span"), { textContent })));
return li;
}));
}
// A day's header (into the list): its date (from when it leaves), km and
// driving time, ✎ for the day's note, the note under it.
_dayHeader(day, from, schedule) {
let km = 0;
let s = 0;
@@ -592,15 +761,90 @@ export class RoutePanelControl {
li.style.setProperty("--day", DAY_COLORS[day % DAY_COLORS.length]);
li.innerHTML = `<b></b><span>${km ? `${km.toFixed(0)} km · ${formatDuration(s)}` : ""}${leaves != null ? ` · leave ${clock(leaves)}` : ""}</span>`;
li.querySelector("b").textContent = date;
return li;
// the day's note and avoids live on its first point (the one after the night spot)
const point = this._points[from];
if (point.avoid) {
const avoided = Object.keys(AVOIDS).filter((k) => point.avoid[k]).map((k) => AVOIDS[k].toLowerCase());
li.querySelector("span").append(` · ${avoided.length ? `avoids ${avoided.join(", ")}` : "avoids nothing"}`);
}
li.appendChild(this._pointButton("✎", "The day's note", true, () => {
point.editingDay = !point.editingDay;
this._renderPoints();
}));
this._list.appendChild(li);
if (point.editingDay) {
const editor = Object.assign(document.createElement("li"), { className: "route-panel__note-editor route-panel__day-note" });
editor.style.setProperty("--day", DAY_COLORS[day % DAY_COLORS.length]);
const text = Object.assign(document.createElement("textarea"), { rows: 2, maxLength: 500, placeholder: "The day's note", value: point.day_note || "" });
text.addEventListener("change", () => {
point.day_note = text.value.trim() || undefined;
this._itineraryChanged();
});
// the day's own avoids (routed apart by the server), else the trip's
const avoid = document.createElement("span");
avoid.className = "route-panel__day-avoid";
const own = Object.assign(document.createElement("input"), { type: "checkbox", checked: !!point.avoid });
const boxes = Object.entries(AVOIDS).map(([key, label]) => {
const box = Object.assign(document.createElement("input"), { type: "checkbox", checked: !!(point.avoid || this._avoid)[key], disabled: !point.avoid });
box.addEventListener("change", () => {
point.avoid = { ...point.avoid, [key]: box.checked };
this._changed();
});
const wrap = document.createElement("label");
wrap.append(box, ` ${label}`);
return wrap;
});
own.addEventListener("change", () => {
point.avoid = own.checked ? Object.fromEntries(Object.keys(AVOIDS).map((k) => [k, !!this._avoid[k]])) : undefined;
this._changed();
});
const ownLabel = document.createElement("label");
ownLabel.append(own, " This day avoids:");
avoid.append(ownLabel, ...boxes);
editor.append(text, avoid);
this._list.appendChild(editor);
} else if (point.day_note) {
const note = Object.assign(document.createElement("li"), { className: "route-panel__note route-panel__day-note", textContent: point.day_note });
note.style.setProperty("--day", DAY_COLORS[day % DAY_COLORS.length]);
this._list.appendChild(note);
}
}
// A stop's stay (minutes) and note, under it.
// A stop's type, stay (minutes) and note, under it.
_noteEditor(point) {
const li = document.createElement("li");
li.className = "route-panel__note-editor";
li.innerHTML = `<label>Stay <input type="number" min="0" step="15" placeholder="0"> min</label><textarea rows="2" maxlength="500" placeholder="Note"></textarea>`;
const [stay, note] = [li.querySelector("input"), li.querySelector("textarea")];
li.innerHTML = `<span><label>Type <select><option value="">—</option></select></label> <label>Stay <input type="number" min="0" step="15" placeholder="0"> min</label></span>
<span class="route-panel__money"><label>Costs <input type="number" name="cost" min="0" step="0.5" placeholder="–"> €</label> <label>paid <input type="number" name="paid" min="0" step="0.5" placeholder="–"> €</label></span>
<span class="route-panel__park-edit">Parking <button type="button" data-park="set"></button> <button type="button" data-park="clear" hidden>No parking</button></span>
<textarea rows="2" maxlength="500" placeholder="Note"></textarea>`;
li.querySelectorAll(".route-panel__money input").forEach((input) => {
input.value = point[input.name] ?? "";
input.addEventListener("change", () => {
const value = Number(input.value);
point[input.name] = input.value.trim() !== "" && value >= 0 ? Math.round(value * 100) / 100 : undefined;
this._itineraryChanged();
});
});
const setPark = li.querySelector('[data-park="set"]');
const clearPark = li.querySelector('[data-park="clear"]');
setPark.textContent = this._parkFor === point ? "Click the map…" : point.park ? "Move: click the map" : "Set: click the map";
clearPark.hidden = !point.park;
setPark.addEventListener("click", () => {
this._parkFor = this._parkFor === point ? null : point;
this._renderPoints();
});
clearPark.addEventListener("click", () => {
point.park = undefined;
this._changed();
});
const [type, stay, note] = [li.querySelector("select"), li.querySelector("input"), li.querySelector("textarea")];
type.append(...Object.entries(STOP_TYPES).map(([value, label]) => new Option(label, value)));
type.value = point.type || "";
type.addEventListener("change", () => {
point.type = type.value || undefined;
this._itineraryChanged();
});
stay.value = point.stay || "";
note.value = point.note || "";
stay.addEventListener("change", () => {
@@ -614,6 +858,28 @@ export class RoutePanelControl {
return li;
}
// The stops' parking spots: a P marker each (drag it to move), a dashed
// line to the place — the walk.
_drawParking() {
this._parkMarkers?.forEach((m) => m.remove());
const parked = this._points.filter((p) => p.park);
this._parkMarkers = parked.map((point) => {
const element = Object.assign(document.createElement("div"), { className: "route-park", textContent: "P", title: point.park.name || "Parking" });
const marker = new Marker({ element, draggable: true }).setLngLat(point.park.lngLat).addTo(this._map);
marker.on("dragend", () => {
const { lng, lat } = marker.getLngLat();
point.park = { lngLat: [lng, lat] };
this._changed();
});
return marker;
});
if (!this._map.isStyleLoaded() && !this._map.getSource(WALK_SOURCE)) return;
const data = { type: "FeatureCollection", features: parked.map((p) => ({ type: "Feature", properties: {}, geometry: { type: "LineString", coordinates: [p.park.lngLat, p.lngLat] } })) };
if (this._map.getSource(WALK_SOURCE)) return this._map.getSource(WALK_SOURCE).setData(data);
this._map.addSource(WALK_SOURCE, { type: "geojson", data });
this._map.addLayer({ id: WALK_SOURCE, type: "line", source: WALK_SOURCE, paint: { "line-color": "#1d4ed8", "line-width": 2.5, "line-dasharray": [1, 1.5] } });
}
_pointButton(text, title, enabled, onClick) {
const button = document.createElement("button");
button.type = "button";
@@ -644,7 +910,7 @@ export class RoutePanelControl {
const response = await fetch(ROUTE_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ locations: this._active().map((p) => p.lngLat), vehicle: this._vehicleId, avoid: this._avoid }),
body: JSON.stringify({ locations: this._active().map((p) => p.park?.lngLat || p.lngLat), vehicle: this._vehicleId, avoid: this._avoid }),
});
data = await response.json().catch(() => ({}));
if (!response.ok) error = data.error || `routing failed (${response.status})`;
@@ -1189,6 +1455,13 @@ function distanceM([lon1, lat1], [lon2, lat2]) {
return 12742000 * Math.asin(Math.sqrt(a));
}
// Parking → the place, straight (the real path ~ a quarter longer).
// ponytail: straight line ×1.25, a foot route from Valhalla if it misleads
function walk(point) {
const m = distanceM(point.park.lngLat, point.lngLat) * 1.25;
return m < 1000 ? `${Math.round(m / 10) * 10} m` : `${(m / 1000).toFixed(1)} km`;
}
export function formatDuration(seconds) {
const minutes = Math.round(seconds / 60);
return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h ${minutes % 60} min`;