Driving menu Trip: the stops as big rows (look, ✓ passed, ↑ ↓, ✕), a stop at the crosshair, the start at the car, search of saved points and offline places; each leg's km and time (legs_s) and the total, in the route panel too; passed stops kept (not routed, dimmed, editable) — a reroute marks them instead of dropping them; /status.html: every status endpoint full width (the debug panel links it); the trip-as-plan-and-log model and planned-vs-driven colors in docs/TODO
CI / check (push) Successful in 22s
CI / deploy (push) Successful in 17s

This commit is contained in:
randy committed 2026-12-01 02:21:14 +01:00
1 parent 0eb9d05cdc
commit 809e88ab1a
14 files changed
+517 -101

No files matched your search

+26
View File
@@ -98,6 +98,30 @@ plan from — the server does the heavy lifting. The UI is built for a mouse tod
(zoom ±, view, overview), Follow and "Back to the position" one button shown only when not (zoom ±, view, overview), Follow and "Back to the position" one button shown only when not
following, 76×76 px; night and exit off the bar following, 76×76 px; night and exit off the bar
** [ ] Softkeys: the CAN keypad's labels on the screen edge next to its keys (G1000 style) ** [ ] Softkeys: the CAN keypad's labels on the screen edge next to its keys (G1000 style)
** [x] Driving menu, Trip: the stops as 76 px rows (tap to look, ↑ ↓ ✕), a stop at the
crosshair, the start moved to the car (`driving.js`, `RoutePanelControl#stops` & co.)
Then: search (saved points + offline places, nearest the crosshair first, + adds), each
leg's km and time and the total; passed stops dimmed and still editable — a reroute marks
them `passed` (kept in the trip, not routed) instead of dropping them, ✓ marks one by
hand (a stop missed out: add it, move it up with ↑, ✓)
** [ ] The trip as plan + log (2026-12-01): start → the server records the trip log (GNSS,
no screen needed) → stops added on or off the route (on foot: not routed, still the
trip's) → end → one library item: the planned route, the driven track, the points with
their visit times. A point's two properties apart: routed or not, and planned / visited
(at) / skipped — `passed` splits into them; visited by the track passing near or by hand
The car's GNSS stays in the car: on foot the log is the car standing. The walk from
whatever else carried a position — a Garmin LiveTrack session (already in), the MQTT
tracker, a LoRa/Meshtastic node later — or the watch's FIT imported afterwards (the
library reads FIT); else just the point, visited by hand
** [ ] Colors: planned vs really driven — the planned route (magenta ahead, the part behind
thin and dashed) and the recorded track solid on top (`--route-driven`), docs/design.adoc
** [ ] The menu while driving: showing routes and points, editing the trip — all of it on the
road, so simple: a few big tiles (Trip, Points, Layers, Search), one level deep, rows
≥ 76 px, a handful per screen, the action a big button (add a stop here / at a point,
skip the next one, move one up/down, show / hide a layer) — no drag, no hover, no small
text fields. Who: the navigator (co-driver) runs the whole UI and the trip's points on the
16" display; the driver only looks at a finished map on Android Auto, touching the 16"
only now and then — so it's simple for a moving car, not driver-distraction rules
* [x] Night mode — topbar button cycles auto (sun below the horizon at the map center) / on / off. The map has its own night palette (`NightMap` in `public/js/map_themes.js`, switched live with setPaintProperty): dark blue-gray ground, roads a step lighter, muted ochre motorways, light-gray labels on dark halos; raster overlays dimmed, our own track/point colors kept * [x] Night mode — topbar button cycles auto (sun below the horizon at the map center) / on / off. The map has its own night palette (`NightMap` in `public/js/map_themes.js`, switched live with setPaintProperty): dark blue-gray ground, roads a step lighter, muted ochre motorways, light-gray labels on dark halos; raster overlays dimmed, our own track/point colors kept
** [x] The rest of the UI is still one invert+dim filter — CSS color tokens and a real dark set instead ** [x] The rest of the UI is still one invert+dim filter — CSS color tokens and a real dark set instead
* [x] Tracker as a top-down vehicle (car / motorbike / bicycle from its icon) rotated by the GNSS course, kept while standing still; "Navigate" (tracker card or Overlays status) follows it heading-up, tilted 60°, vehicle in the lower third — panning by hand ends it * [x] Tracker as a top-down vehicle (car / motorbike / bicycle from its icon) rotated by the GNSS course, kept while standing still; "Navigate" (tracker card or Overlays status) follows it heading-up, tilted 60°, vehicle in the lower third — panning by hand ends it
@@ -400,3 +424,5 @@ already offline work on the road. The Pi only serves; heavy builds stay on brick
* [ ] Expose the build log via an API endpoint, not just embedded in the admin page * [ ] Expose the build log via an API endpoint, not just embedded in the admin page
* [ ] Document all API endpoints somewhere and make them easy to browse (status of each) — * [ ] Document all API endpoints somewhere and make them easy to browse (status of each) —
maybe a status page, login-gated maybe a status page, login-gated
** [x] The status page: `/status.html`, every read-only status endpoint's JSON, full width,
refreshed every 5 s, filter and pause (the Status / debug panel links it)
+5
View File
@@ -496,6 +496,11 @@ module Maptool
erb :symbols, layout: false erb :symbols, layout: false
end end
# Every status endpoint on one full-screen page (they need the login).
get "/status.html" do
erb :status, layout: false
end
# CANopen diagnostics (polls GET /api/can, which needs the login). # CANopen diagnostics (polls GET /api/can, which needs the login).
get "/can.html" do get "/can.html" do
erb :can, layout: false erb :can, layout: false
+6
View File
@@ -253,6 +253,12 @@ route panel, NPS maps, the offline data panel
The route line is the bridge: blue (`--route-planned`) while planning, The route line is the bridge: blue (`--route-planned`) while planning,
magenta (`--route-active`) once it's being navigated. magenta (`--route-active`) once it's being navigated.
On a trip with its log recording, two lines, never mixed up: *planned*
(the route — blue while planning, magenta ahead while navigated, the
planned part behind thin and dashed so a detour shows) and *really driven*
(the recorded track, `--route-driven`, solid, on top). Shape tells them
apart as well as color (S-52's second cue): dashed planned, solid driven.
Sources: IHO S-52 Edition 6.1.1 (2015), sections 2.2.6, 4.2; the avionics Sources: IHO S-52 Edition 6.1.1 (2015), sections 2.2.6, 4.2; the avionics
color meanings are the common glass-cockpit convention (FAA AC 25-11B has color meanings are the common glass-cockpit convention (FAA AC 25-11B has
the color coding guidance, §5.3 — not checked here, its PDF refused the the color coding guidance, §5.3 — not checked here, its PDF refused the
+1
View File
@@ -255,6 +255,7 @@ module Maptool
time_s: data["trip"]["summary"]["time"], countries: along[:countries], time_s: data["trip"]["summary"]["time"], countries: along[:countries],
speed_limits: along[:speed_limits], signals: along[:signals], speed_limits: along[:speed_limits], signals: along[:signals],
legs_km: legs.map { |leg| leg.dig("summary", "length") }, # to each via point, for rerouting legs_km: legs.map { |leg| leg.dig("summary", "length") }, # to each via point, for rerouting
legs_s: legs.map { |leg| leg.dig("summary", "time") }, # the time of each, for the stops list
# lanes: Valhalla's [{directions:, valid:, active:}] bitmasks, at junctions that have them # lanes: Valhalla's [{directions:, valid:, active:}] bitmasks, at junctions that have them
# type: Valhalla's maneuver type (the arrow), street: the road it leads onto # type: Valhalla's maneuver type (the arrow), street: the road it leads onto
maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| maneuver(m) } } } } maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| maneuver(m) } } } }
+24 -10
View File
@@ -39,7 +39,7 @@ module Maptool
def follow(position, speed:, hdop: nil, now: Time.now.to_f, &router) def follow(position, speed:, hdop: nil, now: Time.now.to_f, &router)
trip = get trip = get
route = trip[:route] route = trip[:route]
return unless route && trip[:points].size >= 2 return unless route && trip[:points].count { |p| !p[:passed] } >= 2
at, off = self.class.locate(route[:geometry][:coordinates], position) at, off = self.class.locate(route[:geometry][:coordinates], position)
if off <= ON_ROUTE_M if off <= ON_ROUTE_M
@@ -56,7 +56,7 @@ module Maptool
@rerouting = true @rerouting = true
leg = 0 leg = 0
passed = (route[:properties][:legs_km] || [])[0...-1].map { |km| leg += km }.count { |km| km <= (@last_at || 0) } passed = (route[:properties][:legs_km] || [])[0...-1].map { |km| leg += km }.count { |km| km <= (@last_at || 0) }
points = [{ lngLat: position, name: "My position", nav: false }] + trip[:points].drop(1 + passed) points = self.class.passed_on(trip[:points], passed, position)
Thread.new do Thread.new do
update(points: points, vehicle: trip[:vehicle], avoid: trip[:avoid], editing: trip[:editing], &router) update(points: points, vehicle: trip[:vehicle], avoid: trip[:avoid], editing: trip[:editing], &router)
rescue StandardError => e rescue StandardError => e
@@ -67,6 +67,17 @@ module Maptool
end end
end end
# The points after a detour: the start and the `passed` vias reached so
# far marked passed (the start dropped if it was an earlier "My
# position", not a stop), then the position as the new start, then the rest.
def self.passed_on(points, passed, position)
done, ahead = points.partition { |p| p[:passed] }
ahead = ahead.dup
reached = ahead.shift(1 + passed)
reached.shift if reached.first&.dig(:name) == "My position"
done + reached.map { |p| p.merge(passed: true) } + [{ lngLat: position, name: "My position", nav: false, passed: false }] + ahead
end
# Nearest point on the line ([[lon, lat], ...]): [km along it, meters off it]. # Nearest point on the line ([[lon, lat], ...]): [km along it, meters off it].
def self.locate(coords, (lon, lat)) def self.locate(coords, (lon, lat))
cos = Math.cos(lat * Math::PI / 180) cos = Math.cos(lat * Math::PI / 180)
@@ -86,21 +97,24 @@ module Maptool
best best
end end
# points: [{ lngLat: [lon, lat], name:, nav: }]. Routes through them with # points: [{ lngLat: [lon, lat], name:, nav:, passed: }]. Routes through
# the block (locations, vehicle id, avoid → the /api/route Feature, may # the ones not passed with the block (locations, vehicle id, avoid → the
# raise Routing errors) unless only names/nav changed — the old route # /api/route Feature, may raise Routing errors) unless only names/nav
# stays then. Last write wins. # changed — the old route stays then. Passed points stay in the trip
# (shown dimmed, still editable: a stop missed out added afterwards),
# just not routed. Last write wins.
def update(points:, vehicle:, avoid:, editing:) def update(points:, vehicle:, avoid:, editing:)
points = points.map { |p| { lngLat: p.fetch(:lngLat).map { |v| Float(v) }, name: p[:name], nav: !!p[:nav] } } points = points.map { |p| { lngLat: p.fetch(:lngLat).map { |v| Float(v) }, name: p[:name], nav: !!p[:nav], passed: !!p[:passed] } }
avoid = (avoid || {}).to_h { |k, v| [k.to_sym, !!v] } avoid = (avoid || {}).to_h { |k, v| [k.to_sym, !!v] }
before = get before = get
same_route = before[:points].map { |p| p[:lngLat] } == points.map { |p| p[:lngLat] } && routed = ->(list) { list.reject { |p| p[:passed] }.map { |p| p[:lngLat] } }
same_route = routed.(before[:points]) == routed.(points) &&
before[:vehicle] == vehicle && before[:avoid] == avoid && !before[:error] before[:vehicle] == vehicle && before[:avoid] == avoid && !before[:error]
route, error = if same_route then [before[:route], nil] route, error = if same_route then [before[:route], nil]
elsif points.size < 2 then [nil, nil] elsif routed.(points).size < 2 then [nil, nil]
else else
begin begin
[yield(points.map { |p| p[:lngLat] }, vehicle, avoid), nil] [yield(routed.(points), vehicle, avoid), nil]
rescue Routing::RouteError, Routing::Unavailable => e rescue Routing::RouteError, Routing::Unavailable => e
[nil, e.message] [nil, e.message]
end end
+95
View File
@@ -3588,3 +3588,98 @@ html.follow-3d .maplibregl-ctrl-overview-map { display: none; }
.feather-home { fill: var(--ui-fg); } .feather-home { fill: var(--ui-fg); }
:root[data-palette] .drive-bar button, :root[data-palette] .drive-bar button,
:root[data-palette] .drive-bar__recenter { box-shadow: 0 0 0 1px var(--ui-line), 0 2px 8px rgb(0 0 0 / 0.35); } :root[data-palette] .drive-bar__recenter { box-shadow: 0 0 0 1px var(--ui-line), 0 2px 8px rgb(0 0 0 / 0.35); }
/* The driving mode's Trip menu (driving.js): big rows, big actions, on the
right; the crosshair in the middle of what's left of the map. */
.drive-trip {
position: absolute;
top: 12px;
right: 12px;
bottom: 12px;
z-index: 5;
width: min(540px, 48%);
display: flex;
flex-direction: column;
border-radius: 14px;
background: var(--ui-bg);
color: var(--ui-fg);
box-shadow: 0 0 0 1px var(--ui-line), 0 4px 16px rgb(0 0 0 / 0.35);
overflow: hidden;
}
.drive-trip[hidden] { display: none; }
.drive-trip__head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 0 0 20px;
background: var(--band);
color: var(--band-fg);
font-size: 22px;
font-weight: 700;
}
.drive-trip__close { width: 76px; height: 64px; border: none; background: none; color: inherit; font-size: 26px; cursor: pointer; }
.drive-trip__stops { flex: 1; margin: 0; padding: 0; list-style: none; overflow-y: auto; }
.drive-trip__stops li { display: flex; align-items: stretch; min-height: 76px; border-bottom: 1px solid var(--ui-line); }
.drive-trip__stops button {
border: none;
background: none;
color: inherit;
font: inherit;
cursor: pointer;
}
.drive-trip__stops .drive-bar__stop-name { flex: 1; padding: 0 16px; text-align: left; font-size: 18px; font-weight: 600; }
.drive-trip__stops .drive-bar__stop-up,
.drive-trip__stops .drive-bar__stop-down,
.drive-trip__stops .drive-bar__stop-drop { width: 68px; font-size: 26px; border-left: 1px solid var(--ui-line); }
.drive-trip__stops button:disabled { opacity: 0.25; }
.drive-trip__stops button:active:not(:disabled) { background: var(--accent-bg); }
.drive-trip__empty { padding: 20px 16px; color: var(--ui-muted); font-size: 16px; }
.drive-trip__actions { display: flex; flex-direction: column; gap: 10px; padding: 12px; border-top: 1px solid var(--ui-line); }
.drive-trip__actions button {
min-height: 72px;
border: none;
border-radius: 12px;
background: var(--accent);
color: #fff;
font-size: 19px;
font-weight: 700;
cursor: pointer;
}
.drive-trip__actions [data-action="start"] { background: var(--band); color: var(--band-fg); }
.drive-bar .drive-bar__trip { font-size: 16px; }
.drive-bar button.active { background: var(--accent); }
.drive-crosshair {
position: absolute;
z-index: 4;
width: 44px;
height: 44px;
margin: -22px 0 0 -22px;
pointer-events: none;
background:
linear-gradient(var(--inst-active), var(--inst-active)) center / 3px 100% no-repeat,
linear-gradient(var(--inst-active), var(--inst-active)) center / 100% 3px no-repeat;
filter: drop-shadow(0 0 1px #fff) drop-shadow(0 0 1px #fff);
}
.drive-crosshair[hidden] { display: none; }
.drive-trip__search { padding: 10px 12px; border-bottom: 1px solid var(--ui-line); }
.drive-trip__search input {
width: 100%;
box-sizing: border-box;
height: 60px;
padding: 0 16px;
border: 1px solid var(--ui-line);
border-radius: 10px;
background: var(--ui-bg-2);
color: var(--ui-fg);
font-size: 20px;
}
.drive-trip__stops .drive-bar__stop-name small { display: block; color: var(--ui-muted); font-size: 14px; font-weight: 400; }
.drive-trip__stops .drive-bar__stop-add { width: 76px; font-size: 30px; font-weight: 700; color: var(--accent); border-left: 1px solid var(--ui-line); }
.drive-trip__total { margin-left: 10px; font-size: 16px; font-weight: 500; opacity: 0.8; }
.route-panel__leg { display: block; color: var(--ui-muted); font-size: 11px; }
/* Passed stops (route.js): dimmed, still editable — the buttons keep full strength */
.drive-trip__passed .drive-bar__stop-name,
.route-panel__passed .route-panel__point { opacity: 0.45; }
.drive-trip__stops .drive-bar__stop-done { width: 68px; font-size: 24px; border-left: 1px solid var(--ui-line); color: var(--ui-muted); }
.drive-trip__stops .drive-bar__stop-done.active { color: var(--inst-ok); font-weight: 700; }
.route-marker--passed { opacity: 0.45; }
+6 -70
View File
@@ -1,28 +1,9 @@
import { DEBUG_ICON } from "/js/icons.js"; import { DEBUG_ICON } from "/js/icons.js";
import { escapeHtml } from "/js/gpx.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen } from "/js/panels.js"; import { notifySidePanelOpen, onlyOneSidePanelOpen } from "/js/panels.js";
// Every read-only status endpoint, dumped as raw JSON. No check-update // Sidebar icon pinned to the bottom of the rail, logged-in only (map.js):
// routes here — those reach out to Geofabrik/the internet, not just report // a panel of links — every endpoint's state on the full-screen
// local state. // /status.html, the CANopen diagnostics — and the update check.
const ENDPOINTS = [
"/api/health",
"/api/offline-tiles",
"/api/offline-tiles/build-status",
"/api/offline-regions",
"/api/offline-tiles/cache",
"/api/terrain-tiles",
"/api/terrain-tiles/build-status",
"/api/build-history",
"/api/hiking-trails",
"/api/kiwix",
"/api/plugins",
"/api/gnss/position",
"/api/livetrack/sessions",
];
const REFRESH_MS = 5000; // while open — a running build's progress shows up live
// Sidebar icon pinned to the bottom of the rail, logged-in only (map.js).
export class DebugControl { export class DebugControl {
mount(sidebar) { mount(sidebar) {
this._container = document.createElement("div"); this._container = document.createElement("div");
@@ -32,9 +13,8 @@ export class DebugControl {
this._icon.addEventListener("click", () => this._togglePanel()); this._icon.addEventListener("click", () => this._togglePanel());
this._panel = document.getElementById("debug-panel"); this._panel = document.getElementById("debug-panel");
this._body = this._panel.querySelector(".debug-panel__body");
this._panel.querySelector(".basemap-panel__close").addEventListener("click", () => this._togglePanel(false)); this._panel.querySelector(".basemap-panel__close").addEventListener("click", () => this._togglePanel(false));
onlyOneSidePanelOpen(this._panel, () => this._stop()); onlyOneSidePanelOpen(this._panel, () => this._icon.classList.remove("active"));
sidebar.appendChild(this._container); sidebar.appendChild(this._container);
} }
@@ -42,51 +22,7 @@ export class DebugControl {
_togglePanel(force) { _togglePanel(force) {
const open = force === undefined ? this._panel.hidden : force; const open = force === undefined ? this._panel.hidden : force;
this._panel.hidden = !open; this._panel.hidden = !open;
if (!open) return this._stop(); this._icon.classList.toggle("active", open);
if (open) notifySidePanelOpen(this._panel);
this._icon.classList.add("active");
notifySidePanelOpen(this._panel);
this._refresh();
this._timer = setInterval(() => this._refresh(), REFRESH_MS);
}
_stop() {
this._icon.classList.remove("active");
clearInterval(this._timer);
}
async _refresh() {
const sections = await Promise.all(
ENDPOINTS.map(async (url) => {
let text;
try {
const response = await fetch(url);
const body = await response.text();
try {
text = JSON.stringify(JSON.parse(body), null, 2);
} catch {
text = body;
}
if (!response.ok) text = `HTTP ${response.status}\n${text}`;
} catch (error) {
text = `request failed: ${error.message}`;
}
return { url, text };
}),
);
if (this._panel.hidden) return;
// Keep whichever sections the user collapsed collapsed across refreshes.
const closed = new Set([...this._body.querySelectorAll("details:not([open])")].map((el) => el.dataset.url));
this._body.innerHTML = sections
.map(
({ url, text }) => `
<details data-url="${url}" ${closed.has(url) ? "" : "open"}>
<summary>${url}</summary>
<pre>${escapeHtml(text)}</pre>
</details>
`,
)
.join("");
} }
} }
+120 -2
View File
@@ -1,6 +1,7 @@
import { LngLatBounds } from "/vendor/maplibre-gl/maplibre-gl.mjs"; import { LngLatBounds } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { requestGnssFollow, onRouteChanged } from "/js/panels.js"; import { requestGnssFollow, onRouteChanged } from "/js/panels.js";
import { pauseFollow, resumeFollow, isFollowing } from "/js/gnss.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 // 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 // planning sidebar and panels out of the way. After the research in
@@ -11,8 +12,11 @@ import { pauseFollow, resumeFollow, isFollowing } from "/js/gnss.js";
const KEY = "drivingMode"; const KEY = "drivingMode";
const PITCH_3D = 60; // as map.js's 3D toggle 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 CHECK_MS = 1000; // how often the recenter button looks whether the map follows
const SEARCH_DELAY_MS = 300; // after the last key
export function setupDriving(map, nightButton) { const escapeHtml = (text) => String(text).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
export function setupDriving(map, nightButton, routePanel) {
let route = onRouteChanged((r) => (route = r)); let route = onRouteChanged((r) => (route = r));
const toggle = document.createElement("button"); const toggle = document.createElement("button");
toggle.type = "button"; toggle.type = "button";
@@ -38,6 +42,7 @@ export function setupDriving(map, nightButton) {
button("zoomIn", "+", "Zoom in", () => map.zoomIn()), button("zoomIn", "+", "Zoom in", () => map.zoomIn()),
button("zoomOut", "−", "Zoom out", () => map.zoomOut()), 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("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)", () => { button("overview", "Route", "The whole route (the follow pauses)", () => {
const coords = route?.geometry?.coordinates; const coords = route?.geometry?.coordinates;
if (!coords?.length) return; if (!coords?.length) return;
@@ -53,7 +58,119 @@ export function setupDriving(map, nightButton) {
recenter.hidden = true; recenter.hidden = true;
}); });
recenter.hidden = true; recenter.hidden = true;
map.getContainer().append(bar, recenter); // 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 = () => { const render = () => {
bar.querySelector(".drive-bar__pitch").textContent = map.getPitch() > 0 ? "2D" : "3D"; bar.querySelector(".drive-bar__pitch").textContent = map.getPitch() > 0 ? "2D" : "3D";
@@ -65,6 +182,7 @@ export function setupDriving(map, nightButton) {
setInterval(render, CHECK_MS); setInterval(render, CHECK_MS);
function set(on) { function set(on) {
if (!on) openTrip(false);
document.documentElement.classList.toggle("driving", on); document.documentElement.classList.toggle("driving", on);
bar.hidden = !on; bar.hidden = !on;
toggle.classList.toggle("active", on); toggle.classList.toggle("active", on);
+3 -2
View File
@@ -532,7 +532,6 @@ nightButton.addEventListener("click", () => {
updateNight(); updateNight();
map.on("moveend", updateNight); map.on("moveend", updateNight);
setInterval(updateNight, 60000); setInterval(updateNight, 60000);
setupDriving(map, nightButton);
const sidebar = document.getElementById("sidebar"); const sidebar = document.getElementById("sidebar");
@@ -562,7 +561,9 @@ if (isLoggedIn()) new PluginsControl(map).mount(sidebar);
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Offline hub"></div>`); sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Offline hub"></div>`);
layerToggle.mount(sidebar); layerToggle.mount(sidebar);
layerToggle.setActive("online"); layerToggle.setActive("online");
new RoutePanelControl(map, gnssControl, profilePanel).mount(sidebar); const routePanel = new RoutePanelControl(map, gnssControl, profilePanel);
routePanel.mount(sidebar);
setupDriving(map, nightButton, routePanel);
new OfflineDataControl().mount(sidebar); new OfflineDataControl().mount(sidebar);
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Navigation"></div>`); sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Navigation"></div>`);
+108 -13
View File
@@ -53,13 +53,21 @@ export class RoutePanelControl {
// already passed give way to the current position. // already passed give way to the current position.
onReroute(({ from, passed }) => { onReroute(({ from, passed }) => {
// the shared trip is rerouted by the server, off its own GNSS (TripStore#follow) // the shared trip is rerouted by the server, off its own GNSS (TripStore#follow)
if (this._shared || this._points.length < 2) return; if (this._shared || this._active().length < 2) return;
this._points.splice(0, 1 + passed).forEach((p) => p.marker.remove()); const reached = this._active().slice(0, 1 + passed);
if (reached[0]?.name === "My position") this._removePoint(reached.shift(), { quiet: true });
reached.forEach((p) => this._setPassed(p, true));
this._addPoint(from, "My position", { quiet: true }); this._addPoint(from, "My position", { quiet: true });
this._points.unshift(this._points.pop()); const position = this._points.pop();
const next = this._points.findIndex((p) => !p.passed);
this._points.splice(next < 0 ? this._points.length : next, 0, position);
this._changed(); this._changed();
}); });
onRouteProgress((km) => this._showProgress(km)); onRouteProgress((km) => {
this._showProgress(km);
this._progressKm = km;
this._stopListeners?.forEach((callback) => callback());
});
onRoutePoint(({ lngLat, name }) => { onRoutePoint(({ lngLat, name }) => {
this._setOpen(true); this._setOpen(true);
this._addPoint(lngLat, name); this._addPoint(lngLat, name);
@@ -147,7 +155,7 @@ export class RoutePanelControl {
method: "PUT", method: "PUT",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({
points: this._points.map(({ lngLat, name, nav }) => ({ lngLat, name, nav })), points: this._points.map(({ lngLat, name, nav, passed }) => ({ lngLat, name, nav, passed })),
vehicle: this._vehicleId, vehicle: this._vehicleId,
avoid: this._avoid, avoid: this._avoid,
editing: this._editing, editing: this._editing,
@@ -171,7 +179,7 @@ export class RoutePanelControl {
if (fromElsewhere) { if (fromElsewhere) {
this._points.forEach((p) => p.marker.remove()); this._points.forEach((p) => p.marker.remove());
this._points = []; this._points = [];
trip.points.forEach((p) => this._addPoint(p.lngLat, p.name, { quiet: true, nav: !!p.nav })); trip.points.forEach((p) => this._addPoint(p.lngLat, p.name, { quiet: true, nav: !!p.nav, passed: !!p.passed }));
this._editing = trip.editing; this._editing = trip.editing;
this._avoid = { ...trip.avoid }; this._avoid = { ...trip.avoid };
this._panel.querySelectorAll(".route-panel__avoid input").forEach((input) => (input.checked = !!this._avoid[input.name])); this._panel.querySelectorAll(".route-panel__avoid input").forEach((input) => (input.checked = !!this._avoid[input.name]));
@@ -200,11 +208,12 @@ export class RoutePanelControl {
// A named place (a saved point, a search result) is shown in navigation // A named place (a saved point, a search result) is shown in navigation
// by default; a plain map click only shapes the route. // by default; a plain map click only shapes the route.
_addPoint(lngLat, name, { quiet = false, nav = !!name && name !== "My position" } = {}) { _addPoint(lngLat, name, { quiet = false, nav = !!name && name !== "My position", passed = false } = {}) {
const element = document.createElement("div"); const element = document.createElement("div");
element.className = "route-marker"; element.className = "route-marker";
const marker = new Marker({ element, draggable: true }).setLngLat(lngLat).addTo(this._map); const marker = new Marker({ element, draggable: true }).setLngLat(lngLat).addTo(this._map);
const point = { lngLat, name, nav, marker }; const point = { lngLat, name, nav, marker };
this._setPassed(point, passed);
marker.on("dragend", () => { marker.on("dragend", () => {
const { lng, lat } = marker.getLngLat(); const { lng, lat } = marker.getLngLat();
point.lngLat = [lng, lat]; point.lngLat = [lng, lat];
@@ -249,10 +258,91 @@ export class RoutePanelControl {
this._changed(); this._changed();
} }
_removePoint(point) { // For the driving mode's Trip menu (driving.js): the stops, and editing
// them by index — the same points the panel edits, so the shared trip,
// routing and markers follow as from the panel.
// passed: marked (by a reroute or by hand) — not routed — or behind the
// car by the dashboard's progress along the route; both shown dimmed.
stops() {
return this._points.map((p, i) => ({ name: p.name, lngLat: p.lngLat, label: i === 0 ? "Start" : i === this._points.length - 1 ? "End" : `Via ${i}`,
leg: this._leg(i), passed: p.passed, behind: this._behind(i) }));
}
togglePassed(index) {
const point = this._points[index];
if (!point) return;
this._setPassed(point, !point.passed);
this._changed();
}
_setPassed(point, passed) {
point.passed = !!passed;
point.marker.getElement().classList.toggle("route-marker--passed", point.passed);
}
// The points routed: the ones not passed.
_active() {
return this._points.filter((p) => !p.passed);
}
// The way to point i from the routed one before: { km, s } of the route's
// leg, null for the first routed point, a passed one, or while the route
// doesn't match the points (routing).
_leg(i) {
const { legs_km: km, legs_s: s } = this._route?.properties || {};
const active = this._active();
const at = active.indexOf(this._points[i]);
if (at < 1 || !km || km.length !== active.length - 1) return null;
return { km: km[at - 1], s: s?.[at - 1] };
}
// Behind the car: the dashboard's km along the route past this point's.
_behind(i) {
if (this._progressKm == null || this._points[i]?.passed) return false;
const { legs_km: km } = this._route?.properties || {};
const active = this._active();
const at = active.indexOf(this._points[i]);
if (at < 0 || !km || km.length !== active.length - 1) return false;
return km.slice(0, at).reduce((sum, length) => sum + length, 0) <= this._progressKm + 0.03;
}
onStopsChanged(callback) {
(this._stopListeners ??= []).push(callback);
}
moveStop(index, step) {
if (this._points[index]) this._move(this._points[index], step);
}
removeStop(index) {
if (this._points[index]) this._removePoint(this._points[index]);
}
// A stop before the end (the trip goes on to where it was going), or the
// end itself while there's no route yet.
addStop(lngLat, name = null) {
this._addPoint(lngLat, name, { quiet: true });
if (this._points.length > 2) this._points.splice(this._points.length - 2, 0, this._points.pop());
this._changed();
}
// The start moved to where the car is (GNSS, else the browser's position).
startHere() {
const set = (lngLat) => {
if (this._points[0]?.name === "My position") this._removePoint(this._points[0]);
this._addPoint(lngLat, "My position", { quiet: true });
this._points.unshift(this._points.pop());
this._changed();
};
const fix = this._gnss?.getPosition();
if (fix) return set([fix.lng, fix.lat]);
navigator.geolocation.getCurrentPosition((p) => set([p.coords.longitude, p.coords.latitude]), () => window.alert("Could not determine your location."), { enableHighAccuracy: true });
}
_removePoint(point, { quiet = false } = {}) {
point.marker.remove(); point.marker.remove();
this._points = this._points.filter((p) => p !== point); this._points = this._points.filter((p) => p !== point);
this._changed(); if (!quiet) this._changed();
} }
_clear() { _clear() {
@@ -273,9 +363,12 @@ export class RoutePanelControl {
const label = index === 0 ? "Start" : index === this._points.length - 1 ? "End" : `Via ${index}`; const label = index === 0 ? "Start" : index === this._points.length - 1 ? "End" : `Via ${index}`;
point.marker.getElement().textContent = index === 0 ? "S" : index === this._points.length - 1 ? "E" : String(index); point.marker.getElement().textContent = index === 0 ? "S" : index === this._points.length - 1 ? "E" : String(index);
const li = document.createElement("li"); const li = document.createElement("li");
li.classList.toggle("route-panel__passed", !!point.passed || this._behind(index));
const text = document.createElement("span"); const text = document.createElement("span");
text.className = "route-panel__point"; text.className = "route-panel__point";
text.textContent = `${label} · ${point.name || `${point.lngLat[1].toFixed(5)}, ${point.lngLat[0].toFixed(5)}`}`; text.textContent = `${label} · ${point.name || `${point.lngLat[1].toFixed(5)}, ${point.lngLat[0].toFixed(5)}`}`;
const leg = this._leg(index);
if (leg) text.append(Object.assign(document.createElement("small"), { className: "route-panel__leg", textContent: `+${leg.km.toFixed(1)} km${leg.s != null ? ` · ${formatDuration(leg.s)}` : ""}` }));
li.append( li.append(
text, text,
this._navButton(point, label), this._navButton(point, label),
@@ -288,6 +381,7 @@ export class RoutePanelControl {
text.addEventListener("click", () => this._map.easeTo({ center: point.lngLat, zoom: Math.max(this._map.getZoom(), 14) })); text.addEventListener("click", () => this._map.easeTo({ center: point.lngLat, zoom: Math.max(this._map.getZoom(), 14) }));
this._list.appendChild(li); this._list.appendChild(li);
}); });
this._stopListeners?.forEach((callback) => callback());
this._editingNote.hidden = !this._editing; this._editingNote.hidden = !this._editing;
if (this._editing) this._editingNote.textContent = `Editing "${this._editing.name}"`; if (this._editing) this._editingNote.textContent = `Editing "${this._editing.name}"`;
this._saveButton.textContent = this._editing ? "Save changes" : "Save to library"; this._saveButton.textContent = this._editing ? "Save changes" : "Save to library";
@@ -330,7 +424,7 @@ export class RoutePanelControl {
if (this._shared) return this._pushTrip(); if (this._shared) return this._pushTrip();
const request = ++this._request; const request = ++this._request;
this._route = null; this._route = null;
if (this._points.length < 2) { if (this._active().length < 2) {
this._showResult(null, ""); this._showResult(null, "");
return; return;
} }
@@ -342,7 +436,7 @@ export class RoutePanelControl {
const response = await fetch(ROUTE_URL, { const response = await fetch(ROUTE_URL, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ locations: this._points.map((p) => p.lngLat), vehicle: this._vehicleId, avoid: this._avoid }), body: JSON.stringify({ locations: this._active().map((p) => p.lngLat), vehicle: this._vehicleId, avoid: this._avoid }),
}); });
data = await response.json().catch(() => ({})); data = await response.json().catch(() => ({}));
if (!response.ok) error = data.error || `routing failed (${response.status})`; if (!response.ok) error = data.error || `routing failed (${response.status})`;
@@ -358,6 +452,7 @@ export class RoutePanelControl {
_showResult(route, message) { _showResult(route, message) {
this._draw(); this._draw();
notifyRouteChanged(route); notifyRouteChanged(route);
this._renderPoints(); // the legs' km and time next to the points (the Trip menu's too)
this._saveButton.hidden = !route || !isLoggedIn(); this._saveButton.hidden = !route || !isLoggedIn();
this._directions.hidden = !route; this._directions.hidden = !route;
this._profileButton.hidden = true; this._profileButton.hidden = true;
@@ -516,7 +611,7 @@ export class RoutePanelControl {
...this._profileProperties(), ...this._profileProperties(),
name: name.trim(), name: name.trim(),
via: this._points.map((p) => p.lngLat), via: this._points.map((p) => p.lngLat),
via_points: this._points.map((p) => ({ name: p.name || null, nav: !!p.nav })), via_points: this._points.map((p) => ({ name: p.name || null, nav: !!p.nav, passed: !!p.passed })),
vehicle: this._vehicle, vehicle: this._vehicle,
}, },
}; };
@@ -778,7 +873,7 @@ function distanceM([lon1, lat1], [lon2, lat2]) {
return 12742000 * Math.asin(Math.sqrt(a)); return 12742000 * Math.asin(Math.sqrt(a));
} }
function formatDuration(seconds) { export function formatDuration(seconds) {
const minutes = Math.round(seconds / 60); const minutes = Math.round(seconds / 60);
return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h ${minutes % 60} min`; return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h ${minutes % 60} min`;
} }
+2 -1
View File
@@ -126,12 +126,13 @@ class RoutingTest < Minitest::Test
def test_route_picks_the_costing_by_weight_and_returns_a_line def test_route_picks_the_costing_by_weight_and_returns_a_line
shape = "wdg|xA{ubdQc@w@" shape = "wdg|xA{ubdQc@w@"
reply = JSON.generate(trip: { summary: { length: 1.5, time: 90 }, reply = JSON.generate(trip: { summary: { length: 1.5, time: 90 },
legs: [{ shape: shape, maneuvers: [{ instruction: "Drive north.", length: 1.5, type: 2, street_names: ["Main"] }] }] }) legs: [{ shape: shape, summary: { length: 1.5, time: 90 }, maneuvers: [{ instruction: "Drive north.", length: 1.5, type: 2, street_names: ["Main"] }] }] })
# The per-country lookup failing (400) leaves the route as it is. # The per-country lookup failing (400) leaves the route as it is.
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}", "HTTP/1.1 400 Bad Request\r\nContent-Length: 2\r\n\r\n{}") do |url| request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}", "HTTP/1.1 400 Bad Request\r\nContent-Length: 2\r\n\r\n{}") do |url|
route = Maptool::Routing.route(url, [[9.52, 47.14], [9.53, 47.15]], Maptool::Routing::DEFAULT_VEHICLES[1]) route = Maptool::Routing.route(url, [[9.52, 47.14], [9.53, 47.15]], Maptool::Routing::DEFAULT_VEHICLES[1])
assert_equal [2, "auto", "Drive north."], [route[:geometry][:coordinates].size, route[:properties][:costing], route[:properties][:maneuvers][0][:text]] assert_equal [2, "auto", "Drive north."], [route[:geometry][:coordinates].size, route[:properties][:costing], route[:properties][:maneuvers][0][:text]]
assert_equal({ text: "Drive north.", km: 1.5, type: 2, street: "Main" }, route[:properties][:maneuvers][0]) assert_equal({ text: "Drive north.", km: 1.5, type: 2, street: "Main" }, route[:properties][:maneuvers][0])
assert_equal [[1.5], [90]], route[:properties].values_at(:legs_km, :legs_s) # each leg's km and time, for the stops
end end
assert_includes request, %("costing_options":{"auto":{"height":3.0,"width":2.3}}) assert_includes request, %("costing_options":{"auto":{"height":3.0,"width":2.3}})
+19 -1
View File
@@ -42,13 +42,31 @@ class TripTest < Minitest::Test
3.times { |i| store.follow([17.15, 48.01], speed: 20, now: i + 1, &router) } # ~1.1 km off 3.times { |i| store.follow([17.15, 48.01], speed: 20, now: i + 1, &router) } # ~1.1 km off
Timeout.timeout(5) { sleep 0.05 until store.get[:version] == 2 } Timeout.timeout(5) { sleep 0.05 until store.get[:version] == 2 }
assert_equal [[[17.15, 48.01], [17.2, 48.0]]], calls assert_equal [[[17.15, 48.01], [17.2, 48.0]]], calls
assert_equal "My position", store.get[:points][0][:name] # the start and the via reached: kept, marked passed; the detour starts here
assert_equal [[true, nil], [true, nil], [false, "My position"], [false, nil]], store.get[:points].map { |p| p.values_at(:passed, :name) }
store.follow([17.15, 48.02], speed: 20, now: 5, &router) # within REROUTE_EVERY_S: nothing store.follow([17.15, 48.02], speed: 20, now: 5, &router) # within REROUTE_EVERY_S: nothing
assert_equal 1, calls.size assert_equal 1, calls.size
end end
end end
# A passed point stays in the trip, not in the route; marking one passed
# routes again (fewer locations), only renaming it doesn't.
def test_passed_points_are_kept_but_not_routed
Dir.mktmpdir do |dir|
store = Maptool::TripStore.new(File.join(dir, "trip.json"))
calls = []
router = ->(locations, *) { calls << locations; :route }
points = [{ lngLat: [1, 1], passed: true }, { lngLat: [2, 2] }, { lngLat: [3, 3] }]
trip = store.update(points: points, vehicle: nil, avoid: {}, editing: nil, &router)
assert_equal [[[2.0, 2.0], [3.0, 3.0]]], calls
assert_equal [true, false, false], trip[:points].map { |p| p[:passed] }
points[0] = points[0].merge(name: "Missed it")
store.update(points: points, vehicle: nil, avoid: {}, editing: nil, &router)
assert_equal 1, calls.size
end
end
def test_a_routing_error_is_kept_with_the_points_and_tried_again_next_time def test_a_routing_error_is_kept_with_the_points_and_tried_again_next_time
Dir.mktmpdir do |dir| Dir.mktmpdir do |dir|
store = Maptool::TripStore.new(File.join(dir, "trip.json")) store = Maptool::TripStore.new(File.join(dir, "trip.json"))
+1 -2
View File
@@ -106,11 +106,10 @@
<button type="button" class="basemap-panel__close" aria-label="Close">&times;</button> <button type="button" class="basemap-panel__close" aria-label="Close">&times;</button>
</div> </div>
<div class="basemap-panel__list"> <div class="basemap-panel__list">
<a class="basemap-panel__link" href="/status.html" target="_blank">Server status (all endpoints) ↗</a>
<a class="basemap-panel__link" href="/can.html" target="_blank">CANopen diagnostics ↗</a> <a class="basemap-panel__link" href="/can.html" target="_blank">CANopen diagnostics ↗</a>
<button type="button" class="basemap-panel__link debug-panel__update-check" hidden>Check for an update now</button> <button type="button" class="basemap-panel__link debug-panel__update-check" hidden>Check for an update now</button>
</div> </div>
<!-- Filled by DebugControl (public/js/debug.js), logged-in only. -->
<div class="debug-panel__body"></div>
</div> </div>
<div id="plugins-panel" class="basemap-panel" hidden> <div id="plugins-panel" class="basemap-panel" hidden>
+101
View File
@@ -0,0 +1,101 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>Server status</title>
<link rel="icon" href="/icons/icon.svg" type="image/svg+xml">
<style>
:root { color-scheme: light dark; --muted: GrayText; --line: color-mix(in srgb, CanvasText 15%, transparent); --ok: #2e7d32; --bad: #c62828; }
body { margin: 0; padding: 16px; background: Canvas; color: CanvasText; font: 15px/1.4 -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
header { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; margin-bottom: 12px; }
h1 { font-size: 1.2rem; margin: 0; }
#status { color: var(--muted); font-size: 0.85rem; }
input, button { padding: 6px 10px; font-size: 0.9rem; }
/* the whole width: as many columns as fit, each at least 380px */
#cards { display: grid; gap: 12px; grid-template-columns: repeat(auto-fill, minmax(min(380px, 100%), 1fr)); align-items: start; }
details { border: 1px solid var(--line); border-radius: 8px; min-width: 0; }
summary { display: flex; gap: 10px; align-items: baseline; padding: 8px 12px; cursor: pointer; }
summary code { flex: 1; font-weight: 600; overflow-wrap: anywhere; }
summary .meta { color: var(--muted); font-size: 0.8rem; white-space: nowrap; font-variant-numeric: tabular-nums; }
.dot { width: 10px; height: 10px; border-radius: 50%; flex: none; align-self: center; background: var(--ok); }
.bad .dot { background: var(--bad); }
.bad summary code { color: var(--bad); }
pre { margin: 0; padding: 8px 12px; max-height: 420px; overflow: auto; border-top: 1px solid var(--line); font: 0.8rem/1.35 ui-monospace, SFMono-Regular, Menlo, monospace; }
code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
</style>
</head>
<body>
<header>
<h1>Server status</h1>
<span id="status">loading…</span>
<input id="filter" type="search" placeholder="Filter endpoints or content…">
<button id="pause" type="button">Pause</button>
<a href="/can.html">CANopen diagnostics</a>
</header>
<div id="cards"></div>
<script>
// Every read-only status endpoint (GET, login), its JSON, refreshed every
// REFRESH_MS. Not the check-update ones (they ask the internet) nor the
// big exports (library, sync feed).
const ENDPOINTS = [
"/api/health", "/api/update", "/api/can", "/api/gnss/position", "/api/sim/gnss",
"/api/trip", "/api/vehicles", "/api/live", "/api/livetrack/sessions",
"/api/offline-tiles", "/api/offline-tiles/build-status", "/api/offline-regions", "/api/offline-tiles/cache",
"/api/terrain-tiles", "/api/terrain-tiles/build-status", "/api/routing-tiles", "/api/routing-tiles/build-status",
"/api/build-history", "/api/hiking-trails", "/api/kiwix", "/api/plugins",
];
const REFRESH_MS = 5000;
const cards = document.getElementById("cards");
const filter = document.getElementById("filter");
const pause = document.getElementById("pause");
const status = document.getElementById("status");
const esc = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
let paused = false;
let last = [];
async function load(url) {
const started = performance.now();
try {
const response = await fetch(url, { cache: "no-store" });
const body = await response.text();
let text = body;
try { text = JSON.stringify(JSON.parse(body), null, 2); } catch { /* not JSON */ }
return { url, ok: response.ok, code: response.status, ms: performance.now() - started, text };
} catch (e) {
return { url, ok: false, code: "—", ms: performance.now() - started, text: `request failed: ${e.message}` };
}
}
function render() {
const q = filter.value.trim().toLowerCase();
const closed = new Set([...cards.querySelectorAll("details:not([open])")].map((d) => d.dataset.url));
cards.innerHTML = last.filter((r) => !q || r.url.includes(q) || r.text.toLowerCase().includes(q)).map((r) => `
<details data-url="${r.url}" class="${r.ok ? "" : "bad"}" ${closed.has(r.url) ? "" : "open"}>
<summary><span class="dot"></span><code>${r.url}</code><span class="meta">${r.code} · ${Math.round(r.ms)} ms</span></summary>
<pre>${esc(r.text)}</pre>
</details>`).join("");
const bad = last.filter((r) => !r.ok).length;
status.textContent = `${last.length} endpoints, ${bad ? `${bad} failing` : "all OK"} · ${new Date().toLocaleTimeString()}${paused ? " · paused" : ""}`;
}
async function refresh() {
if (!paused) {
last = await Promise.all(ENDPOINTS.map(load));
render();
if (last.some((r) => r.code === 401)) status.insertAdjacentHTML("beforeend", ' · some need the login — <a href="/login">log in</a>');
}
setTimeout(refresh, REFRESH_MS);
}
filter.addEventListener("input", render);
pause.addEventListener("click", () => {
paused = !paused;
pause.textContent = paused ? "Resume" : "Pause";
render();
});
refresh();
</script>
</body>
</html>