Profiles in a dialog, the chip in the map's bottom-left corner picks one (the Design canvas' Vehicle): a car gains fuel, Euro class, stickers and vignettes / toll units with dates; drive mode's Menu steps through them. Speed limits by country for cars and over 3.5 t (public/js/speed_limits.js, sources in it): the route's roads (km, road class, country), the limit shown the lower of the sign and the profile's; the Route panel's countries with their limits and how the motorways are paid; past a border a card in drive mode (GridBorder). The itinerary in the Route panel (Itinerary): the trip's name, leave time, days start; per stop a night, stay and note, planned times, day headers; another screen's change shown where it happened with Undo
This commit is contained in:
1 parent
a6158f4083
commit
5e31dfaba9
15 files changed
+733
-169
No files matched your search
+299
-53
@@ -1,7 +1,8 @@
|
||||
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
|
||||
import { Marker, Popup } from "/vendor/maplibre-gl/maplibre-gl.mjs";
|
||||
import { ROUTE_ICON, REVERSE_ICON, CLEAR_ICON } from "/js/icons.js";
|
||||
import { notifySidePanelOpen, onlyOneSidePanelOpen, notifyGpxStoreChanged, onRoutePoint, onRouteEdit, notifyRouteChanged, onReroute, onRouteProgress } from "/js/panels.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";
|
||||
|
||||
@@ -18,10 +19,16 @@ 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";
|
||||
// Motorways paid by a time-based vignette rather than per section. Not
|
||||
// reliably tagged as toll in OSM, so every motorway km there counts.
|
||||
const VIGNETTE_COUNTRIES = new Set(["AT", "BG", "CH", "CZ", "HU", "MD", "RO", "SI", "SK"]);
|
||||
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";
|
||||
const SOURCE = "route";
|
||||
const COLOR = "#1d6fdc";
|
||||
@@ -109,6 +116,12 @@ 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._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", () => {
|
||||
@@ -160,10 +173,11 @@ export class RoutePanelControl {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
points: this._points.map(({ lngLat, name, nav, passed }) => ({ lngLat, name, nav, passed })),
|
||||
points: this._points.map(({ lngLat, name, nav, passed, night, stay, note }) => ({ lngLat, name, nav, passed, night, stay, note })),
|
||||
vehicle: this._vehicleId,
|
||||
avoid: this._avoid,
|
||||
editing: this._editing,
|
||||
...this._itinerary,
|
||||
}),
|
||||
});
|
||||
const trip = await response.json().catch(() => ({}));
|
||||
@@ -180,11 +194,17 @@ export class RoutePanelControl {
|
||||
// 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(({ lngLat, name, nav, passed, night, stay, note }) => ({ lngLat, name, nav, passed, night, stay, note }));
|
||||
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 }));
|
||||
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 };
|
||||
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]));
|
||||
@@ -213,11 +233,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 } = {}) {
|
||||
_addPoint(lngLat, name, { quiet = false, nav = !!name && name !== "My position", passed = false, night, stay, note } = {}) {
|
||||
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 };
|
||||
const point = { lngLat, name, nav, marker, night: night || undefined, stay: stay || undefined, note: note || undefined };
|
||||
this._setPassed(point, passed);
|
||||
marker.on("dragend", () => {
|
||||
const { lng, lat } = marker.getLngLat();
|
||||
@@ -331,6 +351,17 @@ export class RoutePanelControl {
|
||||
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) => {
|
||||
@@ -362,13 +393,86 @@ export class RoutePanelControl {
|
||||
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([p.name, p.night, p.stay, p.note]) !== JSON.stringify([before[i]?.name, before[i]?.night, before[i]?.stay, before[i]?.note]));
|
||||
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 = `<span>Another screen ${escapeText(what)}</span> <button type="button">Undo</button>`;
|
||||
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, { quiet: true, nav: !!p.nav, passed: !!p.passed, night: p.night, stay: p.stay, note: p.note }));
|
||||
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._list.appendChild(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;
|
||||
@@ -405,13 +509,27 @@ export class RoutePanelControl {
|
||||
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: role }),
|
||||
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(" · ") }),
|
||||
);
|
||||
li.append(grip, badge, text, this._navButton(point, role), this._pointButton("×", "Remove", true, () => this._removePoint(point)));
|
||||
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.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, () => {
|
||||
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._stopListeners?.forEach((callback) => callback());
|
||||
this._editingNote.hidden = !this._editing;
|
||||
@@ -457,6 +575,45 @@ export class RoutePanelControl {
|
||||
return button;
|
||||
}
|
||||
|
||||
// A day's header: its date (from when it leaves), km and driving time.
|
||||
_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 = `<b></b><span>${km ? `${km.toFixed(0)} km · ${formatDuration(s)}` : ""}${leaves != null ? ` · leave ${clock(leaves)}` : ""}</span>`;
|
||||
li.querySelector("b").textContent = date;
|
||||
return li;
|
||||
}
|
||||
|
||||
// A stop's 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")];
|
||||
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;
|
||||
}
|
||||
|
||||
_pointButton(text, title, enabled, onClick) {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
@@ -782,15 +939,28 @@ export class RoutePanelControl {
|
||||
});
|
||||
}
|
||||
|
||||
// Where the route needs a vignette or pays tolls, country by country.
|
||||
// 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) {
|
||||
const rows = (countries || []).flatMap(({ code, motorway_km: motorway, toll_km: toll }) => {
|
||||
if (VIGNETTE_COUNTRIES.has(code) && motorway > 0) {
|
||||
return [`${code}: vignette, ${motorway.toFixed(0)} km motorway${toll > 0 ? ` (${toll.toFixed(0)} km tolled)` : ""}`];
|
||||
}
|
||||
return toll > 0 ? [`${code}: toll, ${toll.toFixed(0)} km`] : [];
|
||||
this._lastCountries = countries;
|
||||
const v = this._vehicle;
|
||||
const sign = (limit) => `<span class="route-panel__sign">${limit ?? "–"}</span>`;
|
||||
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 = `<b>${code}</b><span>${km.toFixed(0)} km${pays ? ` · ${pays}` : ""}</span>` +
|
||||
(row ? `<span class="route-panel__signs" title="motorway · outside towns · in towns">${[row[0], row[2], row[3]].map(sign).join("")}</span>` : "");
|
||||
return li;
|
||||
});
|
||||
this._countries.replaceChildren(...rows.map((text) => Object.assign(document.createElement("li"), { textContent: text })));
|
||||
this._countries.replaceChildren(...rows);
|
||||
this._countries.hidden = rows.length === 0;
|
||||
}
|
||||
|
||||
@@ -815,30 +985,104 @@ export class RoutePanelControl {
|
||||
|
||||
// --- vehicle --------------------------------------------------------------
|
||||
|
||||
// Profiles (Car, Camper, ...) are shared and edited only when logged in;
|
||||
// which one is in use is this browser's own choice. A change re-routes.
|
||||
// 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 select = this._panel.querySelector(".route-panel__vehicle-select");
|
||||
const editButton = this._panel.querySelector('[data-action="vehicle-edit"]');
|
||||
const fieldset = this._panel.querySelector(".route-panel__vehicle");
|
||||
const inputs = [...fieldset.querySelectorAll("input, select")];
|
||||
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 fill = () => {
|
||||
select.replaceChildren(...this._vehicles.map((v) => new Option(v.name, v.id)));
|
||||
this._vehicle = current();
|
||||
this._vehicleId = select.value = this._vehicle.id;
|
||||
inputs.forEach((input) => (input.value = this._vehicle[input.name] ?? ""));
|
||||
// No type: a car (profiles saved before bicycle/foot existed).
|
||||
const type = (fieldset.querySelector('[name="type"]').value = this._vehicle.type || "car");
|
||||
if (type === "bicycle" && !this._vehicle.bicycle_type) fieldset.querySelector('[name="bicycle_type"]').value = "Hybrid";
|
||||
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 = `<ul class="profile-chip__list" hidden></ul><button type="button" class="profile-chip__button" aria-haspopup="true"></button>`;
|
||||
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 = `<span>${PROFILE_ICONS[typeOf(v)]}</span><b></b><small></small>`;
|
||||
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)));
|
||||
avoidRow.hidden = type !== "car"; // tolls/motorways: a car's choice
|
||||
vignetteList.replaceChildren(...(v.vignettes || []).map((vignette, i) => {
|
||||
const li = document.createElement("li");
|
||||
li.innerHTML = `<input name="country" maxlength="2" placeholder="SK" aria-label="Country">
|
||||
<select name="kind" aria-label="Kind"><option value="vignette">vignette</option><option value="toll">toll unit (over 3.5 t)</option></select>
|
||||
<input name="until" type="date" aria-label="Valid until"><button type="button" aria-label="Remove">✕</button>`;
|
||||
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 = `<span>${PROFILE_ICONS[typeOf(this._vehicle)]}</span> <span></span> ▴`;
|
||||
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;
|
||||
@@ -853,11 +1097,11 @@ export class RoutePanelControl {
|
||||
if (response.ok) {
|
||||
this._vehicles = data;
|
||||
} else {
|
||||
window.alert(data.error || "Could not save the vehicles.");
|
||||
window.alert(data.error || "Could not save the profiles.");
|
||||
this._vehicles = await (await fetch(VEHICLES_URL)).json();
|
||||
}
|
||||
fill();
|
||||
this._fetchRoute();
|
||||
if (edited() === current()) this._fetchRoute();
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -865,33 +1109,35 @@ export class RoutePanelControl {
|
||||
this._vehicleId = this._version >= 0 && this._vehicleId ? this._vehicleId : localStorage.getItem(VEHICLE_KEY);
|
||||
} catch {}
|
||||
fill();
|
||||
select.addEventListener("change", () => {
|
||||
this._selectVehicle(select.value);
|
||||
this._fetchRoute();
|
||||
});
|
||||
|
||||
editButton.hidden = !isLoggedIn();
|
||||
editButton.addEventListener("click", () => (fieldset.hidden = !fieldset.hidden));
|
||||
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") current().name = value;
|
||||
else if (value === "") delete current()[input.name];
|
||||
else if (input.name === "type" || input.name === "bicycle_type") current()[input.name] = value;
|
||||
else current()[input.name] = value;
|
||||
if (input.name === "name") edited().name = value;
|
||||
else if (value === "") delete edited()[input.name];
|
||||
else edited()[input.name] = value;
|
||||
save();
|
||||
}),
|
||||
);
|
||||
fieldset.querySelector('[data-action="vehicle-add"]').addEventListener("click", () => {
|
||||
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({ ...current(), id, name: "New vehicle" });
|
||||
this._selectVehicle(id);
|
||||
this._vehicles.push({ ...edited(), id, name: "New profile" });
|
||||
editId = id;
|
||||
save();
|
||||
});
|
||||
fieldset.querySelector('[data-action="vehicle-delete"]').addEventListener("click", () => {
|
||||
if (this._vehicles.length < 2 || !window.confirm(`Delete the vehicle "${current().name}"?`)) return;
|
||||
this._vehicles = this._vehicles.filter((v) => v !== current());
|
||||
this._selectVehicle(this._vehicles[0].id);
|
||||
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();
|
||||
});
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user