Drive as the Design canvas' Grid: the page as 16 × 10 cells from a screen profile (public/drive/road.json, {area, widget, …} per cell, to be edited in the app later), the map 13 × 8 with nothing over it; the manoeuvre, speed, limit, altitude, time, sun, status (online, rec), next stop with km / ETA to it and to the end, the route's elevation of the next 10 km, a compass; keys Trip, Points, Layers, Search, Menu, − + 3D Follow, Terrain, day/dusk/night. A menu opens in the right 7 × 8 as cells of its own and the map narrows to 9 × 8 (drive_menus.js): Trip and Search as GridTrip / GridSearch (a stop a row, ✓ ↑ ↓ ✕ a cell each; results with their pins on the map); Points as GridPoints (the library nearest the car — /api/search with no words and a center lists every saved feature nearest first — along the route ahead, shown, or one folder at a time; an eye per row, + a point as a stop); Layers as GridLayers (the On the map panel's own switches and Online | Offline, presets Road / Off-road / Overnight, + Keep); Terrain as GridTerrain (roll / pitch dials with the max held, climb and side slope ahead from the DEM, the next 2 km, Level here = can.json's levelling action in two taps), on by itself on an unpaved surface (/api/road now gives Valhalla's surface) or past 10° for 10 s, back after 2 km of paved road, automatic / by hand in the Menu. The dashboard polls for the grid without its overlay; the old drive bar and floating buttons gone
CI / check (push) Successful in 23s
CI / deploy (push) Successful in 17s

This commit is contained in:
randy committed 2026-12-03 10:47:40 +01:00
1 parent 285af64a65
commit f73badd107
14 files changed
+1253 -277

No files matched your search

+233 -135
View File
@@ -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; }
+34
View File
@@ -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" }
]
}
+45 -13
View File
@@ -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) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
// An arrow from the bottom center turning by `angle` (° from straight on),
@@ -66,7 +66,7 @@ const uturnPath = (cls) => `<path class="${cls}" d="M14 30 V14 A5 5 0 0 0 4 14 V
// "uturn", "arrive", "roundabout" drawn their own way.
const MANEUVER_ANGLES = { 1: 0, 2: 45, 3: -45, 7: 0, 8: 0, 9: 45, 10: 90, 11: 135, 14: -135, 15: -90, 16: -45, 17: 0, 18: 45, 19: -45,
20: 45, 21: -45, 22: 0, 23: 30, 24: -30, 25: 0, 37: 30, 38: -30 };
function maneuverSvg(type) {
export function maneuverSvg(type) {
let body;
if (type === 12 || type === 13) body = uturnPath("dash-banner__arrow");
else if (type >= 4 && type <= 6) body = `<path class="dash-banner__arrow" d="M8 30 V4 M8 5 H19 L16 9 L19 13 H8"/>`; // a flag: arriving
@@ -163,8 +163,19 @@ const INCLINOMETER = `
<text x="35" y="60" class="dash-caption">pitch</text>
</svg>`;
// 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/<n>
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);
}
+454
View File
@@ -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) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[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 = `<div class="drive-panel__head">${label} <small class="drive-panel__note"></small></div>
<button type="button" class="drive-panel__close" aria-label="Close">✕</button>${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", `
<div class="drive-points__search"><input type="search" aria-label="Find in the library" placeholder="Find a point, track, folder…" enterkeyhint="search"></div>
<div class="drive-points__bar"></div>
<div class="drive-panel__list drive-points__list"></div>
<div class="drive-panel__foot"></div>
<button type="button" class="drive-panel__wide" data-action="hide-all">Hide all</button>`);
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", `<span class="drive-points__icon" style="color: ${color}">${icon}</span><span class="drive-panel__text"><b>${escapeHtml(name)}</b><small>${escapeHtml(meta)}</small></span>` +
`<span class="drive-points__away">${escapeHtml(away || "")}</span>`, "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 = `<small class="drive-cell__label">${escapeHtml(parent ? `${parent.replaceAll("/", " › ")} ›` : cwd ? "Library ›" : "")}</small><b>${escapeHtml(cwd ? name : "Library")}</b>`;
const nearest = cellButton("mode", `<span class="drive-key__icon">◎</span><span class="drive-key__label">Nearest</span>`, "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", `<span class="drive-key__icon">▣</span><span class="drive-key__label">Folders</span>`, "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", `
<div class="drive-layers__presets"></div>
<div class="drive-panel__cell drive-layers__map"><small class="drive-cell__label">Map</small><span>offline by itself, no signal</span></div>
<div class="drive-layers__source"></div>
<div class="drive-panel__list drive-layers__list"></div>
<div class="drive-panel__foot"></div>
<button type="button" class="drive-panel__wide" data-action="all-off">All off</button>`);
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", `<span class="drive-key__icon">${icon}</span><span class="drive-key__label">${keeping ? `Save as ${label}` : label}</span>`, 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", `<span class="drive-key__icon">${keeping ? "✕" : "+"}</span><span class="drive-key__label">${keeping ? "Cancel" : "Keep"}</span>`,
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 = `<span class="drive-layers__icon" aria-hidden="true">${layer.icon}</span><span class="drive-panel__text"><b>${escapeHtml(layer.name)}</b><small>${escapeHtml(layer.group)}</small></span>`;
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 = `<span class="drive-cell__label">Elevation · the next ${km} km</span>`;
if (points.length < 2) return `${label}<span class="drive-cell__muted">${route ? "Reading the terrain…" : "No route"}</span>`;
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}<svg class="drive-elevation" viewBox="0 0 200 100" preserveAspectRatio="none" role="img" aria-label="Elevation ahead">
<path class="drive-elevation__area" d="${line} L${x(points.at(-1))} 100 L${x(points[0])} 100 Z"/>
<path class="drive-elevation__line" d="${line}"/>
<line class="drive-elevation__here" x1="0" y1="0" x2="0" y2="100"/>
</svg>
<span class="drive-cell__value drive-cell__value--mid">↑ ${Math.round(climb)} m <small>${Math.round(heights[0])} → ${Math.round(heights.at(-1))} m · top ${Math.round(high)} m in ${distance(Math.max(0, top.distance_meters - at))}</small></span>`;
}
// 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) => `<path class="${cls}" d="M${dialPoint(a)} A120 120 0 0 1 ${dialPoint(b)}"/>`;
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", `
<div class="drive-panel__cell drive-terrain__dial" data-key="roll"></div>
<div class="drive-panel__cell drive-terrain__dial" data-key="pitch"></div>
<div class="drive-panel__cell drive-terrain__field" data-field="heading"></div>
<div class="drive-panel__cell drive-terrain__field" data-field="climb"></div>
<div class="drive-panel__cell drive-terrain__field" data-field="across"></div>
<div class="drive-panel__cell drive-terrain__elevation"></div>
<button type="button" class="drive-terrain__level" data-action="level">Level here (zero)</button>
<button type="button" class="drive-terrain__reset" data-action="reset">Reset max</button>
<button type="button" class="drive-terrain__road" data-action="road">Road view</button>`);
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 ? "" : `<path class="drive-terrain__peak" d="M${dialPoint(Math.max(-DIAL_MAX, Math.min(DIAL_MAX, key === "pitch" ? -p : p)))} l-6 -12 h12 Z"/>`;
const sign = (v) => (v > 0 ? "+" : v < 0 ? "−" : "");
return `<svg class="drive-terrain__svg ${severity(key, value)}" viewBox="-135 -120 270 190" role="img" aria-label="${key} ${value == null ? "unknown" : `${Math.round(value)}°`}">
${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")}
<line class="drive-terrain__ground" x1="-130" y1="30" x2="130" y2="30"/>
<g transform="rotate(${angle} 0 30)"><line class="drive-terrain__mast" x1="0" y1="30" x2="0" y2="-100"/><path class="drive-terrain__car" d="${key === "roll" ? CAR_REAR : CAR_SIDE}"/></g>${mark}
</svg>
<span class="drive-terrain__value ${severity(key, value)}">${value == null ? "—" : `${sign(Math.round(value))}${Math.abs(Math.round(value))}°`}</span>
<span class="drive-cell__label">${key} · max ${p == null ? "—" : `${Math.abs(Math.round(p))}°`}</span>`;
};
const field = (name, label, value, unit, cls = "") =>
(el.querySelector(`[data-field="${name}"]`).innerHTML = `<span class="drive-cell__label">${label}</span><span class="drive-cell__value drive-cell__value--mid ${cls}">${value} <small>${unit}</small></span>`);
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 };
}
+409 -119
View File
@@ -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) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[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 = `<div class="drive-trip__head"><span>Trip <small class="drive-trip__total"></small></span><button type="button" class="drive-trip__close" aria-label="Close">✕</button></div>
<div class="drive-trip__log"><button type="button" data-action="log"></button><span class="drive-trip__log-state"></span></div>
<div class="drive-trip__search"><input type="search" placeholder="Search saved points and places…" enterkeyhint="search"></div>
<ol class="drive-trip__stops"></ol>
<div class="drive-trip__actions">
<button type="button" data-action="add">+ Stop at the crosshair</button>
<button type="button" data-action="start">Start from here (the car)</button>
</div>`;
tripPanel.dataset.mode = "trip";
tripPanel.innerHTML = `<div class="drive-panel__head">Trip <small class="drive-trip__total"></small></div>
<button type="button" class="drive-panel__close" aria-label="Close">✕</button>
<button type="button" class="drive-trip__log" data-action="log"></button>
<div class="drive-trip__log-state"><span class="drive-cell__label">Recording</span><span class="drive-trip__log-text"></span></div>
<div class="drive-trip__search"><input type="search" aria-label="Search" placeholder="Search saved points and places…" enterkeyhint="search"></div>
<div class="drive-trip__stops"></div>
<div class="drive-trip__results"></div>
<button type="button" class="drive-panel__primary drive-trip__add" data-action="add">+ Stop at the crosshair</button>
<button type="button" class="drive-trip__start" data-action="start">Start from the car</button>
<button type="button" class="drive-trip__back" data-action="back">← Back to the stops</button>`;
// 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 = `<div class="drive-panel__head">Menu</div>
<button type="button" class="drive-panel__close" aria-label="Close">✕</button>
<button type="button" class="drive-menu__row" data-action="overview">The whole route <small>the follow pauses</small></button>
<button type="button" class="drive-menu__row" data-action="terrain-auto"></button>
<button type="button" class="drive-menu__row" data-action="leave">Leave driving mode</button>`;
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"} <small>tap to switch</small>`; };
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)}<small>${escapeHtml(r.where || "")}</small>`;
const add = button("stop-add", "+", "Add as a stop", () => {
input.value = "";
results = null; // back to the stops, the new one among them
list.replaceChildren(...results.flatMap((r) => [
cellButton("result", `<span class="drive-pin drive-pin--${r.kind}"></span><span class="drive-panel__text"><b>${escapeHtml(r.name)}</b><small>${escapeHtml(r.where || "")} · ${r.away}</small></span>`,
"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 = `<li class="drive-trip__empty">Nothing found.</li>`;
}),
]));
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 ? `<small>+${stop.leg.km.toFixed(1)} km${stop.leg.s != null ? ` · ${formatDuration(stop.leg.s)}` : ""}</small>` : "";
name.innerHTML = `${escapeHtml(stop.label)} · ${escapeHtml(stop.name || `${stop.lngLat[1].toFixed(4)}, ${stop.lngLat[0].toFixed(4)}`)}${leg}`;
const done = button("stop-done", "✓", stop.passed ? "Passed — tap to route through it again" : "Mark as passed (not routed any more)", () => routePanel.togglePassed(i));
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", `<span class="drive-panel__text"><small class="drive-cell__label">${escapeHtml(stop.label)}${leg ? ` · ${leg}` : ""}</small>` +
`<b>${escapeHtml(stop.name || `${stop.lngLat[1].toFixed(4)}, ${stop.lngLat[0].toFixed(4)}`)}</b></span>`, "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 = `<li class="drive-trip__empty">No stops yet — pan the map to a place and add it.</li>`;
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 = `<span class="drive-key__icon">${icon}</span>${label ? `<span class="drive-key__label">${label}</span>` : ""}`;
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 = `<div><span class="drive-cell__value drive-cell--caution">Off the route</span><span class="drive-cell__label">rerouting</span></div>`;
} 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 ? ` <span class="drive-cell__muted">· then ${escapeHtml(n.then.street || n.then.text)}</span>` : "";
el.innerHTML = `${maneuverSvg(type)}<div class="drive-cell__text"><span class="drive-cell__value">${distance(m)}</span><span class="drive-cell__street">${what}${then}</span></div>`;
} else {
el.innerHTML = `<div class="drive-cell__text"><span class="drive-cell__label">On</span><span class="drive-cell__street">${escapeHtml(n?.street ?? "—")}</span></div>`;
}
};
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 = `<svg class="drive-compass${h && !h.live ? " drive-compass--stale" : ""}" viewBox="-50 -50 100 100" role="img" aria-label="${deg == null ? "No heading" : `Heading ${deg}°`}">
<circle r="46" class="drive-compass__ring"/>
<g transform="rotate(${-(deg ?? 0)})">
<path d="M0 -40 L6 0 L0 -6 L-6 0 Z" class="drive-compass__north"/>
<path d="M0 40 L6 0 L0 6 L-6 0 Z" class="drive-compass__south"/>
<text y="-22" transform="rotate(${deg ?? 0} 0 -27)" class="drive-compass__n">N</text>
</g>
<path d="M0 -50 l-5 0 l5 10 l5 -10 z" class="drive-compass__lubber"/>
</svg>
<span class="drive-cell__text"><span class="drive-cell__label">Heading</span><span class="drive-cell__value drive-cell__value--mid">${deg == null ? "—" : String(deg).padStart(3, "0") + "°"} <small>${deg == null ? "" : CARDINALS[Math.round(deg / 45) % 8]}</small></span></span>`;
};
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 = `<span class="drive-cell__label">${FIELDS[cell.value] || cell.value}</span><span class="drive-cell__value ${cls}">${escapeHtml(value)} <small>${escapeHtml(unit)}</small></span>`;
} else if (cell.widget === "maneuver") renderManeuver(el);
else if (cell.widget === "status") {
el.innerHTML = `<b class="drive-status__brand">MAPTOOL</b><span class="drive-cell__muted"><span class="${navigator.onLine ? "drive-status--ok" : ""}">●</span> ${navigator.onLine ? "online" : "offline"}${log?.active ? ` · <span class="drive-status--rec">● rec</span>` : ""}</span>`;
} 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");
+20
View File
@@ -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
+1 -1
View File
@@ -505,7 +505,7 @@ if (isLoggedIn()) new PluginsControl(map).mount(sidebar);
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label"></div>`);
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", `<div class="sidebar-group-label"></div>`);