// The driving grid's Points and Layers menus (driving.js; the Design canvas'
// GridPoints and GridLayers): each a 7 × 8 panel of cells in the profile's
// 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
const PRESETS_KEY = "maptool.layerPresets";
const PRESETS = [["road", "↝", "Road"], ["offroad", "⛰", "Off-road"], ["overnight", "⛺", "Overnight"]];
// What a preset turns on until it's kept otherwise (+ Keep): names as the On the map panel has them.
const DEFAULT_PRESETS = {
road: ["Radar", "Tracker"],
offroad: ["Terrain shading", "Contour lines", "Hiking trails", "Radar"],
overnight: ["Radar", "Wikipedia", "NPS park maps"],
};
const SKIP_LAYERS = new Set(["Dashboard"]); // the grid's own data, not a layer
export const escapeHtml = (text) => String(text ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
// A button that is one cell (or a few) of a menu.
export function cellButton(cls, html, title, action) {
const el = document.createElement("button");
el.type = "button";
el.className = `drive-panel__cell drive-panel__${cls}`;
el.innerHTML = html;
el.title = title;
el.setAttribute("aria-label", title);
el.addEventListener("click", action);
return el;
}
// A hardware key for a button: pressed, it clicks it; its label in the corner (driving.js, the keys)
export function bindKey(el, key) {
el.dataset.key = key;
el.dataset.label = key === "-" ? "−" : key.length === 1 ? key.toUpperCase() : key;
return el;
}
export const emptyRow = (text) => Object.assign(document.createElement("p"), { className: "drive-panel__empty", textContent: text });
function panel(cls, label, inner) {
const el = document.createElement("section");
el.className = `drive-panel ${cls}`;
el.setAttribute("aria-label", label);
el.hidden = true;
el.innerHTML = `
${label}
${inner}`;
return el;
}
const RAD = Math.PI / 180;
const meters = ([lon1, lat1], [lon2, lat2]) => Math.hypot((lon2 - lon1) * Math.cos(((lat1 + lat2) / 2) * RAD), lat2 - lat1) * 111320;
const eyeGlyph = (show) => ({ all: "●", some: "◐", none: "○" })[show];
// Points: the library on the road — nearest the car first (the search's
// "layers" source with no words), or along the route ahead, or only what's
// shown; or one folder at a time with ← up. An eye per row; + adds a point
// as a stop. ctx: { map, gpxPanel, routePanel, lookAt, position, route, atKm, close }.
export function pointsMenu(ctx) {
const el = panel("drive-points", "Points", `
`);
const input = el.querySelector("input");
const bar = el.querySelector(".drive-points__bar");
const list = el.querySelector(".drive-points__list");
const foot = el.querySelector(".drive-panel__foot");
let scope = "near"; // near | ahead | shown | folder
let cwd = "";
let results = [];
let loading = false;
let timer = null;
let seq = 0;
const lib = () => ctx.gpxPanel?.libraryTree() || { folders: new Map(), files: new Map(), filesUnder: () => [] };
const fetchNear = async () => {
const mine = ++seq;
loading = true;
render();
const [lng, lat] = ctx.position();
const url = new URL("/api/search", window.location.origin);
url.search = new URLSearchParams({ q: input.value, sources: "layers", lat, lng });
let found = [];
try { found = (await (await fetch(url)).json()).results; } catch { /* offline for a moment: nothing */ }
if (mine !== seq) return;
loading = false;
results = found.filter(({ bbox }) => bbox).map((r) => ({ ...r, lngLat: [(r.bbox[0] + r.bbox[2]) / 2, (r.bbox[1] + r.bbox[3]) / 2] }));
render();
};
input.addEventListener("input", () => {
if (scope === "folder") scope = "near"; // a search lists every match flat
clearTimeout(timer);
timer = setTimeout(fetchNear, SEARCH_DELAY_MS);
});
// The route still to drive, for "Ahead".
// ponytail: filters the 50 nearest the car, not the whole library along the route
const ahead = () => {
const coords = ctx.route()?.geometry?.coordinates;
if (!coords?.length) return null;
const from = (ctx.atKm() ?? 0) * 1000;
let along = 0;
return coords.filter((c, i) => (along += i ? meters(coords[i - 1], c) : 0) >= from);
};
const shownRows = () => {
if (scope === "shown") return results.filter((r) => ctx.gpxPanel?.isShown(r.ref));
if (scope !== "ahead") return results;
const line = ahead();
if (!line) return [];
return results.filter((r) => line.some((c) => meters(c, r.lngLat) <= AHEAD_M));
};
const toggleShown = async (paths, show) => {
await ctx.gpxPanel?.setShown(paths, show);
render();
};
const rowCells = ({ icon, color, name, meta, away, show, onOpen, onEye, last }) => {
const text = cellButton("item", `${icon}${escapeHtml(name)}${escapeHtml(meta)}` +
`${escapeHtml(away || "")}`, "Show it on the map", onOpen);
const eye = cellButton("eye", eyeGlyph(show), show === "none" ? "Show on the map" : "Hide on the map", onEye);
eye.setAttribute("aria-pressed", String(show !== "none"));
eye.classList.toggle("active", show !== "none");
return [text, eye, last || cellButton("blank", "", "", () => {})];
};
const renderNear = () => {
const rows = shownRows();
list.replaceChildren(...rows.flatMap((r) => {
const line = !/point/i.test(r.kind || "");
const shown = ctx.gpxPanel?.isShown(r.ref);
return rowCells({
icon: line ? "〰" : "●", color: line ? "var(--route-driven)" : "#12bedf", name: r.name,
meta: (r.source_label || "").replaceAll("/", " › "), away: r.distance_km != null ? distance(r.distance_km * 1000) : "",
show: shown ? "all" : "none",
onOpen: async () => {
if (!ctx.gpxPanel?.isShown(r.ref)) await toggleShown([r.ref], true);
ctx.lookAt(r.lngLat);
},
onEye: () => toggleShown([r.ref], !shown),
last: line ? null : cellButton("add", "+", "Add as a stop", () => ctx.routePanel?.addStop(r.lngLat, r.name)),
});
}));
if (!rows.length) list.append(emptyRow(loading ? "Looking…" : scope === "ahead" && !ahead() ? "No route to look along." : "Nothing saved here."));
foot.textContent = `${rows.length} ${scope === "ahead" ? "along the route" : scope === "shown" ? "shown nearby" : "nearest the car"}`;
};
const renderFolder = () => {
const { folders, filesUnder } = lib();
const folder = folders.get(cwd) || folders.get("");
if (!folder) return list.replaceChildren(emptyRow("The library is loading…"));
const shownOf = (paths) => {
const n = paths.filter((p) => ctx.gpxPanel?.isShown(p)).length;
return !paths.length || !n ? "none" : n === paths.length ? "all" : "some";
};
const subfolders = folder.children.filter((c) => c.type === "folder");
const own = folder.children.filter((c) => c.type !== "folder");
list.replaceChildren(...subfolders.flatMap((f) => {
const paths = filesUnder(f.path).map((x) => x.path);
const show = shownOf(paths);
const open = () => { cwd = f.path; render(); };
return rowCells({ icon: "▣", color: "var(--drive-muted)", name: f.name, meta: `${f.children.length} items`, show, onOpen: open,
onEye: () => toggleShown(paths, show === "none"), last: cellButton("open", "›", "Open the folder", open) });
}), ...own.flatMap((file) => {
const shown = ctx.gpxPanel?.isShown(file.path);
const line = file.kinds?.some((k) => k === "track" || k === "route");
return rowCells({
icon: line ? "〰" : "●", color: file.color || (line ? "var(--route-driven)" : "#12bedf"), name: file.name,
meta: file.layer ? "layer" : (file.kinds || []).join(", "), show: shown ? "all" : "none",
onOpen: async () => {
if (!ctx.gpxPanel?.isShown(file.path)) await toggleShown([file.path], true);
ctx.gpxPanel?.zoomTo(file.path);
},
onEye: () => toggleShown([file.path], !shown),
});
}));
if (!folder.children.length) list.append(emptyRow("Nothing here yet."));
const paths = filesUnder(cwd).map((f) => f.path);
foot.textContent = `${paths.filter((p) => ctx.gpxPanel?.isShown(p)).length} of ${paths.length} shown`;
};
function render() {
if (el.hidden) return;
if (scope === "folder") {
const name = lib().folders.get(cwd)?.name;
const parent = cwd.includes("/") ? cwd.slice(0, cwd.lastIndexOf("/")) : "";
bar.innerHTML = "";
const up = cellButton("up", "←", "Up a level", () => { cwd = parent; render(); });
up.disabled = !cwd;
const path = Object.assign(document.createElement("div"), { className: "drive-panel__cell drive-points__path" });
path.innerHTML = `${escapeHtml(parent ? `${parent.replaceAll("/", " › ")} ›` : cwd ? "Library ›" : "")}${escapeHtml(cwd ? name : "Library")}`;
const nearest = cellButton("mode", `◎Nearest`, "Nearest the car", () => { scope = "near"; fetchNear(); });
bar.append(up, path, nearest);
el.querySelector(".drive-panel__note").textContent = "folders";
renderFolder();
} else {
bar.replaceChildren(...[["near", "Near the car"], ["ahead", "Ahead"], ["shown", "Shown"]].map(([id, label], i) => {
const chip = bindKey(cellButton("scope", label, label, () => { scope = id; render(); }), String(i + 1));
chip.setAttribute("aria-pressed", String(scope === id));
return chip;
}), cellButton("mode", `▣Folders`, "Folders", () => { scope = "folder"; input.value = ""; render(); }));
el.querySelector(".drive-panel__note").textContent = input.value.trim() ? `“${input.value.trim()}”` : "near the car";
renderNear();
}
}
el.querySelector(".drive-panel__close").addEventListener("click", ctx.close);
el.querySelector('[data-action="hide-all"]').addEventListener("click", () => {
const shown = [...lib().files.keys()].filter((p) => ctx.gpxPanel?.isShown(p));
toggleShown(shown, false);
});
return {
el,
render,
opened: () => { if (scope !== "folder") fetchNear(); else render(); },
};
}
// Layers: the On the map panel's items cut to the road — presets that turn
// a set on at once (+ Keep saves what's on into one), the map Online |
// Offline, an eye per layer, the ones on first (sorted when the menu opens,
// not while tapping). The switches are the On the map panel's own
// checkboxes, so everything they do (restore, offline checks) stays theirs.
export function layersMenu(ctx) {
const el = panel("drive-layers", "Layers", `
Mapoffline by itself, no signal
`);
const list = el.querySelector(".drive-layers__list");
let order = [];
let keeping = false;
const loadPresets = () => {
try { return { ...DEFAULT_PRESETS, ...JSON.parse(localStorage.getItem(PRESETS_KEY)) }; } catch { return { ...DEFAULT_PRESETS }; }
};
// The On the map items that can be switched here: [name, group, icon, checkbox].
const layers = () => [...document.querySelectorAll("#overlays-panel .overlays-panel__item")].flatMap((li) => {
const toggle = li.querySelector(".overlays-panel__toggle");
const name = li.querySelector(".overlays-panel__name, label")?.textContent.trim();
const hidden = toggle?.closest("[hidden]");
if (!toggle || !name || SKIP_LAYERS.has(name) || toggle.disabled || (hidden && li.contains(hidden))) return [];
let group = li.previousElementSibling;
while (group && !group.classList.contains("overlays-panel__group")) group = group.previousElementSibling;
return [{ name, group: group?.textContent.trim() || "", icon: li.querySelector(".overlays-panel__icon")?.innerHTML || "", toggle }];
});
const set = (layer, on) => { if (layer.toggle.checked !== on) layer.toggle.click(); };
const presetOn = (presets) => {
const on = layers().filter((l) => l.toggle.checked).map((l) => l.name).sort().join("|");
return PRESETS.find(([id]) => [...presets[id]].filter((n) => layers().some((l) => l.name === n)).sort().join("|") === on)?.[0];
};
function render() {
if (el.hidden) return;
const presets = loadPresets();
const current = presetOn(presets);
el.querySelector(".drive-layers__presets").replaceChildren(...PRESETS.map(([id, icon, label], i) => {
const b = cellButton("preset", `${icon}${keeping ? `Save as ${label}` : label}`, label, () => {
if (keeping) {
presets[id] = layers().filter((l) => l.toggle.checked).map((l) => l.name);
try { localStorage.setItem(PRESETS_KEY, JSON.stringify(presets)); } catch { /* private window: not kept */ }
keeping = false;
} else {
for (const layer of layers()) set(layer, presets[id].includes(layer.name));
}
render();
});
b.setAttribute("aria-pressed", String(!keeping && current === id));
return bindKey(b, String(i + 1));
}), (() => {
const keep = cellButton("mode", `${keeping ? "✕" : "+"}${keeping ? "Cancel" : "Keep"}`,
keeping ? "Cancel" : "Keep what is on as a preset", () => { keeping = !keeping; render(); });
keep.setAttribute("aria-pressed", String(keeping));
return keep;
})());
// the map: the On the map panel's own Online / Offline buttons
const options = [...document.querySelectorAll(".onthemap-map .basemap-panel__option")];
const sourcesHidden = !!document.querySelector(".onthemap-map .basemap-panel__sources")?.hidden;
el.querySelector(".drive-layers__source").replaceChildren(...options.map((option) => {
const b = cellButton("scope", option.textContent, `Map: ${option.textContent}`, () => { option.click(); render(); });
b.setAttribute("aria-pressed", String(option.classList.contains("active")));
b.disabled = sourcesHidden;
return b;
}));
const all = layers();
const byName = new Map(all.map((l) => [l.name, l]));
const rows = order.map((n) => byName.get(n)).filter(Boolean);
list.replaceChildren(...rows.flatMap((layer) => {
const on = layer.toggle.checked;
const text = Object.assign(document.createElement("div"), { className: "drive-panel__cell drive-layers__item" });
text.innerHTML = `${layer.icon}${escapeHtml(layer.name)}${escapeHtml(layer.group)}`;
const eye = cellButton("eye", on ? "●" : "○", `${on ? "Hide" : "Show"} ${layer.name}`, () => { set(layer, !on); render(); });
eye.setAttribute("aria-pressed", String(on));
eye.classList.toggle("active", on);
return [text, eye];
}));
if (!rows.length) list.append(emptyRow("No layers to switch here."));
const onCount = all.filter((l) => l.toggle.checked).length;
el.querySelector(".drive-panel__note").textContent = `${current ? PRESETS.find(([id]) => id === current)[2] : "by hand"} · ${onCount} on`;
el.querySelector(".drive-panel__foot").textContent = `${onCount} on · ${all.length - onCount} off`;
}
el.querySelector(".drive-panel__close").addEventListener("click", ctx.close);
el.querySelector('[data-action="all-off"]').addEventListener("click", () => {
for (const layer of layers()) set(layer, false);
render();
});
return {
el,
render,
opened: () => {
keeping = false;
const all = layers();
order = [...all.filter((l) => l.toggle.checked), ...all.filter((l) => !l.toggle.checked)].map((l) => l.name);
render();
},
};
}
// The elevation of the next `km` along the route, from its sampled profile
// (route.js's elevationProfile): the grid's elevation cell, the Terrain view's.
export function elevationHtml(route, atKm, km) {
const windowM = km * 1000;
const at = (atKm ?? 0) * 1000;
const points = (route?.elevation?.profile || []).filter((p) => p.distance_meters >= at - 50 && p.distance_meters <= at + windowM);
const label = `Elevation · the next ${km} km`;
if (points.length < 2) return `${label}${route ? "Reading the terrain…" : "No route"}`;
const heights = points.map((p) => p.elevation_meters);
const [low, high] = [Math.min(...heights), Math.max(...heights)];
const x = (p) => (((p.distance_meters - at) / windowM) * 200).toFixed(1);
const y = (h) => (95 - ((h - low) / (high - low || 1)) * 85).toFixed(1);
const line = points.map((p, i) => `${i ? "L" : "M"}${x(p)} ${y(p.elevation_meters)}`).join(" ");
const climb = heights.reduce((sum, h, i) => sum + (i && h > heights[i - 1] ? h - heights[i - 1] : 0), 0);
const top = points[heights.indexOf(high)];
return `${label}
↑ ${Math.round(climb)} m ${Math.round(heights[0])} → ${Math.round(heights.at(-1))} m · top ${Math.round(high)} m in ${distance(Math.max(0, top.distance_meters - at))}`;
}
// Terrain (the canvas' GridTerrain): off-road only — roll (a rear view) and
// pitch (a side view) on dials, amber past WARN and red past 1.5× (as
// dashboard.js), the maximum held until Reset; heading, the climb and the
// side slope ahead from the DEM along the course; the route's elevation of
// the next 2 km; Level here = can.json's levelling action (SDO, as /can.html).
// ctx: as Points', plus state() (the dashboard's) and settings().
const WARN = { roll: 20, pitch: 25 };
const DIAL_MAX = 45;
const CLIMB_M = 300; // the climb ahead over this far
const ACROSS_AT_M = 50; // the side slope this far ahead, over ±ACROSS_HALF_M
const ACROSS_HALF_M = 15;
const AHEAD_EVERY_MS = 2000; // DEM lookups at most this often
const CARDINALS = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
// The cars stand on the ground line (y 30) and turn about its middle: body
// with the windows cut out (evenodd), wheels drawn over it with a gap round them.
const CAR_REAR = {
body: "M-54 10 L-54 -14 L-44 -18 L-34 -46 L34 -46 L44 -18 L54 -14 L54 10 Z M-27 -40 L-23 -24 L23 -24 L27 -40 Z",
wheels: "M-50 30 V4 h20 V30 Z M30 30 V4 h20 V30 Z",
};
const CAR_SIDE = {
body: "M-64 14 L-64 -10 L-34 -14 L-20 -42 L34 -42 L46 -14 L64 -10 L64 14 Z M-16 -36 L-24 -18 L4 -18 L4 -36 Z M10 -36 L10 -18 L38 -18 L30 -36 Z",
wheels: "M-52 16 a14 14 0 1 0 28 0 a14 14 0 1 0 -28 0 Z M26 16 a14 14 0 1 0 28 0 a14 14 0 1 0 -28 0 Z",
};
const dialPoint = (a) => { const r = ((a - 90) * Math.PI) / 180; return `${(120 * Math.cos(r)).toFixed(1)} ${(30 + 120 * Math.sin(r)).toFixed(1)}`; };
const arc = (a, b, cls) => ``;
const severity = (key, v) => (v == null ? "" : Math.abs(v) >= WARN[key] * 1.5 ? "drive-cell--warn" : Math.abs(v) >= WARN[key] ? "drive-terrain--caution" : "");
// a point `m` meters from [lon, lat] towards `bearing`
const offset = ([lon, lat], bearing, m) => [lon + (m * Math.sin(bearing * RAD)) / (111320 * Math.cos(lat * RAD)), lat + (m * Math.cos(bearing * RAD)) / 111320];
export function terrainMenu(ctx) {
const el = panel("drive-terrain", "Terrain", `
`);
let peak = { roll: null, pitch: null };
let ahead = { climb: null, across: null };
let aheadAt = 0;
let armed = null; // Level here asks for a second tap
const offline = fetch("/api/terrain-tiles").then((r) => r.json()).then((d) => !!d.available).catch(() => false);
// The climb and the side slope ahead, from the DEM along the course.
const lookAhead = async (position, course) => {
if (Date.now() - aheadAt < AHEAD_EVERY_MS || !position || course == null) return;
aheadAt = Date.now();
const off = await offline;
const at = ([lon, lat]) => elevationAt(lon, lat, off, { zoom: 12, smooth: true });
const front = offset(position, course, ACROSS_AT_M);
const [here, far, left, right] = await Promise.all([at(position), at(offset(position, course, CLIMB_M)),
at(offset(front, course - 90, ACROSS_HALF_M)), at(offset(front, course + 90, ACROSS_HALF_M))]);
ahead = {
climb: here != null && far != null ? ((far - here) / CLIMB_M) * 100 : null,
across: left != null && right != null ? Math.atan((left - right) / (2 * ACROSS_HALF_M)) / RAD : null,
};
};
const dial = (key, value) => {
const w = WARN[key];
const angle = value == null ? 0 : key === "pitch" ? -value : value; // the side view faces right: nose up = counter-clockwise
const p = peak[key];
const mark = p == null ? "" : ``;
const sign = (v) => (v > 0 ? "+" : v < 0 ? "−" : "");
return `
${value == null ? "—" : `${sign(Math.round(value))}${Math.abs(Math.round(value))}°`}${key} · max ${p == null ? "—" : `${Math.abs(Math.round(p))}°`}`;
};
const field = (name, label, value, unit, cls = "") =>
(el.querySelector(`[data-field="${name}"]`).innerHTML = `${label}${value} ${unit}`);
function render() {
if (el.hidden) return;
const dash = ctx.state();
const v = dash?.values || {};
for (const key of ["roll", "pitch"]) {
if (v[key] != null && (peak[key] == null || Math.abs(v[key]) > Math.abs(peak[key]))) peak[key] = v[key];
el.querySelector(`[data-dial="${key}"]`).innerHTML = dial(key, v[key]);
}
const h = dash?.heading;
const deg = h ? Math.round(h.deg) % 360 : null;
field("heading", "Heading", deg == null ? "—" : `${String(deg).padStart(3, "0")}°`, deg == null ? "" : CARDINALS[Math.round(deg / 45) % 8]);
const climb = ahead.climb;
field("climb", "Climb ahead", climb == null ? "—" : `${Math.round(climb)} %`, `in ${CLIMB_M} m`, climb != null && Math.abs(climb) >= 15 ? "drive-terrain--caution" : "");
field("across", "Across ahead", ahead.across == null ? "—" : `${Math.abs(Math.round(ahead.across))}°`, "side slope, DEM", severity("roll", ahead.across));
el.querySelector(".drive-terrain__elevation").innerHTML = elevationHtml(ctx.route(), ctx.atKm(), 2);
const source = dash?.simulated ? "from the terrain (simulation)" : v.roll != null || v.pitch != null ? "IMU" : "no tilt signal";
el.querySelector(".drive-panel__note").textContent = [source, dash?.surface?.replaceAll("_", " ")].filter(Boolean).join(" · ");
const level = el.querySelector('[data-action="level"]');
const action = (dash?.actions || []).findIndex((a) => /level/i.test(a.name));
level.disabled = action < 0;
level.title = action < 0 ? "No levelling action in can.json" : "Zero roll and pitch here (the node's SDO)";
level.textContent = armed ? "Tap again to level" : "Level here (zero)";
level.classList.toggle("drive-terrain__level--armed", !!armed);
const position = v.lon != null && v.lat != null ? [v.lon, v.lat] : null;
lookAhead(position, dash?.course ?? h?.deg).then(() => {}, () => {});
}
el.querySelector(".drive-panel__close").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) {
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="level"]').textContent = response?.ok ? "Levelled ✓" : "Levelling failed";
if (response?.ok) peak = { roll: null, pitch: null };
});
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", `
`);
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: A ${day(p[0])} ${time(p[0])} → B ${time(p[1])} · ${km(pieceKm)} move A, B on the map` : "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 = `${label}${escapeHtml(value)}${escapeHtml(sub)}`;
}
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 = `
Day ${d.index} · ${day(d.started_at)}${now ? ' ● now' : ""}
${time(d.started_at)} – ${now ? "…" : time(d.ended_at)}${stats(d)}${now ? " so far" : ""}`;
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 = `✂Stood ${hours(d.cut.stood_s)} · ${CUT[d.cut.kind]}`;
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", `
`);
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 = `${label}${value} ${unit}`);
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 `${none ? "0" : `+${Math.round(cm)} cm`}${none ? "stays" : steps ? `step ${w.step}${w.over ? " · not enough" : ""}` : `${w.cm.toFixed(1)} cm`}`;
}).join("");
el.querySelector(".drive-level__plan").innerHTML = ``;
const scale = 23; // 2° to the inner ring
const clamp = (n) => Math.max(-80, Math.min(80, n));
el.querySelector(".drive-level__bubble").innerHTML = `
ring 2° · green ±${LEVEL_TOL}°`;
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", `
`);
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) => `${escapeHtml(text)}`;
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] || `${String.fromCharCode(65 + (s.index % 26))}`;
const at = arriveAt(s);
row.innerHTML = `${icon}${at != null ? clock(at) : "–"}${s.leg ? `${s.leg.km.toFixed(0)} km` : ""}`;
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")}`;
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")}${clock(t.sunset)} · ${clock(t.dusk)}${at != null ? ` · arrive ${clock(at)}` : ""}`;
} 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)}${glyph} ${temp != null ? `${Math.round(temp)}°` : "–"}${escapeHtml(sub ?? text)}`;
};
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")}offline`));
}
}
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(); } };
}