Files
maptool/public/js/drive_menus.js
T
randy f73badd107
CI / check (push) Successful in 23s
CI / deploy (push) Successful in 17s
Drive as the Design canvas' Grid: the page as 16 × 10 cells from a screen profile (public/drive/road.json, {area, widget, …} per cell, to be edited in the app later), the map 13 × 8 with nothing over it; the manoeuvre, speed, limit, altitude, time, sun, status (online, rec), next stop with km / ETA to it and to the end, the route's elevation of the next 10 km, a compass; keys Trip, Points, Layers, Search, Menu, − + 3D Follow, Terrain, day/dusk/night. A menu opens in the right 7 × 8 as cells of its own and the map narrows to 9 × 8 (drive_menus.js): Trip and Search as GridTrip / GridSearch (a stop a row, ✓ ↑ ↓ ✕ a cell each; results with their pins on the map); Points as GridPoints (the library nearest the car — /api/search with no words and a center lists every saved feature nearest first — along the route ahead, shown, or one folder at a time; an eye per row, + a point as a stop); Layers as GridLayers (the On the map panel's own switches and Online | Offline, presets Road / Off-road / Overnight, + Keep); Terrain as GridTerrain (roll / pitch dials with the max held, climb and side slope ahead from the DEM, the next 2 km, Level here = can.json's levelling action in two taps), on by itself on an unpaved surface (/api/road now gives Valhalla's surface) or past 10° for 10 s, back after 2 km of paved road, automatic / by hand in the Menu. The dashboard polls for the grid without its overlay; the old drive bar and floating buttons gone
2026-12-03 10:47:40 +01:00

455 lines
26 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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";
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) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[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;
}
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 = `<div class="drive-panel__head">${label} <small class="drive-panel__note"></small></div>
<button type="button" class="drive-panel__close" aria-label="Close">✕</button>${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", `
<div class="drive-points__search"><input type="search" aria-label="Find in the library" placeholder="Find a point, track, folder…" enterkeyhint="search"></div>
<div class="drive-points__bar"></div>
<div class="drive-panel__list drive-points__list"></div>
<div class="drive-panel__foot"></div>
<button type="button" class="drive-panel__wide" data-action="hide-all">Hide all</button>`);
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", `<span class="drive-points__icon" style="color: ${color}">${icon}</span><span class="drive-panel__text"><b>${escapeHtml(name)}</b><small>${escapeHtml(meta)}</small></span>` +
`<span class="drive-points__away">${escapeHtml(away || "")}</span>`, "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 = `<small class="drive-cell__label">${escapeHtml(parent ? `${parent.replaceAll("/", " › ")} ›` : cwd ? "Library ›" : "")}</small><b>${escapeHtml(cwd ? name : "Library")}</b>`;
const nearest = cellButton("mode", `<span class="drive-key__icon">◎</span><span class="drive-key__label">Nearest</span>`, "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]) => {
const chip = cellButton("scope", label, label, () => { scope = id; render(); });
chip.setAttribute("aria-pressed", String(scope === id));
return chip;
}), cellButton("mode", `<span class="drive-key__icon">▣</span><span class="drive-key__label">Folders</span>`, "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", `
<div class="drive-layers__presets"></div>
<div class="drive-panel__cell drive-layers__map"><small class="drive-cell__label">Map</small><span>offline by itself, no signal</span></div>
<div class="drive-layers__source"></div>
<div class="drive-panel__list drive-layers__list"></div>
<div class="drive-panel__foot"></div>
<button type="button" class="drive-panel__wide" data-action="all-off">All off</button>`);
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]) => {
const b = cellButton("preset", `<span class="drive-key__icon">${icon}</span><span class="drive-key__label">${keeping ? `Save as ${label}` : label}</span>`, 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 b;
}), (() => {
const keep = cellButton("mode", `<span class="drive-key__icon">${keeping ? "✕" : "+"}</span><span class="drive-key__label">${keeping ? "Cancel" : "Keep"}</span>`,
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 = `<span class="drive-layers__icon" aria-hidden="true">${layer.icon}</span><span class="drive-panel__text"><b>${escapeHtml(layer.name)}</b><small>${escapeHtml(layer.group)}</small></span>`;
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 = `<span class="drive-cell__label">Elevation · the next ${km} km</span>`;
if (points.length < 2) return `${label}<span class="drive-cell__muted">${route ? "Reading the terrain…" : "No route"}</span>`;
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}<svg class="drive-elevation" viewBox="0 0 200 100" preserveAspectRatio="none" role="img" aria-label="Elevation ahead">
<path class="drive-elevation__area" d="${line} L${x(points.at(-1))} 100 L${x(points[0])} 100 Z"/>
<path class="drive-elevation__line" d="${line}"/>
<line class="drive-elevation__here" x1="0" y1="0" x2="0" y2="100"/>
</svg>
<span class="drive-cell__value drive-cell__value--mid">↑ ${Math.round(climb)} m <small>${Math.round(heights[0])} → ${Math.round(heights.at(-1))} m · top ${Math.round(high)} m in ${distance(Math.max(0, top.distance_meters - at))}</small></span>`;
}
// 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"];
const CAR_REAR = "M-46 30 L-46 -4 L-34 -34 L34 -34 L46 -4 L46 30 Z M-50 30 h22 v12 h-22 Z M28 30 h22 v12 h-22 Z";
const CAR_SIDE = "M-62 26 L-62 -2 L-30 -6 L-18 -30 L40 -30 L52 -4 L62 -2 L62 26 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) => `<path class="${cls}" d="M${dialPoint(a)} A120 120 0 0 1 ${dialPoint(b)}"/>`;
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", `
<div class="drive-panel__cell drive-terrain__dial" data-key="roll"></div>
<div class="drive-panel__cell drive-terrain__dial" data-key="pitch"></div>
<div class="drive-panel__cell drive-terrain__field" data-field="heading"></div>
<div class="drive-panel__cell drive-terrain__field" data-field="climb"></div>
<div class="drive-panel__cell drive-terrain__field" data-field="across"></div>
<div class="drive-panel__cell drive-terrain__elevation"></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>`);
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 ? "" : `<path class="drive-terrain__peak" d="M${dialPoint(Math.max(-DIAL_MAX, Math.min(DIAL_MAX, key === "pitch" ? -p : p)))} l-6 -12 h12 Z"/>`;
const sign = (v) => (v > 0 ? "+" : v < 0 ? "−" : "");
return `<svg class="drive-terrain__svg ${severity(key, value)}" viewBox="-135 -120 270 190" role="img" aria-label="${key} ${value == null ? "unknown" : `${Math.round(value)}°`}">
${arc(-w, w, "drive-terrain__ok")}${arc(-w * 1.5, -w, "drive-terrain__amber")}${arc(w, w * 1.5, "drive-terrain__amber")}
${arc(-DIAL_MAX, -w * 1.5, "drive-terrain__red")}${arc(w * 1.5, DIAL_MAX, "drive-terrain__red")}
<line class="drive-terrain__ground" x1="-130" y1="30" x2="130" y2="30"/>
<g transform="rotate(${angle} 0 30)"><line class="drive-terrain__mast" x1="0" y1="30" x2="0" y2="-100"/><path class="drive-terrain__car" d="${key === "roll" ? CAR_REAR : CAR_SIDE}"/></g>${mark}
</svg>
<span class="drive-terrain__value ${severity(key, value)}">${value == null ? "—" : `${sign(Math.round(value))}${Math.abs(Math.round(value))}°`}</span>
<span class="drive-cell__label">${key} · max ${p == null ? "—" : `${Math.abs(Math.round(p))}°`}</span>`;
};
const field = (name, label, value, unit, cls = "") =>
(el.querySelector(`[data-field="${name}"]`).innerHTML = `<span class="drive-cell__label">${label}</span><span class="drive-cell__value drive-cell__value--mid ${cls}">${value} <small>${unit}</small></span>`);
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-key="${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.close);
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 };
}