From 809e88ab1a176f789707471fe36376ca2709b752 Mon Sep 17 00:00:00 2001 From: Roman Priesol Date: Tue, 1 Dec 2026 02:21:14 +0100 Subject: [PATCH] =?UTF-8?q?Driving=20menu=20Trip:=20the=20stops=20as=20big?= =?UTF-8?q?=20rows=20(look,=20=E2=9C=93=20passed,=20=E2=86=91=20=E2=86=93,?= =?UTF-8?q?=20=E2=9C=95),=20a=20stop=20at=20the=20crosshair,=20the=20start?= =?UTF-8?q?=20at=20the=20car,=20search=20of=20saved=20points=20and=20offli?= =?UTF-8?q?ne=20places;=20each=20leg's=20km=20and=20time=20(legs=5Fs)=20an?= =?UTF-8?q?d=20the=20total,=20in=20the=20route=20panel=20too;=20passed=20s?= =?UTF-8?q?tops=20kept=20(not=20routed,=20dimmed,=20editable)=20=E2=80=94?= =?UTF-8?q?=20a=20reroute=20marks=20them=20instead=20of=20dropping=20them;?= =?UTF-8?q?=20/status.html:=20every=20status=20endpoint=20full=20width=20(?= =?UTF-8?q?the=20debug=20panel=20links=20it);=20the=20trip-as-plan-and-log?= =?UTF-8?q?=20model=20and=20planned-vs-driven=20colors=20in=20docs/TODO?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TODO.adoc | 26 +++++++++ app.rb | 5 ++ docs/design.adoc | 6 ++ lib/maptool/routing.rb | 1 + lib/maptool/trip.rb | 34 ++++++++---- public/css/style.css | 95 ++++++++++++++++++++++++++++++++ public/js/debug.js | 76 ++----------------------- public/js/driving.js | 122 ++++++++++++++++++++++++++++++++++++++++- public/js/map.js | 5 +- public/js/route.js | 121 +++++++++++++++++++++++++++++++++++----- test/test_routing.rb | 3 +- test/test_trip.rb | 20 ++++++- views/index.erb | 3 +- views/status.erb | 101 ++++++++++++++++++++++++++++++++++ 14 files changed, 517 insertions(+), 101 deletions(-) create mode 100644 views/status.erb diff --git a/TODO.adoc b/TODO.adoc index 8f0de65..21cc0cf 100644 --- a/TODO.adoc +++ b/TODO.adoc @@ -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 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) +** [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] 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 @@ -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 * [ ] Document all API endpoints somewhere and make them easy to browse (status of each) — 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) diff --git a/app.rb b/app.rb index 9b46aa6..bb78db1 100644 --- a/app.rb +++ b/app.rb @@ -496,6 +496,11 @@ module Maptool erb :symbols, layout: false 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). get "/can.html" do erb :can, layout: false diff --git a/docs/design.adoc b/docs/design.adoc index 9b10583..c398b3f 100644 --- a/docs/design.adoc +++ b/docs/design.adoc @@ -253,6 +253,12 @@ route panel, NPS maps, the offline data panel The route line is the bridge: blue (`--route-planned`) while planning, 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 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 diff --git a/lib/maptool/routing.rb b/lib/maptool/routing.rb index b35c416..0cf6c32 100644 --- a/lib/maptool/routing.rb +++ b/lib/maptool/routing.rb @@ -255,6 +255,7 @@ module Maptool time_s: data["trip"]["summary"]["time"], countries: along[:countries], speed_limits: along[:speed_limits], signals: along[:signals], 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 # type: Valhalla's maneuver type (the arrow), street: the road it leads onto maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| maneuver(m) } } } } diff --git a/lib/maptool/trip.rb b/lib/maptool/trip.rb index e1635bd..4c227f8 100644 --- a/lib/maptool/trip.rb +++ b/lib/maptool/trip.rb @@ -39,7 +39,7 @@ module Maptool def follow(position, speed:, hdop: nil, now: Time.now.to_f, &router) trip = get 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) if off <= ON_ROUTE_M @@ -56,7 +56,7 @@ module Maptool @rerouting = true leg = 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 update(points: points, vehicle: trip[:vehicle], avoid: trip[:avoid], editing: trip[:editing], &router) rescue StandardError => e @@ -67,6 +67,17 @@ module Maptool 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]. def self.locate(coords, (lon, lat)) cos = Math.cos(lat * Math::PI / 180) @@ -86,21 +97,24 @@ module Maptool best end - # points: [{ lngLat: [lon, lat], name:, nav: }]. Routes through them with - # the block (locations, vehicle id, avoid → the /api/route Feature, may - # raise Routing errors) unless only names/nav changed — the old route - # stays then. Last write wins. + # points: [{ lngLat: [lon, lat], name:, nav:, passed: }]. Routes through + # the ones not passed with the block (locations, vehicle id, avoid → the + # /api/route Feature, may raise Routing errors) unless only names/nav + # 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:) - 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] } 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] 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 begin - [yield(points.map { |p| p[:lngLat] }, vehicle, avoid), nil] + [yield(routed.(points), vehicle, avoid), nil] rescue Routing::RouteError, Routing::Unavailable => e [nil, e.message] end diff --git a/public/css/style.css b/public/css/style.css index f01bad1..0a9bac2 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -3588,3 +3588,98 @@ html.follow-3d .maplibregl-ctrl-overview-map { display: none; } .feather-home { fill: var(--ui-fg); } :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); } + +/* 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; } diff --git a/public/js/debug.js b/public/js/debug.js index b0ff77b..1b0bdff 100644 --- a/public/js/debug.js +++ b/public/js/debug.js @@ -1,28 +1,9 @@ import { DEBUG_ICON } from "/js/icons.js"; -import { escapeHtml } from "/js/gpx.js"; import { notifySidePanelOpen, onlyOneSidePanelOpen } from "/js/panels.js"; -// Every read-only status endpoint, dumped as raw JSON. No check-update -// routes here — those reach out to Geofabrik/the internet, not just report -// local state. -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). +// Sidebar icon pinned to the bottom of the rail, logged-in only (map.js): +// a panel of links — every endpoint's state on the full-screen +// /status.html, the CANopen diagnostics — and the update check. export class DebugControl { mount(sidebar) { this._container = document.createElement("div"); @@ -32,9 +13,8 @@ export class DebugControl { this._icon.addEventListener("click", () => this._togglePanel()); 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)); - onlyOneSidePanelOpen(this._panel, () => this._stop()); + onlyOneSidePanelOpen(this._panel, () => this._icon.classList.remove("active")); sidebar.appendChild(this._container); } @@ -42,51 +22,7 @@ export class DebugControl { _togglePanel(force) { const open = force === undefined ? this._panel.hidden : force; this._panel.hidden = !open; - if (!open) return this._stop(); - - 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 }) => ` -
- ${url} -
${escapeHtml(text)}
-
- `, - ) - .join(""); + this._icon.classList.toggle("active", open); + if (open) notifySidePanelOpen(this._panel); } } diff --git a/public/js/driving.js b/public/js/driving.js index 6bb3988..62dd5d8 100644 --- a/public/js/driving.js +++ b/public/js/driving.js @@ -1,6 +1,7 @@ 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 @@ -11,8 +12,11 @@ import { pauseFollow, resumeFollow, isFollowing } from "/js/gnss.js"; 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 -export function setupDriving(map, nightButton) { +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"; @@ -38,6 +42,7 @@ export function setupDriving(map, nightButton) { 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; @@ -53,7 +58,119 @@ export function setupDriving(map, nightButton) { 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 = `
Trip
+ +
    +
    + + +
    `; + 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)}${escapeHtml(r.where || "")}`; + 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 = `
  1. Nothing found.
  2. `; + }; + 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 ? `+${stop.leg.km.toFixed(1)} km${stop.leg.s != null ? ` · ${formatDuration(stop.leg.s)}` : ""}` : ""; + 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 = `
  3. No stops yet — pan the map to a place and add it.
  4. `; + 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"; @@ -65,6 +182,7 @@ export function setupDriving(map, nightButton) { 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); diff --git a/public/js/map.js b/public/js/map.js index 27b05c4..72da5e4 100644 --- a/public/js/map.js +++ b/public/js/map.js @@ -532,7 +532,6 @@ nightButton.addEventListener("click", () => { updateNight(); map.on("moveend", updateNight); setInterval(updateNight, 60000); -setupDriving(map, nightButton); const sidebar = document.getElementById("sidebar"); @@ -562,7 +561,9 @@ if (isLoggedIn()) new PluginsControl(map).mount(sidebar); sidebar.insertAdjacentHTML("beforeend", ``); layerToggle.mount(sidebar); 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); sidebar.insertAdjacentHTML("beforeend", ``); diff --git a/public/js/route.js b/public/js/route.js index 206275b..ed0e744 100644 --- a/public/js/route.js +++ b/public/js/route.js @@ -53,13 +53,21 @@ export class RoutePanelControl { // already passed give way to the current position. onReroute(({ from, passed }) => { // the shared trip is rerouted by the server, off its own GNSS (TripStore#follow) - if (this._shared || this._points.length < 2) return; - this._points.splice(0, 1 + passed).forEach((p) => p.marker.remove()); + if (this._shared || this._active().length < 2) return; + 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._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(); }); - onRouteProgress((km) => this._showProgress(km)); + onRouteProgress((km) => { + this._showProgress(km); + this._progressKm = km; + this._stopListeners?.forEach((callback) => callback()); + }); onRoutePoint(({ lngLat, name }) => { this._setOpen(true); this._addPoint(lngLat, name); @@ -147,7 +155,7 @@ export class RoutePanelControl { method: "PUT", headers: { "Content-Type": "application/json" }, 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, avoid: this._avoid, editing: this._editing, @@ -171,7 +179,7 @@ export class RoutePanelControl { if (fromElsewhere) { this._points.forEach((p) => p.marker.remove()); 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._avoid = { ...trip.avoid }; 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 // 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"); element.className = "route-marker"; const marker = new Marker({ element, draggable: true }).setLngLat(lngLat).addTo(this._map); const point = { lngLat, name, nav, marker }; + this._setPassed(point, passed); marker.on("dragend", () => { const { lng, lat } = marker.getLngLat(); point.lngLat = [lng, lat]; @@ -249,10 +258,91 @@ export class RoutePanelControl { 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(); this._points = this._points.filter((p) => p !== point); - this._changed(); + if (!quiet) this._changed(); } _clear() { @@ -273,9 +363,12 @@ export class RoutePanelControl { 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); const li = document.createElement("li"); + li.classList.toggle("route-panel__passed", !!point.passed || this._behind(index)); const text = document.createElement("span"); text.className = "route-panel__point"; 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( text, 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) })); this._list.appendChild(li); }); + this._stopListeners?.forEach((callback) => callback()); this._editingNote.hidden = !this._editing; if (this._editing) this._editingNote.textContent = `Editing "${this._editing.name}"`; this._saveButton.textContent = this._editing ? "Save changes" : "Save to library"; @@ -330,7 +424,7 @@ export class RoutePanelControl { if (this._shared) return this._pushTrip(); const request = ++this._request; this._route = null; - if (this._points.length < 2) { + if (this._active().length < 2) { this._showResult(null, ""); return; } @@ -342,7 +436,7 @@ export class RoutePanelControl { const response = await fetch(ROUTE_URL, { method: "POST", 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(() => ({})); if (!response.ok) error = data.error || `routing failed (${response.status})`; @@ -358,6 +452,7 @@ export class RoutePanelControl { _showResult(route, message) { this._draw(); notifyRouteChanged(route); + this._renderPoints(); // the legs' km and time next to the points (the Trip menu's too) this._saveButton.hidden = !route || !isLoggedIn(); this._directions.hidden = !route; this._profileButton.hidden = true; @@ -516,7 +611,7 @@ export class RoutePanelControl { ...this._profileProperties(), name: name.trim(), 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, }, }; @@ -778,7 +873,7 @@ function distanceM([lon1, lat1], [lon2, lat2]) { return 12742000 * Math.asin(Math.sqrt(a)); } -function formatDuration(seconds) { +export function formatDuration(seconds) { const minutes = Math.round(seconds / 60); return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h ${minutes % 60} min`; } diff --git a/test/test_routing.rb b/test/test_routing.rb index 5c514ec..0138645 100644 --- a/test/test_routing.rb +++ b/test/test_routing.rb @@ -126,12 +126,13 @@ class RoutingTest < Minitest::Test def test_route_picks_the_costing_by_weight_and_returns_a_line shape = "wdg|xA{ubdQc@w@" 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. 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]) 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 [[1.5], [90]], route[:properties].values_at(:legs_km, :legs_s) # each leg's km and time, for the stops end assert_includes request, %("costing_options":{"auto":{"height":3.0,"width":2.3}}) diff --git a/test/test_trip.rb b/test/test_trip.rb index d78c7c1..4f015e6 100644 --- a/test/test_trip.rb +++ b/test/test_trip.rb @@ -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 Timeout.timeout(5) { sleep 0.05 until store.get[:version] == 2 } 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 assert_equal 1, calls.size 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 Dir.mktmpdir do |dir| store = Maptool::TripStore.new(File.join(dir, "trip.json")) diff --git a/views/index.erb b/views/index.erb index c4c7642..be1064c 100644 --- a/views/index.erb +++ b/views/index.erb @@ -106,11 +106,10 @@
    + Server status (all endpoints) ↗ CANopen diagnostics ↗
    - -