// 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;
}
// A hardware key for a button: pressed, it clicks it; its label in the corner (driving.js, the keys)
export function bindKey(el, key) {
el.dataset.key = key;
el.dataset.label = key === "-" ? "−" : key.length === 1 ? key.toUpperCase() : key;
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 = `
${label}
${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", `
`);
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", `${icon}${escapeHtml(name)}${escapeHtml(meta)}` +
`${escapeHtml(away || "")}`, "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 = `${escapeHtml(parent ? `${parent.replaceAll("/", " › ")} ›` : cwd ? "Library ›" : "")}${escapeHtml(cwd ? name : "Library")}`;
const nearest = cellButton("mode", `◎Nearest`, "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], i) => {
const chip = bindKey(cellButton("scope", label, label, () => { scope = id; render(); }), String(i + 1));
chip.setAttribute("aria-pressed", String(scope === id));
return chip;
}), cellButton("mode", `▣Folders`, "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", `
Mapoffline by itself, no signal
`);
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], i) => {
const b = cellButton("preset", `${icon}${keeping ? `Save as ${label}` : label}`, 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 bindKey(b, String(i + 1));
}), (() => {
const keep = cellButton("mode", `${keeping ? "✕" : "+"}${keeping ? "Cancel" : "Keep"}`,
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 = `${layer.icon}${escapeHtml(layer.name)}${escapeHtml(layer.group)}`;
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 = `Elevation · the next ${km} km`;
if (points.length < 2) return `${label}${route ? "Reading the terrain…" : "No route"}`;
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}
↑ ${Math.round(climb)} m ${Math.round(heights[0])} → ${Math.round(heights.at(-1))} m · top ${Math.round(high)} m in ${distance(Math.max(0, top.distance_meters - at))}`;
}
// 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) => ``;
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", `
`);
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 ? "" : ``;
const sign = (v) => (v > 0 ? "+" : v < 0 ? "−" : "");
return `
${value == null ? "—" : `${sign(Math.round(value))}${Math.abs(Math.round(value))}°`}${key} · max ${p == null ? "—" : `${Math.abs(Math.round(p))}°`}`;
};
const field = (name, label, value, unit, cls = "") =>
(el.querySelector(`[data-field="${name}"]`).innerHTML = `${label}${value} ${unit}`);
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 };
}