818 lines
43 KiB
JavaScript
818 lines
43 KiB
JavaScript
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, switchesMenu, 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 = `<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>
|
||
<button type="button" class="drive-trip__log-state" data-action="recording" title="The recording: its days, export"><span class="drive-cell__label">Recording ▸</span><span class="drive-trip__log-text"></span></button>
|
||
<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="today">Today ▸ <small>the stops left, tonight, the weather, the day's notes</small></button>
|
||
<button type="button" class="drive-menu__row" data-action="switches" hidden>Switches ▸ <small>the relays and lights, what drives them</small></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="voice"></button>
|
||
<button type="button" class="drive-menu__row" data-action="profile"></button>
|
||
<button type="button" class="drive-menu__row" data-action="leave">Leave driving mode</button>`;
|
||
// 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()]} <small>tap to switch</small>`; };
|
||
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"} <small>tap to switch</small>`; };
|
||
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 ?? "—")} <small>tap for the next one</small>`;
|
||
};
|
||
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="switches"]').addEventListener("click", () => open(switches.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", `<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, 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 switches = switchesMenu(menuCtx);
|
||
switches.available().then((yes) => { menuPanel.querySelector('[data-action="switches"]').hidden = !yes; });
|
||
const menus = [points, layers, terrain, level, recording, today, switches];
|
||
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);
|
||
document.documentElement.classList.toggle("trip-rec", !!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, switches.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);
|
||
} 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"
|
||
? `<span class="drive-speed__limit" aria-label="Limit ${limit}"><b>${limit === "unlimited" ? "∞" : limit}</b>${next ? `<small>${escapeHtml(next)}</small>` : ""}</span>` : "";
|
||
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 ? `<div class="dash-lanes drive-ahead__lanes">${lanes.map(laneSvg).join("")}</div>` : "") +
|
||
(signal != null ? `<span class="drive-ahead__signal"><span class="dash-signal"></span>${distance(signal)}</span>` : "");
|
||
};
|
||
|
||
// 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) => `<span class="drive-border__limit"><span class="drive-speed__limit"><b>${v ?? "–"}</b></span><small>${k}</small></span>`;
|
||
let name = border.code;
|
||
try { name = COUNTRY_NAMES.of(border.code); } catch { /* not a region code */ }
|
||
el.innerHTML = `<div class="drive-border__head"><b>${escapeHtml(name)}</b><span class="drive-cell__muted">${border.code}${currentVehicle ? ` · ${escapeHtml(currentVehicle.name)}` : ""}</span></div>` +
|
||
(row ? `<div class="drive-border__signs">${sign(row[0], "Motorway")}${sign(row[2], "Outside towns")}${sign(row[3], "In towns")}</div>` : `<span class="drive-cell__muted">No limits known for ${border.code}</span>`) +
|
||
(pay.how ? `<span class="drive-border__pays">Motorways: ${pay.how} ${pay.has ? "✓" : "— not in the profile"}</span>` : "");
|
||
};
|
||
|
||
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?.arrived) {
|
||
el.innerHTML = `${maneuverSvg(4)}<div class="drive-cell__text"><span class="drive-cell__value">Arrived</span><span class="drive-cell__street">${escapeHtml(n.street || "")}</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();
|
||
if (openPanel === level.el) level.render();
|
||
const a = ahead();
|
||
for (const { cell, el } of cells) {
|
||
if (cell.widget === "field") {
|
||
const name = cell.value;
|
||
const [value, unit, cls = "", extra = ""] = fieldValue(name, a);
|
||
el.innerHTML = `${extra}<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 === "ahead") renderAhead(el);
|
||
else if (cell.widget === "border") renderBorder(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);
|
||
}
|
||
sendLeds();
|
||
}
|
||
map.on("pitchend", render);
|
||
setInterval(render, RENDER_MS);
|
||
|
||
// the keypads' bindings: this car's own (saved in /keypad.html) over the profile's
|
||
const savedBindings = fetch("/api/keypad/bindings", { cache: "no-store" }).then((r) => (r.ok ? r.json() : null)).catch(() => null);
|
||
fetch(PROFILE_URL, { cache: "no-cache" }).then((r) => r.json()).then(async (p) => {
|
||
p.bindings = (await savedBindings)?.bindings || p.bindings;
|
||
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 });
|
||
}
|
||
labelKeys(); // a keypad heard before the profile came
|
||
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.
|
||
// (The keypads' channels: the profile's bindings, further down.)
|
||
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
|
||
});
|
||
|
||
// Keypads (can.json's "keypads", GET /api/keypad, a long poll) and the
|
||
// profile's "bindings" (docs/design.adoc, Switches and the keypad): a
|
||
// channel ("pad.K1", "pad.E3" — a key, a knob, its "press") → an action,
|
||
// another one while a menu is open ("menu"). A screen key's action clicks
|
||
// it; knobs turn: zoom, panX / panY, rows (the menu's ↑ ↓); enter, close.
|
||
// A keypad's heartbeat on the bus labels the screen keys with its
|
||
// channels (none = touch only) and the line under them in the binding's
|
||
// LED colour; its key LEDs follow them, "led_on" (green) while on.
|
||
// ponytail: screen functions only — outputs (relays), the modes (hold,
|
||
// pulse, positions…) and the mapping UI (the canvas' GridBinding) to come.
|
||
const bindings = () => profile?.bindings || [];
|
||
let present = [];
|
||
let ledsSent = {};
|
||
const keyEl = (action) => cells.find((c) => c.cell.widget === "key" && c.cell.action === action)?.el;
|
||
const shortName = (input) => input.slice(input.indexOf(".") + 1).replace(/ press$/, " ⏎");
|
||
function labelKeys() {
|
||
for (const { cell, el } of cells) {
|
||
if (cell.widget !== "key") continue;
|
||
delete el.dataset.keypad;
|
||
delete el.dataset.led;
|
||
}
|
||
for (const b of bindings()) {
|
||
if (!present.some((d) => b.input.startsWith(`${d.name}.`)) || !b.action) continue;
|
||
const knob = KNOB_KEYS[b.action];
|
||
for (const [i, action] of (knob || [b.action]).entries()) {
|
||
const el = keyEl(action);
|
||
if (!el) continue;
|
||
el.dataset.keypad = shortName(b.input) + (knob ? (i ? " ⟲" : " ⟳") : "");
|
||
if (b.led) el.dataset.led = b.led;
|
||
}
|
||
}
|
||
}
|
||
function sendLeds() {
|
||
for (const d of present.filter((p) => p.leds)) {
|
||
const on = {};
|
||
for (const b of bindings()) {
|
||
const k = b.input.startsWith(`${d.name}.`) && /^K\d+$/.exec(b.input.slice(d.name.length + 1))?.[0];
|
||
const el = k && b.led && keyEl(b.action);
|
||
if (el) on[k] = el.disabled ? null : el.getAttribute("aria-pressed") === "true" ? b.led_on || "green" : b.led;
|
||
}
|
||
const body = JSON.stringify({ keypad: d.name, on });
|
||
if (body === ledsSent[d.name]) continue;
|
||
ledsSent[d.name] = body;
|
||
fetch("/api/keypad/leds", { method: "PUT", headers: { "Content-Type": "application/json" }, body }).catch(() => { ledsSent[d.name] = ""; });
|
||
}
|
||
}
|
||
const navKey = (key) => document.dispatchEvent(new KeyboardEvent("keydown", { key }));
|
||
const PAN_PX = 80;
|
||
const knobAction = {
|
||
zoom: (dir) => keyEl(dir > 0 ? "zoomIn" : "zoomOut")?.click(),
|
||
panX: (dir) => map.panBy([dir * PAN_PX, 0], { duration: 100 }),
|
||
panY: (dir) => map.panBy([0, dir * PAN_PX], { duration: 100 }),
|
||
rows: (dir) => navKey(dir > 0 ? "ArrowDown" : "ArrowUp"),
|
||
enter: () => navKey("Enter"),
|
||
close: () => navKey("Escape"),
|
||
};
|
||
const onInput = (event) => {
|
||
if (!document.documentElement.classList.contains("driving")) return;
|
||
const [, channel, turn] = /^(.*?)(?: (⟳|⟲))?$/.exec(event);
|
||
const b = bindings().find((x) => x.input === channel);
|
||
const action = (openPanel && b?.menu) || b?.action;
|
||
if (!action) return;
|
||
if (knobAction[action]) return knobAction[action](turn === "⟲" ? -1 : 1);
|
||
const el = keyEl(action);
|
||
if (el && visible(el)) el.click();
|
||
};
|
||
(async function keypadLoop() {
|
||
let since = null;
|
||
for (;;) {
|
||
let answer = null;
|
||
try {
|
||
const response = await fetch(`/api/keypad${since == null ? "" : `?since=${since}`}`, { cache: "no-store" });
|
||
if (response.status === 404) return; // no keypads configured on this server
|
||
if (response.ok) answer = await response.json();
|
||
} catch { /* the server restarting, offline for a moment */ }
|
||
const now = answer?.present || [];
|
||
if (JSON.stringify(now) !== JSON.stringify(present)) {
|
||
present = now;
|
||
document.documentElement.classList.toggle("drive-keypad", present.length > 0);
|
||
if (present.length) document.documentElement.classList.add("drive-keys");
|
||
ledsSent = {};
|
||
labelKeys();
|
||
sendLeds();
|
||
}
|
||
if (!present.length) {
|
||
since = null;
|
||
await new Promise((r) => setTimeout(r, KEYPAD_ABSENT_MS));
|
||
continue;
|
||
}
|
||
if (since != null) for (const e of answer.events) onInput(e.input);
|
||
since = answer.seq;
|
||
}
|
||
})();
|
||
|
||
let saved = null;
|
||
try { saved = localStorage.getItem(KEY); } catch { /* nothing kept */ }
|
||
set(saved === "on");
|
||
}
|