250 lines
12 KiB
JavaScript
250 lines
12 KiB
JavaScript
import { LngLatBounds } 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";
|
||
|
||
// 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).
|
||
const KEY = "drivingMode";
|
||
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 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 escapeHtml = (text) => String(text).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
||
|
||
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.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 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";
|
||
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>`;
|
||
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.
|
||
const input = tripPanel.querySelector(".drive-trip__search input");
|
||
let results = null;
|
||
let searchTimer = null;
|
||
let searchSeq = 0;
|
||
input.addEventListener("input", () => {
|
||
clearTimeout(searchTimer);
|
||
if (!input.value.trim()) {
|
||
results = null;
|
||
return renderTrip();
|
||
}
|
||
searchTimer = setTimeout(async () => {
|
||
const mine = ++searchSeq;
|
||
const { lng, lat } = map.getCenter();
|
||
const url = new URL("/api/search", window.location.origin);
|
||
url.search = new URLSearchParams({ q: input.value, sources: "layers,places", lat, lng });
|
||
let found = [];
|
||
try { found = (await (await fetch(url)).json()).results; } catch { /* offline for a moment: nothing */ }
|
||
if (mine !== searchSeq) return;
|
||
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();
|
||
}, SEARCH_DELAY_MS);
|
||
});
|
||
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
|
||
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>`;
|
||
};
|
||
const renderTrip = () => {
|
||
if (tripPanel.hidden || !routePanel) return;
|
||
if (results) return renderResults(tripPanel.querySelector(".drive-trip__stops"));
|
||
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));
|
||
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));
|
||
up.disabled = i === 0;
|
||
down.disabled = i === stops.length - 1;
|
||
li.append(name, done, up, down, drop);
|
||
return li;
|
||
}));
|
||
if (!stops.length) list.innerHTML = `<li class="drive-trip__empty">No stops yet — pan the map to a place and add it.</li>`;
|
||
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();
|
||
}
|
||
}
|
||
tripPanel.querySelector(".drive-trip__close").addEventListener("click", () => openTrip(false));
|
||
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);
|
||
|
||
// 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");
|
||
let log = null;
|
||
let driven = [];
|
||
const drawDriven = () => {
|
||
const data = { type: "Feature", geometry: { type: "LineString", coordinates: driven }, properties: {} };
|
||
const source = map.getSource(DRIVEN_SOURCE);
|
||
if (source) return source.setData(data);
|
||
if (!map.isStyleLoaded()) return;
|
||
map.addSource(DRIVEN_SOURCE, { type: "geojson", data });
|
||
map.addLayer({ id: DRIVEN_SOURCE, type: "line", source: DRIVEN_SOURCE, layout: { "line-cap": "round", "line-join": "round" },
|
||
paint: { "line-color": getComputedStyle(document.documentElement).getPropertyValue("--route-driven").trim() || "#c2410c", "line-width": 4 } });
|
||
};
|
||
map.on("style.load", () => driven.length && drawDriven());
|
||
const refreshLog = async () => {
|
||
try {
|
||
const response = await fetch(`/api/trip/log?since=${driven.length}`, { cache: "no-store" });
|
||
if (response.ok) {
|
||
log = await response.json();
|
||
if (!log.active) driven = [];
|
||
else driven = driven.concat(log.coordinates || []);
|
||
drawDriven();
|
||
}
|
||
} catch { /* offline for a moment: the next poll */ }
|
||
renderLog();
|
||
};
|
||
const pollLog = async () => {
|
||
await refreshLog();
|
||
setTimeout(pollLog, LOG_POLL_MS);
|
||
};
|
||
const renderLog = () => {
|
||
logButton.textContent = log?.active ? "End the trip" : "Start the trip (record it)";
|
||
logButton.classList.toggle("drive-trip__log--on", !!log?.active);
|
||
logState.textContent = log?.active ? `● ${log.folder.replace(/^Trips\//, "")} · ${(log.distance_m / 1000).toFixed(1)} km` : "";
|
||
};
|
||
logButton.addEventListener("click", async () => {
|
||
if (log?.active) {
|
||
if (!window.confirm(`End the trip "${log.folder}"? Its track stays in the library.`)) return;
|
||
await fetch("/api/trip/log", { method: "DELETE" });
|
||
} else {
|
||
const ends = routePanel?.stops().at(-1)?.name || "";
|
||
const name = window.prompt("The trip's name:", ends);
|
||
if (name === null) return;
|
||
const response = await fetch("/api/trip/log", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }) });
|
||
if (!response.ok) window.alert((await response.json().catch(() => ({}))).error || `HTTP ${response.status}`);
|
||
}
|
||
driven = [];
|
||
refreshLog();
|
||
});
|
||
if (isLoggedIn()) pollLog();
|
||
else 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);
|
||
|
||
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);
|
||
};
|
||
map.on("pitchend", render);
|
||
onRouteChanged(render);
|
||
setInterval(render, CHECK_MS);
|
||
|
||
function set(on) {
|
||
if (!on) openTrip(false);
|
||
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 */ }
|
||
render();
|
||
map.resize(); // the sidebar came or went
|
||
}
|
||
toggle.addEventListener("click", () => set(bar.hidden));
|
||
let saved = null;
|
||
try { saved = localStorage.getItem(KEY); } catch { /* nothing kept */ }
|
||
set(saved === "on");
|
||
}
|