Driving mode ("Drive": big buttons — follow, zoom, 2D/3D, night, route overview — the sidebar hidden); palettes instead of the inversion (the UI's greys onto --ui-*, MapLibre's controls too, night → Night, new ◑ Dusk); the navigated route magenta, the driven part dimmed; route progress only forward (locate near the last position first); rerouting on the server off its own GNSS (TripStore#follow), the browser's only without the shared trip; the overview map hidden while following in 3D; the topbar's items apart
CI / check (push) Successful in 21s
CI / deploy (push) Successful in 17s

This commit is contained in:
randy committed 2026-12-01 01:44:54 +01:00
1 parent 12b4ac6725
commit 07a4d363ec
13 files changed
+513 -212

No files matched your search

+19 -10
View File
@@ -92,9 +92,10 @@ plan from — the server does the heavy lifting. The UI is built for a mouse tod
* [ ] Nothing reachable only by hover — tooltips and flyouts must open on tap too * [ ] Nothing reachable only by hover — tooltips and flyouts must open on tap too
* [ ] A touch substitute for the Alt+click debug inspector (e.g. long-press) * [ ] A touch substitute for the Alt+click debug inspector (e.g. long-press)
* [x] Side panels as an overlay in portrait instead of a pinned column — under 640 px the pin is ignored and the panel floats over the map at full width (a pinned 300 px panel left the phone a sliver of map); a real bottom sheet still open * [x] Side panels as an overlay in portrait instead of a pinned column — under 640 px the pin is ignored and the panel floats over the map at full width (a pinned 300 px panel left the phone a sliver of map); a real bottom sheet still open
* [ ] Driving mode (field test in the car, 2026-11): tiny icons and lists can't be hit while driving — a separate big-button UI for the few things needed on the road (navigate/follow, night mode, zoom, layer presets) rather than enlarging every planning panel * [x] Driving mode (field test in the car, 2026-11): tiny icons and lists can't be hit while driving — a separate big-button UI for the few things needed on the road (navigate/follow, night mode, zoom, layer presets) rather than enlarging every planning panel. Done: "Drive" in the topbar (`driving.js`), per device — Follow, zoom, 2D/3D, night, route overview, exit down the left side; the sidebar and panels hidden
** [ ] Layer presets on the driving bar
* [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
** [ ] 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
== NPS parks & maps == NPS parks & maps
@@ -227,7 +228,10 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
the route panel routes from the position to the points not reached yet (via points passed the route panel routes from the position to the points not reached yet (via points passed
by km along the route, `legs_km`), at most every 15 s and only moving by km along the route, `legs_km`), at most every 15 s and only moving
*** [ ] Step advance like Ferrostar's DistanceEntryExit (30 m to the step's end, 5 m past it) *** [ ] Step advance like Ferrostar's DistanceEntryExit (30 m to the step's end, 5 m past it)
instead of "the first maneuver ahead by km"; arrival at 30 m instead of "the first maneuver ahead by km"; arrival at 30 m. Done: progress only forward —
the position looked for near the last one first (`locate`, 0.1 km back to 3 km ahead), so a
route along the same road twice or crossing itself doesn't jump; the step still advances 5 m
past the maneuver. Arrival still to do
** [x] The navigation banner across the top (Dashboard widget, on by default): the next ** [x] The navigation banner across the top (Dashboard widget, on by default): the next
maneuver's arrow (Valhalla's maneuver type), distance and street, "then …" when the next one maneuver's arrow (Valhalla's maneuver type), distance and street, "then …" when the next one
follows within 300 m, its lanes from 1 km, the street being driven; `/api/route` maneuvers follows within 300 m, its lanes from 1 km, the street being driven; `/api/route` maneuvers
@@ -244,7 +248,7 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
PBF), and only for the direction driven (`traffic_signals:direction`) PBF), and only for the direction driven (`traffic_signals:direction`)
** [ ] The "Navigate" follow mode for the CAN GNSS position (today the MQTT tracker and the ** [ ] The "Navigate" follow mode for the CAN GNSS position (today the MQTT tracker and the
browser's GNSS control), the dashboard as part of the driving-mode UI browser's GNSS control), the dashboard as part of the driving-mode UI
** [ ] `locate()` scans the whole route each fix — a window around the last hit on long routes ** [x] `locate()` scans the whole route each fix — a window around the last hit on long routes
** [ ] Shared trip — one itinerary per server for every screen (the cab's display, the tablet ** [ ] Shared trip — one itinerary per server for every screen (the cab's display, the tablet
or display in the back, phones): the co-driver adds a stop, the driver's view reroutes on the or display in the back, phones): the co-driver adds a stop, the driver's view reroutes on the
fly without losing the map (no stop / reload / start like Android Auto between two phones) fly without losing the map (no stop / reload / start like Android Auto between two phones)
@@ -253,8 +257,10 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
unchanged), `PUT /api/trip` routes it on the server (not again when only names/nav unchanged), `PUT /api/trip` routes it on the server (not again when only names/nav
changed). Logged in, the route panel edits it and polls it every 2 s — other screens' changed). Logged in, the route panel edits it and polls it every 2 s — other screens'
changes swapped in, the camera untouched, the old route shown until the new one is in changes swapped in, the camera untouched, the old route shown until the new one is in
*** [ ] Rerouting on the server: it has the GNSS (CAN), so off-route detection and the new *** [x] Rerouting on the server: it has the GNSS (CAN), so off-route detection and the new
route once for all screens, not per screen with a dashboard (today's, `dashboard.js`) route once for all screens, not per screen with a dashboard. Done: `TripStore#follow` on
every fix (3 fixes > 30 m off while moving, at most every 15 s), the browser's own reroute
only without the shared trip
*** [ ] An itinerary view: stops by day/night, notes, planned arrival times (Valhalla's leg *** [ ] An itinerary view: stops by day/night, notes, planned arrival times (Valhalla's leg
times), "Add to the trip" from search, the library, park4night and other sources times), "Add to the trip" from search, the library, park4night and other sources
*** [ ] Brick ↔ the car: a trip planned at home on brick handed to the car's server (with *** [ ] Brick ↔ the car: a trip planned at home on brick handed to the car's server (with
@@ -288,8 +294,9 @@ Planning in the NPS look, driving in the cockpit look, joined by the Unigrid bla
. [x] Colors: tokens on `:root` (`--band`, `--inst-*`: ok / caution / warning, magenta = what . [x] Colors: tokens on `:root` (`--band`, `--inst-*`: ok / caution / warning, magenta = what
navigation follows, cyan = set by hand); the dashboard in them — a see-through black bezel, navigation follows, cyan = set by hand); the dashboard in them — a see-through black bezel,
light values, inverted back in night mode light values, inverted back in night mode
. [ ] The route line magenta while it's navigated (follow mode), blue while planning; the next . [x] The route line magenta while it's navigated (follow mode), blue while planning; the next
waypoint and maneuver magenta on the map too waypoint and maneuver magenta on the map too. Done for the line (the driven part dimmed,
while the dashboard is on the route); the waypoint / maneuver marks still to do
. [ ] The rest of the hard-coded colors → tokens (route, warnings, panel states), one place to tune . [ ] The rest of the hard-coded colors → tokens (route, warnings, panel states), one place to tune
. [ ] Panel headers as the Unigrid band: black, white title in National Park (headings weight . [ ] Panel headers as the Unigrid band: black, white title in National Park (headings weight
to vendor), the same band as the topbar to vendor), the same band as the topbar
@@ -300,9 +307,11 @@ Planning in the NPS look, driving in the cockpit look, joined by the Unigrid bla
`--inst-warning` fault) `--inst-warning` fault)
. [x] Palettes after IHO S-52: the same tokens in Day / Dusk / Night (`data-palette` on . [x] Palettes after IHO S-52: the same tokens in Day / Dusk / Night (`data-palette` on
`<html>`), night dim with low blue and no white areas, the speed limit sign dimmed too `<html>`), night dim with low blue and no white areas, the speed limit sign dimmed too
. [ ] Switch them: by the sun (the night mode's auto) and by hand (the topbar button cycles . [x] Switch them: by the sun (the night mode's auto) and by hand (the topbar button cycles
day / dusk / night / auto), replacing the inverting `html.night`; the planning UI's day / dusk / night / auto), replacing the inverting `html.night`; the planning UI's
hard-coded colors onto `--ui-*` first, or a dark palette leaves light panels hard-coded colors onto `--ui-*` first, or a dark palette leaves light panels. Done: the
greys onto `--ui-*` by role, MapLibre's controls/popups too; night mode sets Night, the new
"◑" mode Dusk (the day map)
. [ ] A Dusk map (between Park Tiles and `NightMap`), the map's palette following the UI's . [ ] A Dusk map (between Park Tiles and `NightMap`), the map's palette following the UI's
. [ ] Daylight: a full-opacity bezel preset for sun on the screen . [ ] Daylight: a full-opacity bezel preset for sun on the screen
+11 -3
View File
@@ -395,13 +395,12 @@ module Maptool
# the fix COURSE_MIN_M back when the receiver sends none — following # the fix COURSE_MIN_M back when the receiver sends none — following
# heading-up from behind (followPosition, gnss.js) turns by it. # heading-up from behind (followPosition, gnss.js) turns by it.
def self.gnss_update(gnss, at: Time.now.to_f) def self.gnss_update(gnss, at: Time.now.to_f)
GNSS_LATEST_MUTEX.synchronize do fix = GNSS_LATEST_MUTEX.synchronize do
GNSS_LATEST.merge!(gnss) GNSS_LATEST.merge!(gnss)
next unless gnss.key?(:lat) || gnss.key?(:lon) next unless gnss.key?(:lat) || gnss.key?(:lon)
GNSS_LATEST[:received_at] = at GNSS_LATEST[:received_at] = at
next if gnss.key?(:track) unless gnss.key?(:track)
position = GNSS_LATEST.values_at(:lon, :lat) position = GNSS_LATEST.values_at(:lon, :lat)
from = GNSS_LATEST[:course_from] from = GNSS_LATEST[:course_from]
if from.nil? || (GNSS_LATEST[:speed] || 0) < COURSE_MIN_SPEED if from.nil? || (GNSS_LATEST[:speed] || 0) < COURSE_MIN_SPEED
@@ -411,6 +410,15 @@ module Maptool
GNSS_LATEST[:course_from] = position GNSS_LATEST[:course_from] = position
end end
end end
GNSS_LATEST.dup
end
return unless fix && fix[:lat] && fix[:lon]
# off the shared trip's route: routed again from here (TripStore#follow)
TRIP_STORE.follow([fix[:lon], fix[:lat]], speed: fix[:speed], hdop: fix[:hdop]) do |locations, vehicle, avoid|
Routing.route(VALHALLA_URL, locations, Routing.vehicle(DATA_DIR, vehicle), avoid.transform_keys(&:to_s))
end
end end
# Native CAN (lib/maptool/can.rb), on when data/can.json exists: one # Native CAN (lib/maptool/can.rb), on when data/can.json exists: one
+9 -4
View File
@@ -86,10 +86,15 @@ Our night values are roughly a third of Day's luminance, warm greys, blue
kept low; no white areas (the speed limit sign dims too). The map has its kept low; no white areas (the speed limit sign dims too). The map has its
own night palette (`NightMap`, `map_themes.js`); a Dusk map is still to do. own night palette (`NightMap`, `map_themes.js`); a Dusk map is still to do.
Today the page's night mode inverts the whole UI (`html.night`, the The night mode sets the palette (`map.js`): automatic by the sun or on →
instruments inverted back). The palettes replace that: set the Night (with the night map), "◑" → Dusk over the day map, off → Day. The
`data-palette`, by the sun (already worked out for the night mode) or by planning UI's greys are the `--ui-*` tokens (`--ui-bg`, `--ui-bg-2` for
hand. hover and fills, `--ui-line`, `--ui-fg`, `--ui-muted`); MapLibre's own
controls and popups take them too.
The driving mode (`driving.js`, "Drive" in the topbar) is the cockpit's
input side: big band-black buttons down the map's left — follow, zoom,
2D/3D, night, the route overview — and the planning sidebar hidden.
== Typography == Typography
+61
View File
@@ -25,6 +25,67 @@ module Maptool
@mutex.synchronize { @trip.dup } @mutex.synchronize { @trip.dup }
end end
ON_ROUTE_M = 30 # as the dashboard's
OFF_ROUTE_FIXES = 3
MAX_HDOP = 5
MIN_SPEED = 1.5 # m/s: standing next to the route isn't a detour
REROUTE_EVERY_S = 15
# Every GNSS fix (App.gnss_update): off the trip's route for
# OFF_ROUTE_FIXES fixes while driving, routes again from here to the
# points not reached yet — on the server, so it happens with no screen
# open; the screens pick the new version up by polling. The block routes
# (as #update's). In a thread of its own: CAN's reader doesn't wait.
def follow(position, speed:, hdop: nil, now: Time.now.to_f, &router)
trip = get
route = trip[:route]
return unless route && trip[:points].size >= 2
at, off = self.class.locate(route[:geometry][:coordinates], position)
if off <= ON_ROUTE_M
@off_fixes = 0
@last_at = at
return
end
return if (hdop || 0) > MAX_HDOP
@off_fixes = (@off_fixes || 0) + 1
return if @off_fixes < OFF_ROUTE_FIXES || speed.to_f < MIN_SPEED || (@reroute_at && now - @reroute_at < REROUTE_EVERY_S) || @rerouting
@reroute_at = now
@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)
Thread.new do
update(points: points, vehicle: trip[:vehicle], avoid: trip[:avoid], editing: trip[:editing], &router)
rescue StandardError => e
warn "trip reroute: #{e.message}"
ensure
@rerouting = false
@off_fixes = 0
end
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)
along = 0.0
best = [0.0, Float::INFINITY]
coords.each_cons(2) do |(ax, ay), (bx, by)|
ax *= cos
bx *= cos
px = lon * cos
len2 = (bx - ax)**2 + (by - ay)**2
t = len2.zero? ? 0.0 : (((px - ax) * (bx - ax) + (lat - ay) * (by - ay)) / len2).clamp(0.0, 1.0)
off = Math.hypot(px - (ax + t * (bx - ax)), lat - (ay + t * (by - ay))) * 111_320
length = Math.sqrt(len2) * 111.32
best = [along + t * length, off] if off < best[1]
along += length
end
best
end
# points: [{ lngLat: [lon, lat], name:, nav: }]. Routes through them with # points: [{ lngLat: [lon, lat], name:, nav: }]. Routes through them with
# the block (locations, vehicle id, avoid → the /api/route Feature, may # the block (locations, vehicle id, avoid → the /api/route Feature, may
# raise Routing errors) unless only names/nav changed — the old route # raise Routing errors) unless only names/nav changed — the old route
+206 -172
View File
File diff suppressed because it is too large. Load diff
+33 -6
View File
@@ -1,5 +1,5 @@
import { isLoggedIn } from "/js/auth.js"; import { isLoggedIn } from "/js/auth.js";
import { onRouteChanged, requestReroute, requestGnssFollow } from "/js/panels.js"; import { onRouteChanged, requestReroute, requestGnssFollow, notifyRouteProgress } from "/js/panels.js";
import { elevationAt } from "/js/dem.js"; import { elevationAt } from "/js/dem.js";
// The car's dashboard over the map, off the CAN signals (GET /api/can, // The car's dashboard over the map, off the CAN signals (GET /api/can,
@@ -102,13 +102,27 @@ function prepareRoute(route) {
return { coords, km, limits: route.properties.speed_limits, signals: route.properties.signals || [], maneuvers, viaKm }; return { coords, km, limits: route.properties.speed_limits, signals: route.properties.signals || [], maneuvers, viaKm };
} }
// Nearest point on the route: [km along it, meters off it]. // Nearest point on the route: [km along it, meters off it]. Near the last
// ponytail: scans every segment each fix — a window around the last hit if long routes get slow. // one first (fromKm: LOCATE_BACK_KM behind to LOCATE_AHEAD_KM ahead), so a
function locate(route, position) { // route that comes back along the same road or crosses itself doesn't jump
// to the other pass — progress goes forward, as Ferrostar's does; the whole
// route only when that window has nothing close (a reroute, a restart).
const LOCATE_BACK_KM = 0.1;
const LOCATE_AHEAD_KM = 3;
function locate(route, position, fromKm = null) {
if (fromKm != null) {
const near = locateIn(route, position, fromKm - LOCATE_BACK_KM, fromKm + LOCATE_AHEAD_KM);
if (near[1] <= ON_ROUTE_M) return near;
}
return locateIn(route, position, -Infinity, Infinity);
}
function locateIn(route, position, fromKm, toKm) {
let best = [0, Infinity]; let best = [0, Infinity];
const { coords, km } = route; const { coords, km } = route;
const cos = Math.cos(position[1] * RAD); const cos = Math.cos(position[1] * RAD);
for (let i = 1; i < coords.length; i++) { for (let i = 1; i < coords.length; i++) {
if (km[i] < fromKm || km[i - 1] > toKm) continue;
const [ax, ay] = [coords[i - 1][0] * cos, coords[i - 1][1]]; const [ax, ay] = [coords[i - 1][0] * cos, coords[i - 1][1]];
const [bx, by] = [coords[i][0] * cos, coords[i][1]]; const [bx, by] = [coords[i][0] * cos, coords[i][1]];
const [px, py] = [position[0] * cos, position[1]]; const [px, py] = [position[0] * cos, position[1]];
@@ -161,6 +175,7 @@ export class DashboardControl {
this._route = prepareRoute(route); this._route = prepareRoute(route);
this._lastAt = 0; this._lastAt = 0;
this._offFixes = 0; this._offFixes = 0;
this._sentKm = undefined; // the new route drawn by the next fix
})); }));
this._trace = []; // [lon, lat] fixes TRACE_STEP_M apart, for /api/road this._trace = []; // [lon, lat] fixes TRACE_STEP_M apart, for /api/road
this._road = null; // its last answer this._road = null; // its last answer
@@ -195,6 +210,13 @@ export class DashboardControl {
this._values.roll = deg(left - right); this._values.roll = deg(left - right);
} }
// To the route panel (the driven part dimmed), when it moved ≥ 10 m.
_progress(km) {
if (km === this._sentKm || (km != null && this._sentKm != null && Math.abs(km - this._sentKm) < 0.01)) return;
this._sentKm = km;
notifyRouteProgress(km);
}
// The limit and what's ahead: from the route while on it, else the road. // The limit and what's ahead: from the route while on it, else the road.
_navigate() { _navigate() {
const { lat, lon, speed } = this._values; const { lat, lon, speed } = this._values;
@@ -202,7 +224,7 @@ export class DashboardControl {
const position = [lon, lat]; const position = [lon, lat];
if (!this._trace.length || meters(this._trace.at(-1), position) >= TRACE_STEP_M) this._trace = [...this._trace.slice(-7), position]; if (!this._trace.length || meters(this._trace.at(-1), position) >= TRACE_STEP_M) this._trace = [...this._trace.slice(-7), position];
const [at, off] = this._route ? locate(this._route, position) : [0, Infinity]; const [at, off] = this._route ? locate(this._route, position, this._lastAt || null) : [0, Infinity];
const fresh = position.join() !== this._lastFix; // polled faster than the fixes come const fresh = position.join() !== this._lastFix; // polled faster than the fixes come
this._lastFix = position.join(); this._lastFix = position.join();
if (fresh && this._route && off > ON_ROUTE_M && (this._values.hdop ?? 0) <= MAX_HDOP) this._offFixes++; if (fresh && this._route && off > ON_ROUTE_M && (this._values.hdop ?? 0) <= MAX_HDOP) this._offFixes++;
@@ -216,7 +238,10 @@ export class DashboardControl {
const maneuver = maneuvers[index]; const maneuver = maneuvers[index];
const then = maneuvers[index + 1]; const then = maneuvers[index + 1];
const onStreet = maneuvers[index - 1]?.street; // the one being driven: the last maneuver's const onStreet = maneuvers[index - 1]?.street; // the one being driven: the last maneuver's
if (off <= ON_ROUTE_M) this._lastAt = at; if (off <= ON_ROUTE_M) {
this._lastAt = at;
this._progress(at);
}
this._nav = { this._nav = {
limit: current?.[1] ?? null, limit: current?.[1] ?? null,
next: next && { limit: next[1], m: (next[0] - at) * 1000 }, next: next && { limit: next[1], m: (next[0] - at) * 1000 },
@@ -227,6 +252,7 @@ export class DashboardControl {
}; };
return; return;
} }
this._progress(null);
this._nav = { limit: this._road?.speed_limit ?? null, offRoute: !!this._route, street: this._road?.name }; this._nav = { limit: this._road?.speed_limit ?? null, offRoute: !!this._route, street: this._road?.name };
if (this._route && (speed ?? 0) >= MOVING_MS && Date.now() - this._rerouteAt >= REROUTE_EVERY_MS) { if (this._route && (speed ?? 0) >= MOVING_MS && Date.now() - this._rerouteAt >= REROUTE_EVERY_MS) {
this._rerouteAt = Date.now(); this._rerouteAt = Date.now();
@@ -352,6 +378,7 @@ export class DashboardControl {
} }
_disable() { _disable() {
this._progress(null);
clearTimeout(this._timer); clearTimeout(this._timer);
this._timer = null; this._timer = null;
this._card?.remove(); this._card?.remove();
+74
View File
@@ -0,0 +1,74 @@
import { LngLatBounds } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { requestGnssFollow, onRouteChanged } from "/js/panels.js";
import { pauseFollow, resumeFollow } from "/js/gnss.js";
// Driving mode: the few things needed on the road as big buttons down the
// side of the map, the planning sidebar and panels out of the way (TODO:
// tiny icons can't be hit while driving). Per device (localStorage).
const KEY = "drivingMode";
const PITCH_3D = 60; // as map.js's 3D toggle
export function setupDriving(map, nightButton) {
let route = onRouteChanged((r) => (route = r));
const toggle = document.createElement("button");
toggle.type = "button";
toggle.className = "topbar__drive";
toggle.title = "Driving mode: big buttons, no planning panels";
toggle.textContent = "Drive";
nightButton.before(toggle);
const bar = document.createElement("div");
bar.className = "drive-bar";
bar.hidden = true;
const buttons = {
follow: ["Follow", "Follow the position, heading up in 3D", () => {
requestGnssFollow();
resumeFollow(map);
if (map.getPitch() === 0) map.easeTo({ pitch: PITCH_3D, duration: 300 });
}],
zoomIn: ["+", "Zoom in", () => map.zoomIn()],
zoomOut: ["−", "Zoom out", () => map.zoomOut()],
pitch: ["2D", "2D / 3D", () => map.easeTo({ pitch: map.getPitch() > 0 ? 0 : PITCH_3D, ...(map.getPitch() > 0 && { bearing: 0 }), duration: 300 })],
night: ["", "Night mode", () => nightButton.click()],
overview: ["Route", "The whole route (the follow pauses)", () => {
const coords = route?.geometry?.coordinates;
if (!coords?.length) return;
pauseFollow(map);
map.fitBounds(coords.reduce((b, c) => b.extend(c), new LngLatBounds(coords[0], coords[0])), { padding: 80, pitch: 0, bearing: 0 });
}],
exit: ["✕", "Leave driving mode", () => set(false)],
};
for (const [name, [label, title, action]] of Object.entries(buttons)) {
const button = document.createElement("button");
button.type = "button";
button.className = `drive-bar__${name}`;
button.textContent = label;
button.title = title;
button.setAttribute("aria-label", title);
button.addEventListener("click", action);
bar.appendChild(button);
}
map.getContainer().appendChild(bar);
const render = () => {
bar.querySelector(".drive-bar__pitch").textContent = map.getPitch() > 0 ? "2D" : "3D";
bar.querySelector(".drive-bar__night").textContent = nightButton.textContent;
bar.querySelector(".drive-bar__overview").disabled = !route;
};
map.on("pitchend", render);
nightButton.addEventListener("click", render);
onRouteChanged(render);
function set(on) {
document.documentElement.classList.toggle("driving", on);
bar.hidden = !on;
toggle.classList.toggle("active", on);
try { localStorage.setItem(KEY, on ? "on" : "off"); } catch { /* private window: not kept */ }
render();
map.resize(); // the sidebar came or went
}
toggle.addEventListener("click", () => set(bar.hidden));
let saved = null;
try { saved = localStorage.getItem(KEY); } catch { /* nothing kept */ }
set(saved === "on");
}
+23 -10
View File
@@ -38,27 +38,40 @@ function freeLookState(map) {
button.hidden = true; button.hidden = true;
map.getContainer().appendChild(button); map.getContainer().appendChild(button);
state = { until: 0, button, followedAt: 0 }; state = { until: 0, button, followedAt: 0 };
button.addEventListener("click", () => { button.addEventListener("click", () => resumeFollow(map));
state.until = 0;
button.hidden = true;
clearTimeout(state.timer);
});
const touched = (e) => { const touched = (e) => {
// our own easeTo, or nothing being followed (GNSS off) // our own easeTo, or nothing being followed (GNSS off)
if (!e.originalEvent || Date.now() - state.followedAt > FOLLOWING_MS) return; if (e.originalEvent && Date.now() - state.followedAt <= FOLLOWING_MS) pauseFollow(map);
state.until = Date.now() + FREE_LOOK_MS;
button.hidden = false;
clearTimeout(state.timer);
state.timer = setTimeout(() => (button.hidden = true), FREE_LOOK_MS);
}; };
for (const type of ["dragstart", "zoomstart", "rotatestart", "pitchstart", "move"]) map.on(type, touched); for (const type of ["dragstart", "zoomstart", "rotatestart", "pitchstart", "move"]) map.on(type, touched);
freeLook.set(map, state); freeLook.set(map, state);
return state; return state;
} }
// Also for a view the app moves to itself (the driving bar's route overview).
export function pauseFollow(map) {
const state = freeLookState(map);
state.until = Date.now() + FREE_LOOK_MS;
state.button.hidden = false;
clearTimeout(state.timer);
state.timer = setTimeout(() => (state.button.hidden = true), FREE_LOOK_MS);
}
export function resumeFollow(map) {
const state = freeLookState(map);
state.until = 0;
state.button.hidden = true;
clearTimeout(state.timer);
}
export function followPosition(map, lngLat, heading, speed, duration) { export function followPosition(map, lngLat, heading, speed, duration) {
const free = freeLookState(map); const free = freeLookState(map);
free.followedAt = Date.now(); free.followedAt = Date.now();
// following in 3D like a navigation: the overview map out of the way
// (style.css), back once the follow stops or the view goes 2D
document.documentElement.classList.toggle("follow-3d", map.getPitch() > 0);
clearTimeout(free.followTimer);
free.followTimer = setTimeout(() => document.documentElement.classList.remove("follow-3d"), FOLLOWING_MS);
if (Date.now() < free.until) return; if (Date.now() < free.until) return;
free.button.hidden = true; free.button.hidden = true;
const pitched = map.getPitch() > 0; const pitched = map.getPitch() > 0;
+17 -4
View File
@@ -29,6 +29,7 @@ import { offerSharedFiles } from "/js/share_import.js";
import HomeButton from "/vendor/npmap-home-button/home-button.esm.js"; import HomeButton from "/vendor/npmap-home-button/home-button.esm.js";
import OverviewMap from "/vendor/npmap-overview/overview.esm.js"; import OverviewMap from "/vendor/npmap-overview/overview.esm.js";
import * as maplibregl from "/vendor/maplibre-gl/maplibre-gl.mjs"; import * as maplibregl from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { setupDriving } from "/js/driving.js";
const CENTER = [17.1077, 48.1486]; const CENTER = [17.1077, 48.1486];
const ZOOM = 13; const ZOOM = 13;
@@ -467,10 +468,18 @@ updateSun();
map.on("moveend", updateSun); map.on("moveend", updateSun);
setInterval(updateSun, 60000); setInterval(updateSun, 60000);
// Night mode (html.night, style.css) so the screen doesn't glare in the // Night mode so the screen doesn't glare in the car: "auto" follows the sun
// car: "auto" follows the sun at the map center, or forced on/off — the // at the map center, or by hand — the topbar button cycles them,
// topbar button cycles the three, remembered per device. // remembered per device.
const NIGHT_MODES = { auto: ["◐", "Night mode: automatic (after sunset)"], on: ["☾", "Night mode: on"], off: ["☀", "Night mode: off"] }; // The UI's palette (style.css, after S-52: Day, Dusk, Night) and the map's
// night style: automatic by the sun, or by hand — Dusk the dark UI over the
// day map, "for optional use by day as well" (docs/design.adoc).
const NIGHT_MODES = {
auto: ["◐", "Night mode: automatic (after sunset)"],
on: ["☾", "Night mode: on"],
dusk: ["◑", "Dusk: the dark UI over the day map"],
off: ["☀", "Night mode: off"],
};
const nightButton = document.querySelector(".topbar__night"); const nightButton = document.querySelector(".topbar__night");
const nightMap = new NightMap(map); const nightMap = new NightMap(map);
// The base style's texture patterns (grass, scrub, military hatch) and the // The base style's texture patterns (grass, scrub, military hatch) and the
@@ -506,6 +515,9 @@ const updateNight = () => {
const { lng, lat } = sunAt; const { lng, lat } = sunAt;
const dark = nightMode === "on" || (nightMode === "auto" && getPosition(new Date(), lat, lng).altitude < 0); const dark = nightMode === "on" || (nightMode === "auto" && getPosition(new Date(), lat, lng).altitude < 0);
document.documentElement.classList.toggle("night", dark); document.documentElement.classList.toggle("night", dark);
const palette = dark ? "night" : nightMode === "dusk" ? "dusk" : null;
if (palette) document.documentElement.dataset.palette = palette;
else delete document.documentElement.dataset.palette;
nightMap.set(dark); nightMap.set(dark);
[nightButton.textContent, nightButton.title] = NIGHT_MODES[nightMode] || NIGHT_MODES.auto; [nightButton.textContent, nightButton.title] = NIGHT_MODES[nightMode] || NIGHT_MODES.auto;
}; };
@@ -520,6 +532,7 @@ 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");
+13
View File
@@ -123,6 +123,19 @@ export function notifyRouteChanged(route) {
document.dispatchEvent(new CustomEvent(ROUTE_CHANGED_EVENT, { detail: route })); document.dispatchEvent(new CustomEvent(ROUTE_CHANGED_EVENT, { detail: route }));
} }
// How far along the route the position is, while the dashboard follows it
// (km, or null once it's off it / not navigating): the route panel draws
// the driven part dimmed and the rest as the active route.
const ROUTE_PROGRESS_EVENT = "route-progress";
export function notifyRouteProgress(km) {
document.dispatchEvent(new CustomEvent(ROUTE_PROGRESS_EVENT, { detail: km }));
}
export function onRouteProgress(callback) {
document.addEventListener(ROUTE_PROGRESS_EVENT, (event) => callback(event.detail));
}
// Off the route while navigating: the route panel routes again from `from` // Off the route while navigating: the route panel routes again from `from`
// ([lon, lat]) to the points not yet reached (`passed` via points skipped). // ([lon, lat]) to the points not yet reached (`passed` via points skipped).
const REROUTE_EVENT = "route-reroute"; const REROUTE_EVENT = "route-reroute";
+22 -3
View File
@@ -1,6 +1,6 @@
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs"; import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { ROUTE_ICON, POSITION_ICON, SAVED_POINT_ICON, REVERSE_ICON, CLEAR_ICON, SAVE_ICON } from "/js/icons.js"; import { ROUTE_ICON, POSITION_ICON, SAVED_POINT_ICON, REVERSE_ICON, CLEAR_ICON, SAVE_ICON } from "/js/icons.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen, notifyGpxStoreChanged, onRoutePoint, onRouteEdit, notifyRouteChanged, onReroute } from "/js/panels.js"; import { notifySidePanelOpen, onlyOneSidePanelOpen, notifyGpxStoreChanged, onRoutePoint, onRouteEdit, notifyRouteChanged, onReroute, onRouteProgress } from "/js/panels.js";
import { isLoggedIn } from "/js/auth.js"; import { isLoggedIn } from "/js/auth.js";
import { wirePreview } from "/js/preview.js"; import { wirePreview } from "/js/preview.js";
import { elevationAt } from "/js/dem.js"; import { elevationAt } from "/js/dem.js";
@@ -52,12 +52,14 @@ export class RoutePanelControl {
// Rerouting (the dashboard, off the route): the start and the via points // Rerouting (the dashboard, off the route): the start and the via points
// already passed give way to the current position. // already passed give way to the current position.
onReroute(({ from, passed }) => { onReroute(({ from, passed }) => {
if (this._points.length < 2) return; // 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()); this._points.splice(0, 1 + passed).forEach((p) => p.marker.remove());
this._addPoint(from, "My position", { quiet: true }); this._addPoint(from, "My position", { quiet: true });
this._points.unshift(this._points.pop()); this._points.unshift(this._points.pop());
this._changed(); this._changed();
}); });
onRouteProgress((km) => this._showProgress(km));
onRoutePoint(({ lngLat, name }) => { onRoutePoint(({ lngLat, name }) => {
this._setOpen(true); this._setOpen(true);
this._addPoint(lngLat, name); this._addPoint(lngLat, name);
@@ -455,7 +457,7 @@ export class RoutePanelControl {
source.setData(data); source.setData(data);
return; return;
} }
this._map.addSource(SOURCE, { type: "geojson", data }); this._map.addSource(SOURCE, { type: "geojson", data, lineMetrics: true }); // line-progress for _showProgress
this._map.addLayer({ this._map.addLayer({
id: `${SOURCE}-casing`, id: `${SOURCE}-casing`,
type: "line", type: "line",
@@ -480,6 +482,23 @@ export class RoutePanelControl {
}); });
} }
// Navigated (km along the route, docs/design.adoc): the driven part
// dimmed, the rest magenta (--route-active); null: the planned blue.
_showProgress(km) {
if (!this._map.getLayer(`${SOURCE}-line`)) return;
const total = this._route?.properties.distance_km;
if (km == null || !total) {
this._map.setPaintProperty(`${SOURCE}-line`, "line-gradient", undefined);
return;
}
const css = getComputedStyle(document.documentElement);
const active = css.getPropertyValue("--route-active").trim() || "#a21caf";
const driven = css.getPropertyValue("--ui-muted").trim() || "#6b6b66";
const fraction = Math.min(1, Math.max(0, km / total));
this._map.setPaintProperty(`${SOURCE}-line`, "line-gradient",
fraction > 0 ? ["step", ["line-progress"], driven, fraction, active] : ["step", ["line-progress"], active, 1, active]);
}
// A route item in the library ("Routes" folder), keeping its points and // A route item in the library ("Routes" folder), keeping its points and
// vehicle so it can be routed again later; an edited one is updated in // vehicle so it can be routed again later; an edited one is updated in
// place. // place.
+24
View File
@@ -1,5 +1,6 @@
require_relative "test_helper" require_relative "test_helper"
require "tmpdir" require "tmpdir"
require "timeout"
require_relative "../lib/maptool/trip" require_relative "../lib/maptool/trip"
class TripTest < Minitest::Test class TripTest < Minitest::Test
@@ -25,6 +26,29 @@ class TripTest < Minitest::Test
end end
end end
# Off the route while driving for 3 fixes: routed again from the position
# to the points not reached yet (the first via passed: dropped).
def test_following_reroutes_from_the_position_off_the_route
Dir.mktmpdir do |dir|
store = Maptool::TripStore.new(File.join(dir, "trip.json"))
line = { geometry: { coordinates: [[17.0, 48.0], [17.1, 48.0], [17.2, 48.0]] }, properties: { legs_km: [7.44, 7.44] } }
points = [{ lngLat: [17.0, 48.0] }, { lngLat: [17.1, 48.0] }, { lngLat: [17.2, 48.0] }]
calls = []
router = ->(locations, _vehicle, _avoid) { calls << locations; line }
store.update(points: points, vehicle: nil, avoid: {}, editing: nil, &router)
calls.clear
store.follow([17.15, 48.0], speed: 20, now: 0, &router) # on it, past the via
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]
store.follow([17.15, 48.02], speed: 20, now: 5, &router) # within REROUTE_EVERY_S: nothing
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
View File
@@ -19,6 +19,7 @@
"/js/hiking_trails.js": "/js/hiking_trails.js?v=<%= ASSET_VERSION %>", "/js/hiking_trails.js": "/js/hiking_trails.js?v=<%= ASSET_VERSION %>",
"/js/live.js": "/js/live.js?v=<%= ASSET_VERSION %>", "/js/live.js": "/js/live.js?v=<%= ASSET_VERSION %>",
"/js/dashboard.js": "/js/dashboard.js?v=<%= ASSET_VERSION %>", "/js/dashboard.js": "/js/dashboard.js?v=<%= ASSET_VERSION %>",
"/js/driving.js": "/js/driving.js?v=<%= ASSET_VERSION %>",
"/js/update.js": "/js/update.js?v=<%= ASSET_VERSION %>", "/js/update.js": "/js/update.js?v=<%= ASSET_VERSION %>",
"/js/icons.js": "/js/icons.js?v=<%= ASSET_VERSION %>", "/js/icons.js": "/js/icons.js?v=<%= ASSET_VERSION %>",
"/js/livetrack.js": "/js/livetrack.js?v=<%= ASSET_VERSION %>", "/js/livetrack.js": "/js/livetrack.js?v=<%= ASSET_VERSION %>",