198 lines
9.6 KiB
JavaScript
198 lines
9.6 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";
|
||
|
||
// 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 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__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;
|
||
const visibleCenter = () => {
|
||
const { clientWidth: w, clientHeight: h } = map.getContainer();
|
||
return [(w - tripPanel.offsetWidth) / 2, h / 2];
|
||
};
|
||
const placeCrosshair = () => {
|
||
const [x, y] = visibleCenter();
|
||
crosshair.style.left = `${x}px`;
|
||
crosshair.style.top = `${y}px`;
|
||
};
|
||
// 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.unproject(visibleCenter());
|
||
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), padding: { right: tripPanel.offsetWidth } });
|
||
};
|
||
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();
|
||
placeCrosshair();
|
||
}
|
||
}
|
||
tripPanel.querySelector(".drive-trip__close").addEventListener("click", () => openTrip(false));
|
||
tripPanel.querySelector('[data-action="add"]').addEventListener("click", () => {
|
||
const { lng, lat } = map.unproject(visibleCenter());
|
||
routePanel?.addStop([lng, lat]);
|
||
});
|
||
tripPanel.querySelector('[data-action="start"]').addEventListener("click", () => routePanel?.startHere());
|
||
routePanel?.onStopsChanged(renderTrip);
|
||
window.addEventListener("resize", placeCrosshair);
|
||
map.getContainer().append(bar, recenter, tripPanel, crosshair);
|
||
|
||
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");
|
||
}
|