From f73badd107064206f149fc50f7ff640ae2420577 Mon Sep 17 00:00:00 2001 From: Roman Priesol Date: Thu, 3 Dec 2026 10:47:40 +0100 Subject: [PATCH] =?UTF-8?q?Drive=20as=20the=20Design=20canvas'=20Grid:=20t?= =?UTF-8?q?he=20page=20as=2016=20=C3=97=2010=20cells=20from=20a=20screen?= =?UTF-8?q?=20profile=20(public/drive/road.json,=20{area,=20widget,=20?= =?UTF-8?q?=E2=80=A6}=20per=20cell,=20to=20be=20edited=20in=20the=20app=20?= =?UTF-8?q?later),=20the=20map=2013=20=C3=97=208=20with=20nothing=20over?= =?UTF-8?q?=20it;=20the=20manoeuvre,=20speed,=20limit,=20altitude,=20time,?= =?UTF-8?q?=20sun,=20status=20(online,=20rec),=20next=20stop=20with=20km?= =?UTF-8?q?=20/=20ETA=20to=20it=20and=20to=20the=20end,=20the=20route's=20?= =?UTF-8?q?elevation=20of=20the=20next=2010=20km,=20a=20compass;=20keys=20?= =?UTF-8?q?Trip,=20Points,=20Layers,=20Search,=20Menu,=20=E2=88=92=20+=203?= =?UTF-8?q?D=20Follow,=20Terrain,=20day/dusk/night.=20A=20menu=20opens=20i?= =?UTF-8?q?n=20the=20right=207=20=C3=97=208=20as=20cells=20of=20its=20own?= =?UTF-8?q?=20and=20the=20map=20narrows=20to=209=20=C3=97=208=20(drive=5Fm?= =?UTF-8?q?enus.js):=20Trip=20and=20Search=20as=20GridTrip=20/=20GridSearc?= =?UTF-8?q?h=20(a=20stop=20a=20row,=20=E2=9C=93=20=E2=86=91=20=E2=86=93=20?= =?UTF-8?q?=E2=9C=95=20a=20cell=20each;=20results=20with=20their=20pins=20?= =?UTF-8?q?on=20the=20map);=20Points=20as=20GridPoints=20(the=20library=20?= =?UTF-8?q?nearest=20the=20car=20=E2=80=94=20/api/search=20with=20no=20wor?= =?UTF-8?q?ds=20and=20a=20center=20lists=20every=20saved=20feature=20neare?= =?UTF-8?q?st=20first=20=E2=80=94=20along=20the=20route=20ahead,=20shown,?= =?UTF-8?q?=20or=20one=20folder=20at=20a=20time;=20an=20eye=20per=20row,?= =?UTF-8?q?=20+=20a=20point=20as=20a=20stop);=20Layers=20as=20GridLayers?= =?UTF-8?q?=20(the=20On=20the=20map=20panel's=20own=20switches=20and=20Onl?= =?UTF-8?q?ine=20|=20Offline,=20presets=20Road=20/=20Off-road=20/=20Overni?= =?UTF-8?q?ght,=20+=20Keep);=20Terrain=20as=20GridTerrain=20(roll=20/=20pi?= =?UTF-8?q?tch=20dials=20with=20the=20max=20held,=20climb=20and=20side=20s?= =?UTF-8?q?lope=20ahead=20from=20the=20DEM,=20the=20next=202=20km,=20Level?= =?UTF-8?q?=20here=20=3D=20can.json's=20levelling=20action=20in=20two=20ta?= =?UTF-8?q?ps),=20on=20by=20itself=20on=20an=20unpaved=20surface=20(/api/r?= =?UTF-8?q?oad=20now=20gives=20Valhalla's=20surface)=20or=20past=2010?= =?UTF-8?q?=C2=B0=20for=2010=20s,=20back=20after=202=20km=20of=20paved=20r?= =?UTF-8?q?oad,=20automatic=20/=20by=20hand=20in=20the=20Menu.=20The=20das?= =?UTF-8?q?hboard=20polls=20for=20the=20grid=20without=20its=20overlay;=20?= =?UTF-8?q?the=20old=20drive=20bar=20and=20floating=20buttons=20gone?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TODO.adoc | 25 +- docs/design.adoc | 15 +- lib/maptool/routing.rb | 9 +- lib/maptool/search.rb | 5 +- public/css/style.css | 368 +++++++++++++++++---------- public/drive/road.json | 34 +++ public/js/dashboard.js | 58 ++++- public/js/drive_menus.js | 454 +++++++++++++++++++++++++++++++++ public/js/driving.js | 528 ++++++++++++++++++++++++++++++--------- public/js/gpx.js | 20 ++ public/js/map.js | 2 +- test/test_routing.rb | 4 +- test/test_search.rb | 7 + views/importmap.erb | 1 + 14 files changed, 1253 insertions(+), 277 deletions(-) create mode 100644 public/drive/road.json create mode 100644 public/js/drive_menus.js diff --git a/TODO.adoc b/TODO.adoc index 4408498..7f2d641 100644 --- a/TODO.adoc +++ b/TODO.adoc @@ -97,10 +97,33 @@ plan from — the server does the heavy lifting. The UI is built for a mouse tod * [ ] 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] 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] Layer presets on the driving bar (Layers: Road / Off-road / Overnight, + Keep) ** [x] The bar after the research (docs/design.adoc, "Buttons while driving"): four buttons (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 +** [~] The Grid of the Design canvas (docs/design.adoc, "Layout: a grid"), 2026-12-03: the page + as 16 × 10 cells, the map 13 × 8, nothing over it; which cell shows what is the screen + profile `public/drive/road.json` (`{area, widget, …}`, to be edited in the app later). + Done: manoeuvre, speed, limit, altitude, time, sun, status (online, rec); next stop, km/ETA + to it and to the end; elevation of the next 10 km; compass; keys Trip, Search, Menu (the + whole route, leave), − + 3D Follow, day/dusk/night; a menu in the right 7 × 8, the map + 9 × 8; the dashboard polls for the grid without its overlay. Trip and Search as GridTrip / + GridSearch: the menu area as cells (a stop a row: name over 3, ✓ ↑ ↓ ✕ one each; recording + on top, + stop / start from the car at the foot), results a row each with their pins on the + map (saved cyan, places amber), "← Back to the stops". Points and Layers as GridPoints / + GridLayers (`drive_menus.js`): Points the library nearest the car (`/api/search` with no + words and a center lists every saved feature nearest first), Ahead (within 2 km of the + route still to drive, of those 50), Shown, or one folder at a time; an eye per row, + a + point as a stop. Layers the On the map panel's own checkboxes and Online | Offline, the ones + on first; presets Road / Off-road / Overnight, + Keep saves what's on into one (per + device). Terrain as GridTerrain (⛰): roll and pitch dials (amber / red, the max held until + Reset), heading, climb in 300 m and side slope 50 m ahead (DEM along the course), the + route's next 2 km, Level here (can.json's levelling action, two taps), Road view; on by + itself on an unpaved surface (`/api/road` now gives Valhalla's `surface`, off a route only) + or roll / pitch past 10° for 10 s, back after 2 km of paved road; Menu: automatic / by + hand. Still to do: the surface while on a route (along the route's edges), Surface in the + top row in place of Limit while off-road, + the lanes in the manoeuvre cell, the profile served from `data/` once the editor exists ** [ ] Softkeys: the CAN keypad's labels on the screen edge next to its keys (G1000 style) ** [x] The Trip menu beside the map, not over it (Android Auto's side panel, seen again in signalk-pypilot-newui): the map narrower, its buttons kept, its center (follow, crosshair, diff --git a/docs/design.adoc b/docs/design.adoc index dfdaf41..bc146bc 100644 --- a/docs/design.adoc +++ b/docs/design.adoc @@ -279,7 +279,15 @@ comes from, is one too) of *16 × 10 cells of 80 px* on the navigator's user's to arrange later. Mockups: the Design canvas (claude.ai, private), artboards Grid, -GridTrip, GridSearch. To be tried against: OpenCPN itself. +GridTrip, GridSearch, GridPoints, GridLayers, GridTerrain. To be tried +against: OpenCPN itself. + +Built (2026-12-03): `driving.js` lays the page out as the profile's cells +(`public/drive/road.json`), the menus in `drive_menus.js` — Trip and +Search, Points (the library nearest the car, along the route ahead, shown, +or by folder), Layers (the On the map panel's own switches, presets Road / +Off-road / Overnight, + Keep saves what's on into one) and Terrain. A menu +is a grid of cells too: a row per item, a cell per action. Sources: OpenCPN manuals — Dashboard (opencpn-manuals.github.io/main/dashboard), inland ECDIS getting started; @@ -296,6 +304,11 @@ map, a menu panel or a row of keys — plus the condition that switches it on. Every cell is configurable; the grid differs per screen (16″ 1280×800 is 16 × 10), so profiles are per screen type. Edited in the app, standing only: tap a cell → widget and signal, drag a corner → its size. +Today one profile, `public/drive/road.json` (`columns`, `rows`, the map's +area, the menu's area and the map's beside it, `cells`: `{area, widget, +value | action | km}`; widgets `maneuver`, `field`, `status`, +`elevation`, `compass`, `key`); once the editor exists it saves to +`data/` and the file is the default. *Terrain* (artboard GridTerrain): the inclinometer only off-road — on the road its cells show the elevation ahead. A 7 × 8 panel like a menu, diff --git a/lib/maptool/routing.rb b/lib/maptool/routing.rb index 0cf6c32..bb8942e 100644 --- a/lib/maptool/routing.rb +++ b/lib/maptool/routing.rb @@ -316,17 +316,18 @@ module Maptool end # The road at the end of a short trace ([[lon, lat], ...] oldest first, - # the last few fixes) for driving without a route: its name, class and - # speed limit. Map-matched, so the road actually driven, not just the + # the last few fixes) for driving without a route: its name, class, + # speed limit and surface (Valhalla's: paved_smooth … impassable — the + # driving grid's Terrain view switches itself on past "paved_rough"). Map-matched, so the road actually driven, not just the # nearest one (a bridge over the motorway). def self.road(valhalla_url, points) raise RouteError, "at least two points are needed" if points.size < 2 data = valhalla(valhalla_url, "/trace_attributes", shape: points.map { |lon, lat| { lon: Float(lon), lat: Float(lat) } }, costing: "auto", shape_match: "map_snap", - filters: { attributes: %w[edge.names edge.road_class edge.speed_limit], action: "include" }) + filters: { attributes: %w[edge.names edge.road_class edge.speed_limit edge.surface], action: "include" }) edge = data["edges"]&.last or raise RouteError, "no road here" - { name: edge["names"]&.first, road_class: edge["road_class"], speed_limit: speed_limit(edge["speed_limit"]) } + { name: edge["names"]&.first, road_class: edge["road_class"], speed_limit: speed_limit(edge["speed_limit"]), surface: edge["surface"] }.compact rescue ArgumentError, TypeError raise RouteError, "invalid coordinates" end diff --git a/lib/maptool/search.rb b/lib/maptool/search.rb index 09cd6b7..9c09a79 100644 --- a/lib/maptool/search.rb +++ b/lib/maptool/search.rb @@ -60,7 +60,10 @@ module Maptool def self.query(text, library:, data_dir:, sources: SOURCES.keys, center: nil, kiwix_url: "") words = normalize(text).split - return [] if words.empty? + # No words: only "what's saved near here" (the driving grid's Points) — + # every library feature, nearest first; the other sources need a query. + sources &= ["layers"] if words.empty? + return [] if words.empty? && (center.nil? || sources.empty?) ctx = { text: text.to_s.strip, library: library, data_dir: data_dir, center: center, kiwix_url: kiwix_url.to_s } (sources & SOURCES.keys).flat_map do |source| diff --git a/public/css/style.css b/public/css/style.css index 233b95d..7bf2ceb 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -3527,8 +3527,8 @@ button.basemap-panel__link[hidden] { display: none; } cursor: pointer; } -/* Driving mode (driving.js): big buttons down the map's left side, the - planning sidebar and its panels out of the way. */ +/* Driving mode (driving.js): the cockpit grid below, the planning sidebar + and its panels out of the way. */ .topbar__drive { height: 40px; padding: 0 12px; @@ -3552,119 +3552,76 @@ html.driving .profile-panel, html.driving #map .maplibregl-ctrl-top-right > :not(.maplibregl-ctrl-overview-map), html.driving .topbar__search, html.driving .statusbar { display: none; } -.drive-bar { - position: absolute; - left: 12px; - top: 50%; - transform: translateY(-50%); - z-index: 4; - display: flex; - flex-direction: column; - gap: 10px; - max-height: calc(100% - 24px); /* a low screen: the buttons shrink, to 44 px */ -} -.drive-bar[hidden] { display: none; } -.drive-bar button, -.drive-bar__recenter { - width: 76px; - flex: 0 1 76px; - min-height: 44px; - border: none; - border-radius: 12px; - background: var(--band); - color: var(--band-fg); - font-size: 22px; - font-weight: 700; - box-shadow: 0 2px 8px rgb(0 0 0 / 0.35); - cursor: pointer; -} -.drive-bar .drive-bar__overview { font-size: 16px; } -.drive-bar button:active, -.drive-bar__recenter:active { background: var(--accent); } -/* the one follow / back-to-the-position button, bottom left, only while - the map isn't following (driving.js); gnss.js's own one not meanwhile */ -.drive-bar__recenter { - position: absolute; - left: 12px; - bottom: 36px; - z-index: 4; - width: auto; - height: 76px; - padding: 0 22px; - border: none; - border-radius: 12px; - background: var(--band); - color: var(--band-fg); - font-size: 18px; - font-weight: 700; - box-shadow: 0 2px 8px rgb(0 0 0 / 0.35); - cursor: pointer; -} -.drive-bar__recenter[hidden], -html.driving .follow-resume { display: none; } -.drive-bar button:disabled { opacity: 0.4; } +html.driving .follow-resume { display: none; } /* the Follow key instead */ html.follow-3d .maplibregl-ctrl-overview-map { display: none; } /* npmap's home button draws its house in #333: the UI's text color instead */ .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, beside - the map on the right (the map narrower, its buttons kept, like Android - Auto); the crosshair in the middle of the map. */ -.drive-trip { - flex: 0 0 min(540px, 45%); - margin: 12px; +/* The driving grid (driving.js, the screen profile public/drive/road.json): + the page as columns × rows of cells, 1 px of line between them, the map + one area of it; a menu takes the profile's menu area and the map narrows. */ +:root { --drive-line: #3a3a35; --drive-muted: #9b988d; --drive-key-on: #546619; --drive-input: #2a2b27; --drive-eye: #a5b84f; } +:root[data-palette="dusk"] { --drive-muted: #8c8a82; --drive-key-on: #6e7c32; } +:root[data-palette="night"] { --drive-line: #34332d; --drive-muted: #5f5c55; --drive-key-on: #3c4419; --drive-input: #1c1c19; --drive-eye: #8f9c4d; } +html.driving #app { + display: grid; + grid-template-columns: repeat(var(--drive-cols, 16), minmax(0, 1fr)); + grid-template-rows: repeat(var(--drive-rows, 10), minmax(0, 1fr)); + gap: 1px; + background: var(--drive-line); +} +html.driving .topbar { display: none; } +html.driving .app-body { grid-area: var(--drive-map, 2 / 1 / 10 / 14); } +html:not(.driving) .drive-cell { display: none; } +.drive-cell { + min-width: 0; + min-height: 0; + overflow: hidden; + box-sizing: border-box; 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; + justify-content: center; + gap: 2px; + padding: 6px 10px; 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-cell__label { font-size: 11px; color: var(--drive-muted); text-transform: uppercase; letter-spacing: 0.06em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.drive-cell__value { font-size: 34px; font-weight: 700; font-variant-numeric: tabular-nums; line-height: 1.1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.drive-cell__value small { font-size: 13px; font-weight: 500; color: var(--drive-muted); } +.drive-cell__value--mid { font-size: 22px; } +.drive-cell--small .drive-cell__value { font-size: 22px; } +.drive-cell__muted { font-size: 12px; color: var(--drive-muted); font-weight: 400; } +.drive-cell__text { display: flex; flex-direction: column; min-width: 0; } +.drive-cell__street { font-size: 15px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.drive-cell--warn { color: var(--inst-warning); } +.drive-cell--caution { color: var(--inst-caution); font-size: 22px; } +.drive-cell--limit { color: var(--sign-ring); } +.drive-cell--maneuver, +.drive-cell--compass { flex-direction: row; align-items: center; justify-content: flex-start; gap: 12px; } +.drive-cell--maneuver .dash-banner__icon { width: 42px; height: 56px; } +.drive-status__brand { font-size: 14px; letter-spacing: 0.12em; } +.drive-status--ok { color: var(--inst-ok); } +.drive-status--rec { color: var(--route-driven); } +.drive-elevation { width: 100%; flex: 1; min-height: 0; max-height: 120px; } +.drive-elevation__area { fill: var(--drive-muted); opacity: 0.35; } +.drive-elevation__line { fill: none; stroke: var(--band-fg); stroke-width: 2; vector-effect: non-scaling-stroke; } +.drive-elevation__here { stroke: var(--inst-active); stroke-width: 3; vector-effect: non-scaling-stroke; } +.drive-compass { width: 64px; height: 64px; flex: none; } +.drive-compass--stale { opacity: 0.55; } +.drive-compass__ring { fill: none; stroke: var(--drive-muted); stroke-width: 2; } +.drive-compass__north, .drive-compass__n { fill: var(--inst-warning); } +.drive-compass__south { fill: var(--drive-muted); } +.drive-compass__n { font-size: 14px; font-weight: 800; text-anchor: middle; } +.drive-compass__lubber { fill: var(--inst-active); } +button.drive-cell--key { align-items: center; padding: 0; border: none; font: inherit; cursor: pointer; } +.drive-key__icon { font-size: 24px; line-height: 1; } +.drive-key--big .drive-key__icon { font-size: 34px; } +.drive-key__label { font-size: 12px; font-weight: 700; letter-spacing: 0.06em; text-transform: uppercase; } +button.drive-cell--key[aria-pressed="true"], +button.drive-cell--key:active:not(:disabled) { background: var(--drive-key-on); color: #fff; } +button.drive-cell--key:disabled { opacity: 0.35; cursor: default; } + .drive-crosshair { position: absolute; left: 50%; @@ -3680,43 +3637,102 @@ html.follow-3d .maplibregl-ctrl-overview-map { display: none; } 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); } +.route-panel__leg { display: block; color: var(--ui-muted); font-size: 11px; } +/* Passed stops (route.js): dimmed, still editable — the buttons keep full strength */ +.route-panel__passed .route-panel__point { opacity: 0.45; } +.route-marker--passed { opacity: 0.45; } + +/* The driving grid's menus (driving.js, the canvas' GridTrip / GridSearch): + the menu area as cells of its own, 1 px of line between them, everything + a cell — the stops a row each (name over 3 cells, ✓ ↑ ↓ ✕ one each). */ +.drive-panel { + display: grid; + grid-template-columns: repeat(var(--drive-menu-cols, 7), minmax(0, 1fr)); + grid-template-rows: repeat(var(--drive-menu-rows, 8), minmax(0, 1fr)); + gap: 1px; + min-height: 0; + background: var(--drive-line); + color: var(--band-fg); +} +html:not(.driving) .drive-panel, +.drive-panel[hidden] { display: none; } +html.driving .drive-panel { grid-area: var(--drive-menu, 2 / 10 / 10 / 17); } +.drive-panel > *, +.drive-panel__cell, +.drive-panel__empty { + min-width: 0; + min-height: 0; + box-sizing: border-box; + margin: 0; + border: none; + background: var(--band); + color: var(--band-fg); + font: inherit; +} +.drive-panel button { cursor: pointer; font-size: 26px; } +.drive-panel button:disabled { opacity: 0.3; cursor: default; } +.drive-panel button:active:not(:disabled) { background: var(--drive-key-on); color: #fff; } +.drive-panel__head { grid-area: 1 / 1 / 2 / -2; display: flex; align-items: center; gap: 12px; padding: 0 16px; font-size: 22px; font-weight: 700; white-space: nowrap; overflow: hidden; } +.drive-panel__head small { font-size: 16px; font-weight: 500; color: var(--drive-muted); } +.drive-panel__close { grid-area: 1 / -2 / 2 / -1; } +.drive-panel__text { display: flex; flex-direction: column; min-width: 0; text-align: left; } +.drive-panel__text b { font-size: 19px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.drive-panel__text small { font-size: 13px; color: var(--drive-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.drive-panel__empty { grid-column: 1 / -1; padding: 16px; color: var(--drive-muted); font-size: 16px; } +.drive-panel button.drive-panel__primary { background: var(--drive-key-on); color: #fff; font-size: 18px; font-weight: 700; } +/* the Trip: recording, search, the stops, the actions */ +.drive-trip__log { grid-area: 2 / 1 / 3 / 4; } +.drive-panel button.drive-trip__log { font-size: 18px; font-weight: 700; color: var(--route-driven); } +.drive-panel button.drive-trip__log--on { background: var(--route-driven); color: #fff; } +.drive-trip__log-state { grid-area: 2 / 4 / 3 / -1; display: flex; flex-direction: column; justify-content: center; padding: 0 14px; } +.drive-trip__log-text { font-size: 16px; font-weight: 600; color: var(--drive-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.drive-trip__log-text--on { font-size: 18px; font-weight: 700; color: var(--route-driven); } +.drive-trip__search { grid-area: 3 / 1 / 4 / -1; display: flex; align-items: center; padding: 0 10px; } .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); + border: 1px solid var(--drive-line); + border-radius: 8px; + background: var(--drive-input); + color: var(--band-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; } -.drive-trip__log { display: flex; align-items: center; gap: 12px; padding: 10px 12px; border-bottom: 1px solid var(--ui-line); } -.drive-trip__log[hidden] { display: none; } -.drive-trip__log button { - min-height: 60px; - padding: 0 18px; - border: 2px solid var(--route-driven); - border-radius: 10px; - background: none; - color: var(--ui-fg); - font-size: 18px; - font-weight: 700; - cursor: pointer; +.drive-trip__stops, +.drive-trip__results { + display: grid; + grid-template-columns: repeat(var(--drive-menu-cols, 7), minmax(0, 1fr)); + gap: 1px; + overflow-y: auto; + align-content: start; + background: var(--drive-line); } -.drive-trip__log button.drive-trip__log--on { background: var(--route-driven); color: #fff; } -.drive-trip__log-state { flex: 1; color: var(--route-driven); font-weight: 600; font-size: 15px; } +/* ponytail: rows sized for the 8-row menu (4 stops, 5 results a screen), from the profile if another menu size comes */ +.drive-trip__stops { grid-area: 4 / 1 / -2 / -1; grid-auto-rows: calc((100% - 3px) / 4); } +.drive-trip__results { grid-area: 3 / 1 / -2 / -1; grid-auto-rows: calc((100% - 4px) / 5); } +.drive-panel__stop { grid-column: 1 / -5; padding: 0 14px; display: flex; align-items: center; } +.drive-panel__result { grid-column: 1 / -2; padding: 0 14px; display: flex; align-items: center; gap: 12px; } +.drive-panel__passed .drive-panel__text { opacity: 0.45; } +.drive-panel .drive-panel__done { color: var(--drive-muted); font-weight: 700; } +.drive-panel .drive-panel__done.active { color: var(--inst-ok); } +.drive-panel .drive-panel__drop { font-size: 24px; } +.drive-panel .drive-panel__add { font-size: 32px; font-weight: 700; color: var(--drive-eye); } +.drive-trip__add { grid-area: -2 / 1 / -1 / 5; } +.drive-panel button.drive-trip__start { grid-area: -2 / 5 / -1 / -1; font-size: 17px; font-weight: 700; } +.drive-panel button.drive-trip__back { grid-area: -2 / 1 / -1 / -1; font-size: 17px; font-weight: 700; } +.drive-trip[data-mode="trip"] :is(.drive-trip__results, .drive-trip__back), +.drive-trip[data-mode="search"] :is(.drive-trip__log, .drive-trip__log-state, .drive-trip__stops, .drive-trip__add, .drive-trip__start) { display: none; } +.drive-trip[data-mode="search"] .drive-trip__search { grid-row: 2 / 3; } +.drive-trip[data-mode="search"] .drive-trip__search input { border: 2px solid var(--drive-key-on); } +/* the search's results on the map and in the list: saved points cyan, places amber */ +.drive-pin { width: 14px; height: 14px; flex: none; border-radius: 50%; box-shadow: 0 0 0 2px #fff; } +.maplibregl-marker.drive-pin { width: 18px; height: 18px; box-shadow: 0 0 0 2.5px #fff, 0 1px 4px rgb(0 0 0 / 0.4); } +.drive-pin--saved { background: #12bedf; } +.drive-pin--place { background: #e8a200; } +/* the Menu: a row a cell high each */ +.drive-panel button.drive-menu__row { grid-column: 1 / -1; padding: 0 16px; text-align: left; font-size: 19px; font-weight: 700; } +.drive-menu__row small { margin-left: 8px; font-size: 14px; font-weight: 400; color: var(--drive-muted); } /* The side rail, labelled (map.js sets data-label), and the status bar under the map — the Design canvas' Desktop. */ @@ -4614,3 +4630,85 @@ html.follow-3d .maplibregl-ctrl-overview-map { display: none; } html.driving #map { margin-bottom: 0; } +html.driving .dash-banner { display: none; } /* the grid's manoeuvre cell instead */ + +/* Points and Layers (drive_menus.js, the canvas' GridPoints / GridLayers): + a bar of cells on top, an item a row (its eye, its + or ›), a foot. */ +.drive-panel__list { + grid-area: 4 / 1 / -2 / -1; + display: grid; + grid-template-columns: repeat(var(--drive-menu-cols, 7), minmax(0, 1fr)); + grid-auto-rows: calc((100% - 3px) / 4); /* ponytail: 4 rows a screen, as the 8-row menu */ + gap: 1px; + overflow-y: auto; + align-content: start; + background: var(--drive-line); +} +.drive-panel__foot { grid-area: -2 / 1 / -1 / 5; display: flex; align-items: center; padding: 0 16px; font-size: 15px; color: var(--drive-muted); } +.drive-panel button.drive-panel__wide { grid-area: -2 / 5 / -1 / -1; font-size: 17px; font-weight: 700; } +.drive-points__search { grid-area: 2 / 1 / 3 / -1; display: flex; align-items: center; padding: 0 10px; } +.drive-points__search input { width: 100%; box-sizing: border-box; height: 60px; padding: 0 16px; border: 1px solid var(--drive-line); border-radius: 8px; background: var(--drive-input); color: var(--band-fg); font-size: 20px; } +.drive-points__bar, +.drive-layers__presets, +.drive-layers__source { + display: grid; + grid-template-columns: repeat(var(--drive-menu-cols, 7), minmax(0, 1fr)); + gap: 1px; + background: var(--drive-line); +} +.drive-points__bar { grid-area: 3 / 1 / 4 / -1; } +.drive-layers__presets { grid-area: 2 / 1 / 3 / -1; } +.drive-layers__source { grid-area: 3 / 4 / 4 / -1; grid-template-columns: repeat(2, minmax(0, 1fr)); } +.drive-panel .drive-panel__scope { grid-column: span 2; font-size: 16px; font-weight: 700; } +.drive-layers__source .drive-panel__scope { grid-column: auto; } +.drive-panel__preset { grid-column: span 2; } +.drive-panel__preset, +.drive-panel__mode { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px; } +.drive-panel .drive-panel__scope[aria-pressed="true"], +.drive-panel .drive-panel__preset[aria-pressed="true"], +.drive-panel .drive-panel__mode[aria-pressed="true"] { background: var(--drive-key-on); color: #fff; } +.drive-points__path { grid-column: span 5; display: flex; flex-direction: column; justify-content: center; padding: 0 14px; white-space: nowrap; overflow: hidden; } +.drive-points__path b { font-size: 19px; overflow: hidden; text-overflow: ellipsis; } +.drive-panel .drive-panel__item { grid-column: 1 / -3; display: flex; align-items: center; gap: 12px; padding: 0 14px; } +.drive-points__icon { width: 22px; flex: none; text-align: center; font-size: 20px; } +.drive-points__away { margin-left: auto; font-size: 15px; font-weight: 600; color: var(--drive-muted); font-variant-numeric: tabular-nums; white-space: nowrap; } +.drive-panel .drive-panel__eye { color: var(--drive-muted); } +.drive-panel .drive-panel__eye.active { color: var(--drive-eye); } +.drive-panel .drive-panel__open { font-size: 30px; font-weight: 700; } +.drive-panel .drive-panel__blank { cursor: default; } +.drive-layers__map { grid-area: 3 / 1 / 4 / 4; display: flex; flex-direction: column; justify-content: center; padding: 0 14px; white-space: nowrap; overflow: hidden; } +.drive-layers__map span { font-size: 15px; font-weight: 600; color: var(--drive-muted); overflow: hidden; text-overflow: ellipsis; } +.drive-layers__item { grid-column: 1 / -2; display: flex; align-items: center; gap: 12px; padding: 0 14px; } +.drive-layers__icon { width: 24px; height: 24px; flex: none; color: var(--drive-muted); } +.drive-layers__icon svg { width: 100%; height: 100%; } + +/* Terrain (drive_menus.js, the canvas' GridTerrain): two dials of 3 × 3.5 + cells (roll as a rear view, pitch as a side view), the fields ahead, the + elevation of the next 2 km, the actions at the foot. */ +.drive-terrain__dial { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; padding: 6px; } +.drive-terrain__dial[data-key="roll"] { grid-area: 2 / 1 / 5 / 4; } +.drive-terrain__dial[data-key="pitch"] { grid-area: 2 / 4 / 5 / 8; } +.drive-terrain__svg { width: 100%; max-width: 232px; min-height: 0; flex: 1; color: var(--band-fg); } +.drive-terrain__svg path, .drive-terrain__svg line { fill: none; } +.drive-terrain__ok, .drive-terrain__amber, .drive-terrain__red { stroke-width: 10; } +.drive-terrain__ok { stroke: var(--inst-ok); opacity: 0.55; } +.drive-terrain__amber { stroke: var(--inst-caution); } +.drive-terrain__red { stroke: var(--inst-warning); } +.drive-terrain__ground { stroke: var(--drive-muted); stroke-width: 1; stroke-dasharray: 4 5; } +.drive-terrain__mast { stroke: currentColor; stroke-width: 3; } +.drive-terrain__svg .drive-terrain__car { fill: currentColor; } +.drive-terrain__svg .drive-terrain__peak { fill: var(--band-fg); opacity: 0.8; } +.drive-terrain__value { font-size: 44px; font-weight: 700; line-height: 1; font-variant-numeric: tabular-nums; } +.drive-terrain--caution { color: var(--inst-caution); } +.drive-terrain__field { display: flex; flex-direction: column; justify-content: center; padding: 6px 12px; overflow: hidden; } +.drive-terrain__field[data-field="heading"] { grid-area: 5 / 1 / 6 / 3; } +.drive-terrain__field[data-field="climb"] { grid-area: 5 / 3 / 6 / 5; } +.drive-terrain__field[data-field="across"] { grid-area: 5 / 5 / 6 / 8; } +.drive-terrain__elevation { grid-area: 6 / 1 / 8 / 8; display: flex; flex-direction: column; justify-content: center; gap: 6px; padding: 10px 14px; min-height: 0; overflow: hidden; } +.drive-panel button.drive-terrain__level, +.drive-panel button.drive-terrain__reset, +.drive-panel button.drive-terrain__road { font-size: 17px; font-weight: 700; } +.drive-terrain__level { grid-area: 8 / 1 / 9 / 4; } +.drive-terrain__reset { grid-area: 8 / 4 / 9 / 6; } +.drive-terrain__road { grid-area: 8 / 6 / 9 / 8; } +.drive-panel button.drive-terrain__level--armed { background: var(--inst-caution); color: #000; } diff --git a/public/drive/road.json b/public/drive/road.json new file mode 100644 index 0000000..1d1aa58 --- /dev/null +++ b/public/drive/road.json @@ -0,0 +1,34 @@ +{ + "name": "Road", + "screen": "16 × 10 cells (the navigator's 16″, 1280 × 800)", + "columns": 16, + "rows": 10, + "map": "2 / 1 / 10 / 14", + "menu": { "area": "2 / 10 / 10 / 17", "map": "2 / 1 / 10 / 10" }, + "cells": [ + { "area": "1 / 1 / 2 / 5", "widget": "maneuver" }, + { "area": "1 / 5 / 2 / 7", "widget": "field", "value": "speed" }, + { "area": "1 / 7 / 2 / 9", "widget": "field", "value": "limit" }, + { "area": "1 / 9 / 2 / 11", "widget": "field", "value": "altitude" }, + { "area": "1 / 11 / 2 / 13", "widget": "field", "value": "time" }, + { "area": "1 / 13 / 2 / 15", "widget": "field", "value": "sun" }, + { "area": "1 / 15 / 2 / 17", "widget": "status" }, + { "area": "2 / 14 / 3 / 17", "widget": "field", "value": "nextStop", "small": true }, + { "area": "3 / 14 / 4 / 17", "widget": "field", "value": "toNextStop" }, + { "area": "4 / 14 / 5 / 17", "widget": "field", "value": "etaNextStop" }, + { "area": "5 / 14 / 6 / 17", "widget": "field", "value": "toEnd" }, + { "area": "6 / 14 / 9 / 17", "widget": "elevation", "km": 10 }, + { "area": "9 / 14 / 10 / 17", "widget": "compass" }, + { "area": "10 / 1 / 11 / 3", "widget": "key", "action": "trip" }, + { "area": "10 / 3 / 11 / 5", "widget": "key", "action": "points" }, + { "area": "10 / 5 / 11 / 7", "widget": "key", "action": "layers" }, + { "area": "10 / 7 / 11 / 9", "widget": "key", "action": "search" }, + { "area": "10 / 9 / 11 / 11", "widget": "key", "action": "menu" }, + { "area": "10 / 11 / 11 / 12", "widget": "key", "action": "zoomOut" }, + { "area": "10 / 12 / 11 / 13", "widget": "key", "action": "zoomIn" }, + { "area": "10 / 13 / 11 / 14", "widget": "key", "action": "pitch" }, + { "area": "10 / 14 / 11 / 15", "widget": "key", "action": "follow" }, + { "area": "10 / 15 / 11 / 16", "widget": "key", "action": "terrain" }, + { "area": "10 / 16 / 11 / 17", "widget": "key", "action": "palette" } + ] +} diff --git a/public/js/dashboard.js b/public/js/dashboard.js index 1c13e47..864f66d 100644 --- a/public/js/dashboard.js +++ b/public/js/dashboard.js @@ -49,7 +49,7 @@ const load = () => { const RAD = Math.PI / 180; // meters between two [lon, lat] (equirectangular: fine at these distances) const meters = ([lon1, lat1], [lon2, lat2]) => Math.hypot((lon2 - lon1) * Math.cos(((lat1 + lat2) / 2) * RAD), lat2 - lat1) * 111320; -const distance = (m) => (m >= 1000 ? `${(m / 1000).toFixed(1)} km` : `${Math.round(m / 10) * 10} m`); +export const distance = (m) => (m >= 1000 ? `${(m / 1000).toFixed(1)} km` : `${Math.round(m / 10) * 10} m`); const esc = (text) => String(text ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]); // An arrow from the bottom center turning by `angle` (° from straight on), @@ -66,7 +66,7 @@ const uturnPath = (cls) => `= 4 && type <= 6) body = ``; // a flag: arriving @@ -163,8 +163,19 @@ const INCLINOMETER = ` pitch `; +// The driving grid (driving.js) reads the dashboard: watchDashboard(cb) +// polls the bus while it's on, the overlay's card or not, and hands each +// poll's state to cb; watchDashboard(null) stops that. +let instance = null; +export function watchDashboard(callback) { + if (!instance || !isLoggedIn()) return; // /api/can wants a login + instance._watch = callback; + if (callback && !instance._timer) instance._poll(); +} + export class DashboardControl { constructor(map) { + instance = this; this._map = map; this._settings = load(); this._timer = null; @@ -348,13 +359,15 @@ export class DashboardControl { this._map.getContainer().appendChild(this._banner); this._status.hidden = false; this._status.textContent = "Connecting…"; - this._poll(); + if (!this._timer) this._poll(); } _disable() { - this._progress(null); - clearTimeout(this._timer); - this._timer = null; + if (!this._watch) { + this._progress(null); + clearTimeout(this._timer); + this._timer = null; + } this._card?.remove(); this._card = null; this._banner?.remove(); @@ -363,6 +376,8 @@ export class DashboardControl { } async _poll() { + if (this._busy) return; // the grid and the card both asked + this._busy = true; try { const response = await fetch("/api/can", { cache: "no-store" }); if (!response.ok) throw new Error(`HTTP ${response.status}`); @@ -375,6 +390,7 @@ export class DashboardControl { })); this._updateCourse(this._values); this._simRunning = !!data.simulated; // /sim.html runs it + this._actions = data.actions || []; // can.json's SDO actions (levelling), POST /api/can/actions/ if (this._simRunning) await this._simulateTerrain(); this._navigate(); this._status.textContent = this._simRunning ? "Simulated GNSS" : data.available ? "" : "CAN is off on this server"; @@ -385,7 +401,25 @@ export class DashboardControl { this._status.textContent = `Can't reach the server: ${e.message}`; } this._render(); - if (this._card) this._timer = setTimeout(() => this._poll(), POLL_MS); + this._busy = false; + this._watch?.(this.state()); + this._timer = this._card || this._watch ? setTimeout(() => this._poll(), POLL_MS) : null; + } + + // What the driving grid shows: the signals, the navigation, the heading + // ({ deg, live }), the road's surface (off a route, /api/road), the CAN + // actions, and the km along the route (null off it). + state() { + return { values: this._values, nav: this._nav, heading: this._heading(), simulated: !!this._simRunning, actions: this._actions || [], + surface: this._road?.surface ?? null, course: this._course, atKm: this._route && this._offFixes < OFF_ROUTE_FIXES ? this._lastAt : null }; + } + + // Driving, the GNSS course; standing, the compass — else the last of either, not live. + _heading() { + const v = this._values; + const moving = v.speed != null && v.speed >= MOVING_MS; + const deg = moving ? this._course ?? v.heading : v.heading ?? this._course; + return deg == null ? null : { deg: (deg + 360) % 360, live: moving ? this._course != null : v.heading != null }; } _render() { @@ -414,12 +448,10 @@ export class DashboardControl { text.textContent = value == null ? "—" : `${value > 0 ? "+" : ""}${Math.round(value)}°`; text.setAttribute("class", `dash-value dash-${key}-value ${severity(key, value)}`); } - const moving = v.speed != null && v.speed >= MOVING_MS; - const heading = moving ? this._course ?? v.heading : v.heading ?? this._course; - const live = heading != null && (moving ? this._course != null : v.heading != null); - svg.querySelector(".dash-ring").setAttribute("transform", `rotate(${heading == null ? 0 : -heading})`); - svg.querySelector(".dash-ring").style.opacity = heading == null ? 0.3 : live ? 1 : 0.55; - svg.querySelector(".dash-heading").textContent = heading == null ? "" : `${Math.round((heading + 360) % 360)}°`; + const heading = this._heading(); + svg.querySelector(".dash-ring").setAttribute("transform", `rotate(${heading ? -heading.deg : 0})`); + svg.querySelector(".dash-ring").style.opacity = !heading ? 0.3 : heading.live ? 1 : 0.55; + svg.querySelector(".dash-heading").textContent = heading ? `${Math.round(heading.deg)}°` : ""; speed.querySelector("span").textContent = v.speed == null ? "—" : Math.round(v.speed * 3.6); } diff --git a/public/js/drive_menus.js b/public/js/drive_menus.js new file mode 100644 index 0000000..f0de0ef --- /dev/null +++ b/public/js/drive_menus.js @@ -0,0 +1,454 @@ +// The driving grid's Points and Layers menus (driving.js; the Design canvas' +// GridPoints and GridLayers): each a 7 × 8 panel of cells in the profile's +// menu area, built the same way as the Trip menu. +import { distance } from "/js/dashboard.js"; +import { elevationAt } from "/js/dem.js"; + +const SEARCH_DELAY_MS = 300; +const AHEAD_M = 2000; // "Ahead": saved things this close to the route still to drive +const PRESETS_KEY = "maptool.layerPresets"; +const PRESETS = [["road", "↝", "Road"], ["offroad", "⛰", "Off-road"], ["overnight", "⛺", "Overnight"]]; +// What a preset turns on until it's kept otherwise (+ Keep): names as the On the map panel has them. +const DEFAULT_PRESETS = { + road: ["Radar", "Tracker"], + offroad: ["Terrain shading", "Contour lines", "Hiking trails", "Radar"], + overnight: ["Radar", "Wikipedia", "NPS park maps"], +}; +const SKIP_LAYERS = new Set(["Dashboard"]); // the grid's own data, not a layer + +export const escapeHtml = (text) => String(text ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]); + +// A button that is one cell (or a few) of a menu. +export function cellButton(cls, html, title, action) { + const el = document.createElement("button"); + el.type = "button"; + el.className = `drive-panel__cell drive-panel__${cls}`; + el.innerHTML = html; + el.title = title; + el.setAttribute("aria-label", title); + el.addEventListener("click", action); + return el; +} + +export const emptyRow = (text) => Object.assign(document.createElement("p"), { className: "drive-panel__empty", textContent: text }); + +function panel(cls, label, inner) { + const el = document.createElement("section"); + el.className = `drive-panel ${cls}`; + el.setAttribute("aria-label", label); + el.hidden = true; + el.innerHTML = `
${label}
+ ${inner}`; + return el; +} + +const RAD = Math.PI / 180; +const meters = ([lon1, lat1], [lon2, lat2]) => Math.hypot((lon2 - lon1) * Math.cos(((lat1 + lat2) / 2) * RAD), lat2 - lat1) * 111320; +const eyeGlyph = (show) => ({ all: "●", some: "◐", none: "○" })[show]; + +// Points: the library on the road — nearest the car first (the search's +// "layers" source with no words), or along the route ahead, or only what's +// shown; or one folder at a time with ← up. An eye per row; + adds a point +// as a stop. ctx: { map, gpxPanel, routePanel, lookAt, position, route, atKm, close }. +export function pointsMenu(ctx) { + const el = panel("drive-points", "Points", ` + +
+
+
+ `); + const input = el.querySelector("input"); + const bar = el.querySelector(".drive-points__bar"); + const list = el.querySelector(".drive-points__list"); + const foot = el.querySelector(".drive-panel__foot"); + let scope = "near"; // near | ahead | shown | folder + let cwd = ""; + let results = []; + let loading = false; + let timer = null; + let seq = 0; + const lib = () => ctx.gpxPanel?.libraryTree() || { folders: new Map(), files: new Map(), filesUnder: () => [] }; + + const fetchNear = async () => { + const mine = ++seq; + loading = true; + render(); + const [lng, lat] = ctx.position(); + const url = new URL("/api/search", window.location.origin); + url.search = new URLSearchParams({ q: input.value, sources: "layers", lat, lng }); + let found = []; + try { found = (await (await fetch(url)).json()).results; } catch { /* offline for a moment: nothing */ } + if (mine !== seq) return; + loading = false; + results = found.filter(({ bbox }) => bbox).map((r) => ({ ...r, lngLat: [(r.bbox[0] + r.bbox[2]) / 2, (r.bbox[1] + r.bbox[3]) / 2] })); + render(); + }; + input.addEventListener("input", () => { + if (scope === "folder") scope = "near"; // a search lists every match flat + clearTimeout(timer); + timer = setTimeout(fetchNear, SEARCH_DELAY_MS); + }); + + // The route still to drive, for "Ahead". + // ponytail: filters the 50 nearest the car, not the whole library along the route + const ahead = () => { + const coords = ctx.route()?.geometry?.coordinates; + if (!coords?.length) return null; + const from = (ctx.atKm() ?? 0) * 1000; + let along = 0; + return coords.filter((c, i) => (along += i ? meters(coords[i - 1], c) : 0) >= from); + }; + const shownRows = () => { + if (scope === "shown") return results.filter((r) => ctx.gpxPanel?.isShown(r.ref)); + if (scope !== "ahead") return results; + const line = ahead(); + if (!line) return []; + return results.filter((r) => line.some((c) => meters(c, r.lngLat) <= AHEAD_M)); + }; + + const toggleShown = async (paths, show) => { + await ctx.gpxPanel?.setShown(paths, show); + render(); + }; + const rowCells = ({ icon, color, name, meta, away, show, onOpen, onEye, last }) => { + const text = cellButton("item", `${icon}${escapeHtml(name)}${escapeHtml(meta)}` + + `${escapeHtml(away || "")}`, "Show it on the map", onOpen); + const eye = cellButton("eye", eyeGlyph(show), show === "none" ? "Show on the map" : "Hide on the map", onEye); + eye.setAttribute("aria-pressed", String(show !== "none")); + eye.classList.toggle("active", show !== "none"); + return [text, eye, last || cellButton("blank", "", "", () => {})]; + }; + + const renderNear = () => { + const rows = shownRows(); + list.replaceChildren(...rows.flatMap((r) => { + const line = !/point/i.test(r.kind || ""); + const shown = ctx.gpxPanel?.isShown(r.ref); + return rowCells({ + icon: line ? "〰" : "●", color: line ? "var(--route-driven)" : "#12bedf", name: r.name, + meta: (r.source_label || "").replaceAll("/", " › "), away: r.distance_km != null ? distance(r.distance_km * 1000) : "", + show: shown ? "all" : "none", + onOpen: async () => { + if (!ctx.gpxPanel?.isShown(r.ref)) await toggleShown([r.ref], true); + ctx.lookAt(r.lngLat); + }, + onEye: () => toggleShown([r.ref], !shown), + last: line ? null : cellButton("add", "+", "Add as a stop", () => ctx.routePanel?.addStop(r.lngLat, r.name)), + }); + })); + if (!rows.length) list.append(emptyRow(loading ? "Looking…" : scope === "ahead" && !ahead() ? "No route to look along." : "Nothing saved here.")); + foot.textContent = `${rows.length} ${scope === "ahead" ? "along the route" : scope === "shown" ? "shown nearby" : "nearest the car"}`; + }; + + const renderFolder = () => { + const { folders, filesUnder } = lib(); + const folder = folders.get(cwd) || folders.get(""); + if (!folder) return list.replaceChildren(emptyRow("The library is loading…")); + const shownOf = (paths) => { + const n = paths.filter((p) => ctx.gpxPanel?.isShown(p)).length; + return !paths.length || !n ? "none" : n === paths.length ? "all" : "some"; + }; + const subfolders = folder.children.filter((c) => c.type === "folder"); + const own = folder.children.filter((c) => c.type !== "folder"); + list.replaceChildren(...subfolders.flatMap((f) => { + const paths = filesUnder(f.path).map((x) => x.path); + const show = shownOf(paths); + const open = () => { cwd = f.path; render(); }; + return rowCells({ icon: "▣", color: "var(--drive-muted)", name: f.name, meta: `${f.children.length} items`, show, onOpen: open, + onEye: () => toggleShown(paths, show === "none"), last: cellButton("open", "›", "Open the folder", open) }); + }), ...own.flatMap((file) => { + const shown = ctx.gpxPanel?.isShown(file.path); + const line = file.kinds?.some((k) => k === "track" || k === "route"); + return rowCells({ + icon: line ? "〰" : "●", color: file.color || (line ? "var(--route-driven)" : "#12bedf"), name: file.name, + meta: file.layer ? "layer" : (file.kinds || []).join(", "), show: shown ? "all" : "none", + onOpen: async () => { + if (!ctx.gpxPanel?.isShown(file.path)) await toggleShown([file.path], true); + ctx.gpxPanel?.zoomTo(file.path); + }, + onEye: () => toggleShown([file.path], !shown), + }); + })); + if (!folder.children.length) list.append(emptyRow("Nothing here yet.")); + const paths = filesUnder(cwd).map((f) => f.path); + foot.textContent = `${paths.filter((p) => ctx.gpxPanel?.isShown(p)).length} of ${paths.length} shown`; + }; + + function render() { + if (el.hidden) return; + if (scope === "folder") { + const name = lib().folders.get(cwd)?.name; + const parent = cwd.includes("/") ? cwd.slice(0, cwd.lastIndexOf("/")) : ""; + bar.innerHTML = ""; + const up = cellButton("up", "←", "Up a level", () => { cwd = parent; render(); }); + up.disabled = !cwd; + const path = Object.assign(document.createElement("div"), { className: "drive-panel__cell drive-points__path" }); + path.innerHTML = `${escapeHtml(parent ? `${parent.replaceAll("/", " › ")} ›` : cwd ? "Library ›" : "")}${escapeHtml(cwd ? name : "Library")}`; + const nearest = cellButton("mode", `◎Nearest`, "Nearest the car", () => { scope = "near"; fetchNear(); }); + bar.append(up, path, nearest); + el.querySelector(".drive-panel__note").textContent = "folders"; + renderFolder(); + } else { + bar.replaceChildren(...[["near", "Near the car"], ["ahead", "Ahead"], ["shown", "Shown"]].map(([id, label]) => { + const chip = cellButton("scope", label, label, () => { scope = id; render(); }); + chip.setAttribute("aria-pressed", String(scope === id)); + return chip; + }), cellButton("mode", `▣Folders`, "Folders", () => { scope = "folder"; input.value = ""; render(); })); + el.querySelector(".drive-panel__note").textContent = input.value.trim() ? `“${input.value.trim()}”` : "near the car"; + renderNear(); + } + } + + el.querySelector(".drive-panel__close").addEventListener("click", ctx.close); + el.querySelector('[data-action="hide-all"]').addEventListener("click", () => { + const shown = [...lib().files.keys()].filter((p) => ctx.gpxPanel?.isShown(p)); + toggleShown(shown, false); + }); + return { + el, + render, + opened: () => { if (scope !== "folder") fetchNear(); else render(); }, + }; +} + +// Layers: the On the map panel's items cut to the road — presets that turn +// a set on at once (+ Keep saves what's on into one), the map Online | +// Offline, an eye per layer, the ones on first (sorted when the menu opens, +// not while tapping). The switches are the On the map panel's own +// checkboxes, so everything they do (restore, offline checks) stays theirs. +export function layersMenu(ctx) { + const el = panel("drive-layers", "Layers", ` +
+
Mapoffline by itself, no signal
+
+
+
+ `); + const list = el.querySelector(".drive-layers__list"); + let order = []; + let keeping = false; + + const loadPresets = () => { + try { return { ...DEFAULT_PRESETS, ...JSON.parse(localStorage.getItem(PRESETS_KEY)) }; } catch { return { ...DEFAULT_PRESETS }; } + }; + // The On the map items that can be switched here: [name, group, icon, checkbox]. + const layers = () => [...document.querySelectorAll("#overlays-panel .overlays-panel__item")].flatMap((li) => { + const toggle = li.querySelector(".overlays-panel__toggle"); + const name = li.querySelector(".overlays-panel__name, label")?.textContent.trim(); + const hidden = toggle?.closest("[hidden]"); + if (!toggle || !name || SKIP_LAYERS.has(name) || toggle.disabled || (hidden && li.contains(hidden))) return []; + let group = li.previousElementSibling; + while (group && !group.classList.contains("overlays-panel__group")) group = group.previousElementSibling; + return [{ name, group: group?.textContent.trim() || "", icon: li.querySelector(".overlays-panel__icon")?.innerHTML || "", toggle }]; + }); + const set = (layer, on) => { if (layer.toggle.checked !== on) layer.toggle.click(); }; + const presetOn = (presets) => { + const on = layers().filter((l) => l.toggle.checked).map((l) => l.name).sort().join("|"); + return PRESETS.find(([id]) => [...presets[id]].filter((n) => layers().some((l) => l.name === n)).sort().join("|") === on)?.[0]; + }; + + function render() { + if (el.hidden) return; + const presets = loadPresets(); + const current = presetOn(presets); + el.querySelector(".drive-layers__presets").replaceChildren(...PRESETS.map(([id, icon, label]) => { + const b = cellButton("preset", `${icon}${keeping ? `Save as ${label}` : label}`, label, () => { + if (keeping) { + presets[id] = layers().filter((l) => l.toggle.checked).map((l) => l.name); + try { localStorage.setItem(PRESETS_KEY, JSON.stringify(presets)); } catch { /* private window: not kept */ } + keeping = false; + } else { + for (const layer of layers()) set(layer, presets[id].includes(layer.name)); + } + render(); + }); + b.setAttribute("aria-pressed", String(!keeping && current === id)); + return b; + }), (() => { + const keep = cellButton("mode", `${keeping ? "✕" : "+"}${keeping ? "Cancel" : "Keep"}`, + keeping ? "Cancel" : "Keep what is on as a preset", () => { keeping = !keeping; render(); }); + keep.setAttribute("aria-pressed", String(keeping)); + return keep; + })()); + // the map: the On the map panel's own Online / Offline buttons + const options = [...document.querySelectorAll(".onthemap-map .basemap-panel__option")]; + const sourcesHidden = !!document.querySelector(".onthemap-map .basemap-panel__sources")?.hidden; + el.querySelector(".drive-layers__source").replaceChildren(...options.map((option) => { + const b = cellButton("scope", option.textContent, `Map: ${option.textContent}`, () => { option.click(); render(); }); + b.setAttribute("aria-pressed", String(option.classList.contains("active"))); + b.disabled = sourcesHidden; + return b; + })); + const all = layers(); + const byName = new Map(all.map((l) => [l.name, l])); + const rows = order.map((n) => byName.get(n)).filter(Boolean); + list.replaceChildren(...rows.flatMap((layer) => { + const on = layer.toggle.checked; + const text = Object.assign(document.createElement("div"), { className: "drive-panel__cell drive-layers__item" }); + text.innerHTML = `${escapeHtml(layer.name)}${escapeHtml(layer.group)}`; + const eye = cellButton("eye", on ? "●" : "○", `${on ? "Hide" : "Show"} ${layer.name}`, () => { set(layer, !on); render(); }); + eye.setAttribute("aria-pressed", String(on)); + eye.classList.toggle("active", on); + return [text, eye]; + })); + if (!rows.length) list.append(emptyRow("No layers to switch here.")); + const onCount = all.filter((l) => l.toggle.checked).length; + el.querySelector(".drive-panel__note").textContent = `${current ? PRESETS.find(([id]) => id === current)[2] : "by hand"} · ${onCount} on`; + el.querySelector(".drive-panel__foot").textContent = `${onCount} on · ${all.length - onCount} off`; + } + + el.querySelector(".drive-panel__close").addEventListener("click", ctx.close); + el.querySelector('[data-action="all-off"]').addEventListener("click", () => { + for (const layer of layers()) set(layer, false); + render(); + }); + return { + el, + render, + opened: () => { + keeping = false; + const all = layers(); + order = [...all.filter((l) => l.toggle.checked), ...all.filter((l) => !l.toggle.checked)].map((l) => l.name); + render(); + }, + }; +} + +// The elevation of the next `km` along the route, from its sampled profile +// (route.js's elevationProfile): the grid's elevation cell, the Terrain view's. +export function elevationHtml(route, atKm, km) { + const windowM = km * 1000; + const at = (atKm ?? 0) * 1000; + const points = (route?.elevation?.profile || []).filter((p) => p.distance_meters >= at - 50 && p.distance_meters <= at + windowM); + const label = `Elevation · the next ${km} km`; + if (points.length < 2) return `${label}${route ? "Reading the terrain…" : "No route"}`; + const heights = points.map((p) => p.elevation_meters); + const [low, high] = [Math.min(...heights), Math.max(...heights)]; + const x = (p) => (((p.distance_meters - at) / windowM) * 200).toFixed(1); + const y = (h) => (95 - ((h - low) / (high - low || 1)) * 85).toFixed(1); + const line = points.map((p, i) => `${i ? "L" : "M"}${x(p)} ${y(p.elevation_meters)}`).join(" "); + const climb = heights.reduce((sum, h, i) => sum + (i && h > heights[i - 1] ? h - heights[i - 1] : 0), 0); + const top = points[heights.indexOf(high)]; + return `${label} + + + + + ↑ ${Math.round(climb)} m ${Math.round(heights[0])} → ${Math.round(heights.at(-1))} m · top ${Math.round(high)} m in ${distance(Math.max(0, top.distance_meters - at))}`; +} + +// Terrain (the canvas' GridTerrain): off-road only — roll (a rear view) and +// pitch (a side view) on dials, amber past WARN and red past 1.5× (as +// dashboard.js), the maximum held until Reset; heading, the climb and the +// side slope ahead from the DEM along the course; the route's elevation of +// the next 2 km; Level here = can.json's levelling action (SDO, as /can.html). +// ctx: as Points', plus state() (the dashboard's) and settings(). +const WARN = { roll: 20, pitch: 25 }; +const DIAL_MAX = 45; +const CLIMB_M = 300; // the climb ahead over this far +const ACROSS_AT_M = 50; // the side slope this far ahead, over ±ACROSS_HALF_M +const ACROSS_HALF_M = 15; +const AHEAD_EVERY_MS = 2000; // DEM lookups at most this often +const CARDINALS = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]; +const CAR_REAR = "M-46 30 L-46 -4 L-34 -34 L34 -34 L46 -4 L46 30 Z M-50 30 h22 v12 h-22 Z M28 30 h22 v12 h-22 Z"; +const CAR_SIDE = "M-62 26 L-62 -2 L-30 -6 L-18 -30 L40 -30 L52 -4 L62 -2 L62 26 Z"; +const dialPoint = (a) => { const r = ((a - 90) * Math.PI) / 180; return `${(120 * Math.cos(r)).toFixed(1)} ${(30 + 120 * Math.sin(r)).toFixed(1)}`; }; +const arc = (a, b, cls) => ``; +const severity = (key, v) => (v == null ? "" : Math.abs(v) >= WARN[key] * 1.5 ? "drive-cell--warn" : Math.abs(v) >= WARN[key] ? "drive-terrain--caution" : ""); +// a point `m` meters from [lon, lat] towards `bearing` +const offset = ([lon, lat], bearing, m) => [lon + (m * Math.sin(bearing * RAD)) / (111320 * Math.cos(lat * RAD)), lat + (m * Math.cos(bearing * RAD)) / 111320]; + +export function terrainMenu(ctx) { + const el = panel("drive-terrain", "Terrain", ` +
+
+
+
+
+
+ + + `); + let peak = { roll: null, pitch: null }; + let ahead = { climb: null, across: null }; + let aheadAt = 0; + let armed = null; // Level here asks for a second tap + const offline = fetch("/api/terrain-tiles").then((r) => r.json()).then((d) => !!d.available).catch(() => false); + + // The climb and the side slope ahead, from the DEM along the course. + const lookAhead = async (position, course) => { + if (Date.now() - aheadAt < AHEAD_EVERY_MS || !position || course == null) return; + aheadAt = Date.now(); + const off = await offline; + const at = ([lon, lat]) => elevationAt(lon, lat, off, { zoom: 12, smooth: true }); + const front = offset(position, course, ACROSS_AT_M); + const [here, far, left, right] = await Promise.all([at(position), at(offset(position, course, CLIMB_M)), + at(offset(front, course - 90, ACROSS_HALF_M)), at(offset(front, course + 90, ACROSS_HALF_M))]); + ahead = { + climb: here != null && far != null ? ((far - here) / CLIMB_M) * 100 : null, + across: left != null && right != null ? Math.atan((left - right) / (2 * ACROSS_HALF_M)) / RAD : null, + }; + }; + + const dial = (key, value) => { + const w = WARN[key]; + const angle = value == null ? 0 : key === "pitch" ? -value : value; // the side view faces right: nose up = counter-clockwise + const p = peak[key]; + const mark = p == null ? "" : ``; + const sign = (v) => (v > 0 ? "+" : v < 0 ? "−" : ""); + return ` + ${arc(-w, w, "drive-terrain__ok")}${arc(-w * 1.5, -w, "drive-terrain__amber")}${arc(w, w * 1.5, "drive-terrain__amber")} + ${arc(-DIAL_MAX, -w * 1.5, "drive-terrain__red")}${arc(w * 1.5, DIAL_MAX, "drive-terrain__red")} + + ${mark} + + ${value == null ? "—" : `${sign(Math.round(value))}${Math.abs(Math.round(value))}°`} + ${key} · max ${p == null ? "—" : `${Math.abs(Math.round(p))}°`}`; + }; + const field = (name, label, value, unit, cls = "") => + (el.querySelector(`[data-field="${name}"]`).innerHTML = `${label}${value} ${unit}`); + + function render() { + if (el.hidden) return; + const dash = ctx.state(); + const v = dash?.values || {}; + for (const key of ["roll", "pitch"]) { + if (v[key] != null && (peak[key] == null || Math.abs(v[key]) > Math.abs(peak[key]))) peak[key] = v[key]; + el.querySelector(`[data-key="${key}"]`).innerHTML = dial(key, v[key]); + } + const h = dash?.heading; + const deg = h ? Math.round(h.deg) % 360 : null; + field("heading", "Heading", deg == null ? "—" : `${String(deg).padStart(3, "0")}°`, deg == null ? "" : CARDINALS[Math.round(deg / 45) % 8]); + const climb = ahead.climb; + field("climb", "Climb ahead", climb == null ? "—" : `${Math.round(climb)} %`, `in ${CLIMB_M} m`, climb != null && Math.abs(climb) >= 15 ? "drive-terrain--caution" : ""); + field("across", "Across ahead", ahead.across == null ? "—" : `${Math.abs(Math.round(ahead.across))}°`, "side slope, DEM", severity("roll", ahead.across)); + el.querySelector(".drive-terrain__elevation").innerHTML = elevationHtml(ctx.route(), ctx.atKm(), 2); + const source = dash?.simulated ? "from the terrain (simulation)" : v.roll != null || v.pitch != null ? "IMU" : "no tilt signal"; + el.querySelector(".drive-panel__note").textContent = [source, dash?.surface?.replaceAll("_", " ")].filter(Boolean).join(" · "); + const level = el.querySelector('[data-action="level"]'); + const action = (dash?.actions || []).findIndex((a) => /level/i.test(a.name)); + level.disabled = action < 0; + level.title = action < 0 ? "No levelling action in can.json" : "Zero roll and pitch here (the node's SDO)"; + level.textContent = armed ? "Tap again to level" : "Level here (zero)"; + level.classList.toggle("drive-terrain__level--armed", !!armed); + const position = v.lon != null && v.lat != null ? [v.lon, v.lat] : null; + lookAhead(position, dash?.course ?? h?.deg).then(() => {}, () => {}); + } + + el.querySelector(".drive-panel__close").addEventListener("click", ctx.close); + el.querySelector('[data-action="road"]').addEventListener("click", ctx.close); + el.querySelector('[data-action="reset"]').addEventListener("click", () => { peak = { roll: null, pitch: null }; render(); }); + el.querySelector('[data-action="level"]').addEventListener("click", async () => { + if (!armed) { + armed = setTimeout(() => { armed = null; render(); }, 3000); + return render(); + } + clearTimeout(armed); + armed = null; + const n = (ctx.state()?.actions || []).findIndex((a) => /level/i.test(a.name)); + const response = await fetch(`/api/can/actions/${n}`, { method: "POST" }).catch(() => null); + el.querySelector('[data-action="level"]').textContent = response?.ok ? "Levelled ✓" : "Levelling failed"; + if (response?.ok) peak = { roll: null, pitch: null }; + }); + return { el, render, opened: render }; +} diff --git a/public/js/driving.js b/public/js/driving.js index 918ab42..4461571 100644 --- a/public/js/driving.js +++ b/public/js/driving.js @@ -1,97 +1,155 @@ -import { LngLatBounds } from "/vendor/maplibre-gl/maplibre-gl.mjs"; +import { LngLatBounds, Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs"; import { requestGnssFollow, onRouteChanged } from "/js/panels.js"; import { pauseFollow, resumeFollow, isFollowing } from "/js/gnss.js"; import { formatDuration } from "/js/route.js"; import { isLoggedIn } from "/js/auth.js"; +import { watchDashboard, maneuverSvg, distance } from "/js/dashboard.js"; +import { formatSunInfo } from "/js/sun.js"; +import { pointsMenu, layersMenu, terrainMenu, elevationHtml, cellButton, emptyRow as empty, escapeHtml } from "/js/drive_menus.js"; -// Driving mode: the few things needed on the road as big buttons, the -// planning sidebar and panels out of the way. After the research in -// docs/design.adoc ("Buttons while driving"): four buttons on the map -// (Android Auto's action strip: at most four, 76 px), the recenter button -// only while the map isn't following (as Google Maps), night automatic and -// leaving by the topbar's Drive. Per device (localStorage). +// Driving mode: the grid of docs/design.adoc ("Layout: a grid, not floating +// panels"; the Design canvas' Grid) — the page becomes cells, the map one +// of them, nothing over it; values in cells around it, keys in the bottom +// row, a menu opens in place of the right column and the map narrows. +// Which cell shows what is the screen profile's (public/drive/road.json: +// {area, widget, ...} per cell), to be edited in the app later. Per device +// (localStorage). const KEY = "drivingMode"; +const PROFILE_URL = "/drive/road.json"; 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 RENDER_MS = 1000; // the clock, the follow state; the dashboard's polls render too const SEARCH_DELAY_MS = 300; // after the last key const LOG_POLL_MS = 5000; // the trip log's state and new points const DRIVEN_SOURCE = "trip-driven"; +const OVER_KMH = 3; // as dashboard.js: over the limit by more than this -const escapeHtml = (text) => String(text).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]); +// key action → [icon, label, title] +const KEYS = { + trip: ["⚑", "Trip", "The trip's stops: add, move, remove"], + points: ["◉", "Points", "Saved points and tracks near the car"], + layers: ["◫", "Layers", "Layers on the map, presets"], + search: ["⌕", "Search", "Search saved points and places"], + menu: ["☰", "Menu", "Menu: the whole route, leave driving"], + zoomOut: ["−", "", "Zoom out"], + zoomIn: ["+", "", "Zoom in"], + pitch: ["3D", "", "2D or 3D"], + follow: ["⌖", "", "Follow the position, heading up in 3D"], + terrain: ["⛰", "", "Terrain view: roll, pitch, the slope ahead"], + palette: ["", "", "Day, dusk, night"], +}; +const NOT_YET = new Set(); +// The Terrain view switches itself on off-road (docs/design.adoc, Screen +// profiles): an unpaved surface (/api/road, off a route) or roll / pitch past +// TILT_DEG for TILT_S; back to the road view after PAVED_BACK_M on paved road. +// Closed by hand while still off-road: not again until back on the road. +const UNPAVED = new Set(["compacted", "dirt", "gravel", "path", "impassable"]); +const TILT_DEG = 10; +const TILT_S = 10; +const PAVED_BACK_M = 2000; +const TERRAIN_AUTO_KEY = "maptool.terrainAuto"; +const FIELDS = { speed: "Speed", limit: "Limit", altitude: "Altitude", time: "Time", sun: "Sun", nextStop: "Next stop", + toNextStop: "To next stop", etaNextStop: "ETA next stop", toEnd: "To the end" }; +const CARDINALS = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]; + +const clock = (date) => date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); + +export function setupDriving(map, nightButton, routePanel, gpxPanel) { + const app = document.getElementById("app"); + let route = onRouteChanged((r) => { route = r; render(); }); + let dash = null; // the dashboard's last state + let profile = null; + const cells = []; // [{ cell, el }] + let openPanel = null; -export function setupDriving(map, nightButton, routePanel) { - let route = onRouteChanged((r) => (route = r)); const toggle = document.createElement("button"); toggle.type = "button"; toggle.className = "topbar__drive"; - toggle.title = "Driving mode: big buttons, no planning panels"; + toggle.title = "Driving mode: the cockpit grid, no planning panels"; toggle.textContent = "Drive"; nightButton.before(toggle); - const button = (name, label, title, action) => { - const el = document.createElement("button"); - el.type = "button"; - el.className = `drive-bar__${name}`; - el.textContent = label; - el.title = title; - el.setAttribute("aria-label", title); - el.addEventListener("click", action); - return el; + const overview = () => { + 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 }); }; - const bar = document.createElement("div"); - bar.className = "drive-bar"; - bar.hidden = true; - bar.append( - button("zoomIn", "+", "Zoom in", () => map.zoomIn()), - button("zoomOut", "−", "Zoom out", () => map.zoomOut()), - button("pitch", "3D", "2D / 3D", () => map.easeTo({ pitch: map.getPitch() > 0 ? 0 : PITCH_3D, ...(map.getPitch() > 0 && { bearing: 0 }), duration: 300 })), - button("trip", "Trip", "The trip's stops: add, move, remove", () => openTrip(tripPanel.hidden)), - button("overview", "Route", "The whole route (the follow pauses)", () => { - const coords = route?.geometry?.coordinates; - if (!coords?.length) return; - pauseFollow(map); - map.fitBounds(coords.reduce((b, c) => b.extend(c), new LngLatBounds(coords[0], coords[0])), { padding: 80, pitch: 0, bearing: 0 }); - }), - ); - // the one "follow / back to the position", bottom left, only when needed - const recenter = button("recenter", "Follow", "Follow the position, heading up in 3D", () => { - requestGnssFollow(); - resumeFollow(map); - if (map.getPitch() === 0) map.easeTo({ pitch: PITCH_3D, duration: 300 }); - recenter.hidden = true; - }); - recenter.hidden = true; - // The Trip menu (the navigator's, docs/design.adoc): the stops as big - // rows — tap a name to look at it, ↑ ↓ to reorder, ✕ to drop — and big - // actions: a stop where the crosshair is (pan the map there first), the - // start moved to the car. One level, no dragging, no typing. - const tripPanel = document.createElement("div"); - tripPanel.className = "drive-trip"; + + // The Trip menu (the navigator's, docs/design.adoc; the canvas' GridTrip + // and GridSearch): the menu area as cells too — the stops a row each (name + // over 3 cells, ✓ ↑ ↓ ✕ a cell each), recording on top, the actions at the + // foot. Typing a search turns it into results (+ adds one as a stop), with + // their pins on the map. One level, no dragging. + const tripPanel = document.createElement("section"); + tripPanel.className = "drive-panel drive-trip"; + tripPanel.setAttribute("aria-label", "Trip"); tripPanel.hidden = true; - tripPanel.innerHTML = `
Trip
-
- -
    -
    - - -
    `; + tripPanel.dataset.mode = "trip"; + tripPanel.innerHTML = `
    Trip
    + + +
    Recording
    + +
    +
    + + + `; + // The Menu: what has no key of its own (yet). + const menuPanel = document.createElement("section"); + menuPanel.className = "drive-panel drive-menu"; + menuPanel.setAttribute("aria-label", "Menu"); + menuPanel.hidden = true; + menuPanel.innerHTML = `
    Menu
    + + + + `; + const terrainAuto = () => { try { return localStorage.getItem(TERRAIN_AUTO_KEY) !== "hand"; } catch { return true; } }; + const autoButton = menuPanel.querySelector('[data-action="terrain-auto"]'); + const renderAuto = () => { autoButton.innerHTML = `Terrain view: ${terrainAuto() ? "automatic" : "by hand"} tap to switch`; }; + autoButton.addEventListener("click", () => { + try { localStorage.setItem(TERRAIN_AUTO_KEY, terrainAuto() ? "hand" : "auto"); } catch { /* private window: not kept */ } + renderAuto(); + }); + renderAuto(); + menuPanel.querySelector('[data-action="overview"]').addEventListener("click", overview); + menuPanel.querySelector('[data-action="leave"]').addEventListener("click", () => set(false)); const crosshair = document.createElement("div"); crosshair.className = "drive-crosshair"; crosshair.hidden = true; // Search: saved points (the library) and places (the offline POI - // database), nearest the crosshair first; a result's name shows it, + adds - // it as a stop. While there's a query the list shows results, not stops. + // database), nearest the crosshair first. const input = tripPanel.querySelector(".drive-trip__search input"); let results = null; + let pins = []; let searchTimer = null; let searchSeq = 0; + let searching = false; + const setResults = (list) => { + results = list; + tripPanel.dataset.mode = results ? "search" : "trip"; + for (const pin of pins) pin.remove(); + pins = (results || []).map((r) => { + const el = document.createElement("div"); + el.className = `drive-pin drive-pin--${r.kind}`; + return new Marker({ element: el }).setLngLat(r.lngLat).addTo(map); + }); + renderTrip(); + render(); + }; + const backToStops = () => { + input.value = ""; + clearTimeout(searchTimer); + searchSeq++; + searching = false; + setResults(null); + }; input.addEventListener("input", () => { clearTimeout(searchTimer); - if (!input.value.trim()) { - results = null; - return renderTrip(); - } + if (!input.value.trim()) return setResults(null); + searching = true; + if (!results) setResults([]); // the search layout at once, the input stays focused searchTimer = setTimeout(async () => { const mine = ++searchSeq; const { lng, lat } = map.getCenter(); @@ -100,75 +158,124 @@ export function setupDriving(map, nightButton, routePanel) { 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(); + searching = false; + setResults(found.filter(({ bbox }) => bbox).map(({ name, bbox, source, source_label: where }) => { + const lngLat = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]; + return { name, where, lngLat, kind: source === "places" ? "place" : "saved", away: distance(map.getCenter().distanceTo({ lng: lngLat[0], lat: lngLat[1] })) }; + })); }, SEARCH_DELAY_MS); }); + tripPanel.querySelector('[data-action="back"]').addEventListener("click", backToStops); const lookAt = (lngLat) => { pauseFollow(map); map.easeTo({ center: lngLat, zoom: Math.max(map.getZoom(), 14) }); }; const renderResults = (list) => { - list.replaceChildren(...results.map((r) => { - const li = document.createElement("li"); - const name = button("stop-name", r.name, "Show it on the map", () => lookAt(r.lngLat)); - name.innerHTML = `${escapeHtml(r.name)}${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 + list.replaceChildren(...results.flatMap((r) => [ + cellButton("result", `${escapeHtml(r.name)}${escapeHtml(r.where || "")} · ${r.away}`, + "Show it on the map", () => lookAt(r.lngLat)), + cellButton("add", "+", "Add as a stop", () => { + backToStops(); // 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. `; + }), + ])); + if (!results.length) list.append(empty(searching ? "Searching…" : input.value.trim() ? "Nothing found." : "Type a name — saved points and places, nearest first.")); }; const renderTrip = () => { if (tripPanel.hidden || !routePanel) return; - if (results) return renderResults(tripPanel.querySelector(".drive-trip__stops")); + if (results) return renderResults(tripPanel.querySelector(".drive-trip__results")); 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)); + list.replaceChildren(...stops.flatMap((stop, i) => { + const leg = stop.leg ? `+${stop.leg.km.toFixed(1)} km${stop.leg.s != null ? ` · ${formatDuration(stop.leg.s)}` : ""}` : ""; + const name = cellButton("stop", `${escapeHtml(stop.label)}${leg ? ` · ${leg}` : ""}` + + `${escapeHtml(stop.name || `${stop.lngLat[1].toFixed(4)}, ${stop.lngLat[0].toFixed(4)}`)}`, "Show it on the map", () => lookAt(stop.lngLat)); + name.classList.toggle("drive-panel__passed", !!stop.passed || stop.behind); + const done = cellButton("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)); + const up = cellButton("up", "↑", "Earlier", () => routePanel.moveStop(i, -1)); + const down = cellButton("down", "↓", "Later", () => routePanel.moveStop(i, 1)); + const drop = cellButton("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; + return [name, done, up, down, drop]; })); - if (!stops.length) list.innerHTML = `
  3. No stops yet — pan the map to a place and add it.
  4. `; + if (!stops.length) list.append(empty("No stops yet — pan the map to a place and add it, or search.")); 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(); + // One panel at a time, in the profile's menu area; the map narrows to its + // other area (its center — the follow, the crosshair — stays in view). + // Points and Layers (drive_menus.js): the car's position, else the map's center. + const menuCtx = { + map, gpxPanel, routePanel, lookAt, + position: () => (dash?.values?.lon != null && dash?.values?.lat != null ? [dash.values.lon, dash.values.lat] : map.getCenter().toArray()), + route: () => route, + atKm: () => dash?.atKm, + close: () => open(null), + }; + const points = pointsMenu(menuCtx); + const layers = layersMenu(menuCtx); + const terrain = terrainMenu({ ...menuCtx, state: () => dash }); + const menus = [points, layers, terrain]; + let offRoad = false; + let tiltSince = null; + let pavedM = 0; + let autoOpened = false; + let suppressed = false; + let lastState = Date.now(); + const autoTerrain = (state) => { + const v = state.values || {}; + const now = Date.now(); + const dt = (now - lastState) / 1000; + lastState = now; + const tilted = Math.max(Math.abs(v.roll ?? 0), Math.abs(v.pitch ?? 0)) >= TILT_DEG; + tiltSince = tilted ? tiltSince ?? now : null; + offRoad = UNPAVED.has(state.surface) || (tiltSince != null && now - tiltSince >= TILT_S * 1000); + if (offRoad) pavedM = 0; + else { + suppressed = false; + pavedM += (v.speed ?? 0) * dt; } + if (!terrainAuto()) return; + if (offRoad && !suppressed && !openPanel) { + open(terrain.el); + autoOpened = true; + } else if (autoOpened && openPanel === terrain.el && pavedM >= PAVED_BACK_M) open(null); + }; + function open(panel) { + if (openPanel === terrain.el && panel !== terrain.el) { + if (offRoad) suppressed = true; // closed by hand off-road: stays closed until the road + autoOpened = false; + } + if (panel !== tripPanel && results) backToStops(); // the pins go with the search + openPanel = panel; + tripPanel.hidden = panel !== tripPanel; + menuPanel.hidden = panel !== menuPanel; + for (const menu of menus) { + menu.el.hidden = panel !== menu.el; + if (panel === menu.el) menu.opened(); + } + crosshair.hidden = panel !== tripPanel; + if (profile) app.style.setProperty("--drive-map", panel ? profile.menu.map : profile.map); + map.resize(); + renderTrip(); + render(); } - tripPanel.querySelector(".drive-trip__close").addEventListener("click", () => openTrip(false)); + const togglePanel = (panel) => open(openPanel === panel ? null : panel); + for (const panel of [tripPanel, menuPanel]) panel.querySelector(".drive-panel__close").addEventListener("click", () => open(null)); tripPanel.querySelector('[data-action="add"]').addEventListener("click", () => { const { lng, lat } = map.getCenter(); routePanel?.addStop([lng, lat]); }); tripPanel.querySelector('[data-action="start"]').addEventListener("click", () => routePanel?.startHere()); - routePanel?.onStopsChanged(renderTrip); + routePanel?.onStopsChanged(() => { renderTrip(); render(); }); // The trip log (lib/maptool/trip_log.rb): Start makes the trip's library // folder and records the car's GNSS into it, End closes it; the line // really driven drawn in --route-driven, grown by polling ?since=N. const logButton = tripPanel.querySelector('[data-action="log"]'); - const logState = tripPanel.querySelector(".drive-trip__log-state"); + const logState = tripPanel.querySelector(".drive-trip__log-text"); let log = null; let driven = []; const drawDriven = () => { @@ -198,9 +305,10 @@ export function setupDriving(map, nightButton, routePanel) { setTimeout(pollLog, LOG_POLL_MS); }; const renderLog = () => { - logButton.textContent = log?.active ? "End the trip" : "Start the trip (record it)"; + logButton.textContent = log?.active ? "End the trip" : "Start the trip"; logButton.classList.toggle("drive-trip__log--on", !!log?.active); - logState.textContent = log?.active ? `● ${log.folder.replace(/^Trips\//, "")} · ${(log.distance_m / 1000).toFixed(1)} km` : ""; + logState.textContent = log?.active ? `● ${log.folder.replace(/^Trips\//, "")} · ${(log.distance_m / 1000).toFixed(1)} km` : "Not recording"; + logState.classList.toggle("drive-trip__log-text--on", !!log?.active); }; logButton.addEventListener("click", async () => { if (log?.active) { @@ -217,32 +325,214 @@ export function setupDriving(map, nightButton, routePanel) { refreshLog(); }); if (isLoggedIn()) pollLog(); - else tripPanel.querySelector(".drive-trip__log").hidden = true; - map.getContainer().append(bar, recenter, crosshair); - // the Trip menu beside the map, not over it (like Android Auto's side - // panel): the map gets narrower and keeps its buttons, its center (the - // follow, the crosshair, the overview) stays in what's seen - map.getContainer().after(tripPanel); + else { + logButton.disabled = true; + logButton.textContent = "Start the trip"; + logState.textContent = "Log in to record"; + } + map.getContainer().append(crosshair); + app.append(tripPanel, menuPanel, points.el, layers.el, terrain.el); - const render = () => { - bar.querySelector(".drive-bar__pitch").textContent = map.getPitch() > 0 ? "2D" : "3D"; - bar.querySelector(".drive-bar__overview").disabled = !route; - recenter.hidden = bar.hidden || isFollowing(map); + // --- the grid's cells --------------------------------------------------- + + const keyAction = { + trip: () => { + if (openPanel === tripPanel && results) return backToStops(); + togglePanel(tripPanel); + }, + search: () => { + if (openPanel === tripPanel && results) return open(null); + open(tripPanel); + if (!results) setResults([]); + input.focus(); + }, + menu: () => togglePanel(menuPanel), + points: () => togglePanel(points.el), + layers: () => togglePanel(layers.el), + terrain: () => togglePanel(terrain.el), + zoomOut: () => map.zoomOut(), + zoomIn: () => map.zoomIn(), + pitch: () => map.easeTo({ pitch: map.getPitch() > 0 ? 0 : PITCH_3D, ...(map.getPitch() > 0 && { bearing: 0 }), duration: 300 }), + follow: () => { + requestGnssFollow(); + resumeFollow(map); + if (map.getPitch() === 0) map.easeTo({ pitch: PITCH_3D, duration: 300 }); + render(); + }, + palette: () => nightButton.click(), }; + + const make = (cell) => { + let el; + if (cell.widget === "key") { + const [icon, label, title] = KEYS[cell.action] || ["?", cell.action, cell.action]; + el = document.createElement("button"); + el.type = "button"; + el.title = title; + el.setAttribute("aria-label", label || title); + el.innerHTML = `${icon}${label ? `${label}` : ""}`; + el.disabled = NOT_YET.has(cell.action) || !keyAction[cell.action]; + el.addEventListener("click", () => keyAction[cell.action]?.()); + if (cell.action === "zoomIn" || cell.action === "zoomOut") el.classList.add("drive-key--big"); + } else { + el = document.createElement("div"); + } + el.classList.add("drive-cell", `drive-cell--${cell.widget}`); + if (cell.small) el.classList.add("drive-cell--small"); + el.style.gridArea = cell.area; + return el; + }; + + // To the next stop and to the end, from the km along the route (the start + // of it while not on it): the leg's time in proportion to what's left of it. + // ponytail: a straight share of the leg's time, Valhalla's per-maneuver times if it's off + const ahead = () => { + const p = route?.properties; + const stops = routePanel?.stops().filter((s) => !s.passed) || []; + if (!p?.legs_km?.length || stops.length !== p.legs_km.length + 1) return null; + const at = dash?.atKm ?? 0; + let end = 0; + let i = 0; + for (; i < p.legs_km.length; i++) { + end += p.legs_km[i]; + if (end > at + 0.05) break; + } + i = Math.min(i, p.legs_km.length - 1); + const toNext = Math.max(0, end - at); + const sNext = p.legs_s?.[i] != null && p.legs_km[i] ? (p.legs_s[i] * toNext) / p.legs_km[i] : null; + const toEnd = Math.max(0, p.distance_km - at); + const sEnd = sNext != null ? sNext + p.legs_s.slice(i + 1).reduce((a, b) => a + b, 0) : (p.time_s * toEnd) / p.distance_km; + const stop = stops[i + 1]; + return { name: stop.name || stop.label, toNext, sNext, toEnd, sEnd }; + }; + + // [value, unit, class] + const fieldValue = (name, a) => { + const v = dash?.values || {}; + const nav = dash?.nav; + const kmh = v.speed == null ? null : v.speed * 3.6; + const limit = nav?.limit; + const now = new Date(); + switch (name) { + case "speed": + return [kmh == null ? "—" : Math.round(kmh), "km/h", typeof limit === "number" && kmh > limit + OVER_KMH ? "drive-cell--warn" : ""]; + case "limit": { + const next = nav?.next ? `· ${typeof nav.next.limit === "number" ? nav.next.limit : "∞"} in ${distance(nav.next.m)}` : ""; + return [typeof limit === "number" ? limit : limit === "unlimited" ? "∞" : "—", next, "drive-cell--limit"]; + } + case "altitude": + return [v.alt == null ? "—" : Math.round(v.alt), "m"]; + case "time": + return [clock(now), ""]; + case "sun": { + const { lng, lat } = map.getCenter(); + const info = formatSunInfo(lat, lng, now); + if (!info) return ["—", ""]; + if (info.polar) return [info.polar, ""]; + return info.countdown?.endsWith("sunrise") ? [info.sunrise, "rise"] : [info.sunset, "set"]; + } + case "nextStop": + return [a?.name ?? "—", ""]; + case "toNextStop": + return a ? [a.toNext.toFixed(1), `km${a.sNext != null ? ` · ${formatDuration(a.sNext)}` : ""}`] : ["—", ""]; + case "etaNextStop": + return [a?.sNext != null ? clock(new Date(now.getTime() + a.sNext * 1000)) : "—", ""]; + case "toEnd": + return a ? [a.toEnd.toFixed(1), `km · ${clock(new Date(now.getTime() + a.sEnd * 1000))}`] : ["—", ""]; + default: + return ["?", ""]; + } + }; + + const renderManeuver = (el) => { + const n = dash?.nav; + if (n?.offRoute) { + el.innerHTML = `
    Off the routererouting
    `; + } else if (n?.maneuver) { + const { m, type, street, text, exit } = n.maneuver; + const what = street ? `${exit ? `${exit}. exit · ` : ""}${escapeHtml(street)}` : escapeHtml(text); + const then = n.then ? ` · then ${escapeHtml(n.then.street || n.then.text)}` : ""; + el.innerHTML = `${maneuverSvg(type)}
    ${distance(m)}${what}${then}
    `; + } else { + el.innerHTML = `
    On${escapeHtml(n?.street ?? "—")}
    `; + } + }; + + const renderElevation = (el, cell) => { el.innerHTML = elevationHtml(route, dash?.atKm, cell.km || 10); }; + + + const renderCompass = (el) => { + const h = dash?.heading; + const deg = h ? Math.round(h.deg) % 360 : null; + el.innerHTML = ` + + + + + N + + + + Heading${deg == null ? "—" : String(deg).padStart(3, "0") + "°"} ${deg == null ? "" : CARDINALS[Math.round(deg / 45) % 8]}`; + }; + + const renderKey = (el, cell) => { + const pressed = { trip: openPanel === tripPanel && !results, search: openPanel === tripPanel && !!results, points: openPanel === points.el, layers: openPanel === layers.el, terrain: openPanel === terrain.el, menu: openPanel === menuPanel, pitch: map.getPitch() > 0, follow: isFollowing(map) }[cell.action]; + el.setAttribute("aria-pressed", String(!!pressed)); + if (cell.action === "palette") el.querySelector(".drive-key__icon").textContent = nightButton.textContent; + }; + + function render() { + if (!document.documentElement.classList.contains("driving")) return; + if (openPanel === terrain.el) terrain.render(); + const a = ahead(); + for (const { cell, el } of cells) { + if (cell.widget === "field") { + const [value, unit, cls = ""] = fieldValue(cell.value, a); + el.innerHTML = `${FIELDS[cell.value] || cell.value}${escapeHtml(value)} ${escapeHtml(unit)}`; + } else if (cell.widget === "maneuver") renderManeuver(el); + else if (cell.widget === "status") { + el.innerHTML = `MAPTOOL● ${navigator.onLine ? "online" : "offline"}${log?.active ? ` · ● rec` : ""}`; + } else if (cell.widget === "elevation") renderElevation(el, cell); + else if (cell.widget === "compass") renderCompass(el); + else if (cell.widget === "key") renderKey(el, cell); + } + } map.on("pitchend", render); - onRouteChanged(render); - setInterval(render, CHECK_MS); + setInterval(render, RENDER_MS); + + fetch(PROFILE_URL, { cache: "no-cache" }).then((r) => r.json()).then((p) => { + profile = p; + app.style.setProperty("--drive-cols", p.columns); + app.style.setProperty("--drive-rows", p.rows); + app.style.setProperty("--drive-map", openPanel ? p.menu.map : p.map); + app.style.setProperty("--drive-menu", p.menu.area); + const [r1, c1, r2, c2] = p.menu.area.split("/").map(Number); + app.style.setProperty("--drive-menu-cols", c2 - c1); + app.style.setProperty("--drive-menu-rows", r2 - r1); + for (const cell of p.cells) { + const el = make(cell); + app.append(el); + cells.push({ cell, el }); + } + render(); + map.resize(); + }); function set(on) { - if (!on) openTrip(false); + if (!on) open(null); 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 */ } + watchDashboard(on ? (state) => { + dash = state; + autoTerrain(state); + render(); + } : null); render(); - map.resize(); // the sidebar came or went + map.resize(); // the grid came or went } - toggle.addEventListener("click", () => set(bar.hidden)); + toggle.addEventListener("click", () => set(!document.documentElement.classList.contains("driving"))); let saved = null; try { saved = localStorage.getItem(KEY); } catch { /* nothing kept */ } set(saved === "on"); diff --git a/public/js/gpx.js b/public/js/gpx.js index 5112b64..afa6768 100644 --- a/public/js/gpx.js +++ b/public/js/gpx.js @@ -705,6 +705,26 @@ export class GpxPanelControl { this._renderView(); } + // For the driving grid's Points (driving.js): the tree as indexed by + // _renderTree, whether a node is shown, and showing / hiding nodes. + libraryTree() { + return { folders: this._folders || new Map(), files: this._files || new Map(), filesUnder: (path) => this._filesUnder(path) }; + } + + isShown(path) { + return this._visible.has(path); + } + + async setShown(paths, visible) { + await Promise.all(paths.map((path) => this._toggleFileOnly(path, visible))); + this._saveVisible(); + this._renderView(); + } + + zoomTo(path) { + return this._zoomTo(path); + } + // Search result picked: show its file, then open the matching point's // popup as if it had been clicked on the map. Matched by exact // coordinates (the search index reads the same GeoJSON); a track/line diff --git a/public/js/map.js b/public/js/map.js index bfc6430..3747fd8 100644 --- a/public/js/map.js +++ b/public/js/map.js @@ -505,7 +505,7 @@ if (isLoggedIn()) new PluginsControl(map).mount(sidebar); sidebar.insertAdjacentHTML("beforeend", ``); const routePanel = new RoutePanelControl(map, gnssControl, profilePanel); routePanel.mount(sidebar); -setupDriving(map, nightButton, routePanel); +setupDriving(map, nightButton, routePanel, gpxPanel); new OfflineDataControl().mount(sidebar); sidebar.insertAdjacentHTML("beforeend", ``); diff --git a/test/test_routing.rb b/test/test_routing.rb index 0138645..beea75a 100644 --- a/test/test_routing.rb +++ b/test/test_routing.rb @@ -162,9 +162,9 @@ class RoutingTest < Minitest::Test end def test_the_road_driven_is_the_last_matched_edge - reply = JSON.generate(edges: [{ names: ["A"], road_class: "primary", speed_limit: 90 }, { names: ["B"], road_class: "motorway", speed_limit: "unlimited" }]) + reply = JSON.generate(edges: [{ names: ["A"], road_class: "primary", speed_limit: 90 }, { names: ["B"], road_class: "motorway", speed_limit: "unlimited", surface: "paved_smooth" }]) request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}") do |url| - assert_equal({ name: "B", road_class: "motorway", speed_limit: "unlimited" }, Maptool::Routing.road(url, [[17.1, 48.1], [17.2, 48.2]])) + assert_equal({ name: "B", road_class: "motorway", speed_limit: "unlimited", surface: "paved_smooth" }, Maptool::Routing.road(url, [[17.1, 48.1], [17.2, 48.2]])) end assert_includes request, %("shape_match":"map_snap") assert_raises(Maptool::Routing::RouteError) { Maptool::Routing.road("http://x", [[17.1, 48.1]]) } diff --git a/test/test_search.rb b/test/test_search.rb index ab67c58..e42e3ec 100644 --- a/test/test_search.rb +++ b/test/test_search.rb @@ -55,6 +55,13 @@ class SearchTest < Minitest::Test assert_empty search(" ") end + def test_blank_query_with_a_center_lists_the_library_nearest_first + results = search("", center: [48.72, 21.26]) + assert_equal "Kemp Košice", results.first[:name] + assert(results.all? { |r| r[:source] == "layers" }) + assert_empty search("", center: [48.72, 21.26], sources: ["hiking_trails"]) + end + private def search(text, **opts) diff --git a/views/importmap.erb b/views/importmap.erb index 9d8e7ea..8e752ec 100644 --- a/views/importmap.erb +++ b/views/importmap.erb @@ -20,6 +20,7 @@ "/js/live.js": "/js/live.js?v=<%= ASSET_VERSION %>", "/js/dashboard.js": "/js/dashboard.js?v=<%= ASSET_VERSION %>", "/js/driving.js": "/js/driving.js?v=<%= ASSET_VERSION %>", + "/js/drive_menus.js": "/js/drive_menus.js?v=<%= ASSET_VERSION %>", "/js/update.js": "/js/update.js?v=<%= ASSET_VERSION %>", "/js/icons.js": "/js/icons.js?v=<%= ASSET_VERSION %>", "/js/livetrack.js": "/js/livetrack.js?v=<%= ASSET_VERSION %>",