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, laneSvg, distance, VOICE_KEY } from "/js/dashboard.js";
import { SPEED_LIMITS, COUNTRY_NAMES, isHeavy, motorwayPayment } from "/js/speed_limits.js";
import { currentVehicle, onVehicle } from "/js/panels.js";
import { formatSunInfo } from "/js/sun.js";
import { pointsMenu, layersMenu, terrainMenu, levelMenu, recordingMenu, todayMenu, 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;
const BORDER_MS = 20000; // the border card's time on the screen // 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();
// A knob's function → the screen keys it stands for (their labels: ⟳ ⟲)
const KNOB_KEYS = { zoom: ["zoomIn", "zoomOut"] };
const KEYPAD_ABSENT_MS = 5000; // no keypad on the bus: asked again after this
// 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;
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 = `
Trip
`;
// 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 = `
Menu
`;
// auto: opens off-road and closes back on the road; stay: opens and stays (the inclinometer all along); hand: neither
const TERRAIN_MODES = { auto: "opens and closes by itself", stay: "opens by itself, stays", hand: "by hand" };
const terrainMode = () => { try { const m = localStorage.getItem(TERRAIN_AUTO_KEY); return m in TERRAIN_MODES ? m : "auto"; } catch { return "auto"; } };
const terrainAuto = () => terrainMode() !== "hand";
const autoButton = menuPanel.querySelector('[data-action="terrain-auto"]');
const renderAuto = () => { autoButton.innerHTML = `Terrain view: ${TERRAIN_MODES[terrainMode()]} tap to switch`; };
autoButton.addEventListener("click", () => {
const modes = Object.keys(TERRAIN_MODES);
try { localStorage.setItem(TERRAIN_AUTO_KEY, modes[(modes.indexOf(terrainMode()) + 1) % modes.length]); } catch { /* private window: not kept */ }
renderAuto();
});
renderAuto();
const voiceButton = menuPanel.querySelector('[data-action="voice"]');
const voiceOn = () => { try { return localStorage.getItem(VOICE_KEY) === "on"; } catch { return false; } };
const renderVoice = () => { voiceButton.innerHTML = `Voice prompts: ${voiceOn() ? "on" : "off"} tap to switch`; };
voiceButton.addEventListener("click", () => {
try { localStorage.setItem(VOICE_KEY, voiceOn() ? "off" : "on"); } catch { /* private window: not kept */ }
if (voiceOn()) window.speechSynthesis?.speak(new SpeechSynthesisUtterance("Voice prompts on"));
renderVoice();
});
renderVoice();
// the profile: a tap goes to the next one (re-routes); the dialog is the desktop's
const profileButton = menuPanel.querySelector('[data-action="profile"]');
const renderProfile = () => {
const { current } = routePanel?.profiles() || {};
profileButton.innerHTML = `Profile: ${escapeHtml(current?.name ?? "—")} tap for the next one`;
};
profileButton.addEventListener("click", () => {
const { list, current } = routePanel?.profiles() || { list: [] };
if (!list.length) return;
routePanel.pickProfile(list[(list.indexOf(current) + 1) % list.length].id);
});
onVehicle(renderProfile);
renderProfile();
menuPanel.querySelector('[data-action="overview"]').addEventListener("click", overview);
menuPanel.querySelector('[data-action="today"]').addEventListener("click", () => open(today.el));
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", `${escapeHtml(r.name)}${escapeHtml(r.where || "")} · ${r.away}`,
"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", `${escapeHtml(stop.label)}${leg ? ` · ${leg}` : ""}` +
`${escapeHtml(stop.name || `${stop.lngLat[1].toFixed(4)}, ${stop.lngLat[0].toFixed(4)}`)}`, "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, openLevel: () => open(level.el) });
const level = levelMenu({ ...menuCtx, state: () => dash, openTerrain: () => open(terrain.el) });
const recording = recordingMenu({
...menuCtx,
showBounds: ([w, s, e, n]) => { pauseFollow(map); map.fitBounds([[w, s], [e, n]], { padding: 60, pitch: 0, maxZoom: 15 }); },
endTrip: () => endTrip(),
});
const today = todayMenu(menuCtx);
const menus = [points, layers, terrain, level, recording, today];
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;
// simulated, the tilt is the DEM's slope round the car — on a road cut into a hillside that's the
// hill's, not the car's, so it doesn't count (the surface still does); the dials still show it
const tilted = !state.simulated && 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 (terrainMode() === "auto" && 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
menus.find((m) => m.el === openPanel && m.el !== panel)?.closed?.();
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);
};
const endTrip = async () => {
if (!log?.active || !window.confirm(`End the trip "${log.folder}"? Its track stays in the library.`)) return;
await fetch("/api/trip/log", { method: "DELETE" });
driven = [];
refreshLog();
};
tripPanel.querySelector('[data-action="recording"]').addEventListener("click", () => open(recording.el));
logButton.addEventListener("click", async () => {
if (log?.active) return endTrip();
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, level.el, recording.el, today.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 = `${icon}${label ? `${label}` : ""}`;
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);
} 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": {
// the limit as a sign at the field's end, the next one under it; the speed red past the limit
const next = nav?.next ? `${typeof nav.next.limit === "number" ? nav.next.limit : "∞"} in ${distance(nav.next.m)}` : "";
const sign = typeof limit === "number" || limit === "unlimited"
? `${limit === "unlimited" ? "∞" : limit}${next ? `${escapeHtml(next)}` : ""}` : "";
return [kmh == null ? "—" : Math.round(kmh), "km/h", typeof limit === "number" && kmh > limit + OVER_KMH ? "drive-cell--warn" : "", sign];
}
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 ["?", ""];
}
};
// Under the maneuver, over the map, only when there's something: the next
// maneuver's lanes (from 1 km, further at speed) and the next traffic signal.
const renderAhead = (el) => {
const n = dash?.nav;
const lanes = !n?.arrived && n?.maneuver?.lanes && n.maneuver.m <= n.lanesM ? n.maneuver.lanes : null;
const signal = n?.signal != null && n.signal <= 1000 ? n.signal : null;
el.hidden = !lanes && signal == null;
if (el.hidden) return;
el.innerHTML = (lanes ? `
${lanes.map(laneSvg).join("")}
` : "") +
(signal != null ? `${distance(signal)}` : "");
};
// Past a border (the country along the route, or of the road driven):
// the new country's limits for the profile and how its motorways are
// paid, for BORDER_MS or until tapped (the Design canvas' GridBorder).
let country = null;
let border = null; // { code, until }
const renderBorder = (el) => {
const code = dash?.nav?.country;
if (code && code !== country) {
if (country) border = { code, until: Date.now() + BORDER_MS };
country = code;
}
el.hidden = !border || Date.now() > border.until;
if (el.hidden) return;
if (!el.dataset.wired) {
el.dataset.wired = "1";
el.addEventListener("click", () => { border = null; el.hidden = true; });
}
const heavy = isHeavy(currentVehicle);
const row = SPEED_LIMITS[border.code]?.[heavy ? "heavy" : "car"];
const pay = motorwayPayment(border.code, currentVehicle);
const sign = (v, k) => `${v ?? "–"}${k}`;
let name = border.code;
try { name = COUNTRY_NAMES.of(border.code); } catch { /* not a region code */ }
el.innerHTML = `