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
This commit is contained in:
1 parent
285af64a65
commit
f73badd107
14 files changed
+1253
-277
No files matched your search
+45
-13
@@ -49,7 +49,7 @@ const load = () => {
|
||||
const RAD = Math.PI / 180;
|
||||
// meters between two [lon, lat] (equirectangular: fine at these distances)
|
||||
const meters = ([lon1, lat1], [lon2, lat2]) => Math.hypot((lon2 - lon1) * Math.cos(((lat1 + lat2) / 2) * RAD), lat2 - lat1) * 111320;
|
||||
const distance = (m) => (m >= 1000 ? `${(m / 1000).toFixed(1)} km` : `${Math.round(m / 10) * 10} m`);
|
||||
export const distance = (m) => (m >= 1000 ? `${(m / 1000).toFixed(1)} km` : `${Math.round(m / 10) * 10} m`);
|
||||
const esc = (text) => String(text ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
||||
|
||||
// An arrow from the bottom center turning by `angle` (° from straight on),
|
||||
@@ -66,7 +66,7 @@ const uturnPath = (cls) => `<path class="${cls}" d="M14 30 V14 A5 5 0 0 0 4 14 V
|
||||
// "uturn", "arrive", "roundabout" drawn their own way.
|
||||
const MANEUVER_ANGLES = { 1: 0, 2: 45, 3: -45, 7: 0, 8: 0, 9: 45, 10: 90, 11: 135, 14: -135, 15: -90, 16: -45, 17: 0, 18: 45, 19: -45,
|
||||
20: 45, 21: -45, 22: 0, 23: 30, 24: -30, 25: 0, 37: 30, 38: -30 };
|
||||
function maneuverSvg(type) {
|
||||
export function maneuverSvg(type) {
|
||||
let body;
|
||||
if (type === 12 || type === 13) body = uturnPath("dash-banner__arrow");
|
||||
else if (type >= 4 && type <= 6) body = `<path class="dash-banner__arrow" d="M8 30 V4 M8 5 H19 L16 9 L19 13 H8"/>`; // a flag: arriving
|
||||
@@ -163,8 +163,19 @@ const INCLINOMETER = `
|
||||
<text x="35" y="60" class="dash-caption">pitch</text>
|
||||
</svg>`;
|
||||
|
||||
// The driving grid (driving.js) reads the dashboard: watchDashboard(cb)
|
||||
// polls the bus while it's on, the overlay's card or not, and hands each
|
||||
// poll's state to cb; watchDashboard(null) stops that.
|
||||
let instance = null;
|
||||
export function watchDashboard(callback) {
|
||||
if (!instance || !isLoggedIn()) return; // /api/can wants a login
|
||||
instance._watch = callback;
|
||||
if (callback && !instance._timer) instance._poll();
|
||||
}
|
||||
|
||||
export class DashboardControl {
|
||||
constructor(map) {
|
||||
instance = this;
|
||||
this._map = map;
|
||||
this._settings = load();
|
||||
this._timer = null;
|
||||
@@ -348,13 +359,15 @@ export class DashboardControl {
|
||||
this._map.getContainer().appendChild(this._banner);
|
||||
this._status.hidden = false;
|
||||
this._status.textContent = "Connecting…";
|
||||
this._poll();
|
||||
if (!this._timer) this._poll();
|
||||
}
|
||||
|
||||
_disable() {
|
||||
this._progress(null);
|
||||
clearTimeout(this._timer);
|
||||
this._timer = null;
|
||||
if (!this._watch) {
|
||||
this._progress(null);
|
||||
clearTimeout(this._timer);
|
||||
this._timer = null;
|
||||
}
|
||||
this._card?.remove();
|
||||
this._card = null;
|
||||
this._banner?.remove();
|
||||
@@ -363,6 +376,8 @@ export class DashboardControl {
|
||||
}
|
||||
|
||||
async _poll() {
|
||||
if (this._busy) return; // the grid and the card both asked
|
||||
this._busy = true;
|
||||
try {
|
||||
const response = await fetch("/api/can", { cache: "no-store" });
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
@@ -375,6 +390,7 @@ export class DashboardControl {
|
||||
}));
|
||||
this._updateCourse(this._values);
|
||||
this._simRunning = !!data.simulated; // /sim.html runs it
|
||||
this._actions = data.actions || []; // can.json's SDO actions (levelling), POST /api/can/actions/<n>
|
||||
if (this._simRunning) await this._simulateTerrain();
|
||||
this._navigate();
|
||||
this._status.textContent = this._simRunning ? "Simulated GNSS" : data.available ? "" : "CAN is off on this server";
|
||||
@@ -385,7 +401,25 @@ export class DashboardControl {
|
||||
this._status.textContent = `Can't reach the server: ${e.message}`;
|
||||
}
|
||||
this._render();
|
||||
if (this._card) this._timer = setTimeout(() => this._poll(), POLL_MS);
|
||||
this._busy = false;
|
||||
this._watch?.(this.state());
|
||||
this._timer = this._card || this._watch ? setTimeout(() => this._poll(), POLL_MS) : null;
|
||||
}
|
||||
|
||||
// What the driving grid shows: the signals, the navigation, the heading
|
||||
// ({ deg, live }), the road's surface (off a route, /api/road), the CAN
|
||||
// actions, and the km along the route (null off it).
|
||||
state() {
|
||||
return { values: this._values, nav: this._nav, heading: this._heading(), simulated: !!this._simRunning, actions: this._actions || [],
|
||||
surface: this._road?.surface ?? null, course: this._course, atKm: this._route && this._offFixes < OFF_ROUTE_FIXES ? this._lastAt : null };
|
||||
}
|
||||
|
||||
// Driving, the GNSS course; standing, the compass — else the last of either, not live.
|
||||
_heading() {
|
||||
const v = this._values;
|
||||
const moving = v.speed != null && v.speed >= MOVING_MS;
|
||||
const deg = moving ? this._course ?? v.heading : v.heading ?? this._course;
|
||||
return deg == null ? null : { deg: (deg + 360) % 360, live: moving ? this._course != null : v.heading != null };
|
||||
}
|
||||
|
||||
_render() {
|
||||
@@ -414,12 +448,10 @@ export class DashboardControl {
|
||||
text.textContent = value == null ? "—" : `${value > 0 ? "+" : ""}${Math.round(value)}°`;
|
||||
text.setAttribute("class", `dash-value dash-${key}-value ${severity(key, value)}`);
|
||||
}
|
||||
const moving = v.speed != null && v.speed >= MOVING_MS;
|
||||
const heading = moving ? this._course ?? v.heading : v.heading ?? this._course;
|
||||
const live = heading != null && (moving ? this._course != null : v.heading != null);
|
||||
svg.querySelector(".dash-ring").setAttribute("transform", `rotate(${heading == null ? 0 : -heading})`);
|
||||
svg.querySelector(".dash-ring").style.opacity = heading == null ? 0.3 : live ? 1 : 0.55;
|
||||
svg.querySelector(".dash-heading").textContent = heading == null ? "" : `${Math.round((heading + 360) % 360)}°`;
|
||||
const heading = this._heading();
|
||||
svg.querySelector(".dash-ring").setAttribute("transform", `rotate(${heading ? -heading.deg : 0})`);
|
||||
svg.querySelector(".dash-ring").style.opacity = !heading ? 0.3 : heading.live ? 1 : 0.55;
|
||||
svg.querySelector(".dash-heading").textContent = heading ? `${Math.round(heading.deg)}°` : "";
|
||||
speed.querySelector("span").textContent = v.speed == null ? "—" : Math.round(v.speed * 3.6);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,454 @@
|
||||
// The driving grid's Points and Layers menus (driving.js; the Design canvas'
|
||||
// GridPoints and GridLayers): each a 7 × 8 panel of cells in the profile's
|
||||
// menu area, built the same way as the Trip menu.
|
||||
import { distance } from "/js/dashboard.js";
|
||||
import { elevationAt } from "/js/dem.js";
|
||||
|
||||
const SEARCH_DELAY_MS = 300;
|
||||
const AHEAD_M = 2000; // "Ahead": saved things this close to the route still to drive
|
||||
const PRESETS_KEY = "maptool.layerPresets";
|
||||
const PRESETS = [["road", "↝", "Road"], ["offroad", "⛰", "Off-road"], ["overnight", "⛺", "Overnight"]];
|
||||
// What a preset turns on until it's kept otherwise (+ Keep): names as the On the map panel has them.
|
||||
const DEFAULT_PRESETS = {
|
||||
road: ["Radar", "Tracker"],
|
||||
offroad: ["Terrain shading", "Contour lines", "Hiking trails", "Radar"],
|
||||
overnight: ["Radar", "Wikipedia", "NPS park maps"],
|
||||
};
|
||||
const SKIP_LAYERS = new Set(["Dashboard"]); // the grid's own data, not a layer
|
||||
|
||||
export const escapeHtml = (text) => String(text ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
||||
|
||||
// A button that is one cell (or a few) of a menu.
|
||||
export function cellButton(cls, html, title, action) {
|
||||
const el = document.createElement("button");
|
||||
el.type = "button";
|
||||
el.className = `drive-panel__cell drive-panel__${cls}`;
|
||||
el.innerHTML = html;
|
||||
el.title = title;
|
||||
el.setAttribute("aria-label", title);
|
||||
el.addEventListener("click", action);
|
||||
return el;
|
||||
}
|
||||
|
||||
export const emptyRow = (text) => Object.assign(document.createElement("p"), { className: "drive-panel__empty", textContent: text });
|
||||
|
||||
function panel(cls, label, inner) {
|
||||
const el = document.createElement("section");
|
||||
el.className = `drive-panel ${cls}`;
|
||||
el.setAttribute("aria-label", label);
|
||||
el.hidden = true;
|
||||
el.innerHTML = `<div class="drive-panel__head">${label} <small class="drive-panel__note"></small></div>
|
||||
<button type="button" class="drive-panel__close" aria-label="Close">✕</button>${inner}`;
|
||||
return el;
|
||||
}
|
||||
|
||||
const RAD = Math.PI / 180;
|
||||
const meters = ([lon1, lat1], [lon2, lat2]) => Math.hypot((lon2 - lon1) * Math.cos(((lat1 + lat2) / 2) * RAD), lat2 - lat1) * 111320;
|
||||
const eyeGlyph = (show) => ({ all: "●", some: "◐", none: "○" })[show];
|
||||
|
||||
// Points: the library on the road — nearest the car first (the search's
|
||||
// "layers" source with no words), or along the route ahead, or only what's
|
||||
// shown; or one folder at a time with ← up. An eye per row; + adds a point
|
||||
// as a stop. ctx: { map, gpxPanel, routePanel, lookAt, position, route, atKm, close }.
|
||||
export function pointsMenu(ctx) {
|
||||
const el = panel("drive-points", "Points", `
|
||||
<div class="drive-points__search"><input type="search" aria-label="Find in the library" placeholder="Find a point, track, folder…" enterkeyhint="search"></div>
|
||||
<div class="drive-points__bar"></div>
|
||||
<div class="drive-panel__list drive-points__list"></div>
|
||||
<div class="drive-panel__foot"></div>
|
||||
<button type="button" class="drive-panel__wide" data-action="hide-all">Hide all</button>`);
|
||||
const input = el.querySelector("input");
|
||||
const bar = el.querySelector(".drive-points__bar");
|
||||
const list = el.querySelector(".drive-points__list");
|
||||
const foot = el.querySelector(".drive-panel__foot");
|
||||
let scope = "near"; // near | ahead | shown | folder
|
||||
let cwd = "";
|
||||
let results = [];
|
||||
let loading = false;
|
||||
let timer = null;
|
||||
let seq = 0;
|
||||
const lib = () => ctx.gpxPanel?.libraryTree() || { folders: new Map(), files: new Map(), filesUnder: () => [] };
|
||||
|
||||
const fetchNear = async () => {
|
||||
const mine = ++seq;
|
||||
loading = true;
|
||||
render();
|
||||
const [lng, lat] = ctx.position();
|
||||
const url = new URL("/api/search", window.location.origin);
|
||||
url.search = new URLSearchParams({ q: input.value, sources: "layers", lat, lng });
|
||||
let found = [];
|
||||
try { found = (await (await fetch(url)).json()).results; } catch { /* offline for a moment: nothing */ }
|
||||
if (mine !== seq) return;
|
||||
loading = false;
|
||||
results = found.filter(({ bbox }) => bbox).map((r) => ({ ...r, lngLat: [(r.bbox[0] + r.bbox[2]) / 2, (r.bbox[1] + r.bbox[3]) / 2] }));
|
||||
render();
|
||||
};
|
||||
input.addEventListener("input", () => {
|
||||
if (scope === "folder") scope = "near"; // a search lists every match flat
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(fetchNear, SEARCH_DELAY_MS);
|
||||
});
|
||||
|
||||
// The route still to drive, for "Ahead".
|
||||
// ponytail: filters the 50 nearest the car, not the whole library along the route
|
||||
const ahead = () => {
|
||||
const coords = ctx.route()?.geometry?.coordinates;
|
||||
if (!coords?.length) return null;
|
||||
const from = (ctx.atKm() ?? 0) * 1000;
|
||||
let along = 0;
|
||||
return coords.filter((c, i) => (along += i ? meters(coords[i - 1], c) : 0) >= from);
|
||||
};
|
||||
const shownRows = () => {
|
||||
if (scope === "shown") return results.filter((r) => ctx.gpxPanel?.isShown(r.ref));
|
||||
if (scope !== "ahead") return results;
|
||||
const line = ahead();
|
||||
if (!line) return [];
|
||||
return results.filter((r) => line.some((c) => meters(c, r.lngLat) <= AHEAD_M));
|
||||
};
|
||||
|
||||
const toggleShown = async (paths, show) => {
|
||||
await ctx.gpxPanel?.setShown(paths, show);
|
||||
render();
|
||||
};
|
||||
const rowCells = ({ icon, color, name, meta, away, show, onOpen, onEye, last }) => {
|
||||
const text = cellButton("item", `<span class="drive-points__icon" style="color: ${color}">${icon}</span><span class="drive-panel__text"><b>${escapeHtml(name)}</b><small>${escapeHtml(meta)}</small></span>` +
|
||||
`<span class="drive-points__away">${escapeHtml(away || "")}</span>`, "Show it on the map", onOpen);
|
||||
const eye = cellButton("eye", eyeGlyph(show), show === "none" ? "Show on the map" : "Hide on the map", onEye);
|
||||
eye.setAttribute("aria-pressed", String(show !== "none"));
|
||||
eye.classList.toggle("active", show !== "none");
|
||||
return [text, eye, last || cellButton("blank", "", "", () => {})];
|
||||
};
|
||||
|
||||
const renderNear = () => {
|
||||
const rows = shownRows();
|
||||
list.replaceChildren(...rows.flatMap((r) => {
|
||||
const line = !/point/i.test(r.kind || "");
|
||||
const shown = ctx.gpxPanel?.isShown(r.ref);
|
||||
return rowCells({
|
||||
icon: line ? "〰" : "●", color: line ? "var(--route-driven)" : "#12bedf", name: r.name,
|
||||
meta: (r.source_label || "").replaceAll("/", " › "), away: r.distance_km != null ? distance(r.distance_km * 1000) : "",
|
||||
show: shown ? "all" : "none",
|
||||
onOpen: async () => {
|
||||
if (!ctx.gpxPanel?.isShown(r.ref)) await toggleShown([r.ref], true);
|
||||
ctx.lookAt(r.lngLat);
|
||||
},
|
||||
onEye: () => toggleShown([r.ref], !shown),
|
||||
last: line ? null : cellButton("add", "+", "Add as a stop", () => ctx.routePanel?.addStop(r.lngLat, r.name)),
|
||||
});
|
||||
}));
|
||||
if (!rows.length) list.append(emptyRow(loading ? "Looking…" : scope === "ahead" && !ahead() ? "No route to look along." : "Nothing saved here."));
|
||||
foot.textContent = `${rows.length} ${scope === "ahead" ? "along the route" : scope === "shown" ? "shown nearby" : "nearest the car"}`;
|
||||
};
|
||||
|
||||
const renderFolder = () => {
|
||||
const { folders, filesUnder } = lib();
|
||||
const folder = folders.get(cwd) || folders.get("");
|
||||
if (!folder) return list.replaceChildren(emptyRow("The library is loading…"));
|
||||
const shownOf = (paths) => {
|
||||
const n = paths.filter((p) => ctx.gpxPanel?.isShown(p)).length;
|
||||
return !paths.length || !n ? "none" : n === paths.length ? "all" : "some";
|
||||
};
|
||||
const subfolders = folder.children.filter((c) => c.type === "folder");
|
||||
const own = folder.children.filter((c) => c.type !== "folder");
|
||||
list.replaceChildren(...subfolders.flatMap((f) => {
|
||||
const paths = filesUnder(f.path).map((x) => x.path);
|
||||
const show = shownOf(paths);
|
||||
const open = () => { cwd = f.path; render(); };
|
||||
return rowCells({ icon: "▣", color: "var(--drive-muted)", name: f.name, meta: `${f.children.length} items`, show, onOpen: open,
|
||||
onEye: () => toggleShown(paths, show === "none"), last: cellButton("open", "›", "Open the folder", open) });
|
||||
}), ...own.flatMap((file) => {
|
||||
const shown = ctx.gpxPanel?.isShown(file.path);
|
||||
const line = file.kinds?.some((k) => k === "track" || k === "route");
|
||||
return rowCells({
|
||||
icon: line ? "〰" : "●", color: file.color || (line ? "var(--route-driven)" : "#12bedf"), name: file.name,
|
||||
meta: file.layer ? "layer" : (file.kinds || []).join(", "), show: shown ? "all" : "none",
|
||||
onOpen: async () => {
|
||||
if (!ctx.gpxPanel?.isShown(file.path)) await toggleShown([file.path], true);
|
||||
ctx.gpxPanel?.zoomTo(file.path);
|
||||
},
|
||||
onEye: () => toggleShown([file.path], !shown),
|
||||
});
|
||||
}));
|
||||
if (!folder.children.length) list.append(emptyRow("Nothing here yet."));
|
||||
const paths = filesUnder(cwd).map((f) => f.path);
|
||||
foot.textContent = `${paths.filter((p) => ctx.gpxPanel?.isShown(p)).length} of ${paths.length} shown`;
|
||||
};
|
||||
|
||||
function render() {
|
||||
if (el.hidden) return;
|
||||
if (scope === "folder") {
|
||||
const name = lib().folders.get(cwd)?.name;
|
||||
const parent = cwd.includes("/") ? cwd.slice(0, cwd.lastIndexOf("/")) : "";
|
||||
bar.innerHTML = "";
|
||||
const up = cellButton("up", "←", "Up a level", () => { cwd = parent; render(); });
|
||||
up.disabled = !cwd;
|
||||
const path = Object.assign(document.createElement("div"), { className: "drive-panel__cell drive-points__path" });
|
||||
path.innerHTML = `<small class="drive-cell__label">${escapeHtml(parent ? `${parent.replaceAll("/", " › ")} ›` : cwd ? "Library ›" : "")}</small><b>${escapeHtml(cwd ? name : "Library")}</b>`;
|
||||
const nearest = cellButton("mode", `<span class="drive-key__icon">◎</span><span class="drive-key__label">Nearest</span>`, "Nearest the car", () => { scope = "near"; fetchNear(); });
|
||||
bar.append(up, path, nearest);
|
||||
el.querySelector(".drive-panel__note").textContent = "folders";
|
||||
renderFolder();
|
||||
} else {
|
||||
bar.replaceChildren(...[["near", "Near the car"], ["ahead", "Ahead"], ["shown", "Shown"]].map(([id, label]) => {
|
||||
const chip = cellButton("scope", label, label, () => { scope = id; render(); });
|
||||
chip.setAttribute("aria-pressed", String(scope === id));
|
||||
return chip;
|
||||
}), cellButton("mode", `<span class="drive-key__icon">▣</span><span class="drive-key__label">Folders</span>`, "Folders", () => { scope = "folder"; input.value = ""; render(); }));
|
||||
el.querySelector(".drive-panel__note").textContent = input.value.trim() ? `“${input.value.trim()}”` : "near the car";
|
||||
renderNear();
|
||||
}
|
||||
}
|
||||
|
||||
el.querySelector(".drive-panel__close").addEventListener("click", ctx.close);
|
||||
el.querySelector('[data-action="hide-all"]').addEventListener("click", () => {
|
||||
const shown = [...lib().files.keys()].filter((p) => ctx.gpxPanel?.isShown(p));
|
||||
toggleShown(shown, false);
|
||||
});
|
||||
return {
|
||||
el,
|
||||
render,
|
||||
opened: () => { if (scope !== "folder") fetchNear(); else render(); },
|
||||
};
|
||||
}
|
||||
|
||||
// Layers: the On the map panel's items cut to the road — presets that turn
|
||||
// a set on at once (+ Keep saves what's on into one), the map Online |
|
||||
// Offline, an eye per layer, the ones on first (sorted when the menu opens,
|
||||
// not while tapping). The switches are the On the map panel's own
|
||||
// checkboxes, so everything they do (restore, offline checks) stays theirs.
|
||||
export function layersMenu(ctx) {
|
||||
const el = panel("drive-layers", "Layers", `
|
||||
<div class="drive-layers__presets"></div>
|
||||
<div class="drive-panel__cell drive-layers__map"><small class="drive-cell__label">Map</small><span>offline by itself, no signal</span></div>
|
||||
<div class="drive-layers__source"></div>
|
||||
<div class="drive-panel__list drive-layers__list"></div>
|
||||
<div class="drive-panel__foot"></div>
|
||||
<button type="button" class="drive-panel__wide" data-action="all-off">All off</button>`);
|
||||
const list = el.querySelector(".drive-layers__list");
|
||||
let order = [];
|
||||
let keeping = false;
|
||||
|
||||
const loadPresets = () => {
|
||||
try { return { ...DEFAULT_PRESETS, ...JSON.parse(localStorage.getItem(PRESETS_KEY)) }; } catch { return { ...DEFAULT_PRESETS }; }
|
||||
};
|
||||
// The On the map items that can be switched here: [name, group, icon, checkbox].
|
||||
const layers = () => [...document.querySelectorAll("#overlays-panel .overlays-panel__item")].flatMap((li) => {
|
||||
const toggle = li.querySelector(".overlays-panel__toggle");
|
||||
const name = li.querySelector(".overlays-panel__name, label")?.textContent.trim();
|
||||
const hidden = toggle?.closest("[hidden]");
|
||||
if (!toggle || !name || SKIP_LAYERS.has(name) || toggle.disabled || (hidden && li.contains(hidden))) return [];
|
||||
let group = li.previousElementSibling;
|
||||
while (group && !group.classList.contains("overlays-panel__group")) group = group.previousElementSibling;
|
||||
return [{ name, group: group?.textContent.trim() || "", icon: li.querySelector(".overlays-panel__icon")?.innerHTML || "", toggle }];
|
||||
});
|
||||
const set = (layer, on) => { if (layer.toggle.checked !== on) layer.toggle.click(); };
|
||||
const presetOn = (presets) => {
|
||||
const on = layers().filter((l) => l.toggle.checked).map((l) => l.name).sort().join("|");
|
||||
return PRESETS.find(([id]) => [...presets[id]].filter((n) => layers().some((l) => l.name === n)).sort().join("|") === on)?.[0];
|
||||
};
|
||||
|
||||
function render() {
|
||||
if (el.hidden) return;
|
||||
const presets = loadPresets();
|
||||
const current = presetOn(presets);
|
||||
el.querySelector(".drive-layers__presets").replaceChildren(...PRESETS.map(([id, icon, label]) => {
|
||||
const b = cellButton("preset", `<span class="drive-key__icon">${icon}</span><span class="drive-key__label">${keeping ? `Save as ${label}` : label}</span>`, label, () => {
|
||||
if (keeping) {
|
||||
presets[id] = layers().filter((l) => l.toggle.checked).map((l) => l.name);
|
||||
try { localStorage.setItem(PRESETS_KEY, JSON.stringify(presets)); } catch { /* private window: not kept */ }
|
||||
keeping = false;
|
||||
} else {
|
||||
for (const layer of layers()) set(layer, presets[id].includes(layer.name));
|
||||
}
|
||||
render();
|
||||
});
|
||||
b.setAttribute("aria-pressed", String(!keeping && current === id));
|
||||
return b;
|
||||
}), (() => {
|
||||
const keep = cellButton("mode", `<span class="drive-key__icon">${keeping ? "✕" : "+"}</span><span class="drive-key__label">${keeping ? "Cancel" : "Keep"}</span>`,
|
||||
keeping ? "Cancel" : "Keep what is on as a preset", () => { keeping = !keeping; render(); });
|
||||
keep.setAttribute("aria-pressed", String(keeping));
|
||||
return keep;
|
||||
})());
|
||||
// the map: the On the map panel's own Online / Offline buttons
|
||||
const options = [...document.querySelectorAll(".onthemap-map .basemap-panel__option")];
|
||||
const sourcesHidden = !!document.querySelector(".onthemap-map .basemap-panel__sources")?.hidden;
|
||||
el.querySelector(".drive-layers__source").replaceChildren(...options.map((option) => {
|
||||
const b = cellButton("scope", option.textContent, `Map: ${option.textContent}`, () => { option.click(); render(); });
|
||||
b.setAttribute("aria-pressed", String(option.classList.contains("active")));
|
||||
b.disabled = sourcesHidden;
|
||||
return b;
|
||||
}));
|
||||
const all = layers();
|
||||
const byName = new Map(all.map((l) => [l.name, l]));
|
||||
const rows = order.map((n) => byName.get(n)).filter(Boolean);
|
||||
list.replaceChildren(...rows.flatMap((layer) => {
|
||||
const on = layer.toggle.checked;
|
||||
const text = Object.assign(document.createElement("div"), { className: "drive-panel__cell drive-layers__item" });
|
||||
text.innerHTML = `<span class="drive-layers__icon" aria-hidden="true">${layer.icon}</span><span class="drive-panel__text"><b>${escapeHtml(layer.name)}</b><small>${escapeHtml(layer.group)}</small></span>`;
|
||||
const eye = cellButton("eye", on ? "●" : "○", `${on ? "Hide" : "Show"} ${layer.name}`, () => { set(layer, !on); render(); });
|
||||
eye.setAttribute("aria-pressed", String(on));
|
||||
eye.classList.toggle("active", on);
|
||||
return [text, eye];
|
||||
}));
|
||||
if (!rows.length) list.append(emptyRow("No layers to switch here."));
|
||||
const onCount = all.filter((l) => l.toggle.checked).length;
|
||||
el.querySelector(".drive-panel__note").textContent = `${current ? PRESETS.find(([id]) => id === current)[2] : "by hand"} · ${onCount} on`;
|
||||
el.querySelector(".drive-panel__foot").textContent = `${onCount} on · ${all.length - onCount} off`;
|
||||
}
|
||||
|
||||
el.querySelector(".drive-panel__close").addEventListener("click", ctx.close);
|
||||
el.querySelector('[data-action="all-off"]').addEventListener("click", () => {
|
||||
for (const layer of layers()) set(layer, false);
|
||||
render();
|
||||
});
|
||||
return {
|
||||
el,
|
||||
render,
|
||||
opened: () => {
|
||||
keeping = false;
|
||||
const all = layers();
|
||||
order = [...all.filter((l) => l.toggle.checked), ...all.filter((l) => !l.toggle.checked)].map((l) => l.name);
|
||||
render();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// The elevation of the next `km` along the route, from its sampled profile
|
||||
// (route.js's elevationProfile): the grid's elevation cell, the Terrain view's.
|
||||
export function elevationHtml(route, atKm, km) {
|
||||
const windowM = km * 1000;
|
||||
const at = (atKm ?? 0) * 1000;
|
||||
const points = (route?.elevation?.profile || []).filter((p) => p.distance_meters >= at - 50 && p.distance_meters <= at + windowM);
|
||||
const label = `<span class="drive-cell__label">Elevation · the next ${km} km</span>`;
|
||||
if (points.length < 2) return `${label}<span class="drive-cell__muted">${route ? "Reading the terrain…" : "No route"}</span>`;
|
||||
const heights = points.map((p) => p.elevation_meters);
|
||||
const [low, high] = [Math.min(...heights), Math.max(...heights)];
|
||||
const x = (p) => (((p.distance_meters - at) / windowM) * 200).toFixed(1);
|
||||
const y = (h) => (95 - ((h - low) / (high - low || 1)) * 85).toFixed(1);
|
||||
const line = points.map((p, i) => `${i ? "L" : "M"}${x(p)} ${y(p.elevation_meters)}`).join(" ");
|
||||
const climb = heights.reduce((sum, h, i) => sum + (i && h > heights[i - 1] ? h - heights[i - 1] : 0), 0);
|
||||
const top = points[heights.indexOf(high)];
|
||||
return `${label}<svg class="drive-elevation" viewBox="0 0 200 100" preserveAspectRatio="none" role="img" aria-label="Elevation ahead">
|
||||
<path class="drive-elevation__area" d="${line} L${x(points.at(-1))} 100 L${x(points[0])} 100 Z"/>
|
||||
<path class="drive-elevation__line" d="${line}"/>
|
||||
<line class="drive-elevation__here" x1="0" y1="0" x2="0" y2="100"/>
|
||||
</svg>
|
||||
<span class="drive-cell__value drive-cell__value--mid">↑ ${Math.round(climb)} m <small>${Math.round(heights[0])} → ${Math.round(heights.at(-1))} m · top ${Math.round(high)} m in ${distance(Math.max(0, top.distance_meters - at))}</small></span>`;
|
||||
}
|
||||
|
||||
// Terrain (the canvas' GridTerrain): off-road only — roll (a rear view) and
|
||||
// pitch (a side view) on dials, amber past WARN and red past 1.5× (as
|
||||
// dashboard.js), the maximum held until Reset; heading, the climb and the
|
||||
// side slope ahead from the DEM along the course; the route's elevation of
|
||||
// the next 2 km; Level here = can.json's levelling action (SDO, as /can.html).
|
||||
// ctx: as Points', plus state() (the dashboard's) and settings().
|
||||
const WARN = { roll: 20, pitch: 25 };
|
||||
const DIAL_MAX = 45;
|
||||
const CLIMB_M = 300; // the climb ahead over this far
|
||||
const ACROSS_AT_M = 50; // the side slope this far ahead, over ±ACROSS_HALF_M
|
||||
const ACROSS_HALF_M = 15;
|
||||
const AHEAD_EVERY_MS = 2000; // DEM lookups at most this often
|
||||
const CARDINALS = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
|
||||
const CAR_REAR = "M-46 30 L-46 -4 L-34 -34 L34 -34 L46 -4 L46 30 Z M-50 30 h22 v12 h-22 Z M28 30 h22 v12 h-22 Z";
|
||||
const CAR_SIDE = "M-62 26 L-62 -2 L-30 -6 L-18 -30 L40 -30 L52 -4 L62 -2 L62 26 Z";
|
||||
const dialPoint = (a) => { const r = ((a - 90) * Math.PI) / 180; return `${(120 * Math.cos(r)).toFixed(1)} ${(30 + 120 * Math.sin(r)).toFixed(1)}`; };
|
||||
const arc = (a, b, cls) => `<path class="${cls}" d="M${dialPoint(a)} A120 120 0 0 1 ${dialPoint(b)}"/>`;
|
||||
const severity = (key, v) => (v == null ? "" : Math.abs(v) >= WARN[key] * 1.5 ? "drive-cell--warn" : Math.abs(v) >= WARN[key] ? "drive-terrain--caution" : "");
|
||||
// a point `m` meters from [lon, lat] towards `bearing`
|
||||
const offset = ([lon, lat], bearing, m) => [lon + (m * Math.sin(bearing * RAD)) / (111320 * Math.cos(lat * RAD)), lat + (m * Math.cos(bearing * RAD)) / 111320];
|
||||
|
||||
export function terrainMenu(ctx) {
|
||||
const el = panel("drive-terrain", "Terrain", `
|
||||
<div class="drive-panel__cell drive-terrain__dial" data-key="roll"></div>
|
||||
<div class="drive-panel__cell drive-terrain__dial" data-key="pitch"></div>
|
||||
<div class="drive-panel__cell drive-terrain__field" data-field="heading"></div>
|
||||
<div class="drive-panel__cell drive-terrain__field" data-field="climb"></div>
|
||||
<div class="drive-panel__cell drive-terrain__field" data-field="across"></div>
|
||||
<div class="drive-panel__cell drive-terrain__elevation"></div>
|
||||
<button type="button" class="drive-terrain__level" data-action="level">Level here (zero)</button>
|
||||
<button type="button" class="drive-terrain__reset" data-action="reset">Reset max</button>
|
||||
<button type="button" class="drive-terrain__road" data-action="road">Road view</button>`);
|
||||
let peak = { roll: null, pitch: null };
|
||||
let ahead = { climb: null, across: null };
|
||||
let aheadAt = 0;
|
||||
let armed = null; // Level here asks for a second tap
|
||||
const offline = fetch("/api/terrain-tiles").then((r) => r.json()).then((d) => !!d.available).catch(() => false);
|
||||
|
||||
// The climb and the side slope ahead, from the DEM along the course.
|
||||
const lookAhead = async (position, course) => {
|
||||
if (Date.now() - aheadAt < AHEAD_EVERY_MS || !position || course == null) return;
|
||||
aheadAt = Date.now();
|
||||
const off = await offline;
|
||||
const at = ([lon, lat]) => elevationAt(lon, lat, off, { zoom: 12, smooth: true });
|
||||
const front = offset(position, course, ACROSS_AT_M);
|
||||
const [here, far, left, right] = await Promise.all([at(position), at(offset(position, course, CLIMB_M)),
|
||||
at(offset(front, course - 90, ACROSS_HALF_M)), at(offset(front, course + 90, ACROSS_HALF_M))]);
|
||||
ahead = {
|
||||
climb: here != null && far != null ? ((far - here) / CLIMB_M) * 100 : null,
|
||||
across: left != null && right != null ? Math.atan((left - right) / (2 * ACROSS_HALF_M)) / RAD : null,
|
||||
};
|
||||
};
|
||||
|
||||
const dial = (key, value) => {
|
||||
const w = WARN[key];
|
||||
const angle = value == null ? 0 : key === "pitch" ? -value : value; // the side view faces right: nose up = counter-clockwise
|
||||
const p = peak[key];
|
||||
const mark = p == null ? "" : `<path class="drive-terrain__peak" d="M${dialPoint(Math.max(-DIAL_MAX, Math.min(DIAL_MAX, key === "pitch" ? -p : p)))} l-6 -12 h12 Z"/>`;
|
||||
const sign = (v) => (v > 0 ? "+" : v < 0 ? "−" : "");
|
||||
return `<svg class="drive-terrain__svg ${severity(key, value)}" viewBox="-135 -120 270 190" role="img" aria-label="${key} ${value == null ? "unknown" : `${Math.round(value)}°`}">
|
||||
${arc(-w, w, "drive-terrain__ok")}${arc(-w * 1.5, -w, "drive-terrain__amber")}${arc(w, w * 1.5, "drive-terrain__amber")}
|
||||
${arc(-DIAL_MAX, -w * 1.5, "drive-terrain__red")}${arc(w * 1.5, DIAL_MAX, "drive-terrain__red")}
|
||||
<line class="drive-terrain__ground" x1="-130" y1="30" x2="130" y2="30"/>
|
||||
<g transform="rotate(${angle} 0 30)"><line class="drive-terrain__mast" x1="0" y1="30" x2="0" y2="-100"/><path class="drive-terrain__car" d="${key === "roll" ? CAR_REAR : CAR_SIDE}"/></g>${mark}
|
||||
</svg>
|
||||
<span class="drive-terrain__value ${severity(key, value)}">${value == null ? "—" : `${sign(Math.round(value))}${Math.abs(Math.round(value))}°`}</span>
|
||||
<span class="drive-cell__label">${key} · max ${p == null ? "—" : `${Math.abs(Math.round(p))}°`}</span>`;
|
||||
};
|
||||
const field = (name, label, value, unit, cls = "") =>
|
||||
(el.querySelector(`[data-field="${name}"]`).innerHTML = `<span class="drive-cell__label">${label}</span><span class="drive-cell__value drive-cell__value--mid ${cls}">${value} <small>${unit}</small></span>`);
|
||||
|
||||
function render() {
|
||||
if (el.hidden) return;
|
||||
const dash = ctx.state();
|
||||
const v = dash?.values || {};
|
||||
for (const key of ["roll", "pitch"]) {
|
||||
if (v[key] != null && (peak[key] == null || Math.abs(v[key]) > Math.abs(peak[key]))) peak[key] = v[key];
|
||||
el.querySelector(`[data-key="${key}"]`).innerHTML = dial(key, v[key]);
|
||||
}
|
||||
const h = dash?.heading;
|
||||
const deg = h ? Math.round(h.deg) % 360 : null;
|
||||
field("heading", "Heading", deg == null ? "—" : `${String(deg).padStart(3, "0")}°`, deg == null ? "" : CARDINALS[Math.round(deg / 45) % 8]);
|
||||
const climb = ahead.climb;
|
||||
field("climb", "Climb ahead", climb == null ? "—" : `${Math.round(climb)} %`, `in ${CLIMB_M} m`, climb != null && Math.abs(climb) >= 15 ? "drive-terrain--caution" : "");
|
||||
field("across", "Across ahead", ahead.across == null ? "—" : `${Math.abs(Math.round(ahead.across))}°`, "side slope, DEM", severity("roll", ahead.across));
|
||||
el.querySelector(".drive-terrain__elevation").innerHTML = elevationHtml(ctx.route(), ctx.atKm(), 2);
|
||||
const source = dash?.simulated ? "from the terrain (simulation)" : v.roll != null || v.pitch != null ? "IMU" : "no tilt signal";
|
||||
el.querySelector(".drive-panel__note").textContent = [source, dash?.surface?.replaceAll("_", " ")].filter(Boolean).join(" · ");
|
||||
const level = el.querySelector('[data-action="level"]');
|
||||
const action = (dash?.actions || []).findIndex((a) => /level/i.test(a.name));
|
||||
level.disabled = action < 0;
|
||||
level.title = action < 0 ? "No levelling action in can.json" : "Zero roll and pitch here (the node's SDO)";
|
||||
level.textContent = armed ? "Tap again to level" : "Level here (zero)";
|
||||
level.classList.toggle("drive-terrain__level--armed", !!armed);
|
||||
const position = v.lon != null && v.lat != null ? [v.lon, v.lat] : null;
|
||||
lookAhead(position, dash?.course ?? h?.deg).then(() => {}, () => {});
|
||||
}
|
||||
|
||||
el.querySelector(".drive-panel__close").addEventListener("click", ctx.close);
|
||||
el.querySelector('[data-action="road"]').addEventListener("click", ctx.close);
|
||||
el.querySelector('[data-action="reset"]').addEventListener("click", () => { peak = { roll: null, pitch: null }; render(); });
|
||||
el.querySelector('[data-action="level"]').addEventListener("click", async () => {
|
||||
if (!armed) {
|
||||
armed = setTimeout(() => { armed = null; render(); }, 3000);
|
||||
return render();
|
||||
}
|
||||
clearTimeout(armed);
|
||||
armed = null;
|
||||
const n = (ctx.state()?.actions || []).findIndex((a) => /level/i.test(a.name));
|
||||
const response = await fetch(`/api/can/actions/${n}`, { method: "POST" }).catch(() => null);
|
||||
el.querySelector('[data-action="level"]').textContent = response?.ok ? "Levelled ✓" : "Levelling failed";
|
||||
if (response?.ok) peak = { roll: null, pitch: null };
|
||||
});
|
||||
return { el, render, opened: render };
|
||||
}
|
||||
+409
-119
@@ -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) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[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");
|
||||
|
||||
@@ -705,6 +705,26 @@ export class GpxPanelControl {
|
||||
this._renderView();
|
||||
}
|
||||
|
||||
// For the driving grid's Points (driving.js): the tree as indexed by
|
||||
// _renderTree, whether a node is shown, and showing / hiding nodes.
|
||||
libraryTree() {
|
||||
return { folders: this._folders || new Map(), files: this._files || new Map(), filesUnder: (path) => this._filesUnder(path) };
|
||||
}
|
||||
|
||||
isShown(path) {
|
||||
return this._visible.has(path);
|
||||
}
|
||||
|
||||
async setShown(paths, visible) {
|
||||
await Promise.all(paths.map((path) => this._toggleFileOnly(path, visible)));
|
||||
this._saveVisible();
|
||||
this._renderView();
|
||||
}
|
||||
|
||||
zoomTo(path) {
|
||||
return this._zoomTo(path);
|
||||
}
|
||||
|
||||
// Search result picked: show its file, then open the matching point's
|
||||
// popup as if it had been clicked on the map. Matched by exact
|
||||
// coordinates (the search index reads the same GeoJSON); a track/line
|
||||
|
||||
+1
-1
@@ -505,7 +505,7 @@ if (isLoggedIn()) new PluginsControl(map).mount(sidebar);
|
||||
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label"></div>`);
|
||||
const routePanel = new RoutePanelControl(map, gnssControl, profilePanel);
|
||||
routePanel.mount(sidebar);
|
||||
setupDriving(map, nightButton, routePanel);
|
||||
setupDriving(map, nightButton, routePanel, gpxPanel);
|
||||
new OfflineDataControl().mount(sidebar);
|
||||
|
||||
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label"></div>`);
|
||||
|
||||
Reference in new issue
Block a user