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 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"]); 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
Recording
`; // 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
`; 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"} tap to switch`; }; 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", `${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 }); 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(); } 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 = `${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"); } 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 = `
Off the routererouting
`; } 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 ? ` · then ${escapeHtml(n.then.street || n.then.text)}` : ""; el.innerHTML = `${maneuverSvg(type)}
${distance(m)}${what}${then}
`; } else { el.innerHTML = `
On${escapeHtml(n?.street ?? "—")}
`; } }; 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 = ` N Heading${deg == null ? "—" : String(deg).padStart(3, "0") + "°"} ${deg == null ? "" : CARDINALS[Math.round(deg / 45) % 8]}`; }; 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 = `${FIELDS[cell.value] || cell.value}${escapeHtml(value)} ${escapeHtml(unit)}`; } else if (cell.widget === "maneuver") renderManeuver(el); else if (cell.widget === "status") { el.innerHTML = `MAPTOOL● ${navigator.onLine ? "online" : "offline"}${log?.active ? ` · ● rec` : ""}`; } 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; 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) 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"))); let saved = null; try { saved = localStorage.getItem(KEY); } catch { /* nothing kept */ } set(saved === "on"); }