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
This commit is contained in:
1 parent
5e31dfaba9
commit
87d7bd2463
36 files changed
+2047
-123
No files matched your search
@@ -42,6 +42,10 @@ const LANES_AHEAD_S = 45;
|
||||
const ARRIVE_M = 30; // this close to the end: arrived (navigation goes on: past it, the route turns back)
|
||||
const ARRIVE_TYPES = [4, 5, 6]; // Valhalla's destination maneuvers
|
||||
const DEFAULT_WIDGETS = { inclinometer: true, speed: true, altitude: true, navigation: true, banner: true };
|
||||
// Step advance after Ferrostar's DistanceEntryExit: a maneuver stays the next one
|
||||
// until the position is this far past it (not before reaching it: at the turn the
|
||||
// turn is still shown, "now"), then the one after it
|
||||
const STEP_EXIT_M = 5;
|
||||
const THEN_M = 300; // the maneuver after the next one shown with it when it follows this closely
|
||||
// Voice prompts (speechSynthesis, Valhalla's verbal instructions), on/off in
|
||||
// drive mode's Menu: "In 400 m, turn right…" from SOON_S ahead, the
|
||||
@@ -294,7 +298,7 @@ export class DashboardControl {
|
||||
const nextKm = [...limits, ...roads].map(([km]) => km).filter((km) => km > at).sort((a, b) => a - b).find((km) => limitAt(km) !== limit);
|
||||
const next = nextKm != null ? [nextKm, limitAt(nextKm)] : null;
|
||||
const signal = signals.find(([, , km]) => km > at);
|
||||
const index = maneuvers.findIndex((m) => m.at > at + 0.005);
|
||||
const index = maneuvers.findIndex((m) => m.at > at - STEP_EXIT_M / 1000);
|
||||
const maneuver = maneuvers[index];
|
||||
const then = maneuvers[index + 1];
|
||||
const onStreet = maneuvers[index - 1]?.street; // the one being driven: the last maneuver's
|
||||
@@ -307,7 +311,7 @@ export class DashboardControl {
|
||||
next: next && { limit: next[1], m: (next[0] - at) * 1000 },
|
||||
country: roads.findLast(([km]) => km <= at)?.[2] ?? null,
|
||||
signal: signal && (signal[2] - at) * 1000,
|
||||
maneuver: maneuver && { ...maneuver, m: (maneuver.at - at) * 1000 },
|
||||
maneuver: maneuver && { ...maneuver, m: Math.max(0, (maneuver.at - at) * 1000) },
|
||||
then: maneuver && then && then.at - maneuver.at <= THEN_M / 1000 ? then : null,
|
||||
street: onStreet,
|
||||
arrived: ARRIVE_TYPES.includes(maneuvers.at(-1)?.type) && (!maneuver || (index === maneuvers.length - 1 && (maneuver.at - at) * 1000 <= ARRIVE_M)),
|
||||
|
||||
+458
-2
@@ -3,6 +3,11 @@
|
||||
// menu area, built the same way as the Trip menu.
|
||||
import { distance } from "/js/dashboard.js";
|
||||
import { elevationAt } from "/js/dem.js";
|
||||
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
|
||||
import { DAY_COLORS, formatDuration, STOP_TYPES } from "/js/route.js";
|
||||
import { NPS_SYMBOLS } from "/js/icons.js";
|
||||
import { getTimes } from "/vendor/suncalc/suncalc.js";
|
||||
import { currentVehicle } from "/js/panels.js";
|
||||
|
||||
const SEARCH_DELAY_MS = 300;
|
||||
const AHEAD_M = 2000; // "Ahead": saved things this close to the route still to drive
|
||||
@@ -384,7 +389,7 @@ export function terrainMenu(ctx) {
|
||||
<div class="drive-panel__cell drive-terrain__spare"></div>
|
||||
<button type="button" class="drive-terrain__level" data-action="level">Level here (zero)</button>
|
||||
<button type="button" class="drive-terrain__reset" data-action="reset">Reset max</button>
|
||||
<button type="button" class="drive-terrain__road" data-action="road">Road view</button>`);
|
||||
<button type="button" class="drive-terrain__road" data-action="road">Level ▸</button>`);
|
||||
let peak = { roll: null, pitch: null };
|
||||
let ahead = { climb: null, across: null };
|
||||
let aheadAt = 0;
|
||||
@@ -452,7 +457,7 @@ export function terrainMenu(ctx) {
|
||||
}
|
||||
|
||||
el.querySelector(".drive-panel__close").addEventListener("click", ctx.close);
|
||||
el.querySelector('[data-action="road"]').addEventListener("click", ctx.close);
|
||||
el.querySelector('[data-action="road"]').addEventListener("click", ctx.openLevel);
|
||||
el.querySelector('[data-action="reset"]').addEventListener("click", () => { peak = { roll: null, pitch: null }; render(); });
|
||||
el.querySelector('[data-action="level"]').addEventListener("click", async () => {
|
||||
if (!armed) {
|
||||
@@ -468,3 +473,454 @@ export function terrainMenu(ctx) {
|
||||
});
|
||||
return { el, render, opened: render };
|
||||
}
|
||||
|
||||
// Recording (the Design canvas' GridRecording): the trip log — the running
|
||||
// trip's, else the last one's (lib/maptool/trip_days.rb, /api/trip/log/days)
|
||||
// — as totals and days; the days only cuts in one continuous log (where the
|
||||
// car stood ≥ 4 h, else 03:00), joined or cut by hand. Export: the days
|
||||
// ticked, a piece between A and B on the map (markers snapped to the line),
|
||||
// or the whole trip, as GPX (a track per day) or a .zip of a file per day.
|
||||
// ctx: { map, showBounds, endTrip, close }.
|
||||
export function recordingMenu(ctx) {
|
||||
const el = panel("drive-rec", "Recording", `
|
||||
<div class="drive-panel__cell drive-rec__name"></div>
|
||||
<div class="drive-panel__cell drive-rec__total" data-total="distance"></div>
|
||||
<div class="drive-panel__cell drive-rec__total" data-total="driving"></div>
|
||||
<div class="drive-panel__cell drive-rec__total" data-total="standing"></div>
|
||||
<div class="drive-panel__cell drive-rec__total" data-total="ascent"></div>
|
||||
<div class="drive-rec__days"></div>
|
||||
<form class="drive-panel__cell drive-rec__export" hidden>
|
||||
<fieldset><legend>What</legend>
|
||||
<label><input type="radio" name="what" value="days" checked> <span data-text="days"></span></label>
|
||||
<label><input type="radio" name="what" value="piece"> <span data-text="piece"></span></label>
|
||||
<label><input type="radio" name="what" value="whole"> <span data-text="whole"></span></label></fieldset>
|
||||
<fieldset><legend>Files</legend>
|
||||
<label><input type="radio" name="files" value="one" checked> One GPX, a track per day</label>
|
||||
<label><input type="radio" name="files" value="per_day"> A file per day (.zip)</label></fieldset>
|
||||
<fieldset class="drive-rec__with"><legend>With it</legend>
|
||||
<label><input type="checkbox" name="stops" checked> Stops visited</label>
|
||||
<label><input type="checkbox" name="plan"> Planned route</label>
|
||||
<label><input type="checkbox" name="pauses"> Standing (pauses)</label></fieldset>
|
||||
</form>
|
||||
<button type="button" class="drive-rec__end" data-action="end">End the trip</button>
|
||||
<button type="button" class="drive-rec__cut" data-action="cut">✂ Cut here</button>
|
||||
<button type="button" class="drive-panel__primary drive-rec__go" data-action="export"></button>
|
||||
<button type="button" class="drive-rec__back" data-action="back">← Back</button>
|
||||
<button type="button" class="drive-panel__primary drive-rec__save" data-action="save"></button>`);
|
||||
const $ = (sel) => el.querySelector(sel);
|
||||
const form = $(".drive-rec__export");
|
||||
let data = null;
|
||||
let picked = null; // the days ticked: Set of day numbers
|
||||
let exporting = false;
|
||||
let ab = null; // [A, B] markers while a piece is picked
|
||||
const day = (t) => new Date(t * 1000).toLocaleDateString([], { weekday: "short", day: "numeric", month: "numeric" });
|
||||
const time = (t) => new Date(t * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
||||
const km = (m) => `${Math.round(m / 1000).toLocaleString()} km`;
|
||||
const hours = (s) => formatDuration(s);
|
||||
const stats = (d) => [km(d.distance_m), hours(d.driving_s), d.ascent_m ? `↑ ${Math.round(d.ascent_m).toLocaleString()} m` : ""].filter(Boolean).join(" · ");
|
||||
const CUT = { auto: "cut automatically", night: "cut at 03:00", hand: "cut by hand" };
|
||||
const pickedKm = () => data.days.filter((d) => picked.has(d.index)).reduce((sum, d) => sum + d.distance_m, 0);
|
||||
|
||||
const post = async (body) => {
|
||||
await fetch("/api/trip/log/days", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
||||
load();
|
||||
};
|
||||
|
||||
// A and B: draggable, snapped to the nearest point of the line on drop.
|
||||
const nearest = (lngLat) => data.track.reduce((best, p) => (meters(p, [lngLat.lng, lngLat.lat]) < meters(best, [lngLat.lng, lngLat.lat]) ? p : best));
|
||||
const placeAB = async () => {
|
||||
if (!data.track) data = { ...data, track: (await (await fetch("/api/trip/log/days?track=1", { cache: "no-store" })).json()).track };
|
||||
const days = data.days.filter((d) => picked.has(d.index));
|
||||
const from = days.length ? data.track[days[0].from] : data.track[0];
|
||||
const to = days.length ? data.track[days.at(-1).to - 1] : data.track.at(-1);
|
||||
ab = [from, to].map((p, i) => {
|
||||
const m = Object.assign(document.createElement("div"), { className: "drive-rec__pin", textContent: "AB"[i] });
|
||||
const marker = new Marker({ element: m, draggable: true }).setLngLat(p.slice(0, 2)).addTo(ctx.map);
|
||||
marker.point = p;
|
||||
marker.on("dragend", () => { marker.point = nearest(marker.getLngLat()); marker.setLngLat(marker.point.slice(0, 2)); renderExport(); });
|
||||
return marker;
|
||||
});
|
||||
renderExport();
|
||||
};
|
||||
const removeAB = () => { ab?.forEach((m) => m.remove()); ab = null; };
|
||||
const piece = () => ab && [ab[0].point[2], ab[1].point[2]].sort((a, b) => a - b);
|
||||
|
||||
const renderExport = () => {
|
||||
const what = form.elements.what.value;
|
||||
form.querySelector('[data-text="days"]').textContent = `Days ticked · ${[...picked].sort().map((n) => `Day ${n}`).join(", ") || "none"} · ${km(pickedKm())}`;
|
||||
const p = piece();
|
||||
const pieceKm = p ? data.track.filter((q) => q[2] >= p[0] && q[2] <= p[1]).reduce((s, q, i, a) => s + (i ? meters(a[i - 1], q) : 0), 0) : 0;
|
||||
form.querySelector('[data-text="piece"]').innerHTML = p ? `A piece: <b>A</b> ${day(p[0])} ${time(p[0])} → <b>B</b> ${time(p[1])} · ${km(pieceKm)} <small>move A, B on the map</small>` : "A piece between A and B on the map";
|
||||
form.querySelector('[data-text="whole"]').textContent = `The whole trip · ${km(data.totals.distance_m)}`;
|
||||
const n = what === "days" ? picked.size : what === "piece" ? 1 : data.days.length;
|
||||
$(".drive-rec__save").textContent = `Save ${what === "piece" ? "the piece" : `${n} day${n === 1 ? "" : "s"}`} · ${form.elements.files.value === "per_day" && n > 1 ? "ZIP" : "GPX"}`;
|
||||
$(".drive-rec__save").disabled = what === "days" && !picked.size;
|
||||
};
|
||||
form.addEventListener("change", (e) => {
|
||||
if (e.target.name === "what") (e.target.value === "piece" ? placeAB() : removeAB());
|
||||
renderExport();
|
||||
});
|
||||
|
||||
const render = () => {
|
||||
el.querySelector(".drive-panel__head").firstChild.textContent = exporting ? "Export " : "Recording ";
|
||||
const note = el.querySelector(".drive-panel__note");
|
||||
for (const b of el.querySelectorAll("[data-action]")) b.hidden = !data;
|
||||
if (!data) {
|
||||
note.textContent = "";
|
||||
$(".drive-rec__name").textContent = "No trip recorded yet — Start the trip in the Trip menu";
|
||||
$(".drive-rec__days").replaceChildren();
|
||||
for (const t of el.querySelectorAll(".drive-rec__total")) t.innerHTML = "";
|
||||
form.hidden = true;
|
||||
return;
|
||||
}
|
||||
const tot = data.totals;
|
||||
const span = tot.ended_at - tot.started_at;
|
||||
note.textContent = data.active ? `● REC ${Math.floor(span / 86400) ? `${Math.floor(span / 86400)} d ` : ""}${Math.floor((span % 86400) / 3600)} h` : "ended";
|
||||
note.classList.toggle("drive-rec__live", data.active);
|
||||
$(".drive-rec__name").textContent = (data.folder || "").replace(/^Trips\//, "");
|
||||
const totals = {
|
||||
distance: ["Distance", km(tot.distance_m), `${tot.days} day${tot.days === 1 ? "" : "s"}`],
|
||||
driving: ["Driving", hours(tot.driving_s), tot.driving_s ? `Ø ${Math.round(tot.distance_m / tot.driving_s * 3.6)} km/h` : ""],
|
||||
standing: ["Standing", hours(tot.standing_s), `${tot.stops} stop${tot.stops === 1 ? "" : "s"}`],
|
||||
ascent: ["Ascent", tot.ascent_m ? `${Math.round(tot.ascent_m).toLocaleString()} m` : "—", tot.max_alt_m != null ? `max ${Math.round(tot.max_alt_m).toLocaleString()} m` : ""],
|
||||
};
|
||||
for (const t of el.querySelectorAll(".drive-rec__total")) {
|
||||
const [label, value, sub] = totals[t.dataset.total];
|
||||
t.innerHTML = `<span class="drive-cell__label">${label}</span><b>${escapeHtml(value)}</b><small>${escapeHtml(sub)}</small>`;
|
||||
}
|
||||
const rows = data.days.flatMap((d, i) => {
|
||||
const now = data.active && i === data.days.length - 1;
|
||||
const li = document.createElement("div");
|
||||
li.className = "drive-rec__day";
|
||||
li.style.setProperty("--day", DAY_COLORS[i % DAY_COLORS.length]);
|
||||
li.innerHTML = `<label class="drive-rec__tick"><input type="checkbox" aria-label="Export day ${d.index}"${picked.has(d.index) ? " checked" : ""}></label>
|
||||
<span class="drive-panel__text"><small>Day ${d.index} · ${day(d.started_at)}${now ? ' <em class="drive-rec__live">● now</em>' : ""}</small>
|
||||
<b>${time(d.started_at)} – ${now ? "…" : time(d.ended_at)}</b><small>${stats(d)}${now ? " so far" : ""}</small></span>`;
|
||||
li.querySelector("input").addEventListener("change", (e) => { e.target.checked ? picked.add(d.index) : picked.delete(d.index); render(); });
|
||||
li.append(cellButton("look", "⌕", `Show day ${d.index} on the map`, () => ctx.showBounds(d.bbox)));
|
||||
if (!d.cut) return [li];
|
||||
const cut = document.createElement("div");
|
||||
cut.className = "drive-rec__cutrow";
|
||||
cut.innerHTML = `<span aria-hidden="true">✂</span><span>Stood ${hours(d.cut.stood_s)} · ${CUT[d.cut.kind]}</span>`;
|
||||
cut.append(cellButton("join", "Join", `Join day ${d.index} and day ${d.index + 1}`, () => post({ join: d.cut.next })));
|
||||
return [li, cut];
|
||||
});
|
||||
$(".drive-rec__days").replaceChildren(...rows);
|
||||
$(".drive-rec__days").hidden = exporting;
|
||||
form.hidden = !exporting;
|
||||
$(".drive-rec__end").hidden = exporting || !data.active;
|
||||
$(".drive-rec__cut").hidden = exporting || !data.active;
|
||||
$(".drive-rec__go").hidden = exporting;
|
||||
$(".drive-rec__go").textContent = `Export ${picked.size ? `${picked.size} day${picked.size === 1 ? "" : "s"}` : ""} ▸`;
|
||||
$(".drive-rec__back").hidden = !exporting;
|
||||
$(".drive-rec__save").hidden = !exporting;
|
||||
if (exporting) renderExport();
|
||||
};
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const response = await fetch("/api/trip/log/days", { cache: "no-store" });
|
||||
const fresh = response.ok ? await response.json() : null;
|
||||
if (fresh && (!data || fresh.folder !== data.folder)) picked = new Set(fresh.days.filter((d, i) => !(fresh.active && i === fresh.days.length - 1)).map((d) => d.index));
|
||||
data = fresh && { ...fresh, track: data?.folder === fresh.folder ? data.track : null };
|
||||
} catch { /* offline for a moment */ }
|
||||
render();
|
||||
}
|
||||
|
||||
el.querySelector('[data-action="end"]').addEventListener("click", async () => { await ctx.endTrip(); load(); });
|
||||
el.querySelector('[data-action="cut"]').addEventListener("click", () => post({ cut: Date.now() / 1000 }));
|
||||
el.querySelector('[data-action="export"]').addEventListener("click", () => { exporting = true; render(); });
|
||||
el.querySelector('[data-action="back"]').addEventListener("click", () => { exporting = false; removeAB(); render(); });
|
||||
el.querySelector('[data-action="save"]').addEventListener("click", () => {
|
||||
const what = form.elements.what.value;
|
||||
const q = new URLSearchParams();
|
||||
if (what === "days") q.set("days", [...picked].join(","));
|
||||
if (what === "piece" && piece()) { q.set("from", piece()[0]); q.set("to", piece()[1]); }
|
||||
if (form.elements.files.value === "per_day") q.set("per_day", "1");
|
||||
for (const name of ["stops", "plan", "pauses"]) if (form.elements[name].checked) q.set(name, "1");
|
||||
const a = Object.assign(document.createElement("a"), { href: `/api/trip/log/export?${q}` });
|
||||
a.click();
|
||||
});
|
||||
|
||||
return {
|
||||
el,
|
||||
opened: () => { exporting = false; removeAB(); load(); },
|
||||
closed: () => removeAB(),
|
||||
};
|
||||
}
|
||||
|
||||
// Level (the canvas' GridLevel), standing: the wheel-chock calculation from
|
||||
// the IMU's roll and pitch (right side low, nose up positive, as the
|
||||
// inclinometer) and the profile's wheelbase and track. A wheel's height is
|
||||
// z = x·tan(pitch) − y·tan(roll) (x forward, y right); every wheel is lifted
|
||||
// to the highest one — never dug in — so one stays. Ramps: the lift rounded to
|
||||
// the profile's ramp steps, and the roll / pitch left after them; jacks: the cm.
|
||||
const LEVEL_TOL = 0.5; // ° level enough
|
||||
const DEFAULT_RAMPS = [3, 6, 9];
|
||||
const UNDER_KEY = "maptool.levelUnder";
|
||||
const WHEELS = { FL: [1, -1], FR: [1, 1], RL: [-1, -1], RR: [-1, 1] }; // [forward, right] signs
|
||||
|
||||
export function levelPlan(roll, pitch, wheelbase, track, steps) {
|
||||
const z = Object.fromEntries(Object.entries(WHEELS).map(([k, [fx, sy]]) => [k, (fx * wheelbase) / 2 * Math.tan(pitch * RAD) - (sy * track) / 2 * Math.tan(roll * RAD)]));
|
||||
const top = Math.max(...Object.values(z));
|
||||
const wheels = Object.fromEntries(Object.entries(z).map(([k, v]) => {
|
||||
const cm = (top - v) * 100;
|
||||
if (!steps || cm < 1) return [k, { cm, used: steps ? 0 : cm, step: null }];
|
||||
const i = steps.reduce((best, step, j) => (Math.abs(step - cm) < Math.abs(steps[best] - cm) ? j : best), 0);
|
||||
return [k, { cm, used: steps[i], step: i + 1, over: cm > steps.at(-1) + 1.5 }];
|
||||
}));
|
||||
const after = Object.fromEntries(Object.keys(z).map((k) => [k, z[k] + wheels[k].used / 100]));
|
||||
return {
|
||||
wheels,
|
||||
roll: Math.atan((after.FL + after.RL - after.FR - after.RR) / 2 / track) / RAD,
|
||||
pitch: Math.atan((after.FL + after.FR - after.RL - after.RR) / 2 / wheelbase) / RAD,
|
||||
};
|
||||
}
|
||||
|
||||
export function levelMenu(ctx) {
|
||||
const el = panel("drive-level", "Level", `
|
||||
<div class="drive-panel__cell drive-level__plan"></div>
|
||||
<div class="drive-panel__cell drive-level__bubble"></div>
|
||||
<div class="drive-panel__cell drive-terrain__field" data-field="roll"></div>
|
||||
<div class="drive-panel__cell drive-terrain__field" data-field="pitch"></div>
|
||||
<div class="drive-panel__cell drive-terrain__field" data-field="after"></div>
|
||||
<div class="drive-panel__cell drive-level__advice"></div>
|
||||
<button type="button" class="drive-level__zero" data-action="zero">Zero here</button>
|
||||
<button type="button" class="drive-level__under" data-action="under"></button>
|
||||
<button type="button" class="drive-level__terrain" data-action="terrain">Terrain view</button>`);
|
||||
let armed = null;
|
||||
const under = () => { try { return localStorage.getItem(UNDER_KEY) === "jacks" ? "jacks" : "ramps"; } catch { return "ramps"; } };
|
||||
const deg = (v) => `${v < 0 ? "−" : ""}${Math.abs(v).toFixed(1)}°`;
|
||||
const field = (name, label, value, unit, ok) =>
|
||||
(el.querySelector(`[data-field="${name}"]`).innerHTML = `<span class="drive-cell__label">${label}</span><span class="drive-cell__value drive-cell__value--mid${ok ? " drive-level--ok" : ""}">${value} <small>${unit}</small></span>`);
|
||||
|
||||
function render() {
|
||||
if (el.hidden) return;
|
||||
const dash = ctx.state();
|
||||
const v = dash?.values || {};
|
||||
const vehicle = currentVehicle || {};
|
||||
const guessed = !vehicle.wheelbase || !vehicle.track;
|
||||
const wheelbase = vehicle.wheelbase || (vehicle.length ? vehicle.length * 0.55 : 3);
|
||||
const track = vehicle.track || (vehicle.width ? vehicle.width - 0.25 : 1.6);
|
||||
const ramps = String(vehicle.ramps || "").split(/\s+/).map(Number).filter((n) => n > 0);
|
||||
const steps = under() === "ramps" ? (ramps.length ? ramps : DEFAULT_RAMPS) : null;
|
||||
el.querySelector(".drive-panel__note").textContent = `${vehicle.name || "Car"} · ${wheelbase.toFixed(2)} × ${track.toFixed(2)} m${guessed ? " (guessed: set the wheelbase and track in the profile)" : ""} · ${steps ? `ramps ${steps.join(" · ")} cm` : "jacks"}`;
|
||||
el.querySelector('[data-action="under"]').textContent = steps ? `Ramps ${steps.join(" · ")} cm ▸` : "Jacks ▸";
|
||||
const zero = el.querySelector('[data-action="zero"]');
|
||||
const action = (dash?.actions || []).findIndex((a) => /level/i.test(a.name));
|
||||
zero.disabled = action < 0;
|
||||
zero.title = action < 0 ? "No levelling action in can.json" : "Take this as level (the node's SDO): only on known level ground";
|
||||
zero.textContent = armed ? "Tap again to zero" : "Zero here";
|
||||
zero.classList.toggle("drive-terrain__level--armed", !!armed);
|
||||
|
||||
if (v.roll == null || v.pitch == null) {
|
||||
el.querySelector(".drive-level__plan").innerHTML = "";
|
||||
el.querySelector(".drive-level__bubble").innerHTML = "";
|
||||
for (const f of ["roll", "pitch", "after"]) field(f, f, "—", "");
|
||||
el.querySelector(".drive-level__advice").textContent = "No tilt signal (the IMU node)";
|
||||
return;
|
||||
}
|
||||
const { roll, pitch } = v;
|
||||
const plan = levelPlan(roll, pitch, wheelbase, track, steps);
|
||||
const level = Math.abs(roll) < LEVEL_TOL && Math.abs(pitch) < LEVEL_TOL;
|
||||
const over = Object.values(plan.wheels).some((w) => w.over);
|
||||
const lifted = Object.values(plan.wheels).filter((w) => (steps ? w.used : w.cm) >= 0.5).length;
|
||||
const labels = Object.entries(WHEELS).map(([k, [fx, sy]]) => {
|
||||
const w = plan.wheels[k];
|
||||
const cm = steps ? w.used : w.cm;
|
||||
const none = cm < 0.5;
|
||||
const x = sy * 80, y = -fx * 78;
|
||||
const cls = none ? "drive-level__none" : w.over ? "drive-level__over" : "drive-level__lift";
|
||||
return `<rect class="${cls}" x="${sy * 60 - 8}" y="${y - 18}" width="16" height="36" rx="4"/>
|
||||
<text class="${cls}" x="${x}" y="${y + 4}" text-anchor="${sy < 0 ? "end" : "start"}" font-size="26" font-weight="700">${none ? "0" : `+${Math.round(cm)} cm`}</text>
|
||||
<text class="drive-level__sub" x="${x}" y="${y + 22}" text-anchor="${sy < 0 ? "end" : "start"}" font-size="13">${none ? "stays" : steps ? `step ${w.step}${w.over ? " · not enough" : ""}` : `${w.cm.toFixed(1)} cm`}</text>`;
|
||||
}).join("");
|
||||
el.querySelector(".drive-level__plan").innerHTML = `<svg viewBox="-150 -150 300 300" role="img" aria-label="Lift per wheel">
|
||||
<text class="drive-level__sub" x="0" y="-132" text-anchor="middle" font-size="12" letter-spacing="1.5">FRONT</text>
|
||||
<rect class="drive-level__body" x="-52" y="-112" width="104" height="224" rx="18"/>
|
||||
<path class="drive-level__axis" d="M-44 -78 L44 -78 M-70 0 L70 0 M0 -120 L0 120"/>${labels}</svg>`;
|
||||
const scale = 23; // 2° to the inner ring
|
||||
const clamp = (n) => Math.max(-80, Math.min(80, n));
|
||||
el.querySelector(".drive-level__bubble").innerHTML = `<svg viewBox="-100 -100 200 200" role="img" aria-label="Roll ${deg(roll)}, pitch ${deg(pitch)}">
|
||||
<circle class="drive-level__ring" r="92"/><circle class="drive-level__ring drive-level__ring--inner" r="46"/><circle class="drive-level__tol" r="${LEVEL_TOL * scale}"/>
|
||||
<path class="drive-level__axis" d="M-92 0 L92 0 M0 -92 L0 92"/>
|
||||
<circle class="${level ? "drive-level__dot--ok" : "drive-level__dot"}" cx="${clamp(-roll * scale)}" cy="${clamp(-pitch * scale)}" r="16"/>
|
||||
<text class="drive-level__sub" x="0" y="-74" text-anchor="middle" font-size="11">front</text></svg>
|
||||
<span class="drive-cell__label">ring 2° · green ±${LEVEL_TOL}°</span>`;
|
||||
field("roll", "Roll", deg(roll), roll > 0 ? "right side low" : roll < 0 ? "left side low" : "", Math.abs(roll) < LEVEL_TOL);
|
||||
field("pitch", "Pitch", deg(pitch), pitch < 0 ? "nose low" : pitch > 0 ? "nose high" : "", Math.abs(pitch) < LEVEL_TOL);
|
||||
const afterOk = Math.abs(plan.roll) < LEVEL_TOL && Math.abs(plan.pitch) < LEVEL_TOL;
|
||||
field("after", steps ? "On the ramps" : "Then", `${deg(plan.roll)} / ${deg(plan.pitch)}`, "roll / pitch", afterOk);
|
||||
const advice = el.querySelector(".drive-level__advice");
|
||||
advice.className = `drive-panel__cell drive-level__advice${level ? " drive-level--ok" : over ? " drive-level--over" : ""}`;
|
||||
advice.textContent = level ? `Level — within ±${LEVEL_TOL}° both ways.`
|
||||
: over ? "Past the ramps' top step: another spot, or turn the car so the slope runs along it."
|
||||
: `${steps ? "Drive" : "Jack"} ${lifted === 1 ? "that wheel" : "those wheels"} up${steps ? " the ramps" : ""}; the numbers follow as the car moves.`;
|
||||
}
|
||||
|
||||
el.querySelector(".drive-panel__close").addEventListener("click", ctx.close);
|
||||
el.querySelector('[data-action="terrain"]').addEventListener("click", ctx.openTerrain);
|
||||
el.querySelector('[data-action="under"]').addEventListener("click", () => {
|
||||
try { localStorage.setItem(UNDER_KEY, under() === "ramps" ? "jacks" : "ramps"); } catch { /* private window */ }
|
||||
render();
|
||||
});
|
||||
el.querySelector('[data-action="zero"]').addEventListener("click", async () => {
|
||||
if (!armed) {
|
||||
armed = setTimeout(() => { armed = null; render(); }, 3000);
|
||||
return render();
|
||||
}
|
||||
clearTimeout(armed);
|
||||
armed = null;
|
||||
const n = (ctx.state()?.actions || []).findIndex((a) => /level/i.test(a.name));
|
||||
const response = await fetch(`/api/can/actions/${n}`, { method: "POST" }).catch(() => null);
|
||||
el.querySelector('[data-action="zero"]').textContent = response?.ok ? "Zeroed ✓" : "Zeroing failed";
|
||||
});
|
||||
return { el, render, opened: render };
|
||||
}
|
||||
|
||||
// Today (the Design canvas' GridToday): the rest of the day being driven —
|
||||
// its stops still to come with their arrival, tonight's spot and the sun
|
||||
// there, the weather (Open-Meteo: here now, there at arrival, there tonight),
|
||||
// the day's notes and the Check's items for it. Tomorrow ▸ pages ahead.
|
||||
const WEATHER_TTL_MS = 30 * 60 * 1000;
|
||||
const weatherCache = new Map();
|
||||
const WEATHER = [[0, "☀", "clear"], [3, "⛅", "cloudy"], [48, "🌫", "fog"], [67, "🌧", "rain"], [77, "🌨", "snow"], [82, "🌦", "showers"], [86, "🌨", "snow showers"], [99, "⛈", "storm"]];
|
||||
const weatherText = (code) => WEATHER.find(([max]) => code <= max) || WEATHER.at(-1);
|
||||
|
||||
async function forecast([lon, lat]) {
|
||||
const key = `${lat.toFixed(1)},${lon.toFixed(1)}`; // ~10 km: not a request every km driven
|
||||
const hit = weatherCache.get(key);
|
||||
if (hit && Date.now() - hit.at < WEATHER_TTL_MS) return hit.data;
|
||||
const url = `https://api.open-meteo.com/v1/forecast?${new URLSearchParams({ latitude: lat.toFixed(1), longitude: lon.toFixed(1), hourly: "temperature_2m,weather_code", forecast_days: 3, timezone: "auto", timeformat: "unixtime" })}`;
|
||||
const data = await (await fetch(url)).json();
|
||||
weatherCache.set(key, { at: Date.now(), data });
|
||||
return data;
|
||||
}
|
||||
|
||||
// The forecast's hour nearest t (ms), or the lowest between from and to.
|
||||
function hourAt(data, t) {
|
||||
const times = data?.hourly?.time || [];
|
||||
let best = -1;
|
||||
times.forEach((s, i) => { if (best < 0 || Math.abs(s * 1000 - t) < Math.abs(times[best] * 1000 - t)) best = i; });
|
||||
return best < 0 ? null : { temp: data.hourly.temperature_2m[best], code: data.hourly.weather_code[best] };
|
||||
}
|
||||
|
||||
function lowest(data, from, to) {
|
||||
const times = data?.hourly?.time || [];
|
||||
const temps = times.map((s, i) => (s * 1000 >= from && s * 1000 <= to ? data.hourly.temperature_2m[i] : null)).filter((v) => v != null);
|
||||
return temps.length ? Math.min(...temps) : null;
|
||||
}
|
||||
|
||||
export function todayMenu(ctx) {
|
||||
const el = panel("drive-today", "Today", `
|
||||
<div class="drive-panel__cell drive-today__stops"></div>
|
||||
<div class="drive-panel__cell drive-today__tonight"></div>
|
||||
<div class="drive-panel__cell drive-today__sun"></div>
|
||||
<div class="drive-panel__cell drive-today__weather" data-w="0"></div>
|
||||
<div class="drive-panel__cell drive-today__weather" data-w="1"></div>
|
||||
<div class="drive-panel__cell drive-today__weather" data-w="2"></div>
|
||||
<div class="drive-panel__cell drive-today__notes"></div>
|
||||
<button type="button" class="drive-today__skip" data-action="skip">Skip next</button>
|
||||
<button type="button" class="drive-today__prev" data-action="prev">◂ Today</button>
|
||||
<button type="button" class="drive-today__next" data-action="next">Tomorrow ▸</button>`);
|
||||
let page = 0; // days after the one being driven
|
||||
const clock = (ms) => new Date(ms).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
||||
const label = (text) => `<span class="drive-cell__label">${escapeHtml(text)}</span>`;
|
||||
|
||||
function render() {
|
||||
if (el.hidden || !ctx.routePanel) return;
|
||||
const { stops, days, check } = ctx.routePanel.plan();
|
||||
const ahead = stops.filter((s) => s.index > 0 && !s.passed && !s.behind);
|
||||
const current = ahead[0]?.day ?? Math.max(0, days - 1);
|
||||
const day = Math.min(current + page, days - 1);
|
||||
const left = stops.filter((s) => s.index > 0 && s.day === day && (page > 0 || (!s.passed && !s.behind)));
|
||||
const first = stops.find((s) => s.day === day || (s.night && s.day === day - 1)); // the day leaves from here
|
||||
const dayFirst = stops.find((s) => s.day === day && (s.index === 0 || stops[s.index - 1].night)); // its note is on this one
|
||||
const date = first?.leave != null ? new Date(first.leave).toLocaleDateString([], { weekday: "short", day: "numeric", month: "numeric" }) : "";
|
||||
el.querySelector(".drive-panel__note").textContent = [days > 1 ? `Day ${day + 1} of ${days}` : "", date].filter(Boolean).join(" · ");
|
||||
el.querySelector('[data-action="prev"]').disabled = page === 0;
|
||||
el.querySelector('[data-action="next"]').disabled = day >= days - 1;
|
||||
el.querySelector('[data-action="skip"]').disabled = page > 0 || !ahead.length;
|
||||
|
||||
// arrival: planned, else from now over the legs still to drive
|
||||
let sum = 0;
|
||||
const eta = new Map(ahead.map((s) => [s.index, (sum += (s.leg?.s || 0) * 1000 + (s.stay || 0) * 60000) - (s.stay || 0) * 60000]));
|
||||
const arriveAt = (s) => s.arrive ?? (eta.has(s.index) ? Date.now() + eta.get(s.index) : null);
|
||||
el.querySelector(".drive-today__stops").replaceChildren(...(left.length ? left.map((s) => {
|
||||
const row = document.createElement("div");
|
||||
row.className = "drive-today__stop";
|
||||
const icon = NPS_SYMBOLS[s.type] || `<b>${String.fromCharCode(65 + (s.index % 26))}</b>`;
|
||||
const at = arriveAt(s);
|
||||
row.innerHTML = `<span class="drive-today__icon${s.night ? " drive-today__icon--night" : ""}">${icon}</span>
|
||||
<span class="drive-today__name"><b></b><small></small></span><span class="drive-today__eta">${at != null ? clock(at) : "–"}<small>${s.leg ? `${s.leg.km.toFixed(0)} km` : ""}</small></span>`;
|
||||
row.querySelector("b").textContent = s.name || `${s.lngLat[1].toFixed(4)}, ${s.lngLat[0].toFixed(4)}`;
|
||||
row.querySelector("small").textContent = [STOP_TYPES[s.type], s.night ? "night" : s.stay ? `stay ${formatDuration(s.stay * 60)}` : "", s.park ? `${s.park.name || "parking"} apart` : ""].filter(Boolean).join(" · ");
|
||||
return row;
|
||||
}) : [emptyRow(page ? "No stops that day" : "Nothing left today")]));
|
||||
|
||||
// tonight: the day's night spot (or the end)
|
||||
const night = stops.find((s) => s.day === day && (s.night || s.index === stops.length - 1)) || stops.at(-1);
|
||||
const tonight = el.querySelector(".drive-today__tonight");
|
||||
const sun = el.querySelector(".drive-today__sun");
|
||||
if (night) {
|
||||
tonight.innerHTML = `${label("Tonight")}<span class="drive-today__line"></span>`;
|
||||
tonight.querySelector(".drive-today__line").textContent = [night.name || "the end", night.note].filter(Boolean).join(" · ");
|
||||
const at = arriveAt(night);
|
||||
const t = getTimes(new Date(at ?? Date.now()), night.lngLat[1], night.lngLat[0]);
|
||||
const late = at != null && at > t.sunset.getTime();
|
||||
sun.innerHTML = `${label("Sunset · dark")}<span class="drive-cell__value drive-cell__value--mid${late ? " drive-today--late" : ""}">${clock(t.sunset)} <small>· ${clock(t.dusk)}${at != null ? ` · arrive ${clock(at)}` : ""}</small></span>`;
|
||||
} else {
|
||||
tonight.innerHTML = "";
|
||||
sun.innerHTML = "";
|
||||
}
|
||||
|
||||
// the day's note, the stops' notes still to come, the Check's items for that day
|
||||
const notes = [
|
||||
...(dayFirst?.day_note ? [["", dayFirst.day_note]] : []),
|
||||
...left.filter((s) => s.note).map((s) => [s.name ? `${s.name}: ` : "", s.note]),
|
||||
...check.filter((c) => c.day === day && c.level !== "info").map((c) => ["! ", c.what]),
|
||||
];
|
||||
el.querySelector(".drive-today__notes").replaceChildren(...(notes.length ? notes.map(([who, text]) => {
|
||||
const p = document.createElement("p");
|
||||
p.className = who === "! " ? "drive-today__warn" : "";
|
||||
p.textContent = `${who}${text}`;
|
||||
return p;
|
||||
}) : [emptyRow("No notes for the day")]));
|
||||
|
||||
renderWeather(night, arriveAt(night || {}) ?? null);
|
||||
}
|
||||
|
||||
async function renderWeather(night, arrive) {
|
||||
const cells = [...el.querySelectorAll(".drive-today__weather")];
|
||||
const here = ctx.position();
|
||||
const show = (i, title, temp, code, sub) => {
|
||||
const [, glyph, text] = code != null ? weatherText(code) : [0, "", ""];
|
||||
cells[i].innerHTML = `${label(title)}<span class="drive-cell__value drive-cell__value--mid">${glyph} ${temp != null ? `${Math.round(temp)}°` : "–"}</span><small>${escapeHtml(sub ?? text)}</small>`;
|
||||
};
|
||||
try {
|
||||
const now = hourAt(await forecast(here), Date.now());
|
||||
show(0, "Now · here", now?.temp, now?.code);
|
||||
if (!night) return;
|
||||
const there = await forecast(night.lngLat);
|
||||
const at = hourAt(there, arrive ?? Date.now());
|
||||
show(1, "Arrival · there", at?.temp, at?.code);
|
||||
const evening = new Date(arrive ?? Date.now());
|
||||
evening.setHours(20, 0, 0, 0);
|
||||
const low = lowest(there, evening.getTime(), evening.getTime() + 12 * 3600 * 1000);
|
||||
show(2, "Tonight · there", low, null, "lowest till 08:00");
|
||||
} catch {
|
||||
cells.forEach((c, i) => (c.innerHTML = i ? "" : `${label("Weather")}<small>offline</small>`));
|
||||
}
|
||||
}
|
||||
|
||||
el.querySelector(".drive-panel__close").addEventListener("click", ctx.close);
|
||||
el.querySelector('[data-action="skip"]').addEventListener("click", () => {
|
||||
const { stops } = ctx.routePanel.plan();
|
||||
const next = stops.find((s) => s.index > 0 && !s.passed && !s.behind);
|
||||
if (next && next.index < stops.length - 1) ctx.routePanel.togglePassed(next.index);
|
||||
});
|
||||
el.querySelector('[data-action="prev"]').addEventListener("click", () => { page = Math.max(0, page - 1); render(); });
|
||||
el.querySelector('[data-action="next"]').addEventListener("click", () => { page++; render(); });
|
||||
ctx.routePanel?.onStopsChanged(() => render());
|
||||
return { el, render, opened: () => { page = 0; render(); } };
|
||||
}
|
||||
+29
-15
@@ -7,7 +7,7 @@ import { watchDashboard, maneuverSvg, laneSvg, distance, VOICE_KEY } from "/js/d
|
||||
import { SPEED_LIMITS, COUNTRY_NAMES, isHeavy, motorwayPayment } from "/js/speed_limits.js";
|
||||
import { currentVehicle, onVehicle } from "/js/panels.js";
|
||||
import { formatSunInfo } from "/js/sun.js";
|
||||
import { pointsMenu, layersMenu, terrainMenu, elevationHtml, cellButton, bindKey, emptyRow as empty, escapeHtml } from "/js/drive_menus.js";
|
||||
import { pointsMenu, layersMenu, terrainMenu, levelMenu, recordingMenu, todayMenu, elevationHtml, cellButton, bindKey, emptyRow as empty, escapeHtml } from "/js/drive_menus.js";
|
||||
|
||||
// Driving mode: the grid of docs/design.adoc ("Layout: a grid, not floating
|
||||
// panels"; the Design canvas' Grid) — the page becomes cells, the map one
|
||||
@@ -91,7 +91,7 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) {
|
||||
tripPanel.innerHTML = `<div class="drive-panel__head">Trip <small class="drive-trip__total"></small></div>
|
||||
<button type="button" class="drive-panel__close" aria-label="Close">✕</button>
|
||||
<button type="button" class="drive-trip__log" data-action="log"></button>
|
||||
<div class="drive-trip__log-state"><span class="drive-cell__label">Recording</span><span class="drive-trip__log-text"></span></div>
|
||||
<button type="button" class="drive-trip__log-state" data-action="recording" title="The recording: its days, export"><span class="drive-cell__label">Recording ▸</span><span class="drive-trip__log-text"></span></button>
|
||||
<div class="drive-trip__search"><input type="search" aria-label="Search" placeholder="Search saved points and places…" enterkeyhint="search"></div>
|
||||
<div class="drive-trip__stops"></div>
|
||||
<div class="drive-trip__results"></div>
|
||||
@@ -105,6 +105,7 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) {
|
||||
menuPanel.hidden = true;
|
||||
menuPanel.innerHTML = `<div class="drive-panel__head">Menu</div>
|
||||
<button type="button" class="drive-panel__close" aria-label="Close">✕</button>
|
||||
<button type="button" class="drive-menu__row" data-action="today">Today ▸ <small>the stops left, tonight, the weather, the day's notes</small></button>
|
||||
<button type="button" class="drive-menu__row" data-action="overview">The whole route <small>the follow pauses</small></button>
|
||||
<button type="button" class="drive-menu__row" data-action="terrain-auto"></button>
|
||||
<button type="button" class="drive-menu__row" data-action="voice"></button>
|
||||
@@ -145,6 +146,7 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) {
|
||||
onVehicle(renderProfile);
|
||||
renderProfile();
|
||||
menuPanel.querySelector('[data-action="overview"]').addEventListener("click", overview);
|
||||
menuPanel.querySelector('[data-action="today"]').addEventListener("click", () => open(today.el));
|
||||
menuPanel.querySelector('[data-action="leave"]').addEventListener("click", () => set(false));
|
||||
const crosshair = document.createElement("div");
|
||||
crosshair.className = "drive-crosshair";
|
||||
@@ -247,8 +249,15 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) {
|
||||
};
|
||||
const points = pointsMenu(menuCtx);
|
||||
const layers = layersMenu(menuCtx);
|
||||
const terrain = terrainMenu({ ...menuCtx, state: () => dash });
|
||||
const menus = [points, layers, terrain];
|
||||
const terrain = terrainMenu({ ...menuCtx, state: () => dash, openLevel: () => open(level.el) });
|
||||
const level = levelMenu({ ...menuCtx, state: () => dash, openTerrain: () => open(terrain.el) });
|
||||
const recording = recordingMenu({
|
||||
...menuCtx,
|
||||
showBounds: ([w, s, e, n]) => { pauseFollow(map); map.fitBounds([[w, s], [e, n]], { padding: 60, pitch: 0, maxZoom: 15 }); },
|
||||
endTrip: () => endTrip(),
|
||||
});
|
||||
const today = todayMenu(menuCtx);
|
||||
const menus = [points, layers, terrain, level, recording, today];
|
||||
let offRoad = false;
|
||||
let tiltSince = null;
|
||||
let pavedM = 0;
|
||||
@@ -282,6 +291,7 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) {
|
||||
autoOpened = false;
|
||||
}
|
||||
if (panel !== tripPanel && results) backToStops(); // the pins go with the search
|
||||
menus.find((m) => m.el === openPanel && m.el !== panel)?.closed?.();
|
||||
openPanel = panel;
|
||||
row = 0;
|
||||
tripPanel.hidden = panel !== tripPanel;
|
||||
@@ -344,17 +354,20 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) {
|
||||
logState.textContent = log?.active ? `● ${log.folder.replace(/^Trips\//, "")} · ${(log.distance_m / 1000).toFixed(1)} km` : "Not recording";
|
||||
logState.classList.toggle("drive-trip__log-text--on", !!log?.active);
|
||||
};
|
||||
const endTrip = async () => {
|
||||
if (!log?.active || !window.confirm(`End the trip "${log.folder}"? Its track stays in the library.`)) return;
|
||||
await fetch("/api/trip/log", { method: "DELETE" });
|
||||
driven = [];
|
||||
refreshLog();
|
||||
};
|
||||
tripPanel.querySelector('[data-action="recording"]').addEventListener("click", () => open(recording.el));
|
||||
logButton.addEventListener("click", async () => {
|
||||
if (log?.active) {
|
||||
if (!window.confirm(`End the trip "${log.folder}"? Its track stays in the library.`)) return;
|
||||
await fetch("/api/trip/log", { method: "DELETE" });
|
||||
} else {
|
||||
const ends = routePanel?.stops().at(-1)?.name || "";
|
||||
const name = window.prompt("The trip's name:", ends);
|
||||
if (name === null) return;
|
||||
const response = await fetch("/api/trip/log", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }) });
|
||||
if (!response.ok) window.alert((await response.json().catch(() => ({}))).error || `HTTP ${response.status}`);
|
||||
}
|
||||
if (log?.active) return endTrip();
|
||||
const ends = routePanel?.stops().at(-1)?.name || "";
|
||||
const name = window.prompt("The trip's name:", ends);
|
||||
if (name === null) return;
|
||||
const response = await fetch("/api/trip/log", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }) });
|
||||
if (!response.ok) window.alert((await response.json().catch(() => ({}))).error || `HTTP ${response.status}`);
|
||||
driven = [];
|
||||
refreshLog();
|
||||
});
|
||||
@@ -365,7 +378,7 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) {
|
||||
logState.textContent = "Log in to record";
|
||||
}
|
||||
map.getContainer().append(crosshair);
|
||||
app.append(tripPanel, menuPanel, points.el, layers.el, terrain.el);
|
||||
app.append(tripPanel, menuPanel, points.el, layers.el, terrain.el, level.el, recording.el, today.el);
|
||||
|
||||
// --- the grid's cells ---------------------------------------------------
|
||||
|
||||
@@ -567,6 +580,7 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) {
|
||||
function render() {
|
||||
if (!document.documentElement.classList.contains("driving")) return;
|
||||
if (openPanel === terrain.el) terrain.render();
|
||||
if (openPanel === level.el) level.render();
|
||||
const a = ahead();
|
||||
for (const { cell, el } of cells) {
|
||||
if (cell.widget === "field") {
|
||||
|
||||
+43
-3
@@ -1,6 +1,9 @@
|
||||
import { PLUGIN_ICON } from "/js/icons.js";
|
||||
import { notifyGpxStoreChanged, notifySidePanelOpen, onlyOneSidePanelOpen } from "/js/panels.js";
|
||||
|
||||
const CORRIDORS_KM = [1, 2, 5, 10, 20];
|
||||
const CORRIDOR_KEY = "maptool.pluginCorridorKm";
|
||||
|
||||
// A side panel (#plugins-panel) listing whatever import plugins are on disk (see
|
||||
// lib/maptool/plugins.rb for the contract) — each one just a "Run for
|
||||
// this area" button using the current map viewport as the bbox, so there's
|
||||
@@ -56,28 +59,65 @@ export class PluginsControl {
|
||||
plugins.forEach((plugin) => this._list.appendChild(this._renderItem(plugin)));
|
||||
}
|
||||
|
||||
// Per plugin: "Run for this area"; with "route" in its plugin.json also
|
||||
// "Along the trip's route" N km either side (the corridor remembered); with
|
||||
// "settings" (a login cookie) their fields — a value set shows as "set",
|
||||
// never sent back from the server.
|
||||
_renderItem(plugin) {
|
||||
const li = document.createElement("li");
|
||||
li.className = "plugins-panel__item";
|
||||
li.innerHTML = `
|
||||
<span class="plugins-panel__label"></span>
|
||||
<button type="button" class="plugins-panel__run">Run for this area</button>
|
||||
${plugin.route ? `<span class="plugins-panel__route"><button type="button" class="plugins-panel__run plugins-panel__run--route">Along the trip's route</button>
|
||||
<select class="plugins-panel__corridor" aria-label="How far either side of the route">${CORRIDORS_KM.map((km) => `<option value="${km}">± ${km} km</option>`).join("")}</select></span>` : ""}
|
||||
<span class="plugins-panel__status"></span>
|
||||
${plugin.settings?.length ? `<details class="plugins-panel__settings"><summary>Settings</summary>${plugin.settings.map(() => `<label class="plugins-panel__setting"><span></span><input type="password" autocomplete="off" spellcheck="false"><small></small></label>`).join("")}
|
||||
<button type="button" class="plugins-panel__save">Save</button></details>` : ""}
|
||||
`;
|
||||
li.querySelector(".plugins-panel__label").textContent = plugin.label;
|
||||
|
||||
const button = li.querySelector(".plugins-panel__run");
|
||||
const status = li.querySelector(".plugins-panel__status");
|
||||
button.addEventListener("click", () => this._run(plugin, button, status));
|
||||
const routeButton = li.querySelector(".plugins-panel__run--route");
|
||||
if (routeButton) {
|
||||
const corridor = li.querySelector(".plugins-panel__corridor");
|
||||
corridor.value = localStorage.getItem(CORRIDOR_KEY) || "5";
|
||||
corridor.addEventListener("change", () => localStorage.setItem(CORRIDOR_KEY, corridor.value));
|
||||
routeButton.addEventListener("click", () => this._run(plugin, routeButton, status, { route: "1", corridor_km: corridor.value }));
|
||||
}
|
||||
const fields = [...li.querySelectorAll(".plugins-panel__setting")];
|
||||
fields.forEach((label, i) => {
|
||||
const field = plugin.settings[i];
|
||||
label.querySelector("span").textContent = field.label || field.key;
|
||||
label.querySelector("small").textContent = field.help || "";
|
||||
label.querySelector("input").placeholder = plugin.set?.includes(field.key) ? "set — paste to replace" : "not set";
|
||||
});
|
||||
li.querySelector(".plugins-panel__save")?.addEventListener("click", async () => {
|
||||
const values = Object.fromEntries(plugin.settings.map((f, i) => [f.key, fields[i].querySelector("input").value]).filter(([, v]) => v));
|
||||
try {
|
||||
const response = await fetch(`/api/plugins/${encodeURIComponent(plugin.name)}/settings`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(values) });
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(data.error || `save failed: ${response.status}`);
|
||||
plugin.set = data.set;
|
||||
fields.forEach((label, i) => { const input = label.querySelector("input"); input.value = ""; input.placeholder = data.set.includes(plugin.settings[i].key) ? "set — paste to replace" : "not set"; });
|
||||
status.textContent = "Settings saved";
|
||||
status.classList.remove("plugins-panel__status--error");
|
||||
} catch (err) {
|
||||
status.textContent = err.message;
|
||||
status.classList.add("plugins-panel__status--error");
|
||||
}
|
||||
});
|
||||
return li;
|
||||
}
|
||||
|
||||
async _run(plugin, button, status) {
|
||||
async _run(plugin, button, status, along = null) {
|
||||
button.disabled = true;
|
||||
status.textContent = "Running…";
|
||||
try {
|
||||
const bounds = this._map.getBounds();
|
||||
const body = new URLSearchParams({
|
||||
const body = new URLSearchParams(along || {
|
||||
south: bounds.getSouth(),
|
||||
west: bounds.getWest(),
|
||||
north: bounds.getNorth(),
|
||||
@@ -91,7 +131,7 @@ export class PluginsControl {
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(data.error || `run failed: ${response.status}`);
|
||||
notifyGpxStoreChanged(data.path);
|
||||
status.textContent = "Done";
|
||||
status.textContent = `Done · ${data.count} found`;
|
||||
status.classList.remove("plugins-panel__status--error");
|
||||
} catch (err) {
|
||||
// Plugins::RunError's message (e.g. "plugin exited with status 1")
|
||||
|
||||
+302
-29
@@ -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) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[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`;
|
||||
|
||||
@@ -120,6 +120,23 @@ export class SearchControl {
|
||||
return;
|
||||
}
|
||||
|
||||
// A pasted link (Google Maps, park4night, a page with coordinates):
|
||||
// the server reads the place from it (lib/maptool/link_place.rb)
|
||||
if (/^(https?:\/\/|geo:)\S+$/i.test(query)) {
|
||||
this._renderResults([], true);
|
||||
try {
|
||||
const response = await fetch(`/api/link?${new URLSearchParams({ url: query })}`);
|
||||
const place = await response.json();
|
||||
if (!response.ok) throw new Error(response.status === 401 ? "log in to read links" : place.error);
|
||||
let where = "From the link";
|
||||
try { where = `From ${new URL(place.url || query).hostname}`; } catch { /* geo: */ }
|
||||
this._renderResults([{ name: place.name || `${place.lat.toFixed(5)}, ${place.lng.toFixed(5)}`, where, lat: place.lat, lng: place.lng }]);
|
||||
} catch (err) {
|
||||
this._renderResults([{ status: `That link: ${err.message}` }]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Every source answers on its own; the list re-renders (nearest first
|
||||
// across all of them) as each one comes in.
|
||||
const searchId = (this._searchId = (this._searchId || 0) + 1);
|
||||
|
||||
Reference in new issue
Block a user