import { Marker, Popup } from "/vendor/maplibre-gl/maplibre-gl.mjs"; 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) // instead of a route of its own: every change goes there (routed by the // server), and other screens' changes come in by polling — the points, // vehicle, avoids and route swapped in, the camera left where it is. const TRIP_URL = "/api/trip"; const TRIP_POLL_MS = 2000; const ISOCHRONE_URL = "/api/isochrone"; const REACH_SOURCE = "route-reach"; const PROFILE_SAMPLES = 400; // elevation lookups per route, at least 50 m apart const GRADE_WINDOW_M = 500; // "max grade" is sustained over this distance, not one noisy pixel const VEHICLES_URL = "/api/vehicles"; const VEHICLE_KEY = "maptool.routeVehicle"; const PROFILE_ICONS = { car: "🚗", bicycle: "🚲", foot: "🥾" }; // What the chip and the lists say about a profile, past its name. const profileMeta = (v) => (v.type || "car") === "car" ? [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"; 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) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[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"; // 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, profilePanel) { this._map = map; this._gnss = gnssControl; this._profilePanel = profilePanel; this._reach = null; // the last /api/isochrone FeatureCollection // Elevations from the offline terrain when it's there, as the hillshade does. this._offlineTerrain = fetch("/api/terrain-tiles") .then((r) => r.json()) .then((d) => d.available) .catch(() => false); 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 this._version = -1; // the shared trip's, -1: not loaded yet this._pushing = 0; // PUTs in flight: polls wait for them // Rerouting (the dashboard, off the route): the start and the via points // already passed give way to the current position. onReroute(({ from, passed }) => { // the shared trip is rerouted by the server, off its own GNSS (TripStore#follow) if (this._shared || this._active().length < 2) return; const reached = this._active().slice(0, 1 + passed); if (reached[0]?.name === "My position") this._removePoint(reached.shift(), { quiet: true }); reached.forEach((p) => this._setPassed(p, true)); this._addPoint(from, "My position", { quiet: true }); const position = this._points.pop(); const next = this._points.findIndex((p) => !p.passed); this._points.splice(next < 0 ? this._points.length : next, 0, position); this._changed(); }); onRouteProgress((km) => { this._showProgress(km); this._progressKm = km; this._stopListeners?.forEach((callback) => callback()); }); 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(); this._drawParking(); }); } 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._countries = this._panel.querySelector(".route-panel__countries"); this._setupAvoid(); 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._panel.querySelector('[data-action="search"]').addEventListener("click", () => document.querySelector(".search-panel__input")?.focus()); this._totals = this._panel.querySelector(".route-panel__totals"); const icons = { reverse: REVERSE_ICON, clear: CLEAR_ICON }; 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, 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(); })); this._saveButton.addEventListener("click", () => this._save()); this._profileButton = this._panel.querySelector(".route-panel__profile"); this._profileButton.addEventListener("click", () => { this._profileShown = this._profileProperties(); this._profilePanel.show(this._profileShown); }); this._reachStatus = this._panel.querySelector(".route-panel__reach-status"); this._reachClear = this._panel.querySelector('[data-action="reach-clear"]'); this._panel.querySelector('[data-action="reach"]').addEventListener("click", () => this._showReach()); this._reachClear.addEventListener("click", () => { this._reach = null; this._reachClear.hidden = true; this._reachStatus.hidden = true; this._draw(); }); this._setupVehicle(); onlyOneSidePanelOpen(this._panel, () => this._setOpen(false)); sidebar.appendChild(this._container); this._shared = isLoggedIn(); if (this._shared) { this._pollTrip(); setInterval(() => this._pollTrip(), TRIP_POLL_MS); } } // --- shared trip ------------------------------------------------------------ async _pollTrip() { if (this._pushing) return; try { const response = await fetch(`${TRIP_URL}?version=${this._version}`, { cache: "no-store" }); if (response.status !== 200) return; // 204: unchanged const trip = await response.json(); if (!this._pushing && trip.version > this._version) this._applyTrip(trip, true); } catch { // offline for a moment: the next poll } } async _pushTrip() { const request = ++this._request; this._pushing++; // the old route stays on the map (the driver's view) until the new one is in if (this._points.length >= 2) this._summary.textContent = "Routing…"; try { const response = await fetch(TRIP_URL, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ points: this._points.map(stopData), vehicle: this._vehicleId, avoid: this._avoid, editing: this._editing, ...this._itinerary, }), }); const trip = await response.json().catch(() => ({})); if (!response.ok) throw new Error(trip.error || `HTTP ${response.status}`); if (request === this._request) this._applyTrip(trip, false); } catch (err) { if (request === this._request) this._showResult(null, `Not saved: ${err.message}`); } finally { this._pushing--; } } // The server's trip into the panel: its route always, its points (and // vehicle, avoids, the library route being edited) when they came from // another screen. _applyTrip(trip, fromElsewhere) { const first = this._version < 0; this._version = trip.version; if (fromElsewhere) { 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, { ...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; this._avoid = { ...trip.avoid }; this._panel.querySelectorAll(".route-panel__avoid input").forEach((input) => (input.checked = !!this._avoid[input.name])); if (trip.vehicle && trip.vehicle !== this._vehicleId) { if (this._selectVehicle) this._selectVehicle(trip.vehicle); else this._vehicleId = trip.vehicle; } this._renderPoints(); } this._route = trip.route; this._showResult(trip.route, trip.error ? `No route: ${trip.error}` : ""); } _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 --------------------------------------------------------------- // 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, 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, 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(); point.lngLat = [lng, lat]; point.name = null; // no longer that place this._changed(); }); 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(); } // 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(); // 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); 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(); } // For the driving mode's Trip menu (driving.js): the stops, and editing // them by index — the same points the panel edits, so the shared trip, // routing and markers follow as from the panel. // passed: marked (by a reroute or by hand) — not routed — or behind the // car by the dashboard's progress along the route; both shown dimmed. stops() { return this._points.map((p, i) => ({ name: p.name, lngLat: p.lngLat, label: i === 0 ? "Start" : i === this._points.length - 1 ? "End" : `Via ${i}`, 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; this._setPassed(point, !point.passed); this._changed(); } _setPassed(point, passed) { point.passed = !!passed; point.marker.getElement().classList.toggle("route-marker--passed", point.passed); } // The points routed: the ones not passed. _active() { return this._points.filter((p) => !p.passed); } // The way to point i from the routed one before: { km, s } of the route's // leg, null for the first routed point, a passed one, or while the route // doesn't match the points (routing). _leg(i) { const { legs_km: km, legs_s: s } = this._route?.properties || {}; const active = this._active(); const at = active.indexOf(this._points[i]); if (at < 1 || !km || km.length !== active.length - 1) return null; return { km: km[at - 1], s: s?.[at - 1] }; } // Behind the car: the dashboard's km along the route past this point's. _behind(i) { if (this._progressKm == null || this._points[i]?.passed) return false; const { legs_km: km } = this._route?.properties || {}; const active = this._active(); const at = active.indexOf(this._points[i]); if (at < 0 || !km || km.length !== active.length - 1) return false; return km.slice(0, at).reduce((sum, length) => sum + length, 0) <= this._progressKm + 0.03; } onStopsChanged(callback) { (this._stopListeners ??= []).push(callback); } moveStop(index, step) { if (this._points[index]) this._move(this._points[index], step); } removeStop(index) { if (this._points[index]) this._removePoint(this._points[index]); } // A stop before the end (the trip goes on to where it was going), or the // end itself while there's no route yet. addStop(lngLat, name = null) { this._addPoint(lngLat, name, { quiet: true }); if (this._points.length > 2) this._points.splice(this._points.length - 2, 0, this._points.pop()); this._changed(); } // The profiles and the one in use, for the driving Menu's row; picking // one re-routes. profiles() { return { list: this._vehicles || [], current: this._vehicle || null }; } pickProfile(id) { this._selectVehicle?.(id); this._fetchRoute(); } // The start moved to where the car is (GNSS, else the browser's position). startHere() { const set = (lngLat) => { if (this._points[0]?.name === "My position") this._removePoint(this._points[0]); this._addPoint(lngLat, "My position", { quiet: true }); this._points.unshift(this._points.pop()); this._changed(); }; const fix = this._gnss?.getPosition(); if (fix) return set([fix.lng, fix.lat]); navigator.geolocation.getCurrentPosition((p) => set([p.coords.longitude, p.coords.latitude]), () => window.alert("Could not determine your location."), { enableHighAccuracy: true }); } _removePoint(point, { quiet = false } = {}) { point.marker.remove(); this._points = this._points.filter((p) => p !== point); if (!quiet) this._changed(); } _clear() { this._points.forEach((p) => p.marker.remove()); this._points = []; this._editing = null; this._changed(); } _changed() { this._renderPoints(); this._fetchRoute(); } // Night / stay / note / the trip's name and start: no new route, the // shared trip saved (the server doesn't route again for these). _itineraryChanged() { this._renderPoints(); if (this._shared) this._pushTrip(); } // The planned times: leaving at the trip's start, each leg's time, a stay // where set; a night stop ends the day, the next one leaves at "Days start" // (09:00). [{ arrive, leave, day }] in ms, null where unknown (no start, a // leg not routed yet). _schedule() { const last = this._points.length - 1; const [dh, dm] = (this._itinerary.day_start || "09:00").split(":").map(Number); let t = this._itinerary.start ? new Date(this._itinerary.start).getTime() : null; let day = 0; return this._points.map((p, i) => { if (i > 0 && t != null) { const leg = this._leg(i); t = leg?.s != null ? t + leg.s * 1000 : null; } const arrive = i > 0 ? t : null; let leave = null; if (t != null && i < last) { if (p.night) { const next = new Date(t); next.setDate(next.getDate() + 1); next.setHours(dh, dm, 0, 0); leave = next.getTime(); } else leave = t + (p.stay || 0) * 60000; } const out = { arrive, leave, day }; if (p.night && i < last) day++; t = leave; return out; }); } // Another screen changed the trip: where (the first point added or moved, // else the first one changed) a popup says so, with Undo (the points and // the itinerary as they were, saved back). The map isn't moved. _showRemoteChange(before, beforeItinerary) { const key = (p) => p.lngLat.join(); 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(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; if (!at) return; const what = added ? `added ${added.name || "a point"}` : removed ? "removed a point" : changed ? `changed ${changed.name || "a point"}` : "changed the trip"; const el = document.createElement("div"); el.className = "route-remote"; el.innerHTML = `Another screen ${escapeText(what)} `; this._remotePopup?.remove(); this._remotePopup = new Popup({ closeButton: false, closeOnClick: true, className: "route-remote-popup" }).setLngLat(at).setDOMContent(el).addTo(this._map); el.querySelector("button").addEventListener("click", () => { this._remotePopup.remove(); this._points.forEach((p) => p.marker.remove()); this._points = []; 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(); }); clearTimeout(this._remoteTimer); this._remoteTimer = setTimeout(() => this._remotePopup?.remove(), 15000); } // The Desktop artboard's list: a grip to drag the point to another place, // its letter (the same on its marker), name and role, then the leg to the // next one as a dashed line between them. _renderPoints() { this._list.innerHTML = ""; const last = this._points.length - 1; 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._dayHeader(schedule[index].day, index, schedule); const letter = String.fromCharCode(65 + (index % 26)); const role = index === 0 ? "Start" : index === last ? "End" : `Via ${index}`; 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 (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"; li.classList.toggle("route-panel__passed", !!point.passed || this._behind(index)); const grip = Object.assign(document.createElement("span"), { className: "route-panel__grip", textContent: "⋮⋮", title: "Drag to reorder" }); li.draggable = true; li.addEventListener("dragstart", (event) => { this._dragging = point; event.dataTransfer.effectAllowed = "move"; li.classList.add("route-panel__dragging"); }); li.addEventListener("dragend", () => li.classList.remove("route-panel__dragging")); li.addEventListener("dragover", (event) => event.preventDefault()); li.addEventListener("drop", (event) => { event.preventDefault(); const from = this._points.indexOf(this._dragging); this._dragging = null; if (from < 0 || from === index) return; 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, 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"; text.append( Object.assign(document.createElement("span"), { className: "route-panel__name", textContent: point.name || `${point.lngLat[1].toFixed(5)}, ${point.lngLat[0].toFixed(5)}` }), Object.assign(document.createElement("small"), { className: "route-panel__role", textContent: [point.night && index < last ? "☾ night" : role, point.stay && !point.night ? `stay ${formatDuration(point.stay * 60)}` : ""].filter(Boolean).join(" · ") }), ); 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("✎", "Type, stay and note", true, () => { point.editingNote = !point.editingNote; this._renderPoints(); }); li.append(grip, badge, text, time, night, edit, this._navButton(point, role), this._pointButton("×", "Remove", true, () => this._removePoint(point))); // Hover/hold previews the point; a click on its name commits. wirePreview(this._map, text, () => ({ lngLat: point.lngLat })); text.addEventListener("click", () => this._map.easeTo({ center: point.lngLat, zoom: Math.max(this._map.getZoom(), 14) })); 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}"`; this._saveButton.textContent = this._editing ? "Save changes" : "Save to library"; } // The totals card: distance, time, climb (once the terrain's sampled), // arrival if leaving now. _renderTotals(route) { this._totals.hidden = !route; if (!route) return; const { distance_km: km, time_s: seconds } = route.properties; const arrive = new Date(Date.now() + seconds * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); const cells = [ [`${km.toFixed(km < 10 ? 1 : 0)} km`, "distance"], [formatDuration(seconds), "time"], [route.elevation ? `${Math.round(route.elevation.gain)} m` : "…", "climb"], [arrive, "arrive"], ]; this._totals.innerHTML = cells.map(([value, key]) => `${value}${key}`).join(""); if (route.elevation) { this._totals.insertAdjacentHTML("beforeend", `↓ ${Math.round(route.elevation.loss)} m · steepest ${route.elevation.maxGrade.toFixed(0)} %`); } } // 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(); if (this._shared) this._pushTrip(); // the server keeps the route, only the flag changes }); button.classList.add("route-panel__nav"); button.classList.toggle("active", !!point.nav); button.setAttribute("aria-pressed", !!point.nav); return button; } // 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; for (let i = from + 1; i < this._points.length; i++) { const leg = this._leg(i); km += leg?.km || 0; s += leg?.s || 0; if (this._points[i].night) break; } const leaves = schedule[from].leave; const date = leaves != null ? new Date(leaves).toLocaleDateString([], { weekday: "short", day: "numeric", month: "numeric" }) : `Day ${day + 1}`; const li = document.createElement("li"); li.className = "route-panel__day"; li.style.setProperty("--day", DAY_COLORS[day % DAY_COLORS.length]); li.innerHTML = `${km ? `${km.toFixed(0)} km · ${formatDuration(s)}` : ""}${leaves != null ? ` · leave ${clock(leaves)}` : ""}`; li.querySelector("b").textContent = date; // 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 type, stay (minutes) and note, under it. _noteEditor(point) { const li = document.createElement("li"); li.className = "route-panel__note-editor"; li.innerHTML = ` Parking `; 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", () => { point.stay = Math.max(0, Math.round(Number(stay.value) || 0)) || undefined; this._itineraryChanged(); }); note.addEventListener("change", () => { point.note = note.value.trim() || undefined; this._itineraryChanged(); }); 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"; 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() { if (this._shared) return this._pushTrip(); const request = ++this._request; this._route = null; if (this._active().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._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})`; } 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(); notifyRouteChanged(route); this._renderPoints(); // the legs' km and time next to the points (the Trip menu's too) this._saveButton.hidden = !route || !isLoggedIn(); this._directions.hidden = !route; this._profileButton.hidden = true; this._showCountries(route?.properties.countries); this._renderTotals(route); this._summary.textContent = message; if (this._profileShown && this._profilePanel.shown === this._profileShown) this._profilePanel.hide(); this._profileShown = null; if (!route) return; const { maneuvers } = route.properties; this._directions.querySelector(".route-panel__fold-meta").textContent = `${maneuvers.length} steps`; 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); }); this._addElevation(route); } // Sampled from the terrain tiles once the route is there; adds climb, // descent and the steepest sustained grade to the summary. async _addElevation(route) { const profile = await elevationProfile(route.geometry.coordinates, await this._offlineTerrain); if (this._route !== route || !profile) return; route.elevation = profile; this._renderTotals(route); this._profileButton.hidden = false; // the route's profile docked under the map while planning (not driving) if (!document.documentElement.classList.contains("driving")) { this._profileShown = this._profileProperties(); this._profilePanel.show(this._profileShown); } } // What TrackProfilePanel (and a library track) reads. _profileProperties() { const { distance_km: km, time_s: seconds } = this._route.properties; const elevation = this._route.elevation; return { name: this._editing?.name || "Route", vehicle_type: this._vehicle?.type || "car", // picks the default split length distance_meters: km * 1000, duration_secs: seconds, ...(elevation && { elevation_gain_meters: elevation.gain, profile: elevation.profile }), }; } // From the start point (or the map center with no points yet). async _showReach() { const center = this._points[0]?.lngLat || this._map.getCenter().toArray(); const minutes = this._panel.querySelector(".route-panel__reach select").value.split(",").map(Number); this._reachStatus.hidden = false; this._reachStatus.textContent = "Computing reach…"; try { const response = await fetch(ISOCHRONE_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ center, minutes, vehicle: this._vehicleId, avoid: this._avoid }), }); const data = await response.json().catch(() => ({})); if (!response.ok) throw new Error(data.error || `failed (${response.status})`); this._reach = data; } catch (err) { this._reachStatus.textContent = `No reach: ${err.message}`; return; } this._reachStatus.textContent = `Reach from ${this._points[0] ? "the start" : "the map center"}: ${minutes.map((m) => formatDuration(m * 60)).join(", ")}`; this._reachClear.hidden = false; this._draw(); } _draw() { if (!this._map.isStyleLoaded() && !this._map.getSource(SOURCE)) return; // style.load draws it const reach = this._reach || { type: "FeatureCollection", features: [] }; if (this._map.getSource(REACH_SOURCE)) { this._map.getSource(REACH_SOURCE).setData(reach); } else { // Valhalla colors each contour (properties.color); drawn under the route. this._map.addSource(REACH_SOURCE, { type: "geojson", data: reach }); this._map.addLayer({ id: `${REACH_SOURCE}-fill`, type: "fill", source: REACH_SOURCE, paint: { "fill-color": ["get", "color"], "fill-opacity": 0.15 }, }); this._map.addLayer({ id: `${REACH_SOURCE}-outline`, type: "line", source: REACH_SOURCE, paint: { "line-color": ["get", "color"], "line-width": 2 }, }); } // the traffic signals on it as points next to the line const signals = (this._route?.properties.signals || []).map(([lon, lat]) => ({ type: "Feature", geometry: { type: "Point", coordinates: [lon, lat] }, properties: {} })); const data = { type: "FeatureCollection", features: this._route ? [this._route, ...signals] : [] }; const source = this._map.getSource(SOURCE); if (source) { source.setData(data); return; } this._map.addSource(SOURCE, { type: "geojson", data, lineMetrics: true }); // line-progress for _showProgress // the part behind while navigated: thin and dashed, under the line, which goes clear there (_showProgress) this._map.addLayer({ id: `${SOURCE}-behind`, type: "line", source: SOURCE, filter: ["==", ["geometry-type"], "LineString"], layout: { "line-join": "round", visibility: "none" }, paint: { "line-color": getComputedStyle(document.documentElement).getPropertyValue("--ui-muted").trim() || "#6b6b66", "line-width": 2.5, "line-dasharray": [2, 2] }, }); 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 }, }); this._map.addLayer({ id: `${SOURCE}-signals`, type: "circle", source: SOURCE, minzoom: 14, filter: ["==", ["geometry-type"], "Point"], paint: { "circle-radius": 5, "circle-color": "#222", "circle-stroke-color": "#f9a825", "circle-stroke-width": 2.5 }, }); } // Navigated (km along the route, docs/design.adoc): the part behind thin // and dashed, the rest magenta (--route-active); null: the planned blue. _showProgress(km) { if (!this._map.getLayer(`${SOURCE}-line`)) return; const total = this._route?.properties.distance_km; const navigated = km != null && !!total; this._map.setLayoutProperty(`${SOURCE}-behind`, "visibility", navigated ? "visible" : "none"); if (!navigated) { this._map.setPaintProperty(`${SOURCE}-line`, "line-gradient", undefined); this._map.setPaintProperty(`${SOURCE}-casing`, "line-gradient", undefined); return; } const active = getComputedStyle(document.documentElement).getPropertyValue("--route-active").trim() || "#a21caf"; const clear = "rgba(0, 0, 0, 0)"; const fraction = Math.min(1, Math.max(0, km / total)); // behind the car the line and its casing go clear: the dashed layer under them shows, the log's track over it const ahead = (color) => (fraction > 0 ? ["step", ["line-progress"], clear, fraction, color] : ["step", ["line-progress"], color, 1, color]); this._map.setPaintProperty(`${SOURCE}-line`, "line-gradient", ahead(active)); this._map.setPaintProperty(`${SOURCE}-casing`, "line-gradient", ahead("#fff")); } // 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, speed_limits: _limits, signals: _signals, ...properties } = this._route.properties; const feature = { 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), via_points: this._points.map((p) => ({ name: p.name || null, nav: !!p.nav, passed: !!p.passed })), 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; 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 to the library"; } // 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) { const { features } = await (await fetch(`/api/library/node/${encodeURIComponent(key)}`)).json(); return features.find((f) => f.geometry.type === "LineString")?.properties.id; } // "Saved point": a search over the library's points (GET /api/search, // the "layers" source, nearest the map center first); a pick adds it. _setupSavedPoints() { const box = this._panel.querySelector(".route-panel__saved"); const input = box.querySelector("input"); const list = box.querySelector("ul"); let timer = null; let request = 0; this._panel.querySelector('[data-action="saved-point"]').addEventListener("click", () => { box.hidden = !box.hidden; if (!box.hidden) input.focus(); }); input.addEventListener("input", () => { clearTimeout(timer); timer = setTimeout(async () => { const mine = ++request; const center = this._map.getCenter(); const url = new URL("/api/search", window.location.origin); url.search = new URLSearchParams({ q: input.value, sources: "layers", lat: center.lat, lng: center.lng }); let results = []; try { if (input.value.trim()) results = (await (await fetch(url)).json()).results; } catch {} if (mine !== request) return; const points = results.filter(({ bbox }) => bbox && bbox[0] === bbox[2] && bbox[1] === bbox[3]); list.replaceChildren( ...points.map(({ name, bbox, source_label: folder }) => { const item = document.createElement("li"); const button = Object.assign(document.createElement("button"), { type: "button", textContent: name, title: folder }); button.addEventListener("click", () => { this._addPoint(bbox.slice(0, 2), name); box.hidden = true; input.value = ""; list.replaceChildren(); }); item.appendChild(button); return item; }), ); if (!points.length && input.value.trim()) list.replaceChildren(Object.assign(document.createElement("li"), { textContent: "No saved points found." })); }, 250); }); } // Country by country on the route: the profile's limits there (motorway / // outside towns / in towns), how its motorways are paid and whether the // profile has it (a vignette, or a toll unit over 3.5 t), the km driven. // Motorway km in a vignette country count whole: the vignette isn't // reliably tagged as toll in OSM. _showCountries(countries) { this._lastCountries = countries; const v = this._vehicle; const sign = (limit) => `${limit ?? "–"}`; const rows = (countries || []).map(({ code, km, motorway_km: motorway, toll_km: toll }) => { const row = SPEED_LIMITS[code]?.[isHeavy(v) ? "heavy" : "car"]; const pay = motorwayPayment(code, v); const pays = pay.how && motorway > 0 ? `${pay.how} ${pay.has ? "✓" : pay.has === false && pay.until ? `ended ${pay.until}` : "—"}` : toll > 0 ? `toll, ${toll.toFixed(0)} km` : ""; const li = document.createElement("li"); li.classList.toggle("route-panel__country--missing", pay.how != null && motorway > 0 && !pay.has); li.innerHTML = `${code}${km.toFixed(0)} km${pays ? ` · ${pays}` : ""}` + (row ? `${[row[0], row[2], row[3]].map(sign).join("")}` : ""); return li; }); this._countries.replaceChildren(...rows); this._countries.hidden = rows.length === 0; } // Avoid tolls / motorways for the whole route; this browser's choice. _setupAvoid() { try { this._avoid = JSON.parse(localStorage.getItem(AVOID_KEY)) || {}; } catch { this._avoid = {}; } this._panel.querySelectorAll(".route-panel__avoid input").forEach((input) => { input.checked = Boolean(this._avoid[input.name]); input.addEventListener("change", () => { this._avoid[input.name] = input.checked; try { localStorage.setItem(AVOID_KEY, JSON.stringify(this._avoid)); } catch {} this._fetchRoute(); }); }); } // --- vehicle -------------------------------------------------------------- // Profiles (Car, Camper, Bicycle, ...) are shared and edited only when // logged in, in a dialog (the Design canvas' Vehicle); which one is in use // is this browser's own choice (or the shared trip's), picked from the chip // in the map's bottom-left corner. A change re-routes. async _setupVehicle() { const dialog = document.querySelector("dialog.profiles"); const fieldset = dialog.querySelector(".profiles__form"); const inputs = [...fieldset.querySelectorAll(":scope > label input, :scope > label select")]; const list = dialog.querySelector(".profiles__list ul"); const vignetteList = dialog.querySelector(".profiles__vignettes ul"); const avoidRow = this._panel.querySelector(".route-panel__avoid"); try { this._vehicles = await (await fetch(VEHICLES_URL)).json(); } catch { return; } let editId = null; // the profile open in the dialog, apart from the one in use const current = () => this._vehicles.find((v) => v.id === this._vehicleId) || this._vehicles[0]; const edited = () => this._vehicles.find((v) => v.id === editId) || current(); const typeOf = (v) => v.type || "car"; const chip = document.createElement("div"); chip.className = "maplibregl-ctrl profile-chip"; chip.innerHTML = ``; const chipButton = chip.querySelector(".profile-chip__button"); const chipList = chip.querySelector(".profile-chip__list"); this._map.addControl({ onAdd: () => chip, onRemove: () => chip.remove() }, "bottom-left"); const row = (v, onPick) => { const li = document.createElement("li"); const button = Object.assign(document.createElement("button"), { type: "button" }); button.innerHTML = `${PROFILE_ICONS[typeOf(v)]}`; button.querySelector("b").textContent = v.name; button.querySelector("small").textContent = profileMeta(v); button.addEventListener("click", () => onPick(v)); li.appendChild(button); return li; }; const fillForm = () => { const v = edited(); list.replaceChildren(...this._vehicles.map((p) => { const li = row(p, (picked) => { editId = picked.id; fillForm(); }); li.classList.toggle("is-open", p === v); return li; })); inputs.forEach((input) => (input.value = v[input.name] ?? "")); const type = (fieldset.querySelector('[name="type"]').value = typeOf(v)); if (type === "bicycle" && !v.bicycle_type) fieldset.querySelector('[name="bicycle_type"]').value = "Hybrid"; fieldset.querySelectorAll("[data-for]").forEach((el) => (el.hidden = !el.dataset.for.split(" ").includes(type))); vignetteList.replaceChildren(...(v.vignettes || []).map((vignette, i) => { const li = document.createElement("li"); li.innerHTML = ` `; li.querySelector('[name="country"]').value = vignette.country || ""; li.querySelector('[name="kind"]').value = vignette.kind || "vignette"; li.querySelector('[name="until"]').value = vignette.until || ""; li.querySelectorAll("input, select").forEach((el) => el.addEventListener("change", () => { const value = el.value.trim(); if (value) vignette[el.name] = el.name === "country" ? value.toUpperCase() : value; else delete vignette[el.name]; if (vignette.country?.length === 2) save(); })); li.querySelector("button").addEventListener("click", () => { v.vignettes.splice(i, 1); save(); }); return li; })); }; const fill = () => { this._vehicle = current(); this._vehicleId = this._vehicle.id; chipButton.innerHTML = `${PROFILE_ICONS[typeOf(this._vehicle)]} ▴`; chipButton.children[1].textContent = [this._vehicle.name, typeOf(this._vehicle) === "car" ? profileMeta(this._vehicle) : ""].filter(Boolean).join(" · "); chipList.replaceChildren(...this._vehicles.map((v) => { const li = row(v, (picked) => { chipList.hidden = true; this._selectVehicle(picked.id); this._fetchRoute(); }); li.classList.toggle("is-current", v === this._vehicle); return li; })); if (isLoggedIn()) { const edit = Object.assign(document.createElement("button"), { type: "button", className: "profile-chip__edit", textContent: "Edit profiles…" }); edit.addEventListener("click", () => { chipList.hidden = true; editId = this._vehicleId; fillForm(); dialog.showModal(); }); chipList.appendChild(Object.assign(document.createElement("li"), { className: "profile-chip__edit-row" })).appendChild(edit); } avoidRow.hidden = typeOf(this._vehicle) !== "car"; // tolls/motorways: a car's choice if (this._lastCountries) this._showCountries(this._lastCountries); if (dialog.open) fillForm(); notifyVehicle(this._vehicle); }; this._selectVehicle = (id) => { this._vehicleId = id; try { localStorage.setItem(VEHICLE_KEY, id); } catch {} fill(); }; const save = async () => { const response = await fetch(VEHICLES_URL, { method: "PUT", body: JSON.stringify(this._vehicles) }); const data = await response.json().catch(() => ({})); if (response.ok) { this._vehicles = data; } else { window.alert(data.error || "Could not save the profiles."); this._vehicles = await (await fetch(VEHICLES_URL)).json(); } fill(); if (edited() === current()) this._fetchRoute(); }; try { // the shared trip's vehicle, when it came in before the vehicles did this._vehicleId = this._version >= 0 && this._vehicleId ? this._vehicleId : localStorage.getItem(VEHICLE_KEY); } catch {} fill(); chipButton.addEventListener("click", () => (chipList.hidden = !chipList.hidden)); document.addEventListener("click", (e) => !chip.contains(e.target) && (chipList.hidden = true)); dialog.querySelector(".profiles__close").addEventListener("click", () => dialog.close()); inputs.forEach((input) => input.addEventListener("change", () => { const value = input.value.trim(); if (input.name === "name") edited().name = value; else if (value === "") delete edited()[input.name]; else edited()[input.name] = value; save(); }), ); dialog.querySelector('[data-action="vignette-add"]').addEventListener("click", () => { (edited().vignettes ||= []).push({ country: "", kind: "vignette" }); fillForm(); vignetteList.lastElementChild?.querySelector("input")?.focus(); }); dialog.querySelector('[data-action="vehicle-add"]').addEventListener("click", () => { const id = `v${Date.now().toString(36)}`; this._vehicles.push({ ...edited(), id, name: "New profile" }); editId = id; save(); }); dialog.querySelector('[data-action="vehicle-delete"]').addEventListener("click", () => { if (this._vehicles.length < 2 || !window.confirm(`Delete the profile "${edited().name}"?`)) return; const gone = edited(); this._vehicles = this._vehicles.filter((v) => v !== gone); editId = null; if (gone === current()) this._selectVehicle(this._vehicles[0].id); save(); }); } } // The route's coordinates resampled every ≥50 m (at most PROFILE_SAMPLES // points), each with its terrain elevation, as TrackProfilePanel's // `profile`; plus total climb/descent and the steepest grade sustained // over GRADE_WINDOW_M. null when no elevation could be read. async function elevationProfile(coordinates, offline) { const along = [0]; for (let i = 1; i < coordinates.length; i++) along.push(along[i - 1] + distanceM(coordinates[i - 1], coordinates[i])); const total = along.at(-1); const step = Math.max(50, total / PROFILE_SAMPLES); const samples = []; let segment = 1; for (let d = 0; d < total; d += step) { while (along[segment] < d) segment++; const [a, b] = [coordinates[segment - 1], coordinates[segment]]; const t = (d - along[segment - 1]) / (along[segment] - along[segment - 1] || 1); samples.push({ distance_meters: d, lon: a[0] + (b[0] - a[0]) * t, lat: a[1] + (b[1] - a[1]) * t }); } samples.push({ distance_meters: total, lon: coordinates.at(-1)[0], lat: coordinates.at(-1)[1] }); const elevations = await Promise.all(samples.map((s) => elevationAt(s.lon, s.lat, offline))); const profile = samples.map((s, i) => ({ ...s, elevation_meters: elevations[i] })).filter((p) => p.elevation_meters != null); if (profile.length < 2) return null; let gain = 0; let loss = 0; let maxGrade = 0; let j = 0; profile.forEach((p, i) => { if (i > 0) { const climb = p.elevation_meters - profile[i - 1].elevation_meters; if (climb > 0) gain += climb; else loss -= climb; } while (j < profile.length - 1 && profile[j].distance_meters - p.distance_meters < GRADE_WINDOW_M) j++; const run = profile[j].distance_meters - p.distance_meters; if (run >= GRADE_WINDOW_M) maxGrade = Math.max(maxGrade, (Math.abs(profile[j].elevation_meters - p.elevation_meters) / run) * 100); }); return { profile, gain, loss, maxGrade }; } function distanceM([lon1, lat1], [lon2, lat2]) { const rad = Math.PI / 180; const a = Math.sin(((lat2 - lat1) * rad) / 2) ** 2 + Math.cos(lat1 * rad) * Math.cos(lat2 * rad) * Math.sin(((lon2 - lon1) * rad) / 2) ** 2; 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`; }