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

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

No files matched your search

+458 -2
View File
@@ -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(); } };
}