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
CI / check (push) Successful in 23s
CI / deploy (push) Successful in 17s

This commit is contained in:
randy committed 2026-12-03 10:47:40 +01:00
1 parent 285af64a65
commit f73badd107
14 files changed
+1253 -277

No files matched your search

+409 -119
View File
@@ -1,97 +1,155 @@
import { LngLatBounds } from "/vendor/maplibre-gl/maplibre-gl.mjs";
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, emptyRow as empty, escapeHtml } from "/js/drive_menus.js";
// Driving mode: the few things needed on the road as big buttons, the
// planning sidebar and panels out of the way. After the research in
// docs/design.adoc ("Buttons while driving"): four buttons on the map
// (Android Auto's action strip: at most four, 76 px), the recenter button
// only while the map isn't following (as Google Maps), night automatic and
// leaving by the topbar's Drive. Per device (localStorage).
// 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 CHECK_MS = 1000; // how often the recenter button looks whether the map follows
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
const escapeHtml = (text) => String(text).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
// 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"]);
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", 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;
export function setupDriving(map, nightButton, routePanel) {
let route = onRouteChanged((r) => (route = r));
const toggle = document.createElement("button");
toggle.type = "button";
toggle.className = "topbar__drive";
toggle.title = "Driving mode: big buttons, no planning panels";
toggle.title = "Driving mode: the cockpit grid, no planning panels";
toggle.textContent = "Drive";
nightButton.before(toggle);
const button = (name, label, title, action) => {
const el = document.createElement("button");
el.type = "button";
el.className = `drive-bar__${name}`;
el.textContent = label;
el.title = title;
el.setAttribute("aria-label", title);
el.addEventListener("click", action);
return el;
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 });
};
const bar = document.createElement("div");
bar.className = "drive-bar";
bar.hidden = true;
bar.append(
button("zoomIn", "+", "Zoom in", () => map.zoomIn()),
button("zoomOut", "−", "Zoom out", () => map.zoomOut()),
button("pitch", "3D", "2D / 3D", () => map.easeTo({ pitch: map.getPitch() > 0 ? 0 : PITCH_3D, ...(map.getPitch() > 0 && { bearing: 0 }), duration: 300 })),
button("trip", "Trip", "The trip's stops: add, move, remove", () => openTrip(tripPanel.hidden)),
button("overview", "Route", "The whole route (the follow pauses)", () => {
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 one "follow / back to the position", bottom left, only when needed
const recenter = button("recenter", "Follow", "Follow the position, heading up in 3D", () => {
requestGnssFollow();
resumeFollow(map);
if (map.getPitch() === 0) map.easeTo({ pitch: PITCH_3D, duration: 300 });
recenter.hidden = true;
});
recenter.hidden = true;
// The Trip menu (the navigator's, docs/design.adoc): the stops as big
// rows — tap a name to look at it, ↑ ↓ to reorder, ✕ to drop — and big
// actions: a stop where the crosshair is (pan the map there first), the
// start moved to the car. One level, no dragging, no typing.
const tripPanel = document.createElement("div");
tripPanel.className = "drive-trip";
// 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.innerHTML = `<div class="drive-trip__head"><span>Trip <small class="drive-trip__total"></small></span><button type="button" class="drive-trip__close" aria-label="Close">✕</button></div>
<div class="drive-trip__log"><button type="button" data-action="log"></button><span class="drive-trip__log-state"></span></div>
<div class="drive-trip__search"><input type="search" placeholder="Search saved points and places…" enterkeyhint="search"></div>
<ol class="drive-trip__stops"></ol>
<div class="drive-trip__actions">
<button type="button" data-action="add">+ Stop at the crosshair</button>
<button type="button" data-action="start">Start from here (the car)</button>
</div>`;
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; a result's name shows it, + adds
// it as a stop. While there's a query the list shows results, not stops.
// 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()) {
results = null;
return renderTrip();
}
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();
@@ -100,75 +158,124 @@ export function setupDriving(map, nightButton, routePanel) {
let found = [];
try { found = (await (await fetch(url)).json()).results; } catch { /* offline for a moment: nothing */ }
if (mine !== searchSeq) return;
results = found.filter(({ bbox }) => bbox).map(({ name, bbox, source_label: where }) => ({ name, where, lngLat: [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2] }));
renderTrip();
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.map((r) => {
const li = document.createElement("li");
const name = button("stop-name", r.name, "Show it on the map", () => lookAt(r.lngLat));
name.innerHTML = `${escapeHtml(r.name)}<small>${escapeHtml(r.where || "")}</small>`;
const add = button("stop-add", "+", "Add as a stop", () => {
input.value = "";
results = null; // back to the stops, the new one among them
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);
});
li.append(name, add);
return li;
}));
if (!results.length) list.innerHTML = `<li class="drive-trip__empty">Nothing found.</li>`;
}),
]));
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__stops"));
if (results) return renderResults(tripPanel.querySelector(".drive-trip__results"));
const stops = routePanel.stops();
const list = tripPanel.querySelector(".drive-trip__stops");
list.replaceChildren(...stops.map((stop, i) => {
const li = document.createElement("li");
const name = button("stop-name", "", "Show it on the map", () => lookAt(stop.lngLat));
const leg = stop.leg ? `<small>+${stop.leg.km.toFixed(1)} km${stop.leg.s != null ? ` · ${formatDuration(stop.leg.s)}` : ""}</small>` : "";
name.innerHTML = `${escapeHtml(stop.label)} · ${escapeHtml(stop.name || `${stop.lngLat[1].toFixed(4)}, ${stop.lngLat[0].toFixed(4)}`)}${leg}`;
const done = button("stop-done", "✓", stop.passed ? "Passed — tap to route through it again" : "Mark as passed (not routed any more)", () => routePanel.togglePassed(i));
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);
li.classList.toggle("drive-trip__passed", !!stop.passed || stop.behind);
const up = button("stop-up", "↑", "Earlier", () => routePanel.moveStop(i, -1));
const down = button("stop-down", "↓", "Later", () => routePanel.moveStop(i, 1));
const drop = button("stop-drop", "✕", "Remove this stop", () => routePanel.removeStop(i));
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;
li.append(name, done, up, down, drop);
return li;
return [name, done, up, down, drop];
}));
if (!stops.length) list.innerHTML = `<li class="drive-trip__empty">No stops yet — pan the map to a place and add it.</li>`;
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)}` : "";
};
function openTrip(open) {
tripPanel.hidden = !open;
crosshair.hidden = !open;
bar.querySelector(".drive-bar__trip").classList.toggle("active", open);
if (open) {
renderTrip();
// 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;
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();
}
tripPanel.querySelector(".drive-trip__close").addEventListener("click", () => openTrip(false));
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);
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-state");
const logState = tripPanel.querySelector(".drive-trip__log-text");
let log = null;
let driven = [];
const drawDriven = () => {
@@ -198,9 +305,10 @@ export function setupDriving(map, nightButton, routePanel) {
setTimeout(pollLog, LOG_POLL_MS);
};
const renderLog = () => {
logButton.textContent = log?.active ? "End the trip" : "Start the trip (record it)";
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` : "";
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) {
@@ -217,32 +325,214 @@ export function setupDriving(map, nightButton, routePanel) {
refreshLog();
});
if (isLoggedIn()) pollLog();
else tripPanel.querySelector(".drive-trip__log").hidden = true;
map.getContainer().append(bar, recenter, crosshair);
// the Trip menu beside the map, not over it (like Android Auto's side
// panel): the map gets narrower and keeps its buttons, its center (the
// follow, the crosshair, the overview) stays in what's seen
map.getContainer().after(tripPanel);
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);
const render = () => {
bar.querySelector(".drive-bar__pitch").textContent = map.getPitch() > 0 ? "2D" : "3D";
bar.querySelector(".drive-bar__overview").disabled = !route;
recenter.hidden = bar.hidden || isFollowing(map);
// --- 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");
} 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 "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 [value, unit, cls = ""] = fieldValue(cell.value, a);
el.innerHTML = `<span class="drive-cell__label">${FIELDS[cell.value] || cell.value}</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);
onRouteChanged(render);
setInterval(render, CHECK_MS);
setInterval(render, RENDER_MS);
fetch(PROFILE_URL, { cache: "no-cache" }).then((r) => r.json()).then((p) => {
profile = p;
app.style.setProperty("--drive-cols", p.columns);
app.style.setProperty("--drive-rows", p.rows);
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-rows", r2 - r1);
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) openTrip(false);
if (!on) open(null);
document.documentElement.classList.toggle("driving", on);
bar.hidden = !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 sidebar came or went
map.resize(); // the grid came or went
}
toggle.addEventListener("click", () => set(bar.hidden));
toggle.addEventListener("click", () => set(!document.documentElement.classList.contains("driving")));
let saved = null;
try { saved = localStorage.getItem(KEY); } catch { /* nothing kept */ }
set(saved === "on");