Files
maptool/public/js/driving.js
T

619 lines
32 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.
import { LngLatBounds, Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { requestGnssFollow, onRouteChanged } from "/js/panels.js";
import { pauseFollow, resumeFollow, isFollowing } from "/js/gnss.js";
import { formatDuration } from "/js/route.js";
import { isLoggedIn } from "/js/auth.js";
import { watchDashboard, maneuverSvg, distance } from "/js/dashboard.js";
import { formatSunInfo } from "/js/sun.js";
import { pointsMenu, layersMenu, terrainMenu, elevationHtml, cellButton, bindKey, emptyRow as empty, escapeHtml } from "/js/drive_menus.js";
// Driving mode: the grid of docs/design.adoc ("Layout: a grid, not floating
// panels"; the Design canvas' Grid) — the page becomes cells, the map one
// of them, nothing over it; values in cells around it, keys in the bottom
// row, a menu opens in place of the right column and the map narrows.
// Which cell shows what is the screen profile's (public/drive/road.json:
// {area, widget, ...} per cell), to be edited in the app later. Per device
// (localStorage).
const KEY = "drivingMode";
const PROFILE_URL = "/drive/road.json";
const PITCH_3D = 60; // as map.js's 3D toggle
const RENDER_MS = 1000; // the clock, the follow state; the dashboard's polls render too
const SEARCH_DELAY_MS = 300; // after the last key
const LOG_POLL_MS = 5000; // the trip log's state and new points
const DRIVEN_SOURCE = "trip-driven";
const OVER_KMH = 3; // as dashboard.js: over the limit by more than this
// key action → [icon, label, title]
const KEYS = {
trip: ["⚑", "Trip", "The trip's stops: add, move, remove"],
points: ["◉", "Points", "Saved points and tracks near the car"],
layers: ["◫", "Layers", "Layers on the map, presets"],
search: ["⌕", "Search", "Search saved points and places"],
menu: ["☰", "Menu", "Menu: the whole route, leave driving"],
zoomOut: ["−", "", "Zoom out"],
zoomIn: ["+", "", "Zoom in"],
pitch: ["3D", "", "2D or 3D"],
follow: ["⌖", "", "Follow the position, heading up in 3D"],
terrain: ["⛰", "", "Terrain view: roll, pitch, the slope ahead"],
palette: ["", "", "Day, dusk, night"],
};
const NOT_YET = new Set();
// The Terrain view switches itself on off-road (docs/design.adoc, Screen
// profiles): an unpaved surface (/api/road, off a route) or roll / pitch past
// TILT_DEG for TILT_S; back to the road view after PAVED_BACK_M on paved road.
// Closed by hand while still off-road: not again until back on the road.
const UNPAVED = new Set(["compacted", "dirt", "gravel", "path", "impassable"]);
// Valhalla's surfaces, shown in place of the limit while the terrain view is open
const SURFACES = { paved_smooth: "Paved", paved: "Paved", paved_rough: "Rough", compacted: "Compacted", dirt: "Dirt", gravel: "Gravel", path: "Track", impassable: "Impassable" };
const TILT_DEG = 10;
const TILT_S = 10;
const PAVED_BACK_M = 2000;
const TERRAIN_AUTO_KEY = "maptool.terrainAuto";
const FIELDS = { speed: "Speed", limit: "Limit", surface: "Surface", altitude: "Altitude", time: "Time", sun: "Sun", nextStop: "Next stop",
toNextStop: "To next stop", etaNextStop: "ETA next stop", toEnd: "To the end" };
const CARDINALS = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
const clock = (date) => date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
export function setupDriving(map, nightButton, routePanel, gpxPanel) {
const app = document.getElementById("app");
let route = onRouteChanged((r) => { route = r; render(); });
let dash = null; // the dashboard's last state
let profile = null;
const cells = []; // [{ cell, el }]
let openPanel = null;
const toggle = document.createElement("button");
toggle.type = "button";
toggle.className = "topbar__drive";
toggle.title = "Driving mode: the cockpit grid, no planning panels";
toggle.textContent = "Drive";
nightButton.before(toggle);
const overview = () => {
const coords = route?.geometry?.coordinates;
if (!coords?.length) return;
pauseFollow(map);
map.fitBounds(coords.reduce((b, c) => b.extend(c), new LngLatBounds(coords[0], coords[0])), { padding: 80, pitch: 0, bearing: 0 });
};
// The Trip menu (the navigator's, docs/design.adoc; the canvas' GridTrip
// and GridSearch): the menu area as cells too — the stops a row each (name
// over 3 cells, ✓ ↑ ↓ ✕ a cell each), recording on top, the actions at the
// foot. Typing a search turns it into results (+ adds one as a stop), with
// their pins on the map. One level, no dragging.
const tripPanel = document.createElement("section");
tripPanel.className = "drive-panel drive-trip";
tripPanel.setAttribute("aria-label", "Trip");
tripPanel.hidden = true;
tripPanel.dataset.mode = "trip";
tripPanel.innerHTML = `<div class="drive-panel__head">Trip <small class="drive-trip__total"></small></div>
<button type="button" class="drive-panel__close" aria-label="Close">✕</button>
<button type="button" class="drive-trip__log" data-action="log"></button>
<div class="drive-trip__log-state"><span class="drive-cell__label">Recording</span><span class="drive-trip__log-text"></span></div>
<div class="drive-trip__search"><input type="search" aria-label="Search" placeholder="Search saved points and places…" enterkeyhint="search"></div>
<div class="drive-trip__stops"></div>
<div class="drive-trip__results"></div>
<button type="button" class="drive-panel__primary drive-trip__add" data-action="add">+ Stop at the crosshair</button>
<button type="button" class="drive-trip__start" data-action="start">Start from the car</button>
<button type="button" class="drive-trip__back" data-action="back">← Back to the stops</button>`;
// The Menu: what has no key of its own (yet).
const menuPanel = document.createElement("section");
menuPanel.className = "drive-panel drive-menu";
menuPanel.setAttribute("aria-label", "Menu");
menuPanel.hidden = true;
menuPanel.innerHTML = `<div class="drive-panel__head">Menu</div>
<button type="button" class="drive-panel__close" aria-label="Close">✕</button>
<button type="button" class="drive-menu__row" data-action="overview">The whole route <small>the follow pauses</small></button>
<button type="button" class="drive-menu__row" data-action="terrain-auto"></button>
<button type="button" class="drive-menu__row" data-action="leave">Leave driving mode</button>`;
const terrainAuto = () => { try { return localStorage.getItem(TERRAIN_AUTO_KEY) !== "hand"; } catch { return true; } };
const autoButton = menuPanel.querySelector('[data-action="terrain-auto"]');
const renderAuto = () => { autoButton.innerHTML = `Terrain view: ${terrainAuto() ? "automatic" : "by hand"} <small>tap to switch</small>`; };
autoButton.addEventListener("click", () => {
try { localStorage.setItem(TERRAIN_AUTO_KEY, terrainAuto() ? "hand" : "auto"); } catch { /* private window: not kept */ }
renderAuto();
});
renderAuto();
menuPanel.querySelector('[data-action="overview"]').addEventListener("click", overview);
menuPanel.querySelector('[data-action="leave"]').addEventListener("click", () => set(false));
const crosshair = document.createElement("div");
crosshair.className = "drive-crosshair";
crosshair.hidden = true;
// Search: saved points (the library) and places (the offline POI
// database), nearest the crosshair first.
const input = tripPanel.querySelector(".drive-trip__search input");
let results = null;
let pins = [];
let searchTimer = null;
let searchSeq = 0;
let searching = false;
const setResults = (list) => {
results = list;
tripPanel.dataset.mode = results ? "search" : "trip";
for (const pin of pins) pin.remove();
pins = (results || []).map((r) => {
const el = document.createElement("div");
el.className = `drive-pin drive-pin--${r.kind}`;
return new Marker({ element: el }).setLngLat(r.lngLat).addTo(map);
});
renderTrip();
render();
};
const backToStops = () => {
input.value = "";
clearTimeout(searchTimer);
searchSeq++;
searching = false;
setResults(null);
};
input.addEventListener("input", () => {
clearTimeout(searchTimer);
if (!input.value.trim()) return setResults(null);
searching = true;
if (!results) setResults([]); // the search layout at once, the input stays focused
searchTimer = setTimeout(async () => {
const mine = ++searchSeq;
const { lng, lat } = map.getCenter();
const url = new URL("/api/search", window.location.origin);
url.search = new URLSearchParams({ q: input.value, sources: "layers,places", lat, lng });
let found = [];
try { found = (await (await fetch(url)).json()).results; } catch { /* offline for a moment: nothing */ }
if (mine !== searchSeq) return;
searching = false;
setResults(found.filter(({ bbox }) => bbox).map(({ name, bbox, source, source_label: where }) => {
const lngLat = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2];
return { name, where, lngLat, kind: source === "places" ? "place" : "saved", away: distance(map.getCenter().distanceTo({ lng: lngLat[0], lat: lngLat[1] })) };
}));
}, SEARCH_DELAY_MS);
});
tripPanel.querySelector('[data-action="back"]').addEventListener("click", backToStops);
const lookAt = (lngLat) => {
pauseFollow(map);
map.easeTo({ center: lngLat, zoom: Math.max(map.getZoom(), 14) });
};
const renderResults = (list) => {
list.replaceChildren(...results.flatMap((r) => [
cellButton("result", `<span class="drive-pin drive-pin--${r.kind}"></span><span class="drive-panel__text"><b>${escapeHtml(r.name)}</b><small>${escapeHtml(r.where || "")} · ${r.away}</small></span>`,
"Show it on the map", () => lookAt(r.lngLat)),
cellButton("add", "+", "Add as a stop", () => {
backToStops(); // back to the stops, the new one among them
routePanel.addStop(r.lngLat, r.name);
}),
]));
if (!results.length) list.append(empty(searching ? "Searching…" : input.value.trim() ? "Nothing found." : "Type a name — saved points and places, nearest first."));
};
const renderTrip = () => {
if (tripPanel.hidden || !routePanel) return;
if (results) return renderResults(tripPanel.querySelector(".drive-trip__results"));
const stops = routePanel.stops();
const list = tripPanel.querySelector(".drive-trip__stops");
list.replaceChildren(...stops.flatMap((stop, i) => {
const leg = stop.leg ? `+${stop.leg.km.toFixed(1)} km${stop.leg.s != null ? ` · ${formatDuration(stop.leg.s)}` : ""}` : "";
const name = cellButton("stop", `<span class="drive-panel__text"><small class="drive-cell__label">${escapeHtml(stop.label)}${leg ? ` · ${leg}` : ""}</small>` +
`<b>${escapeHtml(stop.name || `${stop.lngLat[1].toFixed(4)}, ${stop.lngLat[0].toFixed(4)}`)}</b></span>`, "Show it on the map", () => lookAt(stop.lngLat));
name.classList.toggle("drive-panel__passed", !!stop.passed || stop.behind);
const done = cellButton("done", "✓", stop.passed ? "Passed — tap to route through it again" : "Mark as passed (not routed any more)", () => routePanel.togglePassed(i));
done.classList.toggle("active", !!stop.passed);
const up = cellButton("up", "↑", "Earlier", () => routePanel.moveStop(i, -1));
const down = cellButton("down", "↓", "Later", () => routePanel.moveStop(i, 1));
const drop = cellButton("drop", "✕", "Remove this stop", () => routePanel.removeStop(i));
up.disabled = i === 0;
down.disabled = i === stops.length - 1;
return [name, done, up, down, drop];
}));
if (!stops.length) list.append(empty("No stops yet — pan the map to a place and add it, or search."));
const p = route?.properties;
tripPanel.querySelector(".drive-trip__total").textContent = p && stops.length > 1 ? `${p.distance_km.toFixed(1)} km · ${formatDuration(p.time_s)}` : "";
};
// One panel at a time, in the profile's menu area; the map narrows to its
// other area (its center — the follow, the crosshair — stays in view).
// Points and Layers (drive_menus.js): the car's position, else the map's center.
const menuCtx = {
map, gpxPanel, routePanel, lookAt,
position: () => (dash?.values?.lon != null && dash?.values?.lat != null ? [dash.values.lon, dash.values.lat] : map.getCenter().toArray()),
route: () => route,
atKm: () => dash?.atKm,
close: () => open(null),
};
const points = pointsMenu(menuCtx);
const layers = layersMenu(menuCtx);
const terrain = terrainMenu({ ...menuCtx, state: () => dash });
const menus = [points, layers, terrain];
let offRoad = false;
let tiltSince = null;
let pavedM = 0;
let autoOpened = false;
let suppressed = false;
let lastState = Date.now();
const autoTerrain = (state) => {
const v = state.values || {};
const now = Date.now();
const dt = (now - lastState) / 1000;
lastState = now;
const tilted = Math.max(Math.abs(v.roll ?? 0), Math.abs(v.pitch ?? 0)) >= TILT_DEG;
tiltSince = tilted ? tiltSince ?? now : null;
offRoad = UNPAVED.has(state.surface) || (tiltSince != null && now - tiltSince >= TILT_S * 1000);
if (offRoad) pavedM = 0;
else {
suppressed = false;
pavedM += (v.speed ?? 0) * dt;
}
if (!terrainAuto()) return;
if (offRoad && !suppressed && !openPanel) {
open(terrain.el);
autoOpened = true;
} else if (autoOpened && openPanel === terrain.el && pavedM >= PAVED_BACK_M) open(null);
};
function open(panel) {
if (openPanel === terrain.el && panel !== terrain.el) {
if (offRoad) suppressed = true; // closed by hand off-road: stays closed until the road
autoOpened = false;
}
if (panel !== tripPanel && results) backToStops(); // the pins go with the search
openPanel = panel;
row = 0;
tripPanel.hidden = panel !== tripPanel;
menuPanel.hidden = panel !== menuPanel;
for (const menu of menus) {
menu.el.hidden = panel !== menu.el;
if (panel === menu.el) menu.opened();
}
crosshair.hidden = panel !== tripPanel;
if (profile) app.style.setProperty("--drive-map", panel ? profile.menu.map : profile.map);
map.resize();
renderTrip();
render();
}
const togglePanel = (panel) => open(openPanel === panel ? null : panel);
for (const panel of [tripPanel, menuPanel]) panel.querySelector(".drive-panel__close").addEventListener("click", () => open(null));
tripPanel.querySelector('[data-action="add"]').addEventListener("click", () => {
const { lng, lat } = map.getCenter();
routePanel?.addStop([lng, lat]);
});
tripPanel.querySelector('[data-action="start"]').addEventListener("click", () => routePanel?.startHere());
routePanel?.onStopsChanged(() => { renderTrip(); render(); });
// The trip log (lib/maptool/trip_log.rb): Start makes the trip's library
// folder and records the car's GNSS into it, End closes it; the line
// really driven drawn in --route-driven, grown by polling ?since=N.
const logButton = tripPanel.querySelector('[data-action="log"]');
const logState = tripPanel.querySelector(".drive-trip__log-text");
let log = null;
let driven = [];
const drawDriven = () => {
const data = { type: "Feature", geometry: { type: "LineString", coordinates: driven }, properties: {} };
const source = map.getSource(DRIVEN_SOURCE);
if (source) return source.setData(data);
if (!map.isStyleLoaded()) return;
map.addSource(DRIVEN_SOURCE, { type: "geojson", data });
map.addLayer({ id: DRIVEN_SOURCE, type: "line", source: DRIVEN_SOURCE, layout: { "line-cap": "round", "line-join": "round" },
paint: { "line-color": getComputedStyle(document.documentElement).getPropertyValue("--route-driven").trim() || "#c2410c", "line-width": 4 } });
};
map.on("style.load", () => driven.length && drawDriven());
const refreshLog = async () => {
try {
const response = await fetch(`/api/trip/log?since=${driven.length}`, { cache: "no-store" });
if (response.ok) {
log = await response.json();
if (!log.active) driven = [];
else driven = driven.concat(log.coordinates || []);
drawDriven();
}
} catch { /* offline for a moment: the next poll */ }
renderLog();
};
const pollLog = async () => {
await refreshLog();
setTimeout(pollLog, LOG_POLL_MS);
};
const renderLog = () => {
logButton.textContent = log?.active ? "End the trip" : "Start the trip";
logButton.classList.toggle("drive-trip__log--on", !!log?.active);
logState.textContent = log?.active ? `● ${log.folder.replace(/^Trips\//, "")} · ${(log.distance_m / 1000).toFixed(1)} km` : "Not recording";
logState.classList.toggle("drive-trip__log-text--on", !!log?.active);
};
logButton.addEventListener("click", async () => {
if (log?.active) {
if (!window.confirm(`End the trip "${log.folder}"? Its track stays in the library.`)) return;
await fetch("/api/trip/log", { method: "DELETE" });
} else {
const ends = routePanel?.stops().at(-1)?.name || "";
const name = window.prompt("The trip's name:", ends);
if (name === null) return;
const response = await fetch("/api/trip/log", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }) });
if (!response.ok) window.alert((await response.json().catch(() => ({}))).error || `HTTP ${response.status}`);
}
driven = [];
refreshLog();
});
if (isLoggedIn()) pollLog();
else {
logButton.disabled = true;
logButton.textContent = "Start the trip";
logState.textContent = "Log in to record";
}
map.getContainer().append(crosshair);
app.append(tripPanel, menuPanel, points.el, layers.el, terrain.el);
// --- the grid's cells ---------------------------------------------------
const keyAction = {
trip: () => {
if (openPanel === tripPanel && results) return backToStops();
togglePanel(tripPanel);
},
search: () => {
if (openPanel === tripPanel && results) return open(null);
open(tripPanel);
if (!results) setResults([]);
input.focus();
},
menu: () => togglePanel(menuPanel),
points: () => togglePanel(points.el),
layers: () => togglePanel(layers.el),
terrain: () => togglePanel(terrain.el),
zoomOut: () => map.zoomOut(),
zoomIn: () => map.zoomIn(),
pitch: () => map.easeTo({ pitch: map.getPitch() > 0 ? 0 : PITCH_3D, ...(map.getPitch() > 0 && { bearing: 0 }), duration: 300 }),
follow: () => {
requestGnssFollow();
resumeFollow(map);
if (map.getPitch() === 0) map.easeTo({ pitch: PITCH_3D, duration: 300 });
render();
},
palette: () => nightButton.click(),
};
const make = (cell) => {
let el;
if (cell.widget === "key") {
const [icon, label, title] = KEYS[cell.action] || ["?", cell.action, cell.action];
el = document.createElement("button");
el.type = "button";
el.title = title;
el.setAttribute("aria-label", label || title);
el.innerHTML = `<span class="drive-key__icon">${icon}</span>${label ? `<span class="drive-key__label">${label}</span>` : ""}`;
el.disabled = NOT_YET.has(cell.action) || !keyAction[cell.action];
el.addEventListener("click", () => keyAction[cell.action]?.());
if (cell.action === "zoomIn" || cell.action === "zoomOut") el.classList.add("drive-key--big");
if (cell.key) bindKey(el, cell.key); // "keypad" too, for when the keypad is on the bus
} else {
el = document.createElement("div");
}
el.classList.add("drive-cell", `drive-cell--${cell.widget}`);
if (cell.small) el.classList.add("drive-cell--small");
el.style.gridArea = cell.area;
return el;
};
// To the next stop and to the end, from the km along the route (the start
// of it while not on it): the leg's time in proportion to what's left of it.
// ponytail: a straight share of the leg's time, Valhalla's per-maneuver times if it's off
const ahead = () => {
const p = route?.properties;
const stops = routePanel?.stops().filter((s) => !s.passed) || [];
if (!p?.legs_km?.length || stops.length !== p.legs_km.length + 1) return null;
const at = dash?.atKm ?? 0;
let end = 0;
let i = 0;
for (; i < p.legs_km.length; i++) {
end += p.legs_km[i];
if (end > at + 0.05) break;
}
i = Math.min(i, p.legs_km.length - 1);
const toNext = Math.max(0, end - at);
const sNext = p.legs_s?.[i] != null && p.legs_km[i] ? (p.legs_s[i] * toNext) / p.legs_km[i] : null;
const toEnd = Math.max(0, p.distance_km - at);
const sEnd = sNext != null ? sNext + p.legs_s.slice(i + 1).reduce((a, b) => a + b, 0) : (p.time_s * toEnd) / p.distance_km;
const stop = stops[i + 1];
return { name: stop.name || stop.label, toNext, sNext, toEnd, sEnd };
};
// [value, unit, class]
const fieldValue = (name, a) => {
const v = dash?.values || {};
const nav = dash?.nav;
const kmh = v.speed == null ? null : v.speed * 3.6;
const limit = nav?.limit;
const now = new Date();
switch (name) {
case "speed":
return [kmh == null ? "—" : Math.round(kmh), "km/h", typeof limit === "number" && kmh > limit + OVER_KMH ? "drive-cell--warn" : ""];
case "limit": {
const next = nav?.next ? `· ${typeof nav.next.limit === "number" ? nav.next.limit : "∞"} in ${distance(nav.next.m)}` : "";
return [typeof limit === "number" ? limit : limit === "unlimited" ? "∞" : "—", next, "drive-cell--limit"];
}
case "surface":
return [SURFACES[dash?.surface] || "—", dash?.surface ? "" : "unknown", UNPAVED.has(dash?.surface) ? "drive-terrain--caution" : ""];
case "altitude":
return [v.alt == null ? "—" : Math.round(v.alt), "m"];
case "time":
return [clock(now), ""];
case "sun": {
const { lng, lat } = map.getCenter();
const info = formatSunInfo(lat, lng, now);
if (!info) return ["—", ""];
if (info.polar) return [info.polar, ""];
return info.countdown?.endsWith("sunrise") ? [info.sunrise, "rise"] : [info.sunset, "set"];
}
case "nextStop":
return [a?.name ?? "—", ""];
case "toNextStop":
return a ? [a.toNext.toFixed(1), `km${a.sNext != null ? ` · ${formatDuration(a.sNext)}` : ""}`] : ["—", ""];
case "etaNextStop":
return [a?.sNext != null ? clock(new Date(now.getTime() + a.sNext * 1000)) : "—", ""];
case "toEnd":
return a ? [a.toEnd.toFixed(1), `km · ${clock(new Date(now.getTime() + a.sEnd * 1000))}`] : ["—", ""];
default:
return ["?", ""];
}
};
const renderManeuver = (el) => {
const n = dash?.nav;
if (n?.offRoute) {
el.innerHTML = `<div><span class="drive-cell__value drive-cell--caution">Off the route</span><span class="drive-cell__label">rerouting</span></div>`;
} else if (n?.maneuver) {
const { m, type, street, text, exit } = n.maneuver;
const what = street ? `${exit ? `${exit}. exit · ` : ""}${escapeHtml(street)}` : escapeHtml(text);
const then = n.then ? ` <span class="drive-cell__muted">· then ${escapeHtml(n.then.street || n.then.text)}</span>` : "";
el.innerHTML = `${maneuverSvg(type)}<div class="drive-cell__text"><span class="drive-cell__value">${distance(m)}</span><span class="drive-cell__street">${what}${then}</span></div>`;
} else {
el.innerHTML = `<div class="drive-cell__text"><span class="drive-cell__label">On</span><span class="drive-cell__street">${escapeHtml(n?.street ?? "—")}</span></div>`;
}
};
const renderElevation = (el, cell) => { el.innerHTML = elevationHtml(route, dash?.atKm, cell.km || 10); };
const renderCompass = (el) => {
const h = dash?.heading;
const deg = h ? Math.round(h.deg) % 360 : null;
el.innerHTML = `<svg class="drive-compass${h && !h.live ? " drive-compass--stale" : ""}" viewBox="-50 -50 100 100" role="img" aria-label="${deg == null ? "No heading" : `Heading ${deg}°`}">
<circle r="46" class="drive-compass__ring"/>
<g transform="rotate(${-(deg ?? 0)})">
<path d="M0 -40 L6 0 L0 -6 L-6 0 Z" class="drive-compass__north"/>
<path d="M0 40 L6 0 L0 6 L-6 0 Z" class="drive-compass__south"/>
<text y="-22" transform="rotate(${deg ?? 0} 0 -27)" class="drive-compass__n">N</text>
</g>
<path d="M0 -50 l-5 0 l5 10 l5 -10 z" class="drive-compass__lubber"/>
</svg>
<span class="drive-cell__text"><span class="drive-cell__label">Heading</span><span class="drive-cell__value drive-cell__value--mid">${deg == null ? "—" : String(deg).padStart(3, "0") + "°"} <small>${deg == null ? "" : CARDINALS[Math.round(deg / 45) % 8]}</small></span></span>`;
};
const renderKey = (el, cell) => {
const pressed = { trip: openPanel === tripPanel && !results, search: openPanel === tripPanel && !!results, points: openPanel === points.el, layers: openPanel === layers.el, terrain: openPanel === terrain.el, menu: openPanel === menuPanel, pitch: map.getPitch() > 0, follow: isFollowing(map) }[cell.action];
el.setAttribute("aria-pressed", String(!!pressed));
if (cell.action === "palette") el.querySelector(".drive-key__icon").textContent = nightButton.textContent;
};
function render() {
if (!document.documentElement.classList.contains("driving")) return;
if (openPanel === terrain.el) terrain.render();
const a = ahead();
for (const { cell, el } of cells) {
if (cell.widget === "field") {
const name = cell.value === "limit" && openPanel === terrain.el ? "surface" : cell.value; // off-road the surface matters, not the limit
const [value, unit, cls = ""] = fieldValue(name, a);
el.innerHTML = `<span class="drive-cell__label">${FIELDS[name] || name}</span><span class="drive-cell__value ${cls}">${escapeHtml(value)} <small>${escapeHtml(unit)}</small></span>`;
} else if (cell.widget === "maneuver") renderManeuver(el);
else if (cell.widget === "status") {
el.innerHTML = `<b class="drive-status__brand">MAPTOOL</b><span class="drive-cell__muted"><span class="${navigator.onLine ? "drive-status--ok" : ""}">●</span> ${navigator.onLine ? "online" : "offline"}${log?.active ? ` · <span class="drive-status--rec">● rec</span>` : ""}</span>`;
} else if (cell.widget === "elevation") renderElevation(el, cell);
else if (cell.widget === "compass") renderCompass(el);
else if (cell.widget === "key") renderKey(el, cell);
}
}
map.on("pitchend", render);
setInterval(render, RENDER_MS);
fetch(PROFILE_URL, { cache: "no-cache" }).then((r) => r.json()).then((p) => {
profile = p;
// Cells of p.cell px at most; on a bigger screen only the map's columns
// and rows (beside an open menu) stretch, the rest stays cell-sized.
const [mr1, mc1, mr2, mc2] = p.menu.map.split("/").map(Number);
const track = (n, from, to) => Array.from({ length: n }, (_, i) => (i + 1 >= from && i + 1 < to ? "minmax(0, 1fr)" : "var(--cell)")).join(" ");
// One scale for everything (--s): the cells, the type, the icons — the
// same elements on a 7″ as on the 16″, only smaller; never bigger than drawn.
const fit = () => {
const scale = Math.min(1, window.innerWidth / (p.columns * (p.cell || 80)), window.innerHeight / (p.rows * (p.cell || 80)));
app.style.setProperty("--s", scale.toFixed(3));
app.style.setProperty("--cell", `${((p.cell || 80) * scale).toFixed(1)}px`);
};
fit();
window.addEventListener("resize", fit);
app.style.setProperty("--drive-columns", track(p.columns, mc1, mc2));
app.style.setProperty("--drive-row-sizes", track(p.rows, mr1, mr2));
app.style.setProperty("--drive-map", openPanel ? p.menu.map : p.map);
app.style.setProperty("--drive-menu", p.menu.area);
const [r1, c1, r2, c2] = p.menu.area.split("/").map(Number);
app.style.setProperty("--drive-menu-cols", c2 - c1);
app.style.setProperty("--drive-menu-mid", r2 - r1 - 4); // the list rows between the 3 on top and the foot
for (const cell of p.cells) {
const el = make(cell);
app.append(el);
cells.push({ cell, el });
}
render();
map.resize();
});
function set(on) {
if (!on) open(null);
document.documentElement.classList.toggle("driving", on);
toggle.classList.toggle("active", on);
try { localStorage.setItem(KEY, on ? "on" : "off"); } catch { /* private window: not kept */ }
watchDashboard(on ? (state) => {
dash = state;
autoTerrain(state);
render();
} : null);
render();
map.resize(); // the grid came or went
}
toggle.addEventListener("click", () => set(!document.documentElement.classList.contains("driving")));
// Keys (canvas GridKeys): a screen key's "key" in the profile clicks it, a
// menu's [data-key] buttons too (1 2 3, H); in an open menu ↑ ↓ move the row
// (the keypad's encoder will send the same arrows), Enter its first button,
// Space its eye, + adds it, ⌫ up a folder, Esc closes. The labels in the
// corners show from the first key pressed on, so a touch-only screen stays clean.
// ponytail: keyboard only; the keypad's keys and its heartbeat switching the
// labels to "keypad" wait for the keypad on the bus (and the diagnostics' mapping)
const KEYS_SEEN = "maptool.driveKeys";
let row = 0;
try { if (localStorage.getItem(KEYS_SEEN)) document.documentElement.classList.add("drive-keys"); } catch { /* nothing kept */ }
const norm = (k) => (k.length === 1 ? k.toLowerCase() : k);
const visible = (b) => b.offsetParent && !b.disabled;
const rowsOf = (panel) => {
const rows = new Map();
for (const b of panel.querySelectorAll("button:not(.drive-panel__close)")) {
if (!visible(b)) continue;
const top = Math.round(b.getBoundingClientRect().top);
rows.set(top, [...(rows.get(top) || []), b]);
}
return [...rows].sort((a, b) => a[0] - b[0]).map(([, r]) => r);
};
const markRow = (scroll) => {
for (const b of document.querySelectorAll(".drive-focus")) b.classList.remove("drive-focus", "drive-focus--main");
if (!openPanel || !document.documentElement.classList.contains("drive-keys")) return [];
const rows = rowsOf(openPanel);
row = Math.max(0, Math.min(row, rows.length - 1));
const current = rows[row] || [];
for (const b of current) b.classList.add("drive-focus");
current[0]?.classList.add("drive-focus--main");
if (scroll) current[0]?.scrollIntoView({ block: "nearest" });
return current;
};
let marking = 0; // the menus re-render their rows: the highlight follows, once a frame
new MutationObserver(() => { marking ||= requestAnimationFrame(() => { marking = 0; markRow(false); }); }).observe(app, { childList: true, subtree: true });
document.addEventListener("keydown", (e) => {
if (!document.documentElement.classList.contains("driving") || e.ctrlKey || e.altKey || e.metaKey) return;
const key = norm(e.key);
const move = key === "ArrowUp" ? -1 : key === "ArrowDown" ? 1 : 0;
if (e.target.matches?.("input, textarea, select")) {
if (key === "Escape" || move) e.target.blur(); else return; // typing a search
}
if (!document.documentElement.classList.contains("drive-keys")) {
document.documentElement.classList.add("drive-keys");
try { localStorage.setItem(KEYS_SEEN, "1"); } catch { /* private window: not kept */ }
}
const current = markRow(false);
const press = (b) => (b && visible(b) ? (b.click(), true) : false);
const bound = (scope) => [...(scope?.querySelectorAll("[data-key]") || [])].find((b) => norm(b.dataset.key) === key && visible(b));
let done = false;
if (key === "Escape") done = !!openPanel && (open(null), true);
else if (openPanel && move) { row += move; markRow(true); done = true; }
else if (openPanel && key === "Enter") done = press(current[0]);
else if (openPanel && key === " ") done = press(current.find((b) => b.classList.contains("drive-panel__eye")));
else if (openPanel && key === "Backspace") done = press(openPanel.querySelector(".drive-panel__up"));
if (!done && openPanel && key === "+") done = press(current.find((b) => b.classList.contains("drive-panel__add")));
if (!done) done = press(bound(openPanel) || bound(app));
if (done) e.preventDefault(); // F1, F5, / are the browser's otherwise
});
let saved = null;
try { saved = localStorage.getItem(KEY); } catch { /* nothing kept */ }
set(saved === "on");
}