diff --git a/TODO.adoc b/TODO.adoc index 2366746..7734d38 100644 --- a/TODO.adoc +++ b/TODO.adoc @@ -10,17 +10,19 @@ independence from connectivity. * [x] Offline vector tiles (PMTiles/MBTiles) for Europe/world via Planetiler or MapTiler — Geofabrik per-country extracts, `osmium merge`, Planetiler's default OpenMapTiles profile straight to PMTiles (`lib/maptool/pmtiles_builder.rb`); offline now shares the exact same style/palette as online (`ONLINE_STYLE_PATCH`) instead of a separate protomaps-schema theme * [x] Shaded relief / DEM layer — hillshade toggle in the sidebar, sourced from public Terrarium tiles online; reads `data/terrain.pmtiles` for offline if one's been generated (see docs/development.adoc), otherwise the toggle is online-only for now -** [ ] Terrain slope readout for parking (numeric, not just visual shading) * [ ] Contour lines from OSM for hikes and mountain passes * [x] Hiking trail overlay — Waymarked Trails raster tiles online (`public/js/hiking_trails.js`), colored per-route by the OSM `colour` tag they already render (the KST/KČT paint-blaze colors in Slovakia/Czechia, plain red elsewhere). Click queries a one-off Overpass `around` search (racing 3 public mirrors) for the route's name/colour/network/operator/distance ** [x] Offline copy wired in for real, no custom Planetiler profile needed — `Maptool::HikingTrails` (`lib/maptool/hiking_trails.rb`) runs `osmium tags-filter r/route=hiking` + `add-locations-to-ways` + `cat -f opl` against the *same* per-country Geofabrik `.osm.pbf` already downloaded for `offline.pmtiles`, no new download. One `data/hiking_trails/.geojson` per country (not one combined file), generated as the last step of every offline build and cached like `geofabrik_cache` (skipped once already newer than its source PBF) — a many-country selection no longer means one giant file, since `GET /api/hiking-trails` lists available countries and the Overlays panel's own checklist only fetches `GET /tiles/hiking_trails/.geojson` for whichever ones get ticked. Offline click uses a local `queryRenderedFeatures` hit-test instead of Overpass — instant, no network. See docs/development.adoc * [x] Overpass/OSM scripts to extract POIs (drinking water, dump stations, LPG, public toilets, laundromats, shops, springs) — `rake overpass:pois`, see docs/development.adoc; writes a `.geojson` to drop in `data/gpx/` or upload. Also runnable from inside the app itself now, see the import plugins entry below (`plugins/overpass-pois` wraps this same query). Each category now carries a real `POI_ICONS` glyph and color (not p4n2gpx's plain red marker) plus a popup description built from opening_hours/operator/website tags * [x] Import plugins: a pluggable way to add more data sources (Park4Night, iOverlander, Freecampsites, ...) without their scrapers necessarily living in this (public) repo — sidebar icon (logged in only) lists whatever's under `plugins/`, "Run for this area" uses the current map viewport as the bbox, no separate area-picker needed. Contract: a `plugin.json` manifest + a script that reads `--south`/`--west`/`--north`/`--east` and prints a GeoJSON `FeatureCollection` to stdout (`lib/maptool/plugins.rb`, `GET /api/plugins`, `POST /api/plugins/:name/run`) — output saved the same way an upload would be. `plugins/overpass-pois` ships as the reference example; a private/ToS-sensitive scraper just drops its own directory in locally and is never `git add`ed ** [x] Park4Night — private plugin (`data/plugins/p4n2gpx/`, outside this repo per the "ToS-sensitive scraper" note above); iOverlander/Freecampsites still open, same story -** [ ] Along the planned route (2026-12-01): Park4Night and overpass-pois fetch the whole - viewport/bbox today — a second mode for a corridor around the route (a few km either side): - the plugin contract gains the route (a polyline / buffered boxes, not one big bbox), the - results into the trip's folder +** [x] Along the planned route (2026-12-01): "Along the trip's route" ± 1/2/5/10/20 km in the + plugins panel; a plugin with `"route": true` gets `--route= --corridor-km=N` + (overpass-pois: Overpass' `around:` over the thinned route; p4n2gpx: circles along it, + `lib/maptool/corridor.rb`), points further off dropped by maptool, into the recorded trip's + folder when one runs. Plugin settings (`"settings"` in plugin.json: a login cookie) set in the + panel, kept in `data/plugin_settings.json`, given to the command as env vars — p4n2gpx's + `P4N_SESSION_COOKIE` (park4night's login is behind reCAPTCHA: a browser's Cookie header) ** [x] A private plugin's own dependencies now have somewhere to live too: `data/plugins/` is under the persistent `data/` bind mount (survives a redeploy, unlike `build/`), and `docs/deployment.adoc` documents the convention * [x] Kiwix/ZIM offline Wikipedia linked to POI GPS coordinates — proxied through this app (`GET /kiwix/*` in app.rb) rather than a direct link to kiwix-serve — production sits behind a reverse proxy that only forwards to this app, so no address exists for a browser to reach kiwix-serve at directly; kiwix-serve runs with `--urlRootLocation=/kiwix` so its own emitted links already match. `KIWIX_URL` + `GET /api/kiwix` reachability check, same optional-integration pattern as offline.pmtiles/terrain.pmtiles; `docker-compose.yaml` now runs a `kiwix` service, ZIM not included (see docs/development.adoc for where to get one) ** [x] Replaced the old per-popup "Nearby on Wikipedia" link (one POI at a time, easy to miss) with a standalone "Wikipedia" layer under Tracks & Points — a live `GET /api/kiwix/nearby` refetch on every pan/zoom, not a saved file. kiwix-serve's own geo search never echoes back a result's coordinates, so `Maptool::Kiwix.nearby` fetches each matching article's own page too and reads its `` tag — verified against the real production ZIM (~1.6s for a 30-result page; tried parallelizing those fetches with threads, no measured gain, kept sequential) @@ -154,6 +156,14 @@ plan from — the server does the heavy lifting. The UI is built for a mouse tod append-only journal per trip (`data/trip_log/.ndjson`, fsynced every 5 s, a torn last line skipped), a restart picks the running trip up from it; the library's track built from it every 5 min and at the end. Still to do: the pictogram, a walk from another device shown with it, visited points +** [x] The recording's days and export (the canvas' GridRecording, 2026-12-03): the Trip menu's + "Recording ▸" opens it — the running trip, else the last one: totals, the days (one log, the + days only cuts: stood ≥ 4 h, else 03:00; ✂ Cut here and Join kept as journal lines), ⌕ a day + on the map; Export the days ticked, a piece between draggable A–B markers or the whole trip as + one GPX (a track per day, times per point) or a .zip of a file per day, with the stops near + the line, the planned route, the stands (`lib/maptool/trip_days.rb`, + `/api/trip/log/days`, `/api/trip/log/export`). Not yet: renaming the trip there, the days + named by place (no reverse geocoding offline), moving a cut by hand ** [x] Colors: planned vs really driven — the planned route (magenta ahead, the part behind thin and dashed) and the recorded track solid on top (`--route-driven`), docs/design.adoc ** [x] The menu while driving: showing routes and points, editing the trip — all of it on the @@ -302,7 +312,7 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho * [x] A "follow" mode like a car navigation: camera locked to the GNSS position, rotated to the heading, pitched ~60°, smooth easing — the tracker's "Navigate" (see the Tablet-friendly section); follows the MQTT tracker, not the browser's own GNSS control yet -** [ ] Real 3D relief from the raster-dem terrain and Liberty's `building-3d` extrusions while navigating +** [x] Real 3D relief from the raster-dem terrain and Liberty's `building-3d` extrusions while navigating (the 3D mode has both) * [ ] Full navigation (the car's main screen while driving; everything from our own Valhalla tiles, no online service — Valhalla has OSM `maxspeed`, `traffic_signals` and turn lanes) ** [x] Basics on the dashboard (`public/js/dashboard.js`): the speed limit as a sign and a red @@ -324,7 +334,7 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho route = over 30 m from its line for 3 fixes in a row (fixes with HDOP > 5 don't count), then the route panel routes from the position to the points not reached yet (via points passed by km along the route, `legs_km`), at most every 15 s and only moving -*** [ ] Step advance like Ferrostar's DistanceEntryExit (30 m to the step's end, 5 m past it) +*** [x] Step advance like Ferrostar's DistanceEntryExit (30 m to the step's end, 5 m past it) instead of "the first maneuver ahead by km"; arrival at 30 m. Done: progress only forward — the position looked for near the last one first (`locate`, 0.1 km back to 3 km ahead), so a route along the same road twice or crossing itself doesn't jump; the step still advances 5 m @@ -354,7 +364,7 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho browser's GNSS control), the dashboard as part of the driving-mode UI. Done: drive mode's Follow follows the CAN GNSS; the LTE tracker (MQTT) is a tracker layer to switch on (a second car, the car seen from home), Meshtastic the same with the nodes picked -*** [ ] Any point of a tracker layer can be the one the map follows — one at a time (picking +*** [x] Any point of a tracker layer can be the one the map follows — one at a time (picking another one, or the car's own GNSS, takes it over); today only the MQTT tracker's card has "Navigate" ** [x] `locate()` scans the whole route each fix — a window around the last hit on long routes ** [ ] Shared trip — one itinerary per server for every screen (the cab's display, the tablet @@ -375,6 +385,16 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho (the day ends), stay and note; day headers with km and time; another screen's change shown where it happened with Undo. Not yet: the route coloured by day, each stop's source, the drive mode's Trip menu by days +*** Planning (the canvas' Plan and GridToday, ideas from azedler/roadplanner), in this order: +**** [x] A stop's type (its NPS pictogram on the marker and in the list), notes on the trip, + the days (on a day's first point) and the stops; + on a leg inserts the next point there +**** [x] The place and where the car stays apart: Parking in a stop's ✎, a P marker (drag it), the route goes there, the walk ×1.25 straight +**** [x] A pasted link (Google Maps, park4night, a page with coordinates) becomes a place in the search (/api/link, logged in); + puts it on the leg it lengthens least +**** [x] Avoids for the trip (+ ferries, unpaved) or a day (the day's ✎; routed in pieces, joined). Soft preferences (camps ≤ 40 €, lakes) not yet: for the Check / search when wanted +**** [x] Check (a fold in the Route panel): no leave time, a day over 8 h driving, a night spot after sunset, a long walk from the parking, motorways without the vignette; each with ⌖. Not yet: a day's avoids vs its route, winter-closed roads, opening hours +**** [x] Costs (a fold): fuel = km × the profile's consumption × the trip's fuel price, each stop's costs / paid, the budget left. Not yet: documents / receipts per stop, prices per country +**** [x] Today in drive mode (Menu ▸ Today): the stops left with arrival, tonight, sunset, Open-Meteo weather, the day's notes and Check items, Skip next, Tomorrow ▸. Not yet: Late +30 min +**** [ ] MCP over maptool (later) *** [ ] Brick ↔ the car: a trip planned at home on brick handed to the car's server (with the library sync, or "send to the car") *** [ ] Push instead of polling (SSE) if 2 s ever feels slow @@ -397,7 +417,8 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho trips over our Valhalla (2–8 km each, one after another) at 90 % of the road's limit, a fix a second into the same `gnss.*` signals / GNSS_LATEST as the node's (ignored meanwhile) *** [x] The dashboard's tilt from the terrain's slope while simulating -*** [ ] Replay a library track (GPX/FIT with times) instead, at its own speed +*** [x] Replay a library track (GPX/FIT with times) instead, at its own speed (`/sim.html`, + `GnssSim#replay`; stops longer than 30 s shortened to it) ** [x] Free look while following: moving the map by hand pauses the follow, "Back to the position" or 15 s untouched resumes it * [x] While following a planned route: the route ahead highlighted, distance to the next @@ -458,7 +479,12 @@ are in home-gitops `docs/canopen-nodes.adoc` ("Inšpirácia: Garmin Tread / zūm as a live layer with trails, short messages, "come here" into the trip * [ ] Audio: volume / mute from the keypad and the app, navigation prompts ducking the music -* [ ] Level gauge from IMU (ESP32/RPi) — camper tilt, wheel-chock leveling calculation +* [x] Level gauge from IMU (ESP32/RPi) — camper tilt, wheel-chock leveling calculation (the canvas' + GridLevel, 2026-12-03): Terrain → "Level ▸" (in place of Road view; ✕ closes it the same): the + car from above with the cm under each wheel (lifted to the highest, never dug in), rounded to + the profile's ramp steps or exact for jacks, the bubble, roll / pitch now and after; the + profile's new wheelbase, track and ramps fields (guessed from length / width when unset). + Not yet: a pitch target (the bed's head up), only the two low wheels on ramps * [ ] Victron/Home Assistant via MQTT or WebSocket — battery SoC, tank levels, temperatures * [ ] Plot GPS track with historical battery/speed data diff --git a/app.rb b/app.rb index 9a20de2..4dbcc33 100644 --- a/app.rb +++ b/app.rb @@ -4,6 +4,7 @@ require "oauth2" require "securerandom" require "zip" require "stringio" +require "tempfile" require_relative "lib/maptool/gpx" require_relative "lib/maptool/fit" require_relative "lib/maptool/gpx_store" @@ -17,6 +18,8 @@ require_relative "lib/maptool/can_recorder" require_relative "lib/maptool/gnss_sim" require_relative "lib/maptool/trip" require_relative "lib/maptool/trip_log" +require_relative "lib/maptool/trip_days" +require_relative "lib/maptool/link_place" require_relative "lib/maptool/updater" require_relative "lib/maptool/sync" require "ipaddr" @@ -25,6 +28,7 @@ require_relative "lib/maptool/livetrack_store" require_relative "lib/maptool/livetrack_client" require_relative "lib/maptool/kiwix" require_relative "lib/maptool/plugins" +require_relative "lib/maptool/corridor" require_relative "lib/maptool/pmtiles_builder" require_relative "lib/maptool/search" @@ -172,6 +176,7 @@ module Maptool # above can't. Checked after PLUGINS_DIR (see Plugins.list/run), so a # same-named private plugin never shadows the built-in one. PLUGINS_DIRS = [PLUGINS_DIR, File.join(DATA_DIR, "plugins")].freeze + PLUGIN_SETTINGS = File.join(DATA_DIR, "plugin_settings.json") # Shared secret for the Garmin LiveTrack webhook (a Google Apps Script # watching Gmail for LiveTrack emails, see docs/deployment.adoc) — not a @@ -812,6 +817,87 @@ module Maptool json folder: TRIP_LOG.stop end + # The recording's days (lib/maptool/trip_days.rb) — the running trip's, or + # the last one's: totals, the days with what cut them, and (?track=1) the + # line as [lon, lat, t] for picking a piece on the map. + get "/api/trip/log/days" do + require_login! + rec = TRIP_LOG.recording + halt 404, json(error: "no trip recorded") unless rec && rec[:points].size >= 2 + + points = rec[:points] + days = TripDays.days(points, TripDays.cuts(points, hand: rec[:hand], joined: rec[:joined])) + body = { folder: rec[:folder], active: rec[:active], started_at: rec[:started_at], + totals: TripDays.stats(points).merge(days: days.size, started_at: points.first[3], ended_at: points.last[3]), + days: days.map { |d| d.merge(bbox: TripDays.bbox(points[d[:from]...d[:to]])) } } + body[:track] = points.map { |lon, lat, _, t| [lon.round(6), lat.round(6), t] } if params[:track] + json body + end + + # {"cut": t} or {"join": t} (epoch s; a cut with none: now). + post "/api/trip/log/days" do + require_login! + body = JSON.parse(request.body.read) + kind = body.key?("join") ? :join : :cut + TRIP_LOG.mark(kind, Float(body[kind.to_s] || Time.now.to_f)) + json ok: true + rescue JSON::ParserError, TypeError + halt 400, json(error: "invalid JSON") + rescue ArgumentError => e + halt 422, json(error: e.message) + end + + # The recording as GPX: ?days=1,2 (those days), ?from=t&to=t (a piece), + # neither: the whole trip — a track per day (?per_day=1: a .gpx per day in + # a .zip), with ?stops=1 the trip's stops near the line, ?plan=1 the + # planned route, ?pauses=1 the stands as waypoints. + get "/api/trip/log/export" do + require_login! + rec = TRIP_LOG.recording + halt 404, json(error: "no trip recorded") unless rec && rec[:points].size >= 2 + + points = rec[:points] + days = TripDays.days(points, TripDays.cuts(points, hand: rec[:hand], joined: rec[:joined])) + name = rec[:folder].to_s.delete_prefix("Trips/") + label = ->(d) { "#{name} · Day #{d[:index]} · #{Time.at(d[:started_at]).strftime('%Y-%m-%d')}" } + pieces = if params[:from] && params[:to] + from, to = [params[:from], params[:to]].map(&:to_f).sort + piece = points.select { |p| p[3].between?(from, to) } + [["#{name} · #{Time.at(from).strftime('%d. %m. %H:%M')} – #{Time.at(to).strftime('%H:%M')}", piece]] + else + picked = params[:days].to_s.split(",").map(&:to_i) + days.select { |d| picked.empty? || picked.include?(d[:index]) }.map { |d| [label.(d), points[d[:from]...d[:to]]] } + end + pieces = pieces.reject { |_, piece| piece.size < 2 } + halt 422, json(error: "nothing to export") if pieces.empty? + + folder = rec[:folder] ? (LIBRARY.folder_features(rec[:folder]) rescue []) : [] + extras = lambda do |piece| + line = piece.map { |p| p.first(2) } + out = [] + out += folder.select { |f| f.dig("properties", "kind") == "route" } if params[:plan] + if params[:stops] + out += folder.select { |f| f.dig("geometry", "type") == "Point" && Corridor.distance_km(f["geometry"]["coordinates"], line) <= 0.3 } + end + out += TripDays.pauses(piece) if params[:pauses] + out + end + if params[:per_day] && pieces.size > 1 + content_type "application/zip" + attachment "#{name}.zip" + Zip::OutputStream.write_buffer do |zip| + pieces.each do |title, piece| + zip.put_next_entry("#{title.tr('/', '-')}.gpx") + zip.write(TripDays.gpx([[title, piece]], extras.(piece))) + end + end.string + else + content_type "application/gpx+xml" + attachment "#{pieces.size == 1 ? pieces.first.first.tr('/', '-') : name}.gpx" + TripDays.gpx(pieces, extras.(pieces.flat_map(&:last))) + end + end + get "/api/trip" do require_login! trip = TRIP_STORE.get @@ -826,7 +912,8 @@ module Maptool halt 400, json(error: "points must be a list of {lngLat: [lon, lat]}") unless body[:points].is_a?(Array) && body[:points].all? { |p| p.is_a?(Hash) && p[:lngLat].is_a?(Array) } json(TRIP_STORE.update(points: body[:points], vehicle: body[:vehicle], avoid: body[:avoid], editing: body[:editing], - name: body[:name], start: body[:start], day_start: body[:day_start]) do |locations, vehicle, avoid| + name: body[:name], start: body[:start], day_start: body[:day_start], note: body[:note], + budget: body[:budget], fuel_price: body[:fuel_price]) do |locations, vehicle, avoid| Routing.route(VALHALLA_URL, locations, Routing.vehicle(DATA_DIR, vehicle), avoid.transform_keys(&:to_s)) end) rescue JSON::ParserError @@ -927,6 +1014,17 @@ module Maptool center: center, kiwix_url: KIWIX_URL) end + # A link pasted into the search → a place (lib/maptool/link_place.rb). + # The server fetches the page, so only for a logged-in user. + get "/api/link" do + require_login! + place = LinkPlace.resolve(params[:url].to_s) + halt 404, json(error: "no coordinates in that link or its page") unless place + json place + rescue LinkPlace::Error => e + halt 422, json(error: e.message) + end + # Pinged once per page load (public/js/map.js) — url is a same-origin # path (not kiwix-serve's own address, which the browser can't reach # directly behind the reverse proxy in front of this app), proxied by @@ -1262,32 +1360,65 @@ module Maptool # for the contract) — read-only, doesn't need require_login! the way # actually running one does below. get "/api/plugins" do - json Plugins.list(PLUGINS_DIRS) + saved = Plugins.saved_settings(PLUGIN_SETTINGS) + json(Plugins.list(PLUGINS_DIRS).map { |p| p.merge("set" => (saved[p["name"]] || {}).keys) }) + end + + # A plugin's settings (its plugin.json "settings": a login cookie, a key): + # {KEY: value}, an empty value clears it. Kept in data/, never sent back. + put "/api/plugins/:name/settings" do + require_login! + json set: Plugins.save_settings(PLUGIN_SETTINGS, PLUGINS_DIRS, params[:name], JSON.parse(request.body.read)) + rescue Plugins::RunError => e + halt 404, json(error: e.message) + rescue JSON::ParserError + halt 400, json(error: "invalid JSON") end # Runs one plugin for the given bbox (the current map viewport, from # the frontend's "Run for this area" button) and imports its GeoJSON # output into a folder of its own, named after the area's center and # the run's time — so one run's POIs stay apart from another's. + # + # route=1&corridor_km=N instead: along the shared trip's route, N km + # either side (a plugin with "route": true covers just that; the points + # further off are dropped either way), into the recorded trip's folder + # when one is running. post "/api/plugins/:name/run" do require_login! - bbox = %w[south west north east].map { |key| params[key].to_s } - halt 400, json(error: "south, west, north, east are required") if bbox.any?(&:empty?) + timestamp = Time.now.strftime("%y%m%d_%H%M") + env = Plugins.saved_settings(PLUGIN_SETTINGS)[params[:name]] || {} + if params[:route] + coords = TRIP_STORE.get[:route]&.dig(:geometry, :coordinates) + halt 422, json(error: "the trip has no route") unless coords && coords.size >= 2 + corridor = params[:corridor_km].to_f + halt 400, json(error: "corridor_km must be 0.5 to 50") unless (0.5..50).cover?(corridor) - south, west, north, east = bbox.map(&:to_f) - begin - geojson = Plugins.run(PLUGINS_DIRS, params[:name], [south, west, north, east]) - rescue Plugins::RunError => e - halt 502, json(error: e.message) + geojson = Tempfile.create(["route", ".geojson"]) do |file| + file.write(JSON.generate(type: "LineString", coordinates: coords)) + file.flush + Plugins.run(PLUGINS_DIRS, params[:name], Corridor.bbox(coords, corridor), route: file.path, corridor_km: corridor, env: env) + end + geojson["features"] = geojson["features"].select do |f| + f.dig("geometry", "type") != "Point" || Corridor.distance_km(f["geometry"]["coordinates"], coords) <= corridor + end + name = "#{params[:name]} along the route #{format('%g', corridor)} km #{timestamp}" + folder = TRIP_LOG.status[:folder] || name + else + bbox = %w[south west north east].map { |key| params[key].to_s } + halt 400, json(error: "south, west, north, east are required") if bbox.any?(&:empty?) + + south, west, north, east = bbox.map(&:to_f) + geojson = Plugins.run(PLUGINS_DIRS, params[:name], [south, west, north, east], env: env) + center_lat = format("%.2f", (south + north) / 2) + center_lon = format("%.2f", (west + east) / 2) + folder = name = "#{params[:name]}_#{center_lat}_#{center_lon}_#{timestamp}" end - center_lat = format("%.2f", (south + north) / 2) - center_lon = format("%.2f", (west + east) / 2) - timestamp = Time.now.strftime("%y%m%d_%H%M") - name = "#{params[:name]}_#{center_lat}_#{center_lon}_#{timestamp}" - - keys = LIBRARY.import(folder: name, filename: "#{name}.geojson", io: StringIO.new(JSON.generate(geojson))) - json path: keys.first, tree: LIBRARY.tree + keys = LIBRARY.import(folder: folder, filename: "#{name}.geojson", io: StringIO.new(JSON.generate(geojson))) + json path: keys.first, tree: LIBRARY.tree, count: geojson["features"].size + rescue Plugins::RunError => e + halt 502, json(error: e.message) end # Called by the Apps Script watching Gmail for Garmin LiveTrack emails — @@ -1487,7 +1618,17 @@ module Maptool # {"trip": true}: along the shared trip's route (to try the navigation) route = TRIP_STORE.get[:route] if body["trip"] halt 422, json(error: "the trip has no route") if body["trip"] && !route - if route then nil + # {"track": "item:"}: a library track replayed at its own speed + if body["track"] + begin + line = JSON.parse(LIBRARY.geojson(body["track"].to_s))["features"].find { |f| f.dig("geometry", "type") == "LineString" } + rescue Library::NotFound + halt 404, json(error: "no such track") + end + track = line&.dig("properties", "profile")&.filter_map { |p| [p["lon"], p["lat"], p["elapsed_secs"]] if p["elapsed_secs"] } + halt 422, json(error: "the track has no times") if track.nil? || track.size < 2 + end + if route || track then nil elsif lon.nil? codes = (PmtilesBuilder.offline_meta(DATA_DIR) || {}).fetch("sources", []).map { |source| source["code"] } bboxes = codes.filter_map { |code| PmtilesBuilder.country_bbox(code) } @@ -1497,7 +1638,7 @@ module Maptool end CAN_STORE.override_prefix = "gnss." - GNSS_SIM.start(lon, lat, bboxes: bboxes, route: route) do |fix| + GNSS_SIM.start(lon, lat, bboxes: bboxes, route: route, track: track) do |fix| CAN_STORE.put(fix.except(:time).transform_keys { |key| "gnss.#{key}" }) App.gnss_update(fix) end diff --git a/docker-compose.yaml b/docker-compose.yaml index f24fc03..a8ae8fc 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -43,9 +43,9 @@ services: # as the other optional secrets here. P4N_USER/P4N_PASSWORD alone # don't actually work here — park4night's login form is behind # invisible reCAPTCHA, which no browserless login can satisfy — so - # P4N_SESSION_COOKIE (a real logged-in browser's session cookie, - # copied out by hand and refreshed whenever it expires) is what - # p4n2gpx.rb's make_session actually ends up using. + # the cookies of a Firefox logged in on the host (the plugin's own + # firefox_cookie.py on a host timer, docs/deployment.adoc) or P4N_SESSION_COOKIE (a browser's Cookie header, by hand — + # also settable in the plugins panel) are what it ends up using. P4N_USER: ${P4N_USER:-} P4N_PASSWORD: ${P4N_PASSWORD:-} P4N_SESSION_COOKIE: ${P4N_SESSION_COOKIE:-} diff --git a/docs/deployment.adoc b/docs/deployment.adoc index 5ce4a72..dfd6cd1 100644 --- a/docs/deployment.adoc +++ b/docs/deployment.adoc @@ -193,6 +193,37 @@ Its `.env` adds: * `SYNC_SERVER_URL` (`https://map.priesol.net`) and `SYNC_TOKEN`: it's a sync client. * `SELF_UPDATE=1` — the update button (below). +=== park4night's login from the Pi's Firefox + +The private p4n2gpx plugin (`data/plugins/p4n2gpx/`) borrows a logged-in +browser's cookies (park4night's login is behind reCAPTCHA). Log in once in +Firefox on the Pi as `randy` ("remember me" ticked; on its screen or over +remote desktop). A timer on the host runs the plugin's `firefox_cookie.py` +as that user: it copies only park4night.com's cookies into +`data/plugins/p4n2gpx/firefox-cookie` (mode 600). The profile itself (every +synced password, every site's cookies) is never mounted into the container. + +---- +# /etc/systemd/system/p4n-cookie.service +[Unit] +Description=park4night cookies from Firefox for maptool's p4n2gpx plugin +[Service] +Type=oneshot +User=randy +ExecStart=/usr/bin/python3 -I /srv/podman/maptool/data/plugins/p4n2gpx/firefox_cookie.py + +# /etc/systemd/system/p4n-cookie.timer +[Unit] +Description=park4night cookies from Firefox every 15 min +[Timer] +OnBootSec=2min +OnUnitActiveSec=15min +[Install] +WantedBy=timers.target +---- + +`systemctl daemon-reload && systemctl enable --now p4n-cookie.timer`. + === Updates (a button, not CI) CI deploys brick only: the car's server is often offline, and a deploy diff --git a/lib/maptool/corridor.rb b/lib/maptool/corridor.rb new file mode 100644 index 0000000..4d5554f --- /dev/null +++ b/lib/maptool/corridor.rb @@ -0,0 +1,66 @@ +module Maptool + # A corridor either side of a route ([[lon, lat], ...]): what a plugin run + # along the trip's route covers (lib/maptool/plugins.rb). Flat-earth + # distances (equirectangular per segment) — fine for a few km either side. + module Corridor + KM_PER_DEG = 111.32 + + def self.km(a, b) + Math.hypot((b[0] - a[0]) * Math.cos((a[1] + b[1]) / 2 * Math::PI / 180), b[1] - a[1]) * KM_PER_DEG + end + + # The route's vertices at least step_km apart (its ends kept): a short + # enough line for a query (Overpass' around: takes a polyline). + def self.thin(coords, step_km) + kept = [coords.first] + coords.each { |c| kept << c if km(kept.last, c) >= step_km } + kept << coords.last unless kept.last == coords.last + kept + end + + # Circles ([[lon, lat], radius km]) covering the corridor half_km either + # side: centers every 1.5 × half_km along the line, radius 1.25 × half_km + # (√(0.75² + 1²) = 1.25, so no gap between two of them at the corridor's edge). + def self.circles(coords, half_km) + step = 1.5 * half_km + centers = [coords.first] + left = step + coords.each_cons(2) do |a, b| + length = km(a, b) + at = 0.0 + while length - at >= left + at += left + t = at / length + centers << [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t] + left = step + end + left -= length - at + end + centers << coords.last unless centers.last == coords.last + centers.map { |c| [c, 1.25 * half_km] } + end + + # Shortest distance (km) from a point to the line. + def self.distance_km(point, coords) + lat0 = point[1] * Math::PI / 180 + xy = ->(c) { [(c[0] - point[0]) * Math.cos(lat0) * KM_PER_DEG, (c[1] - point[1]) * KM_PER_DEG] } + return Math.hypot(*xy.(coords.first)) if coords.size == 1 + + coords.each_cons(2).map do |a, b| + (ax, ay), (bx, by) = xy.(a), xy.(b) + dx, dy = bx - ax, by - ay + len2 = dx * dx + dy * dy + t = len2.zero? ? 0.0 : (-(ax * dx + ay * dy) / len2).clamp(0.0, 1.0) + Math.hypot(ax + t * dx, ay + t * dy) + end.min + end + + # [south, west, north, east] around the line, half_km wider each way. + def self.bbox(coords, half_km) + lons, lats = coords.map(&:first), coords.map { |c| c[1] } + dlat = half_km / KM_PER_DEG + dlon = half_km / (KM_PER_DEG * Math.cos(lats.map(&:abs).max * Math::PI / 180)) + [lats.min - dlat, lons.min - dlon, lats.max + dlat, lons.max + dlon] + end + end +end diff --git a/lib/maptool/gnss_sim.rb b/lib/maptool/gnss_sim.rb index ffab080..8dee7f9 100644 --- a/lib/maptool/gnss_sim.rb +++ b/lib/maptool/gnss_sim.rb @@ -54,12 +54,16 @@ module Maptool # Feature), that route from its start first, random trips after it; # each fix to the block: # { lat:, lon:, speed: m/s, satellites:, hdop:, mode: 3, time: the simulation's epoch s }. - def start(lon = nil, lat = nil, bboxes: nil, route: nil, &on_fix) + # With track ([[lon, lat, elapsed s], ...], a library track's) instead: + # that track replayed at its own speed, then it stops. + def start(lon = nil, lat = nil, bboxes: nil, route: nil, track: nil, &on_fix) stop @error = nil @clock = Time.now.to_f @mutex.synchronize do @thread = Thread.new do + next replay(track, &on_fix) if track + position, route = if route then [route[:geometry][:coordinates].first, with_detours(route)] elsif bboxes then random_start(bboxes) else [[Float(lon), Float(lat)], nil] @@ -120,6 +124,34 @@ module Maptool coords.last end + MAX_GAP_S = 30 # a stop longer than this in a replayed track: cut to it + + # A recorded track driven again at its own pace (sped up like the + # rest): points [lon, lat, elapsed s]; long stops shortened to MAX_GAP_S. + def replay(points, &on_fix) + shift = 0.0 + points = points.each_cons(2).each_with_object([[*points.first.first(2), 0.0]]) do |(a, b), out| + shift += [b[2] - a[2] - MAX_GAP_S, 0].max + out << [b[0], b[1], b[2] - points.first[2] - shift] + end + t = 0.0 + i = 1 + while i < points.size + t += TICK_S * @speedup + @clock += TICK_S * @speedup + i += 1 while i < points.size - 1 && points[i][2] < t + a, b = points[i - 1], points[i] + dt = b[2] - a[2] + f = dt.positive? ? ((t - a[2]) / dt).clamp(0.0, 1.0) : 1.0 + lon, lat = a.first(2).zip(b.first(2)).map { |p, q| p + (q - p) * f } + speed = dt.positive? ? self.class.meters(a, b) / dt : 0.0 + on_fix&.call(lat: lat, lon: lon, speed: speed, satellites: 12, hdop: 0.8, mode: 3, time: @clock.round(1)) + break if i == points.size - 1 && f >= 1 + + @sleep.call(TICK_S) + end + end + def speed_kmh(limit) (limit == "unlimited" ? UNLIMITED_KMH : limit || NO_LIMIT_KMH) * LIMIT_SHARE end diff --git a/lib/maptool/gpx.rb b/lib/maptool/gpx.rb index 97cb041..484f446 100644 --- a/lib/maptool/gpx.rb +++ b/lib/maptool/gpx.rb @@ -117,9 +117,14 @@ module Maptool if route segments.flatten(1).each { |c| add_text(element.add_element("rtept", position_attributes(c)), "ele", c[2]) } else + times = props["times"] if segments.size == 1 # a LineString's: an ISO time per point segments.each do |segment| trkseg = element.add_element("trkseg") - segment.each { |c| add_text(trkseg.add_element("trkpt", position_attributes(c)), "ele", c[2]) } + segment.each_with_index do |c, i| + trkpt = trkseg.add_element("trkpt", position_attributes(c)) + add_text(trkpt, "ele", c[2]) + add_text(trkpt, "time", times&.[](i)) + end end end end diff --git a/lib/maptool/library.rb b/lib/maptool/library.rb index f18a5eb..e377ac9 100644 --- a/lib/maptool/library.rb +++ b/lib/maptool/library.rb @@ -539,6 +539,11 @@ module Maptool # A folder's own items (not its subfolders') as one GPX with points and # tracks together — what Locus imports into one folder. + # A folder's own features (not its subfolders'). + def folder_features(path) + export_entries(path).map { |e| e[:feature] } + end + def export_gpx(path) Gpx.from_features(export_entries(path).map { |e| e[:feature] }) end diff --git a/lib/maptool/link_place.rb b/lib/maptool/link_place.rb new file mode 100644 index 0000000..24f53d9 --- /dev/null +++ b/lib/maptool/link_place.rb @@ -0,0 +1,107 @@ +require "net/http" +require "uri" +require "ipaddr" +require "resolv" +require "cgi" + +module Maptool + # A link pasted into the search (the Design canvas' Plan) → a place: + # { name:, lat:, lng:, url: }, or nil. The coordinates come from the URL + # itself (Google Maps' @lat,lng / !3d!4d / ?q=, geo:), else from the page + # it leads to (redirects followed: maps.app.goo.gl): its geo meta tags, + # JSON-LD, or a map link in it — the way a chat app unfurls a link, one + # page the user pasted. Only public addresses are fetched (never this + # server's LAN). + module LinkPlace + MAX_BYTES = 2_000_000 + MAX_REDIRECTS = 5 + TIMEOUT_S = 10 + LAT_LNG = /(-?\d{1,2}\.\d+)\s*[,;]\s*(-?\d{1,3}\.\d+)/ + + class Error < StandardError; end + + def self.resolve(url) + place = from_url(url) + return place if place + + html, final = fetch(url) + from_url(final) || from_html(html)&.then { |p| p.merge(url: final) } + end + + # Coordinates in the link itself. + def self.from_url(url) + text = CGI.unescape(url.to_s) + lat, lng = text.match(/!3d(-?\d+\.\d+)!4d(-?\d+\.\d+)/)&.captures || + text.match(/[?&](?:q|query|ll|destination|daddr|center)=(?:loc:)?#{LAT_LNG}/)&.captures || + text.match(/@#{LAT_LNG}/)&.captures || + text.match(/\Ageo:#{LAT_LNG}/)&.captures || + text.match(%r{/place/#{LAT_LNG}})&.captures + return nil unless lat + + name = text[%r{/place/([^/@]+)/}, 1]&.tr("+", " ") + place(name, lat, lng, url) + end + + # Coordinates in the page: meta tags, JSON-LD, then a map link. + def self.from_html(html) + meta = ->(key) { html[/]+(?:property|name)=["']#{Regexp.escape(key)}["'][^>]*content=["']([^"']+)/i, 1] || html[/]+content=["']([^"']+)["'][^>]*(?:property|name)=["']#{Regexp.escape(key)}["']/i, 1] } + name = meta.("og:title") || html[%r{]*>([^<]+)}i, 1] + name = CGI.unescapeHTML(name.strip) if name + lat, lng = [meta.("place:location:latitude") || meta.("og:latitude"), meta.("place:location:longitude") || meta.("og:longitude")] + lat, lng = (meta.("geo.position") || meta.("ICBM"))&.match(LAT_LNG)&.captures unless lat && lng + lat, lng = html.match(/"latitude"\s*:\s*"?(-?\d+\.\d+)"?\s*,\s*"longitude"\s*:\s*"?(-?\d+\.\d+)/)&.captures unless lat && lng + lat, lng = html.scan(%r{https?://(?:www\.)?google\.[a-z.]+/maps[^"'\s<>]*}).lazy.filter_map { |u| from_url(CGI.unescapeHTML(u)) }.first&.values_at(:lat, :lng) unless lat && lng + lat && lng ? place(name, lat, lng, nil) : nil + end + + def self.place(name, lat, lng, url) + lat = Float(lat) + lng = Float(lng) + return nil unless lat.between?(-90, 90) && lng.between?(-180, 180) + + { name: name&.strip&.then { |n| n.empty? ? nil : n[0, 160] }, lat: lat, lng: lng, url: url }.compact + end + + # [body, final url]; raises Error. + def self.fetch(url, redirects = MAX_REDIRECTS) + uri = URI.parse(url) + raise Error, "only http(s) links" unless %w[http https].include?(uri.scheme) && uri.host + ip = public_ip(uri.host) + http = Net::HTTP.new(uri.host, uri.port) + http.ipaddr = ip # the address checked, not a second lookup + http.use_ssl = uri.scheme == "https" + http.open_timeout = http.read_timeout = TIMEOUT_S + request = Net::HTTP::Get.new(uri, "User-Agent" => "Mozilla/5.0 (maptool link preview)", "Accept" => "text/html") + http.request(request) do |response| + case response + when Net::HTTPRedirection + raise Error, "too many redirects" if redirects.zero? + + return fetch(URI.join(url, response["location"]).to_s, redirects - 1) + when Net::HTTPSuccess + body = +"" + response.read_body do |chunk| + body << chunk + break if body.bytesize > MAX_BYTES + end + return [body.force_encoding("UTF-8").scrub, url] + else + raise Error, "the page answered #{response.code}" + end + end + rescue URI::InvalidURIError, SocketError, Timeout::Error, SystemCallError, OpenSSL::SSL::SSLError, Net::HTTPBadResponse => e + raise Error, e.message + end + + def self.public_ip(host) + address = Resolv.getaddress(host) + ip = IPAddr.new(address) + raise Error, "not a public address" if ip.private? || ip.loopback? || ip.link_local? || address.start_with?("0.") || ip == IPAddr.new("::") || + IPAddr.new("100.64.0.0/10").include?(ip) # CGNAT: Tailscale + + address + rescue Resolv::ResolvError + raise Error, "unknown host #{host}" + end + end +end diff --git a/lib/maptool/overpass_pois.rb b/lib/maptool/overpass_pois.rb index 39e0dc4..f1ff16c 100644 --- a/lib/maptool/overpass_pois.rb +++ b/lib/maptool/overpass_pois.rb @@ -58,9 +58,10 @@ module Maptool ["operator", "Operator"], ].freeze - # bbox: [south, west, north, east] (Overpass's own axis order). - def self.fetch(bbox, timeout: 60) - query = build_query(bbox, timeout: timeout) + # bbox: [south, west, north, east] (Overpass's own axis order); or + # around: [radius m, [[lon, lat], ...]] — a corridor along a line. + def self.fetch(bbox, timeout: 60, around: nil) + query = build_query(bbox, timeout: timeout, around: around) errors = OVERPASS_APIS.map do |url| return post(URI(url), query, timeout) rescue FetchError, Net::OpenTimeout, Net::ReadTimeout, SystemCallError, SocketError, OpenSSL::SSL::SSLError, JSON::ParserError => e @@ -83,8 +84,13 @@ module Maptool JSON.parse(response.body) end - def self.build_query(bbox, timeout: 60) - bbox_str = bbox.join(",") + def self.build_query(bbox, timeout: 60, around: nil) + bbox_str = if around + radius, line = around + "around:#{radius.round},#{line.map { |lon, lat| "#{lat.round(5)},#{lon.round(5)}" }.join(',')}" + else + bbox.join(",") + end filters = CATEGORIES.keys.map do |tags| conditions = tags.map { |k, v| %(["#{k}"="#{v}"]) }.join "node#{conditions}(#{bbox_str});" diff --git a/lib/maptool/plugins.rb b/lib/maptool/plugins.rb index a67a294..6b4013c 100644 --- a/lib/maptool/plugins.rb +++ b/lib/maptool/plugins.rb @@ -1,5 +1,6 @@ require "json" require "open3" +require "fileutils" module Maptool # Runs an external "importer" script that turns a bbox into a GeoJSON @@ -33,26 +34,64 @@ module Maptool Dir.glob(File.join(dir, "*", "plugin.json")).filter_map do |manifest_path| name = File.basename(File.dirname(manifest_path)) manifest = JSON.parse(File.read(manifest_path)) - { "name" => name, "label" => manifest["label"] || name } + { "name" => name, "label" => manifest["label"] || name, "route" => manifest["route"] == true, + "settings" => setting_fields(manifest) } rescue JSON::ParserError nil end end.uniq { |plugin| plugin["name"] }.sort_by { |p| p["label"] } end - # bbox: [south, west, north, east]. Raises RunError with a short + # The settings a plugin asks for in its plugin.json ("settings": [{"key": + # "P4N_COOKIE", "label": "…", "help": "…"}]) — a login cookie, a key — + # set in the panel, kept server-side (never sent back to a browser) and + # handed to the plugin's command as environment variables. A key is an + # env var name; anything else in the list is ignored. + SETTING_KEY = /\A[A-Z][A-Z0-9_]*\z/ + + def self.setting_fields(manifest) + Array(manifest["settings"]).select { |f| f.is_a?(Hash) && f["key"].to_s =~ SETTING_KEY } + .map { |f| f.slice("key", "label", "help") } + end + + # Saved settings: { name => { KEY => value } } in one JSON file (mode 600). + def self.saved_settings(path) + File.file?(path) ? JSON.parse(File.read(path)) : {} + rescue JSON::ParserError + {} + end + + # Sets (or, empty, clears) the plugin's declared keys only. + def self.save_settings(path, dirs, name, values) + plugin_dir = find(dirs, name) + fields = setting_fields(JSON.parse(File.read(File.join(plugin_dir, "plugin.json")))).map { |f| f["key"] } + all = saved_settings(path) + mine = (all[name] || {}).merge(values.to_h.slice(*fields).transform_values { |v| v.to_s.strip }) + all[name] = mine.reject { |_, v| v.empty? } + FileUtils.mkdir_p(File.dirname(path)) + File.write("#{path}.part", JSON.generate(all), perm: 0o600) + File.rename("#{path}.part", path) + all[name].keys + end + + def self.find(dirs, name) + raise RunError, "unknown plugin" unless name =~ NAME_PATTERN + + Array(dirs).map { |dir| File.join(dir, name) }.find { |dir| File.file?(File.join(dir, "plugin.json")) } or raise RunError, "unknown plugin" + end + + # bbox: [south, west, north, east]. With route (a GeoJSON file's path, + # the trip's route) and corridor_km, a plugin with "route": true in its + # plugin.json also gets --route= --corridor-km= (the bbox is + # then the corridor's). env: its saved settings. Raises RunError with a short # message on anything that isn't a clean run — an unknown plugin, a # non-zero exit, or output that isn't a GeoJSON FeatureCollection — so # the route can turn it into a single error response without knowing # any of these details itself. When the same name exists under more # than one of `dirs`, the first one that has it wins — same precedence # as list's `uniq` above. - def self.run(dirs, name, bbox) - raise RunError, "unknown plugin" unless name =~ NAME_PATTERN - - plugin_dir = Array(dirs).map { |dir| File.join(dir, name) }.find { |dir| File.file?(File.join(dir, "plugin.json")) } - raise RunError, "unknown plugin" unless plugin_dir - + def self.run(dirs, name, bbox, route: nil, corridor_km: nil, env: {}) + plugin_dir = find(dirs, name) manifest_path = File.join(plugin_dir, "plugin.json") command = begin @@ -64,8 +103,9 @@ module Maptool south, west, north, east = bbox args = ["--south=#{south}", "--west=#{west}", "--north=#{north}", "--east=#{east}"] + args += ["--route=#{route}", "--corridor-km=#{corridor_km}"] if route - stdout, stderr, status = Open3.capture3(command, *args, chdir: plugin_dir) + stdout, stderr, status = Open3.capture3(env.to_h, command, *args, chdir: plugin_dir) # First stderr line too — for a Ruby plugin that's the exception # message (e.g. "...: unexpected response 406"), the only clue to why. unless status.success? diff --git a/lib/maptool/routing.rb b/lib/maptool/routing.rb index 57e4a41..69e23c0 100644 --- a/lib/maptool/routing.rb +++ b/lib/maptool/routing.rb @@ -185,7 +185,8 @@ module Maptool BICYCLE_TYPES = %w[Road Hybrid Cross Mountain].freeze # speed: km/h (bicycle, foot); hills: 0 avoid .. 1 seek (Valhalla's # use_hills); sac: the hardest SAC hiking grade allowed on foot. - VEHICLE_LIMITS = { height: 1..6, width: 1..4, length: 2..25, weight: 0.5..60, speed: 1..60, hills: 0..1, sac: 1..6 }.freeze + # wheelbase, track (m): the level gauge's geometry (drive_menus.js levelMenu). + VEHICLE_LIMITS = { height: 1..6, width: 1..4, length: 2..25, weight: 0.5..60, wheelbase: 1..10, track: 1..3, consumption: 1..100, speed: 1..60, hills: 0..1, sac: 1..6 }.freeze # Up to this weight Valhalla's "auto" costing (with height/width) fits # better than "truck": a camper isn't kept off roads closed to lorries. CAR_MAX_WEIGHT = 3.5 @@ -249,6 +250,9 @@ module Maptool raise ArgumentError, "#{name}: invalid Euro class" unless euro.nil? || EUROS.include?(euro) stickers = values["stickers"].to_s.strip[0, 80] + # the levelling ramps' steps, cm ("3 6 9"), for the level gauge + ramps = values["ramps"].to_s.scan(/\d+(?:[.,]\d+)?/).map { |s| s.tr(",", ".").to_f } + raise ArgumentError, "#{name}: ramps: up to 6 steps of 1 to 40 cm" unless ramps.size <= 6 && ramps.all? { |cm| (1..40).cover?(cm) } list = values["vignettes"] || [] raise ArgumentError, "#{name}: invalid vignettes" unless list.is_a?(Array) && list.size <= 30 @@ -262,7 +266,8 @@ module Maptool { country: country, kind: kind, until: (until_date unless until_date.empty?) }.compact end - { fuel: fuel, euro: euro, stickers: (stickers unless stickers.empty?), vignettes: (vignettes unless vignettes.empty?) } + { fuel: fuel, euro: euro, stickers: (stickers unless stickers.empty?), vignettes: (vignettes unless vignettes.empty?), + ramps: (ramps.sort.map { |cm| cm % 1 == 0 ? cm.to_i : cm }.join(" ") unless ramps.empty?) } end private_class_method :car_details @@ -293,6 +298,37 @@ module Maptool raise RouteError, "invalid coordinates" end + # Routes of consecutive pieces (a trip's days with avoids of their own, + # TripStore) as one: the lines joined, km along it shifted by the pieces + # before, the countries summed. + def self.merge(parts) + return parts.first if parts.size <= 1 + + km = 0.0 + coords = [] + out = { distance_km: 0.0, time_s: 0.0, legs_km: [], legs_s: [], maneuvers: [], speed_limits: [], signals: [], roads: [] } + countries = {} + parts.each do |part| + props = part[:properties] + line = part[:geometry][:coordinates] + coords.concat(coords.empty? ? line : line.drop(1)) + out[:distance_km] += props[:distance_km] + out[:time_s] += props[:time_s] + %i[legs_km legs_s maneuvers].each { |key| out[key].concat(props[key] || []) } + out[:speed_limits].concat((props[:speed_limits] || []).map { |at, limit| [(at + km).round(3), limit] }) + out[:signals].concat((props[:signals] || []).map { |lon, lat, at| [lon, lat, (at + km).round(3)] }) + out[:roads].concat((props[:roads] || []).map { |at, *rest| [(at + km).round(3), *rest] }) + (props[:countries] || []).each do |row| + sum = countries[row[:code]] ||= { code: row[:code], km: 0.0, motorway_km: 0.0, toll_km: 0.0 } + %i[km motorway_km toll_km].each { |key| sum[key] = (sum[key] + row[key].to_f).round(1) } + end + km += props[:distance_km] + end + first = parts.first + { type: "Feature", geometry: { type: "LineString", coordinates: coords }, + properties: first[:properties].merge(out, distance_km: out[:distance_km].round(3), countries: countries.values) } + end + def self.maneuver(m) { text: m["instruction"], km: m["length"], type: m["type"], street: (m["begin_street_names"] || m["street_names"])&.first, exit: m["roundabout_exit_count"], lanes: m["lanes"], @@ -429,6 +465,8 @@ module Maptool avoid = {} unless avoid.is_a?(Hash) options = options.merge(use_tolls: 0.0) if avoid["tolls"] options = options.merge(use_highways: 0.0) if avoid["highways"] + options = options.merge(use_ferry: 0.0) if avoid["ferries"] + options = options.merge(exclude_unpaved: true) if avoid["unpaved"] [costing, options] end private_class_method :costing diff --git a/lib/maptool/trip.rb b/lib/maptool/trip.rb index 8c51cf6..520802e 100644 --- a/lib/maptool/trip.rb +++ b/lib/maptool/trip.rb @@ -12,8 +12,14 @@ module Maptool EMPTY = { version: 0, points: [], vehicle: nil, avoid: {}, editing: nil, route: nil, error: nil }.freeze # The itinerary: the trip's name, when it starts (local "YYYY-MM-DDTHH:MM") # and when a day after a night stop starts ("HH:MM"); per point a night - # stop (the day ends there), the stay in minutes and a note. + # stop (the day ends there), the stay in minutes, a note, its type (an + # NPS pictogram's name, public/js/route.js STOP_TYPES) and, on a day's + # first point, the day's note; park: where the car stays ({ lngLat:, + # name: }, the route goes there, the place is a walk away); on a day's + # first point avoid: the day's own (AVOIDS), else the trip's; cost / paid: + # € planned there and paid; the trip's own note, budget and fuel price. MAX_STAY_MIN = 7 * 24 * 60 + AVOIDS = %i[tolls highways ferries unpaved].freeze DATE_TIME = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}\z/ TIME = /\A\d{2}:\d{2}\z/ @@ -21,17 +27,38 @@ module Maptool stay = p[:stay].nil? || p[:stay].to_s.empty? ? nil : Integer(p[:stay], exception: false) raise ArgumentError, "stay must be 0–#{MAX_STAY_MIN} minutes" if stay && !(0..MAX_STAY_MIN).cover?(stay) - note = p[:note].to_s.strip[0, 500] + note, day_note = [p[:note], p[:day_note]].map { |n| n.to_s.strip[0, 500] } + type = p[:type].to_s + raise ArgumentError, "type must be an icon name" unless type.empty? || type.match?(/\A[a-z0-9-]{1,60}\z/) + + cost, paid = [p[:cost], p[:paid]].map { |v| money(v) } + avoid = (p[:avoid].to_h.slice(*AVOIDS).to_h { |k, v| [k, !!v] } if p[:avoid].is_a?(Hash)) + park = ({ lngLat: p[:park].fetch(:lngLat).map { |v| Float(v) }, name: p[:park][:name]&.to_s&.strip&.[](0, 120) }.compact if p[:park].is_a?(Hash)) + { lngLat: p.fetch(:lngLat).map { |v| Float(v) }, name: p[:name], nav: !!p[:nav], passed: !!p[:passed], - night: (true if p[:night]), stay: (stay if stay&.positive?), note: (note unless note.empty?) }.compact + night: (true if p[:night]), stay: (stay if stay&.positive?), note: (note unless note.empty?), + type: (type unless type.empty?), day_note: (day_note unless day_note.empty?), park: park, avoid: avoid, cost: cost, paid: paid }.compact end - def self.itinerary(name:, start:, day_start:) + # € or nil; ArgumentError past MAX_MONEY or below 0. + MAX_MONEY = 1_000_000 + def self.money(value) + return nil if value.nil? || value.to_s.strip.empty? + + amount = Float(value, exception: false) + raise ArgumentError, "amounts must be 0–#{MAX_MONEY}" unless amount && (0..MAX_MONEY).cover?(amount) + + amount.round(2) + end + + def self.itinerary(name:, start:, day_start:, note: nil, budget: nil, fuel_price: nil) name = name.to_s.strip[0, 80] + note = note.to_s.strip[0, 2000] raise ArgumentError, "start must be YYYY-MM-DDTHH:MM" unless start.to_s.empty? || start.to_s.match?(DATE_TIME) raise ArgumentError, "day_start must be HH:MM" unless day_start.to_s.empty? || day_start.to_s.match?(TIME) - { name: (name unless name.empty?), start: (start unless start.to_s.empty?), day_start: (day_start unless day_start.to_s.empty?) } + { name: (name unless name.empty?), start: (start unless start.to_s.empty?), day_start: (day_start unless day_start.to_s.empty?), + note: (note unless note.empty?), budget: money(budget), fuel_price: money(fuel_price) }.compact end def initialize(path) @@ -134,25 +161,41 @@ module Maptool [here, GnssSim.bearing(GnssSim.point_at(coords, km, [to - 0.02, 0].max), GnssSim.point_at(coords, km, [to + 0.02, km.last].min)).round(1)] end + # The points to route, in pieces of the same avoids: [[locations, + # avoid], ...] — one piece unless a day has avoids of its own (on its + # first point in the list, the one after the night spot). A leg takes + # the avoids of the day it's driven in. + def self.pieces(points, avoid) + day = points.first&.dig(:avoid) || avoid + legs = points.each_with_index.filter_map do |p, i| + day = points[i + 1]&.dig(:avoid) || avoid if p[:night] # the next day leaves from the night spot + [p.dig(:park, :lngLat) || p[:lngLat], day] unless p[:passed] + end + legs.each_cons(2).chunk_while { |x, y| x[0][1] == y[0][1] }.map do |run| + [[run.first[0][0], *run.map { |_, to| to[0] }], run.first[0][1]] + end + end + # points: [{ lngLat: [lon, lat], name:, nav:, passed: }]. Routes through # the ones not passed with the block (locations, vehicle id, avoid → the # /api/route Feature, may raise Routing errors) unless only names/nav # changed — the old route stays then. Passed points stay in the trip # (shown dimmed, still editable: a stop missed out added afterwards), # just not routed. Last write wins. - def update(points:, vehicle:, avoid:, editing:, name: nil, start: nil, day_start: nil) + def update(points:, vehicle:, avoid:, editing:, name: nil, start: nil, day_start: nil, note: nil, budget: nil, fuel_price: nil) points = points.map { |p| self.class.point(p) } - itinerary = self.class.itinerary(name: name, start: start, day_start: day_start) + itinerary = self.class.itinerary(name: name, start: start, day_start: day_start, note: note, budget: budget, fuel_price: fuel_price) avoid = (avoid || {}).to_h { |k, v| [k.to_sym, !!v] } before = get - routed = ->(list) { list.reject { |p| p[:passed] }.map { |p| p[:lngLat] } } - same_route = routed.(before[:points]) == routed.(points) && + routed = ->(list) { list.reject { |p| p[:passed] }.map { |p| p.dig(:park, :lngLat) || p[:lngLat] } } + same_route = self.class.pieces(before[:points], before[:avoid]) == self.class.pieces(points, avoid) && before[:vehicle] == vehicle && before[:avoid] == avoid && !before[:error] route, error = if same_route then [before[:route], nil] elsif routed.(points).size < 2 then [nil, nil] else begin - [yield(routed.(points), vehicle, avoid), nil] + pieces = self.class.pieces(points, avoid) + [Routing.merge(pieces.map { |locations, day_avoid| yield(locations, vehicle, day_avoid) }), nil] rescue Routing::RouteError, Routing::Unavailable => e [nil, e.message] end diff --git a/lib/maptool/trip_days.rb b/lib/maptool/trip_days.rb new file mode 100644 index 0000000..b42d568 --- /dev/null +++ b/lib/maptool/trip_days.rb @@ -0,0 +1,94 @@ +require "time" +require_relative "track_stats" +require_relative "gpx" + +module Maptool + # The days of a recorded trip (the Design canvas' GridRecording): the log + # stays one continuous journal (lib/maptool/trip_log.rb), the days are only + # cuts in it — where the car stood ≥ STOOD_S, else at NIGHT_HOUR local time + # (a drive through the night with no long stop), plus the cuts made by + # hand, minus the ones joined. A cut is the index of a day's first point. + # points: [[lon, lat, alt, t], ...] (t: epoch s), as the journal has them. + module TripDays + STOOD_S = 4 * 3600 + NIGHT_HOUR = 3 + PAUSE_S = 300 # this long between two fixes: standing (a fix comes every 10 m moved) + + # [[index, "auto" | "night" | "hand"], ...], sorted. hand / joined: epoch + # s — a hand cut starts the day at the first point from then on; a join + # names the cut by its day's first point's time. + # ponytail: NIGHT_HOUR in the server's time zone, the client's if they differ + def self.cuts(points, hand: [], joined: []) + t = points.map { |p| p[3] } + auto = (1...points.size).select { |i| t[i] - t[i - 1] >= STOOD_S } + night = (1...points.size).select do |i| + crossed = Time.at(t[i]).then { |b| Time.new(b.year, b.month, b.day, NIGHT_HOUR) } + crossed = crossed - 86_400 if crossed.to_f > t[i] + crossed.to_f > t[i - 1] && auto.none? { |j| (t[j] - t[i]).abs < 12 * 3600 } + end + by_hand = hand.filter_map { |h| t.index { |x| x >= h } }.select { |i| i.positive? } + all = auto.map { |i| [i, "auto"] } + night.map { |i| [i, "night"] } + by_hand.map { |i| [i, "hand"] } + all.reject { |i, _| joined.any? { |j| (t[i] - j).abs < 0.05 } }.uniq(&:first).sort_by(&:first) + end + + # The days: { index:, from:, to: (exclusive), started_at:, ended_at:, + # distance_m:, driving_s:, ascent_m:, max_alt_m:, cut: (what ends it: + # { kind:, stood_s:, at: [lon, lat], next: its time }) }. + def self.days(points, cuts) + bounds = [0, *cuts.map(&:first), points.size] + bounds.each_cons(2).each_with_index.map do |(from, to), n| + piece = points[from...to] + day = { index: n + 1, from: from, to: to, started_at: piece.first[3], ended_at: piece.last[3] }.merge(stats(piece)) + if to < points.size + day[:cut] = { kind: cuts[n][1], stood_s: (points[to][3] - piece.last[3]).round, at: piece.last.first(2), next: points[to][3] } + end + day + end + end + + def self.stats(piece) + coords = piece.map { |lon, lat, alt| alt ? [lon, lat, alt] : [lon, lat] } + gaps = piece.each_cons(2).map { |a, b| b[3] - a[3] } + { + distance_m: TrackStats.compute(coords)["distance_meters"], + driving_s: gaps.select { |g| g < PAUSE_S }.sum.round, + standing_s: gaps.select { |g| g >= PAUSE_S }.sum.round, + stops: gaps.count { |g| g >= PAUSE_S }, + ascent_m: TrackStats.compute(coords)["elevation_gain_meters"], + max_alt_m: piece.filter_map { |p| p[2] }.max, + } + end + + # [west, south, east, north] of a piece. + def self.bbox(piece) + lons, lats = piece.map(&:first), piece.map { |p| p[1] } + [lons.min, lats.min, lons.max, lats.max] + end + + # A GPX of tracks — pieces: [[name, points], ...] — with each point's + # time; extras: Features to add (the planned route, stops, pauses). + def self.gpx(pieces, extras = []) + tracks = pieces.map do |name, piece| + { "type" => "Feature", "geometry" => { "type" => "LineString", "coordinates" => piece.map { |lon, lat, alt| alt ? [lon, lat, alt] : [lon, lat] } }, + "properties" => { "kind" => "track", "name" => name, "activity_type" => "driving", + "times" => piece.map { |p| Time.at(p[3]).utc.iso8601 } } } + end + Gpx.from_features(extras + tracks) + end + + # The stands (≥ PAUSE_S) in a piece as waypoints. + def self.pauses(piece) + piece.each_cons(2).filter_map do |a, b| + next if b[3] - a[3] < PAUSE_S + + { "type" => "Feature", "geometry" => { "type" => "Point", "coordinates" => a.first(2) }, + "properties" => { "name" => "Stood #{duration(b[3] - a[3])}", "time" => Time.at(a[3]).utc.iso8601 } } + end + end + + def self.duration(seconds) + h, m = (seconds / 60).round.divmod(60) + h.positive? ? format("%d h %02d", h, m) : "#{m} min" + end + end +end diff --git a/lib/maptool/trip_log.rb b/lib/maptool/trip_log.rb index 4945877..4f5ee0a 100644 --- a/lib/maptool/trip_log.rb +++ b/lib/maptool/trip_log.rb @@ -117,6 +117,47 @@ module Maptool end end + # The running trip's journal, else the newest (the trip just ended), read + # whole: { folder:, started_at:, points:, hand:, joined:, active: } — or nil. + def recording + path = @mutex.synchronize do + @file&.flush + @trip ? @trip[:path] : Dir[File.join(@dir, "*.ndjson")].max_by { |p| File.basename(p, ".ndjson").to_i } + end + return nil unless path + + out = { points: [], hand: [], joined: [], active: false, path: path } + File.foreach(path) do |line| + entry = JSON.parse(line) rescue next + case entry + when Array then out[:points] << entry + when Hash + out[:folder] ||= entry["trip"] + out[:started_at] ||= entry["started_at"] + out[:hand] << entry["cut"] if entry["cut"] + out[:joined] << entry["join"] if entry["join"] + end + end + out[:active] = @mutex.synchronize { @trip&.dig(:path) == path } + out + end + + # A day cut by hand at `at` (epoch s), or a cut joined (`at`: its day's + # first point's time): a line in the journal, the trip itself untouched. + def mark(kind, at) + raise ArgumentError, "cut or join" unless %i[cut join].include?(kind) + + path = recording&.dig(:path) or raise ArgumentError, "no trip recorded" + @mutex.synchronize do + if @trip && @trip[:path] == path + journal(kind => at.to_f) + sync + else + File.open(path, "a") { |f| f.puts(JSON.generate(kind => at.to_f)) } + end + end + end + private # The newest journal with no end: the trip still running. diff --git a/plugins/overpass-pois/plugin.json b/plugins/overpass-pois/plugin.json index 13e3440..4fb1d33 100644 --- a/plugins/overpass-pois/plugin.json +++ b/plugins/overpass-pois/plugin.json @@ -1,4 +1,5 @@ { "label": "Camper POIs (Overpass)", - "command": "./run.rb" + "command": "./run.rb", + "route": true } diff --git a/plugins/overpass-pois/run.rb b/plugins/overpass-pois/run.rb index 1c846ee..5d532c3 100755 --- a/plugins/overpass-pois/run.rb +++ b/plugins/overpass-pois/run.rb @@ -7,10 +7,19 @@ # did all the real work for the "rake overpass:pois" dev-time task this # plugin now sits alongside as a second way to run the same query. +# Along the trip's route (--route= --corridor-km): +# Overpass' around: with the route thinned to a vertex every half corridor. + require_relative "../../lib/maptool/overpass_pois" +require_relative "../../lib/maptool/corridor" args = ARGV.to_h { |arg| arg.sub(/\A--/, "").split("=", 2) } bbox = %w[south west north east].map { |key| Float(args.fetch(key)) } +around = if args["route"] + corridor = Float(args.fetch("corridor-km")) + line = Maptool::Corridor.thin(JSON.parse(File.read(args["route"]))["coordinates"], [corridor / 2, 0.5].max) + [corridor * 1000, line] + end -response = Maptool::OverpassPois.fetch(bbox) +response = Maptool::OverpassPois.fetch(bbox, timeout: around ? 180 : 60, around: around) puts JSON.generate(Maptool::OverpassPois.to_geojson(response)) diff --git a/public/css/style.css b/public/css/style.css index 3c37f39..396406d 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -2788,6 +2788,50 @@ button.basemap-panel__link[hidden] { display: none; } color: #c62828; } +.plugins-panel__route { + flex-basis: 100%; + display: flex; + justify-content: flex-end; + gap: 6px; +} + +.plugins-panel__corridor { + font: inherit; + font-size: 12px; +} + +.plugins-panel__settings { + flex-basis: 100%; + font-size: 12px; +} + +.plugins-panel__settings summary { + color: var(--ui-muted); + cursor: pointer; +} + +.plugins-panel__setting { + display: flex; + flex-direction: column; + gap: 2px; + margin: 6px 0; +} + +.plugins-panel__setting input { + font: inherit; +} + +.plugins-panel__setting small { + color: var(--ui-muted); + white-space: normal; + max-width: 260px; +} + +.plugins-panel__save { + font: inherit; + font-size: 12px; +} + .plugins-panel__empty { color: var(--ui-muted); white-space: normal; @@ -4827,5 +4871,134 @@ html.driving .drive-cell--field { position: relative; } .route-panel__note-editor { list-style: none; display: flex; flex-direction: column; gap: 4px; padding: 4px 0 8px 36px; font-size: 12px; } .route-panel__note-editor input { width: 5em; } .route-panel__note-editor textarea { font: inherit; resize: vertical; } +.route-panel__trip textarea { flex: 1 1 100%; font: 12px inherit; color: var(--ui-fg); background: var(--ui-bg-2); border: none; border-radius: 4px; padding: 3px 6px; resize: vertical; field-sizing: content; } +.route-panel .route-panel__leg.route-panel__leg { display: flex; align-items: center; gap: 6px; } +.route-panel__leg span { flex: 1; } +.route-panel__leg--insert { color: var(--accent); font-weight: 600; } +.route-panel__day-note { list-style: none; margin: 0 0 4px 18px; border-left: 3px solid var(--day); } +.route-panel__note-editor.route-panel__day-note { padding: 0 0 6px 6px; } +.route-panel__check--warn > summary { color: #b45309; } +.route-panel__check ul { list-style: none; margin: 0; padding: 0; } +.route-panel__check li { display: flex; gap: 6px; align-items: center; padding: 3px 0; font-size: 12px; border-bottom: 1px solid var(--ui-line); } +.route-panel__check li span { flex: 1; } +.route-panel__check li::before { width: 14px; font-weight: 800; text-align: center; } +.route-panel__check-bad::before { content: "✗"; color: #c2410c; } +.route-panel__check-warn::before { content: "!"; color: #b45309; } +.route-panel__check-info::before { content: "i"; color: var(--ui-muted); } +.route-panel__costs ul { list-style: none; margin: 0; padding: 0; } +.route-panel__costs li { display: flex; gap: 8px; padding: 3px 0; font-size: 12px; border-bottom: 1px solid var(--ui-line); } +.route-panel__costs li span:nth-child(2) { flex: 1; color: var(--ui-muted); } +.route-panel__costs li span:last-child { font-variant-numeric: tabular-nums; } +.route-panel__money input, .route-panel__trip input[type="number"] { width: 5em; } +.route-panel__day-avoid { display: flex; flex-wrap: wrap; gap: 4px 10px; } +/* where the car stays: a P marker on the map, a row under the stop */ +.route-park { width: 20px; height: 20px; border-radius: 4px; background: #1d4ed8; border: 2px solid #fff; color: #fff; + font: 700 12px/20px sans-serif; text-align: center; cursor: grab; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3); } +.route-panel__park { display: block; font-size: 12px; } +.route-panel__park::before { content: "P"; display: inline-block; width: 15px; margin-right: 5px; border-radius: 3px; background: #1d4ed8; + color: #fff; font-weight: 700; font-size: 10px; text-align: center; } +.route-panel__park-edit button { font: inherit; } +/* a stop's type: its NPS pictogram in the badge and on the marker */ +.route-panel__badge svg { width: 15px; height: 15px; } +.route-marker svg { width: 14px; height: 14px; vertical-align: -2px; } .route-remote-popup .maplibregl-popup-content { padding: 6px 10px; font-size: 12px; } .route-remote button { border: none; background: none; color: var(--accent); font-weight: 700; cursor: pointer; } + +/* Recording (drive_menus.js recordingMenu, the canvas' GridRecording): the + name, four totals, the days a row each with the cuts between them, or the + export form; the actions at the foot. */ +.drive-trip__log-state { text-align: left; } +.drive-rec__name { grid-area: 2 / 1 / 3 / -1; display: flex; align-items: center; padding: 0 16px; font-size: calc(20px * var(--s, 1)); font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.drive-rec__total { display: flex; flex-direction: column; justify-content: center; padding: 0 12px; white-space: nowrap; overflow: hidden; } +.drive-rec__total b { font-size: calc(24px * var(--s, 1)); font-variant-numeric: tabular-nums; line-height: 1.1; } +.drive-rec__total small { font-size: calc(12px * var(--s, 1)); color: var(--drive-muted); } +.drive-rec__total[data-total="distance"] { grid-area: 3 / 1 / 4 / 3; } +.drive-rec__total[data-total="driving"] { grid-area: 3 / 3 / 4 / 5; } +.drive-rec__total[data-total="standing"] { grid-area: 3 / 5 / 4 / 7; } +.drive-rec__total[data-total="ascent"] { grid-area: 3 / 7 / 4 / 8; } +.drive-rec__days { grid-area: 4 / 1 / -2 / -1; overflow-y: auto; display: flex; flex-direction: column; gap: 1px; background: var(--drive-line); } +.drive-rec__days[hidden], .drive-rec__export[hidden] { display: none; } +.drive-rec__day { flex: none; height: var(--cell, 80px); display: flex; align-items: stretch; background: var(--band); border-left: 6px solid var(--day); } +.drive-rec__tick { width: var(--cell, 80px); flex: none; display: flex; align-items: center; justify-content: center; } +.drive-rec__tick input { width: 30px; height: 30px; accent-color: var(--drive-key-on); } +.drive-rec__day .drive-panel__text { flex: 1; justify-content: center; padding: 0 12px; } +.drive-rec__day .drive-panel__look { width: var(--cell, 80px); flex: none; background: none; } +.drive-rec__cutrow { flex: none; height: calc(var(--cell, 80px) / 2); display: flex; align-items: center; gap: 10px; padding-left: 28px; background: var(--band); color: var(--drive-muted); font-size: calc(14px * var(--s, 1)); } +.drive-rec__cutrow span:nth-child(2) { flex: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.drive-panel .drive-rec__cutrow button { height: 100%; padding: 0 16px; background: none; border-left: 1px solid var(--drive-line); font-size: calc(14px * var(--s, 1)); font-weight: 700; } +.drive-rec__live { color: var(--route-driven); font-style: normal; } +.drive-panel__note.drive-rec__live { color: var(--route-driven); font-weight: 700; } +.drive-rec__export { grid-area: 4 / 1 / -2 / -1; display: flex; flex-direction: column; gap: 14px; padding: 14px 16px; overflow-y: auto; } +.drive-rec__export fieldset { margin: 0; padding: 0; border: none; display: flex; flex-direction: column; gap: 4px; } +.drive-rec__export fieldset.drive-rec__with { flex-flow: row wrap; gap: 4px 24px; } +.drive-rec__export legend { font-size: calc(11px * var(--s, 1)); color: var(--drive-muted); text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 6px; } +.drive-rec__export label { display: flex; align-items: center; gap: 12px; min-height: 44px; font-size: calc(17px * var(--s, 1)); } +.drive-rec__export label small { color: var(--drive-muted); font-size: calc(13px * var(--s, 1)); } +.drive-rec__export input { width: 24px; height: 24px; accent-color: var(--drive-key-on); } +.drive-rec__end { grid-area: -2 / 1 / -1 / 3; } +.drive-panel button.drive-rec__end { background: var(--route-driven); color: #fff; font-size: calc(17px * var(--s, 1)); font-weight: 700; } +.drive-rec__cut { grid-area: -2 / 3 / -1 / 5; } +.drive-rec__go { grid-area: -2 / 5 / -1 / 8; } +.drive-rec__back { grid-area: -2 / 1 / -1 / 4; } +.drive-rec__save { grid-area: -2 / 4 / -1 / 8; } +.drive-panel button.drive-rec__cut, +.drive-panel button.drive-rec__back { font-size: calc(17px * var(--s, 1)); font-weight: 700; } +.drive-panel [data-action][hidden] { display: none; } +.drive-rec__pin { width: 30px; height: 30px; border-radius: 50%; background: #fff; color: #1a1a1a; border: 3px solid var(--route-driven); display: grid; place-items: center; font: 700 15px/1 system-ui, sans-serif; cursor: grab; } + +/* Level (drive_menus.js levelMenu, the canvas' GridLevel): the car from + above with the cm under each wheel, the bubble, roll / pitch now and after. */ +.drive-level__plan { grid-area: 2 / 1 / 6 / 5; display: flex; align-items: center; justify-content: center; padding: 6px; } +.drive-level__bubble { grid-area: 2 / 5 / 6 / 8; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; padding: 6px; } +.drive-level__plan svg, .drive-level__bubble svg { width: 100%; height: 100%; min-height: 0; flex: 1 1 0; max-width: calc(var(--cell, 80px) * 3.8); } +.drive-level__plan svg text { font-variant-numeric: tabular-nums; } +.drive-level__body { fill: none; stroke: var(--band-fg); stroke-width: 3; } +.drive-level__axis { stroke: var(--drive-muted); stroke-width: 1; stroke-dasharray: 3 5; fill: none; } +.drive-level__sub { fill: var(--drive-muted); } +rect.drive-level__none { fill: var(--band-fg); } text.drive-level__none { fill: var(--drive-muted); } +.drive-level__lift { fill: var(--inst-caution); } +.drive-level__over { fill: var(--inst-warning); } +.drive-level__ring { fill: none; stroke: var(--drive-muted); stroke-width: 2; } +.drive-level__ring--inner { stroke-width: 1; stroke-dasharray: 3 4; } +.drive-level__tol { fill: var(--inst-ok); opacity: 0.25; } +.drive-level__dot { fill: var(--inst-caution); stroke: #fff; stroke-width: 2; } +.drive-level__dot--ok { fill: var(--inst-ok); stroke: #fff; stroke-width: 2; } +.drive-level [data-field="roll"] { grid-area: 6 / 1 / 7 / 3; } +.drive-level [data-field="pitch"] { grid-area: 6 / 3 / 7 / 5; } +.drive-level [data-field="after"] { grid-area: 6 / 5 / 7 / 8; } +.drive-level--ok { color: var(--inst-ok); } +.drive-level--over { color: var(--inst-warning); } +/* Today (drive_menus.js todayMenu, the canvas' GridToday) */ +.drive-today__stops { grid-area: 2 / 1 / 4 / -1; display: flex; flex-direction: column; overflow: hidden; } +.drive-today__stop { flex: 1; display: flex; align-items: center; gap: 12px; padding: 0 14px; min-height: 0; border-bottom: 1px solid var(--drive-line); } +.drive-today__icon { width: calc(40px * var(--s, 1)); height: calc(40px * var(--s, 1)); flex: none; border-radius: 50%; background: var(--accent); color: #fff; + display: flex; align-items: center; justify-content: center; } +.drive-today__icon--night { background: #3d4a6b; } +.drive-today__icon svg { width: 60%; height: 60%; } +.drive-today__name { flex: 1; min-width: 0; display: flex; flex-direction: column; } +.drive-today__name b { font-size: calc(19px * var(--s, 1)); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.drive-today__name small, .drive-today__eta small { font-size: calc(13px * var(--s, 1)); color: var(--drive-muted); } +.drive-today__eta { display: flex; flex-direction: column; align-items: flex-end; font-size: calc(22px * var(--s, 1)); font-weight: 700; font-variant-numeric: tabular-nums; } +.drive-today__tonight { grid-area: 4 / 1 / 5 / 5; padding: 6px 14px; display: flex; flex-direction: column; justify-content: center; min-width: 0; } +.drive-today__line { font-size: calc(15px * var(--s, 1)); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.drive-today__sun { grid-area: 4 / 5 / 5 / 8; padding: 6px 14px; display: flex; flex-direction: column; justify-content: center; } +.drive-today--late { color: var(--inst-caution); } +.drive-today__weather { padding: 6px 12px; display: flex; flex-direction: column; justify-content: center; white-space: nowrap; overflow: hidden; } +.drive-today__weather small { color: var(--drive-muted); } +.drive-today__weather[data-w="0"] { grid-area: 5 / 1 / 6 / 3; } +.drive-today__weather[data-w="1"] { grid-area: 5 / 3 / 6 / 5; } +.drive-today__weather[data-w="2"] { grid-area: 5 / 5 / 6 / 8; } +.drive-today__notes { grid-area: 6 / 1 / -2 / -1; padding: 6px 14px; overflow: hidden; font-size: calc(16px * var(--s, 1)); } +.drive-today__notes p { margin: 0 0 6px; } +.drive-today__warn { color: var(--inst-caution); } +.drive-today__skip { grid-area: -2 / 1 / -1 / 3; } +.drive-today__prev { grid-area: -2 / 3 / -1 / 5; } +.drive-today__next { grid-area: -2 / 5 / -1 / 8; } +.drive-panel button.drive-today__skip, .drive-panel button.drive-today__prev, .drive-panel button.drive-today__next { font-size: calc(17px * var(--s, 1)); font-weight: 700; } +.drive-level__advice { grid-area: 7 / 1 / 8 / -1; display: flex; align-items: center; padding: 0 16px; font-size: calc(16px * var(--s, 1)); line-height: 1.3; } +.drive-level__zero { grid-area: -2 / 1 / -1 / 3; } +.drive-level__under { grid-area: -2 / 3 / -1 / 6; } +.drive-level__terrain { grid-area: -2 / 6 / -1 / 8; } +.drive-panel button.drive-level__zero, +.drive-panel button.drive-level__under, +.drive-panel button.drive-level__terrain { font-size: calc(16px * var(--s, 1)); font-weight: 700; } diff --git a/public/js/dashboard.js b/public/js/dashboard.js index f93ad00..3241417 100644 --- a/public/js/dashboard.js +++ b/public/js/dashboard.js @@ -42,6 +42,10 @@ const LANES_AHEAD_S = 45; const ARRIVE_M = 30; // this close to the end: arrived (navigation goes on: past it, the route turns back) const ARRIVE_TYPES = [4, 5, 6]; // Valhalla's destination maneuvers const DEFAULT_WIDGETS = { inclinometer: true, speed: true, altitude: true, navigation: true, banner: true }; +// Step advance after Ferrostar's DistanceEntryExit: a maneuver stays the next one +// until the position is this far past it (not before reaching it: at the turn the +// turn is still shown, "now"), then the one after it +const STEP_EXIT_M = 5; const THEN_M = 300; // the maneuver after the next one shown with it when it follows this closely // Voice prompts (speechSynthesis, Valhalla's verbal instructions), on/off in // drive mode's Menu: "In 400 m, turn right…" from SOON_S ahead, the @@ -294,7 +298,7 @@ export class DashboardControl { const nextKm = [...limits, ...roads].map(([km]) => km).filter((km) => km > at).sort((a, b) => a - b).find((km) => limitAt(km) !== limit); const next = nextKm != null ? [nextKm, limitAt(nextKm)] : null; const signal = signals.find(([, , km]) => km > at); - const index = maneuvers.findIndex((m) => m.at > at + 0.005); + const index = maneuvers.findIndex((m) => m.at > at - STEP_EXIT_M / 1000); const maneuver = maneuvers[index]; const then = maneuvers[index + 1]; const onStreet = maneuvers[index - 1]?.street; // the one being driven: the last maneuver's @@ -307,7 +311,7 @@ export class DashboardControl { next: next && { limit: next[1], m: (next[0] - at) * 1000 }, country: roads.findLast(([km]) => km <= at)?.[2] ?? null, signal: signal && (signal[2] - at) * 1000, - maneuver: maneuver && { ...maneuver, m: (maneuver.at - at) * 1000 }, + maneuver: maneuver && { ...maneuver, m: Math.max(0, (maneuver.at - at) * 1000) }, then: maneuver && then && then.at - maneuver.at <= THEN_M / 1000 ? then : null, street: onStreet, arrived: ARRIVE_TYPES.includes(maneuvers.at(-1)?.type) && (!maneuver || (index === maneuvers.length - 1 && (maneuver.at - at) * 1000 <= ARRIVE_M)), diff --git a/public/js/drive_menus.js b/public/js/drive_menus.js index b02776e..6146c11 100644 --- a/public/js/drive_menus.js +++ b/public/js/drive_menus.js @@ -3,6 +3,11 @@ // menu area, built the same way as the Trip menu. import { distance } from "/js/dashboard.js"; import { elevationAt } from "/js/dem.js"; +import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs"; +import { DAY_COLORS, formatDuration, STOP_TYPES } from "/js/route.js"; +import { NPS_SYMBOLS } from "/js/icons.js"; +import { getTimes } from "/vendor/suncalc/suncalc.js"; +import { currentVehicle } from "/js/panels.js"; const SEARCH_DELAY_MS = 300; const AHEAD_M = 2000; // "Ahead": saved things this close to the route still to drive @@ -384,7 +389,7 @@ export function terrainMenu(ctx) {
- `); + `); let peak = { roll: null, pitch: null }; let ahead = { climb: null, across: null }; let aheadAt = 0; @@ -452,7 +457,7 @@ export function terrainMenu(ctx) { } el.querySelector(".drive-panel__close").addEventListener("click", ctx.close); - el.querySelector('[data-action="road"]').addEventListener("click", ctx.close); + el.querySelector('[data-action="road"]').addEventListener("click", ctx.openLevel); el.querySelector('[data-action="reset"]').addEventListener("click", () => { peak = { roll: null, pitch: null }; render(); }); el.querySelector('[data-action="level"]').addEventListener("click", async () => { if (!armed) { @@ -468,3 +473,454 @@ export function terrainMenu(ctx) { }); return { el, render, opened: render }; } + +// Recording (the Design canvas' GridRecording): the trip log — the running +// trip's, else the last one's (lib/maptool/trip_days.rb, /api/trip/log/days) +// — as totals and days; the days only cuts in one continuous log (where the +// car stood ≥ 4 h, else 03:00), joined or cut by hand. Export: the days +// ticked, a piece between A and B on the map (markers snapped to the line), +// or the whole trip, as GPX (a track per day) or a .zip of a file per day. +// ctx: { map, showBounds, endTrip, close }. +export function recordingMenu(ctx) { + const el = panel("drive-rec", "Recording", ` +
+
+
+
+
+
+ + + + + + `); + const $ = (sel) => el.querySelector(sel); + const form = $(".drive-rec__export"); + let data = null; + let picked = null; // the days ticked: Set of day numbers + let exporting = false; + let ab = null; // [A, B] markers while a piece is picked + const day = (t) => new Date(t * 1000).toLocaleDateString([], { weekday: "short", day: "numeric", month: "numeric" }); + const time = (t) => new Date(t * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); + const km = (m) => `${Math.round(m / 1000).toLocaleString()} km`; + const hours = (s) => formatDuration(s); + const stats = (d) => [km(d.distance_m), hours(d.driving_s), d.ascent_m ? `↑ ${Math.round(d.ascent_m).toLocaleString()} m` : ""].filter(Boolean).join(" · "); + const CUT = { auto: "cut automatically", night: "cut at 03:00", hand: "cut by hand" }; + const pickedKm = () => data.days.filter((d) => picked.has(d.index)).reduce((sum, d) => sum + d.distance_m, 0); + + const post = async (body) => { + await fetch("/api/trip/log/days", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); + load(); + }; + + // A and B: draggable, snapped to the nearest point of the line on drop. + const nearest = (lngLat) => data.track.reduce((best, p) => (meters(p, [lngLat.lng, lngLat.lat]) < meters(best, [lngLat.lng, lngLat.lat]) ? p : best)); + const placeAB = async () => { + if (!data.track) data = { ...data, track: (await (await fetch("/api/trip/log/days?track=1", { cache: "no-store" })).json()).track }; + const days = data.days.filter((d) => picked.has(d.index)); + const from = days.length ? data.track[days[0].from] : data.track[0]; + const to = days.length ? data.track[days.at(-1).to - 1] : data.track.at(-1); + ab = [from, to].map((p, i) => { + const m = Object.assign(document.createElement("div"), { className: "drive-rec__pin", textContent: "AB"[i] }); + const marker = new Marker({ element: m, draggable: true }).setLngLat(p.slice(0, 2)).addTo(ctx.map); + marker.point = p; + marker.on("dragend", () => { marker.point = nearest(marker.getLngLat()); marker.setLngLat(marker.point.slice(0, 2)); renderExport(); }); + return marker; + }); + renderExport(); + }; + const removeAB = () => { ab?.forEach((m) => m.remove()); ab = null; }; + const piece = () => ab && [ab[0].point[2], ab[1].point[2]].sort((a, b) => a - b); + + const renderExport = () => { + const what = form.elements.what.value; + form.querySelector('[data-text="days"]').textContent = `Days ticked · ${[...picked].sort().map((n) => `Day ${n}`).join(", ") || "none"} · ${km(pickedKm())}`; + const p = piece(); + const pieceKm = p ? data.track.filter((q) => q[2] >= p[0] && q[2] <= p[1]).reduce((s, q, i, a) => s + (i ? meters(a[i - 1], q) : 0), 0) : 0; + form.querySelector('[data-text="piece"]').innerHTML = p ? `A piece: A ${day(p[0])} ${time(p[0])} → B ${time(p[1])} · ${km(pieceKm)} move A, B on the map` : "A piece between A and B on the map"; + form.querySelector('[data-text="whole"]').textContent = `The whole trip · ${km(data.totals.distance_m)}`; + const n = what === "days" ? picked.size : what === "piece" ? 1 : data.days.length; + $(".drive-rec__save").textContent = `Save ${what === "piece" ? "the piece" : `${n} day${n === 1 ? "" : "s"}`} · ${form.elements.files.value === "per_day" && n > 1 ? "ZIP" : "GPX"}`; + $(".drive-rec__save").disabled = what === "days" && !picked.size; + }; + form.addEventListener("change", (e) => { + if (e.target.name === "what") (e.target.value === "piece" ? placeAB() : removeAB()); + renderExport(); + }); + + const render = () => { + el.querySelector(".drive-panel__head").firstChild.textContent = exporting ? "Export " : "Recording "; + const note = el.querySelector(".drive-panel__note"); + for (const b of el.querySelectorAll("[data-action]")) b.hidden = !data; + if (!data) { + note.textContent = ""; + $(".drive-rec__name").textContent = "No trip recorded yet — Start the trip in the Trip menu"; + $(".drive-rec__days").replaceChildren(); + for (const t of el.querySelectorAll(".drive-rec__total")) t.innerHTML = ""; + form.hidden = true; + return; + } + const tot = data.totals; + const span = tot.ended_at - tot.started_at; + note.textContent = data.active ? `● REC ${Math.floor(span / 86400) ? `${Math.floor(span / 86400)} d ` : ""}${Math.floor((span % 86400) / 3600)} h` : "ended"; + note.classList.toggle("drive-rec__live", data.active); + $(".drive-rec__name").textContent = (data.folder || "").replace(/^Trips\//, ""); + const totals = { + distance: ["Distance", km(tot.distance_m), `${tot.days} day${tot.days === 1 ? "" : "s"}`], + driving: ["Driving", hours(tot.driving_s), tot.driving_s ? `Ø ${Math.round(tot.distance_m / tot.driving_s * 3.6)} km/h` : ""], + standing: ["Standing", hours(tot.standing_s), `${tot.stops} stop${tot.stops === 1 ? "" : "s"}`], + ascent: ["Ascent", tot.ascent_m ? `${Math.round(tot.ascent_m).toLocaleString()} m` : "—", tot.max_alt_m != null ? `max ${Math.round(tot.max_alt_m).toLocaleString()} m` : ""], + }; + for (const t of el.querySelectorAll(".drive-rec__total")) { + const [label, value, sub] = totals[t.dataset.total]; + t.innerHTML = `${label}${escapeHtml(value)}${escapeHtml(sub)}`; + } + const rows = data.days.flatMap((d, i) => { + const now = data.active && i === data.days.length - 1; + const li = document.createElement("div"); + li.className = "drive-rec__day"; + li.style.setProperty("--day", DAY_COLORS[i % DAY_COLORS.length]); + li.innerHTML = ` + Day ${d.index} · ${day(d.started_at)}${now ? ' ● now' : ""} + ${time(d.started_at)} – ${now ? "…" : time(d.ended_at)}${stats(d)}${now ? " so far" : ""}`; + li.querySelector("input").addEventListener("change", (e) => { e.target.checked ? picked.add(d.index) : picked.delete(d.index); render(); }); + li.append(cellButton("look", "⌕", `Show day ${d.index} on the map`, () => ctx.showBounds(d.bbox))); + if (!d.cut) return [li]; + const cut = document.createElement("div"); + cut.className = "drive-rec__cutrow"; + cut.innerHTML = `Stood ${hours(d.cut.stood_s)} · ${CUT[d.cut.kind]}`; + cut.append(cellButton("join", "Join", `Join day ${d.index} and day ${d.index + 1}`, () => post({ join: d.cut.next }))); + return [li, cut]; + }); + $(".drive-rec__days").replaceChildren(...rows); + $(".drive-rec__days").hidden = exporting; + form.hidden = !exporting; + $(".drive-rec__end").hidden = exporting || !data.active; + $(".drive-rec__cut").hidden = exporting || !data.active; + $(".drive-rec__go").hidden = exporting; + $(".drive-rec__go").textContent = `Export ${picked.size ? `${picked.size} day${picked.size === 1 ? "" : "s"}` : ""} ▸`; + $(".drive-rec__back").hidden = !exporting; + $(".drive-rec__save").hidden = !exporting; + if (exporting) renderExport(); + }; + + async function load() { + try { + const response = await fetch("/api/trip/log/days", { cache: "no-store" }); + const fresh = response.ok ? await response.json() : null; + if (fresh && (!data || fresh.folder !== data.folder)) picked = new Set(fresh.days.filter((d, i) => !(fresh.active && i === fresh.days.length - 1)).map((d) => d.index)); + data = fresh && { ...fresh, track: data?.folder === fresh.folder ? data.track : null }; + } catch { /* offline for a moment */ } + render(); + } + + el.querySelector('[data-action="end"]').addEventListener("click", async () => { await ctx.endTrip(); load(); }); + el.querySelector('[data-action="cut"]').addEventListener("click", () => post({ cut: Date.now() / 1000 })); + el.querySelector('[data-action="export"]').addEventListener("click", () => { exporting = true; render(); }); + el.querySelector('[data-action="back"]').addEventListener("click", () => { exporting = false; removeAB(); render(); }); + el.querySelector('[data-action="save"]').addEventListener("click", () => { + const what = form.elements.what.value; + const q = new URLSearchParams(); + if (what === "days") q.set("days", [...picked].join(",")); + if (what === "piece" && piece()) { q.set("from", piece()[0]); q.set("to", piece()[1]); } + if (form.elements.files.value === "per_day") q.set("per_day", "1"); + for (const name of ["stops", "plan", "pauses"]) if (form.elements[name].checked) q.set(name, "1"); + const a = Object.assign(document.createElement("a"), { href: `/api/trip/log/export?${q}` }); + a.click(); + }); + + return { + el, + opened: () => { exporting = false; removeAB(); load(); }, + closed: () => removeAB(), + }; +} + +// Level (the canvas' GridLevel), standing: the wheel-chock calculation from +// the IMU's roll and pitch (right side low, nose up positive, as the +// inclinometer) and the profile's wheelbase and track. A wheel's height is +// z = x·tan(pitch) − y·tan(roll) (x forward, y right); every wheel is lifted +// to the highest one — never dug in — so one stays. Ramps: the lift rounded to +// the profile's ramp steps, and the roll / pitch left after them; jacks: the cm. +const LEVEL_TOL = 0.5; // ° level enough +const DEFAULT_RAMPS = [3, 6, 9]; +const UNDER_KEY = "maptool.levelUnder"; +const WHEELS = { FL: [1, -1], FR: [1, 1], RL: [-1, -1], RR: [-1, 1] }; // [forward, right] signs + +export function levelPlan(roll, pitch, wheelbase, track, steps) { + const z = Object.fromEntries(Object.entries(WHEELS).map(([k, [fx, sy]]) => [k, (fx * wheelbase) / 2 * Math.tan(pitch * RAD) - (sy * track) / 2 * Math.tan(roll * RAD)])); + const top = Math.max(...Object.values(z)); + const wheels = Object.fromEntries(Object.entries(z).map(([k, v]) => { + const cm = (top - v) * 100; + if (!steps || cm < 1) return [k, { cm, used: steps ? 0 : cm, step: null }]; + const i = steps.reduce((best, step, j) => (Math.abs(step - cm) < Math.abs(steps[best] - cm) ? j : best), 0); + return [k, { cm, used: steps[i], step: i + 1, over: cm > steps.at(-1) + 1.5 }]; + })); + const after = Object.fromEntries(Object.keys(z).map((k) => [k, z[k] + wheels[k].used / 100])); + return { + wheels, + roll: Math.atan((after.FL + after.RL - after.FR - after.RR) / 2 / track) / RAD, + pitch: Math.atan((after.FL + after.FR - after.RL - after.RR) / 2 / wheelbase) / RAD, + }; +} + +export function levelMenu(ctx) { + const el = panel("drive-level", "Level", ` +
+
+
+
+
+
+ + + `); + let armed = null; + const under = () => { try { return localStorage.getItem(UNDER_KEY) === "jacks" ? "jacks" : "ramps"; } catch { return "ramps"; } }; + const deg = (v) => `${v < 0 ? "−" : ""}${Math.abs(v).toFixed(1)}°`; + const field = (name, label, value, unit, ok) => + (el.querySelector(`[data-field="${name}"]`).innerHTML = `${label}${value} ${unit}`); + + function render() { + if (el.hidden) return; + const dash = ctx.state(); + const v = dash?.values || {}; + const vehicle = currentVehicle || {}; + const guessed = !vehicle.wheelbase || !vehicle.track; + const wheelbase = vehicle.wheelbase || (vehicle.length ? vehicle.length * 0.55 : 3); + const track = vehicle.track || (vehicle.width ? vehicle.width - 0.25 : 1.6); + const ramps = String(vehicle.ramps || "").split(/\s+/).map(Number).filter((n) => n > 0); + const steps = under() === "ramps" ? (ramps.length ? ramps : DEFAULT_RAMPS) : null; + el.querySelector(".drive-panel__note").textContent = `${vehicle.name || "Car"} · ${wheelbase.toFixed(2)} × ${track.toFixed(2)} m${guessed ? " (guessed: set the wheelbase and track in the profile)" : ""} · ${steps ? `ramps ${steps.join(" · ")} cm` : "jacks"}`; + el.querySelector('[data-action="under"]').textContent = steps ? `Ramps ${steps.join(" · ")} cm ▸` : "Jacks ▸"; + const zero = el.querySelector('[data-action="zero"]'); + const action = (dash?.actions || []).findIndex((a) => /level/i.test(a.name)); + zero.disabled = action < 0; + zero.title = action < 0 ? "No levelling action in can.json" : "Take this as level (the node's SDO): only on known level ground"; + zero.textContent = armed ? "Tap again to zero" : "Zero here"; + zero.classList.toggle("drive-terrain__level--armed", !!armed); + + if (v.roll == null || v.pitch == null) { + el.querySelector(".drive-level__plan").innerHTML = ""; + el.querySelector(".drive-level__bubble").innerHTML = ""; + for (const f of ["roll", "pitch", "after"]) field(f, f, "—", ""); + el.querySelector(".drive-level__advice").textContent = "No tilt signal (the IMU node)"; + return; + } + const { roll, pitch } = v; + const plan = levelPlan(roll, pitch, wheelbase, track, steps); + const level = Math.abs(roll) < LEVEL_TOL && Math.abs(pitch) < LEVEL_TOL; + const over = Object.values(plan.wheels).some((w) => w.over); + const lifted = Object.values(plan.wheels).filter((w) => (steps ? w.used : w.cm) >= 0.5).length; + const labels = Object.entries(WHEELS).map(([k, [fx, sy]]) => { + const w = plan.wheels[k]; + const cm = steps ? w.used : w.cm; + const none = cm < 0.5; + const x = sy * 80, y = -fx * 78; + const cls = none ? "drive-level__none" : w.over ? "drive-level__over" : "drive-level__lift"; + return ` + ${none ? "0" : `+${Math.round(cm)} cm`} + ${none ? "stays" : steps ? `step ${w.step}${w.over ? " · not enough" : ""}` : `${w.cm.toFixed(1)} cm`}`; + }).join(""); + el.querySelector(".drive-level__plan").innerHTML = ` + FRONT + + ${labels}`; + const scale = 23; // 2° to the inner ring + const clamp = (n) => Math.max(-80, Math.min(80, n)); + el.querySelector(".drive-level__bubble").innerHTML = ` + + + + front + ring 2° · green ±${LEVEL_TOL}°`; + field("roll", "Roll", deg(roll), roll > 0 ? "right side low" : roll < 0 ? "left side low" : "", Math.abs(roll) < LEVEL_TOL); + field("pitch", "Pitch", deg(pitch), pitch < 0 ? "nose low" : pitch > 0 ? "nose high" : "", Math.abs(pitch) < LEVEL_TOL); + const afterOk = Math.abs(plan.roll) < LEVEL_TOL && Math.abs(plan.pitch) < LEVEL_TOL; + field("after", steps ? "On the ramps" : "Then", `${deg(plan.roll)} / ${deg(plan.pitch)}`, "roll / pitch", afterOk); + const advice = el.querySelector(".drive-level__advice"); + advice.className = `drive-panel__cell drive-level__advice${level ? " drive-level--ok" : over ? " drive-level--over" : ""}`; + advice.textContent = level ? `Level — within ±${LEVEL_TOL}° both ways.` + : over ? "Past the ramps' top step: another spot, or turn the car so the slope runs along it." + : `${steps ? "Drive" : "Jack"} ${lifted === 1 ? "that wheel" : "those wheels"} up${steps ? " the ramps" : ""}; the numbers follow as the car moves.`; + } + + el.querySelector(".drive-panel__close").addEventListener("click", ctx.close); + el.querySelector('[data-action="terrain"]').addEventListener("click", ctx.openTerrain); + el.querySelector('[data-action="under"]').addEventListener("click", () => { + try { localStorage.setItem(UNDER_KEY, under() === "ramps" ? "jacks" : "ramps"); } catch { /* private window */ } + render(); + }); + el.querySelector('[data-action="zero"]').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="zero"]').textContent = response?.ok ? "Zeroed ✓" : "Zeroing failed"; + }); + return { el, render, opened: render }; +} + +// Today (the Design canvas' GridToday): the rest of the day being driven — +// its stops still to come with their arrival, tonight's spot and the sun +// there, the weather (Open-Meteo: here now, there at arrival, there tonight), +// the day's notes and the Check's items for it. Tomorrow ▸ pages ahead. +const WEATHER_TTL_MS = 30 * 60 * 1000; +const weatherCache = new Map(); +const WEATHER = [[0, "☀", "clear"], [3, "⛅", "cloudy"], [48, "🌫", "fog"], [67, "🌧", "rain"], [77, "🌨", "snow"], [82, "🌦", "showers"], [86, "🌨", "snow showers"], [99, "⛈", "storm"]]; +const weatherText = (code) => WEATHER.find(([max]) => code <= max) || WEATHER.at(-1); + +async function forecast([lon, lat]) { + const key = `${lat.toFixed(1)},${lon.toFixed(1)}`; // ~10 km: not a request every km driven + const hit = weatherCache.get(key); + if (hit && Date.now() - hit.at < WEATHER_TTL_MS) return hit.data; + const url = `https://api.open-meteo.com/v1/forecast?${new URLSearchParams({ latitude: lat.toFixed(1), longitude: lon.toFixed(1), hourly: "temperature_2m,weather_code", forecast_days: 3, timezone: "auto", timeformat: "unixtime" })}`; + const data = await (await fetch(url)).json(); + weatherCache.set(key, { at: Date.now(), data }); + return data; +} + +// The forecast's hour nearest t (ms), or the lowest between from and to. +function hourAt(data, t) { + const times = data?.hourly?.time || []; + let best = -1; + times.forEach((s, i) => { if (best < 0 || Math.abs(s * 1000 - t) < Math.abs(times[best] * 1000 - t)) best = i; }); + return best < 0 ? null : { temp: data.hourly.temperature_2m[best], code: data.hourly.weather_code[best] }; +} + +function lowest(data, from, to) { + const times = data?.hourly?.time || []; + const temps = times.map((s, i) => (s * 1000 >= from && s * 1000 <= to ? data.hourly.temperature_2m[i] : null)).filter((v) => v != null); + return temps.length ? Math.min(...temps) : null; +} + +export function todayMenu(ctx) { + const el = panel("drive-today", "Today", ` +
+
+
+
+
+
+
+ + + `); + let page = 0; // days after the one being driven + const clock = (ms) => new Date(ms).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); + const label = (text) => `${escapeHtml(text)}`; + + function render() { + if (el.hidden || !ctx.routePanel) return; + const { stops, days, check } = ctx.routePanel.plan(); + const ahead = stops.filter((s) => s.index > 0 && !s.passed && !s.behind); + const current = ahead[0]?.day ?? Math.max(0, days - 1); + const day = Math.min(current + page, days - 1); + const left = stops.filter((s) => s.index > 0 && s.day === day && (page > 0 || (!s.passed && !s.behind))); + const first = stops.find((s) => s.day === day || (s.night && s.day === day - 1)); // the day leaves from here + const dayFirst = stops.find((s) => s.day === day && (s.index === 0 || stops[s.index - 1].night)); // its note is on this one + const date = first?.leave != null ? new Date(first.leave).toLocaleDateString([], { weekday: "short", day: "numeric", month: "numeric" }) : ""; + el.querySelector(".drive-panel__note").textContent = [days > 1 ? `Day ${day + 1} of ${days}` : "", date].filter(Boolean).join(" · "); + el.querySelector('[data-action="prev"]').disabled = page === 0; + el.querySelector('[data-action="next"]').disabled = day >= days - 1; + el.querySelector('[data-action="skip"]').disabled = page > 0 || !ahead.length; + + // arrival: planned, else from now over the legs still to drive + let sum = 0; + const eta = new Map(ahead.map((s) => [s.index, (sum += (s.leg?.s || 0) * 1000 + (s.stay || 0) * 60000) - (s.stay || 0) * 60000])); + const arriveAt = (s) => s.arrive ?? (eta.has(s.index) ? Date.now() + eta.get(s.index) : null); + el.querySelector(".drive-today__stops").replaceChildren(...(left.length ? left.map((s) => { + const row = document.createElement("div"); + row.className = "drive-today__stop"; + const icon = NPS_SYMBOLS[s.type] || `${String.fromCharCode(65 + (s.index % 26))}`; + const at = arriveAt(s); + row.innerHTML = `${icon} + ${at != null ? clock(at) : "–"}${s.leg ? `${s.leg.km.toFixed(0)} km` : ""}`; + row.querySelector("b").textContent = s.name || `${s.lngLat[1].toFixed(4)}, ${s.lngLat[0].toFixed(4)}`; + row.querySelector("small").textContent = [STOP_TYPES[s.type], s.night ? "night" : s.stay ? `stay ${formatDuration(s.stay * 60)}` : "", s.park ? `${s.park.name || "parking"} apart` : ""].filter(Boolean).join(" · "); + return row; + }) : [emptyRow(page ? "No stops that day" : "Nothing left today")])); + + // tonight: the day's night spot (or the end) + const night = stops.find((s) => s.day === day && (s.night || s.index === stops.length - 1)) || stops.at(-1); + const tonight = el.querySelector(".drive-today__tonight"); + const sun = el.querySelector(".drive-today__sun"); + if (night) { + tonight.innerHTML = `${label("Tonight")}`; + tonight.querySelector(".drive-today__line").textContent = [night.name || "the end", night.note].filter(Boolean).join(" · "); + const at = arriveAt(night); + const t = getTimes(new Date(at ?? Date.now()), night.lngLat[1], night.lngLat[0]); + const late = at != null && at > t.sunset.getTime(); + sun.innerHTML = `${label("Sunset · dark")}${clock(t.sunset)} · ${clock(t.dusk)}${at != null ? ` · arrive ${clock(at)}` : ""}`; + } else { + tonight.innerHTML = ""; + sun.innerHTML = ""; + } + + // the day's note, the stops' notes still to come, the Check's items for that day + const notes = [ + ...(dayFirst?.day_note ? [["", dayFirst.day_note]] : []), + ...left.filter((s) => s.note).map((s) => [s.name ? `${s.name}: ` : "", s.note]), + ...check.filter((c) => c.day === day && c.level !== "info").map((c) => ["! ", c.what]), + ]; + el.querySelector(".drive-today__notes").replaceChildren(...(notes.length ? notes.map(([who, text]) => { + const p = document.createElement("p"); + p.className = who === "! " ? "drive-today__warn" : ""; + p.textContent = `${who}${text}`; + return p; + }) : [emptyRow("No notes for the day")])); + + renderWeather(night, arriveAt(night || {}) ?? null); + } + + async function renderWeather(night, arrive) { + const cells = [...el.querySelectorAll(".drive-today__weather")]; + const here = ctx.position(); + const show = (i, title, temp, code, sub) => { + const [, glyph, text] = code != null ? weatherText(code) : [0, "", ""]; + cells[i].innerHTML = `${label(title)}${glyph} ${temp != null ? `${Math.round(temp)}°` : "–"}${escapeHtml(sub ?? text)}`; + }; + try { + const now = hourAt(await forecast(here), Date.now()); + show(0, "Now · here", now?.temp, now?.code); + if (!night) return; + const there = await forecast(night.lngLat); + const at = hourAt(there, arrive ?? Date.now()); + show(1, "Arrival · there", at?.temp, at?.code); + const evening = new Date(arrive ?? Date.now()); + evening.setHours(20, 0, 0, 0); + const low = lowest(there, evening.getTime(), evening.getTime() + 12 * 3600 * 1000); + show(2, "Tonight · there", low, null, "lowest till 08:00"); + } catch { + cells.forEach((c, i) => (c.innerHTML = i ? "" : `${label("Weather")}offline`)); + } + } + + el.querySelector(".drive-panel__close").addEventListener("click", ctx.close); + el.querySelector('[data-action="skip"]').addEventListener("click", () => { + const { stops } = ctx.routePanel.plan(); + const next = stops.find((s) => s.index > 0 && !s.passed && !s.behind); + if (next && next.index < stops.length - 1) ctx.routePanel.togglePassed(next.index); + }); + el.querySelector('[data-action="prev"]').addEventListener("click", () => { page = Math.max(0, page - 1); render(); }); + el.querySelector('[data-action="next"]').addEventListener("click", () => { page++; render(); }); + ctx.routePanel?.onStopsChanged(() => render()); + return { el, render, opened: () => { page = 0; render(); } }; +} diff --git a/public/js/driving.js b/public/js/driving.js index 21bbf59..ce6f160 100644 --- a/public/js/driving.js +++ b/public/js/driving.js @@ -7,7 +7,7 @@ import { watchDashboard, maneuverSvg, laneSvg, distance, VOICE_KEY } from "/js/d import { SPEED_LIMITS, COUNTRY_NAMES, isHeavy, motorwayPayment } from "/js/speed_limits.js"; import { currentVehicle, onVehicle } from "/js/panels.js"; import { formatSunInfo } from "/js/sun.js"; -import { pointsMenu, layersMenu, terrainMenu, elevationHtml, cellButton, bindKey, emptyRow as empty, escapeHtml } from "/js/drive_menus.js"; +import { pointsMenu, layersMenu, terrainMenu, levelMenu, recordingMenu, todayMenu, elevationHtml, cellButton, bindKey, emptyRow as empty, escapeHtml } from "/js/drive_menus.js"; // 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 @@ -91,7 +91,7 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) { tripPanel.innerHTML = `
Trip
-
Recording
+
@@ -105,6 +105,7 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) { menuPanel.hidden = true; menuPanel.innerHTML = `
Menu
+ @@ -145,6 +146,7 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) { onVehicle(renderProfile); renderProfile(); menuPanel.querySelector('[data-action="overview"]').addEventListener("click", overview); + menuPanel.querySelector('[data-action="today"]').addEventListener("click", () => open(today.el)); menuPanel.querySelector('[data-action="leave"]').addEventListener("click", () => set(false)); const crosshair = document.createElement("div"); crosshair.className = "drive-crosshair"; @@ -247,8 +249,15 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) { }; const points = pointsMenu(menuCtx); const layers = layersMenu(menuCtx); - const terrain = terrainMenu({ ...menuCtx, state: () => dash }); - const menus = [points, layers, terrain]; + const terrain = terrainMenu({ ...menuCtx, state: () => dash, openLevel: () => open(level.el) }); + const level = levelMenu({ ...menuCtx, state: () => dash, openTerrain: () => open(terrain.el) }); + const recording = recordingMenu({ + ...menuCtx, + showBounds: ([w, s, e, n]) => { pauseFollow(map); map.fitBounds([[w, s], [e, n]], { padding: 60, pitch: 0, maxZoom: 15 }); }, + endTrip: () => endTrip(), + }); + const today = todayMenu(menuCtx); + const menus = [points, layers, terrain, level, recording, today]; let offRoad = false; let tiltSince = null; let pavedM = 0; @@ -282,6 +291,7 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) { autoOpened = false; } if (panel !== tripPanel && results) backToStops(); // the pins go with the search + menus.find((m) => m.el === openPanel && m.el !== panel)?.closed?.(); openPanel = panel; row = 0; tripPanel.hidden = panel !== tripPanel; @@ -344,17 +354,20 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) { 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); }; + const endTrip = async () => { + if (!log?.active || !window.confirm(`End the trip "${log.folder}"? Its track stays in the library.`)) return; + await fetch("/api/trip/log", { method: "DELETE" }); + driven = []; + refreshLog(); + }; + tripPanel.querySelector('[data-action="recording"]').addEventListener("click", () => open(recording.el)); logButton.addEventListener("click", async () => { - if (log?.active) { - if (!window.confirm(`End the trip "${log.folder}"? Its track stays in the library.`)) return; - await fetch("/api/trip/log", { method: "DELETE" }); - } else { - const ends = routePanel?.stops().at(-1)?.name || ""; - const name = window.prompt("The trip's name:", ends); - if (name === null) return; - const response = await fetch("/api/trip/log", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }) }); - if (!response.ok) window.alert((await response.json().catch(() => ({}))).error || `HTTP ${response.status}`); - } + if (log?.active) return endTrip(); + const ends = routePanel?.stops().at(-1)?.name || ""; + const name = window.prompt("The trip's name:", ends); + if (name === null) return; + const response = await fetch("/api/trip/log", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }) }); + if (!response.ok) window.alert((await response.json().catch(() => ({}))).error || `HTTP ${response.status}`); driven = []; refreshLog(); }); @@ -365,7 +378,7 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) { logState.textContent = "Log in to record"; } map.getContainer().append(crosshair); - app.append(tripPanel, menuPanel, points.el, layers.el, terrain.el); + app.append(tripPanel, menuPanel, points.el, layers.el, terrain.el, level.el, recording.el, today.el); // --- the grid's cells --------------------------------------------------- @@ -567,6 +580,7 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) { function render() { if (!document.documentElement.classList.contains("driving")) return; if (openPanel === terrain.el) terrain.render(); + if (openPanel === level.el) level.render(); const a = ahead(); for (const { cell, el } of cells) { if (cell.widget === "field") { diff --git a/public/js/plugins.js b/public/js/plugins.js index a45674b..fc20d6f 100644 --- a/public/js/plugins.js +++ b/public/js/plugins.js @@ -1,6 +1,9 @@ import { PLUGIN_ICON } from "/js/icons.js"; import { notifyGpxStoreChanged, notifySidePanelOpen, onlyOneSidePanelOpen } from "/js/panels.js"; +const CORRIDORS_KM = [1, 2, 5, 10, 20]; +const CORRIDOR_KEY = "maptool.pluginCorridorKm"; + // A side panel (#plugins-panel) listing whatever import plugins are on disk (see // lib/maptool/plugins.rb for the contract) — each one just a "Run for // this area" button using the current map viewport as the bbox, so there's @@ -56,28 +59,65 @@ export class PluginsControl { plugins.forEach((plugin) => this._list.appendChild(this._renderItem(plugin))); } + // Per plugin: "Run for this area"; with "route" in its plugin.json also + // "Along the trip's route" N km either side (the corridor remembered); with + // "settings" (a login cookie) their fields — a value set shows as "set", + // never sent back from the server. _renderItem(plugin) { const li = document.createElement("li"); li.className = "plugins-panel__item"; li.innerHTML = ` + ${plugin.route ? ` + ` : ""} + ${plugin.settings?.length ? `
Settings${plugin.settings.map(() => ``).join("")} +
` : ""} `; li.querySelector(".plugins-panel__label").textContent = plugin.label; const button = li.querySelector(".plugins-panel__run"); const status = li.querySelector(".plugins-panel__status"); button.addEventListener("click", () => this._run(plugin, button, status)); + const routeButton = li.querySelector(".plugins-panel__run--route"); + if (routeButton) { + const corridor = li.querySelector(".plugins-panel__corridor"); + corridor.value = localStorage.getItem(CORRIDOR_KEY) || "5"; + corridor.addEventListener("change", () => localStorage.setItem(CORRIDOR_KEY, corridor.value)); + routeButton.addEventListener("click", () => this._run(plugin, routeButton, status, { route: "1", corridor_km: corridor.value })); + } + const fields = [...li.querySelectorAll(".plugins-panel__setting")]; + fields.forEach((label, i) => { + const field = plugin.settings[i]; + label.querySelector("span").textContent = field.label || field.key; + label.querySelector("small").textContent = field.help || ""; + label.querySelector("input").placeholder = plugin.set?.includes(field.key) ? "set — paste to replace" : "not set"; + }); + li.querySelector(".plugins-panel__save")?.addEventListener("click", async () => { + const values = Object.fromEntries(plugin.settings.map((f, i) => [f.key, fields[i].querySelector("input").value]).filter(([, v]) => v)); + try { + const response = await fetch(`/api/plugins/${encodeURIComponent(plugin.name)}/settings`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(values) }); + const data = await response.json().catch(() => ({})); + if (!response.ok) throw new Error(data.error || `save failed: ${response.status}`); + plugin.set = data.set; + fields.forEach((label, i) => { const input = label.querySelector("input"); input.value = ""; input.placeholder = data.set.includes(plugin.settings[i].key) ? "set — paste to replace" : "not set"; }); + status.textContent = "Settings saved"; + status.classList.remove("plugins-panel__status--error"); + } catch (err) { + status.textContent = err.message; + status.classList.add("plugins-panel__status--error"); + } + }); return li; } - async _run(plugin, button, status) { + async _run(plugin, button, status, along = null) { button.disabled = true; status.textContent = "Running…"; try { const bounds = this._map.getBounds(); - const body = new URLSearchParams({ + const body = new URLSearchParams(along || { south: bounds.getSouth(), west: bounds.getWest(), north: bounds.getNorth(), @@ -91,7 +131,7 @@ export class PluginsControl { const data = await response.json().catch(() => ({})); if (!response.ok) throw new Error(data.error || `run failed: ${response.status}`); notifyGpxStoreChanged(data.path); - status.textContent = "Done"; + status.textContent = `Done · ${data.count} found`; status.classList.remove("plugins-panel__status--error"); } catch (err) { // Plugins::RunError's message (e.g. "plugin exited with status 1") diff --git a/public/js/route.js b/public/js/route.js index efe12b4..3575772 100644 --- a/public/js/route.js +++ b/public/js/route.js @@ -1,10 +1,11 @@ import { Marker, Popup } from "/vendor/maplibre-gl/maplibre-gl.mjs"; -import { ROUTE_ICON, REVERSE_ICON, CLEAR_ICON } from "/js/icons.js"; +import { ROUTE_ICON, REVERSE_ICON, CLEAR_ICON, NPS_SYMBOLS } from "/js/icons.js"; import { notifySidePanelOpen, onlyOneSidePanelOpen, notifyGpxStoreChanged, onRoutePoint, onRouteEdit, notifyRouteChanged, onReroute, onRouteProgress, notifyVehicle } from "/js/panels.js"; import { isLoggedIn } from "/js/auth.js"; import { SPEED_LIMITS, isHeavy, motorwayPayment } from "/js/speed_limits.js"; import { wirePreview } from "/js/preview.js"; import { elevationAt } from "/js/dem.js"; +import { getTimes } from "/vendor/suncalc/suncalc.js"; const ROUTE_URL = "/api/route"; // Logged in, the panel edits this server's shared trip (lib/maptool/trip.rb) @@ -26,10 +27,32 @@ const profileMeta = (v) => ? [v.height && `${v.height} m`, v.weight && `${v.weight} t`].filter(Boolean).join(" · ") : [v.speed && `${v.speed} km/h`, v.sac && `up to T${v.sac}`].filter(Boolean).join(" · "); const AVOID_KEY = "maptool.routeAvoid"; -const DAY_COLORS = ["#a21caf", "#1d6fdc", "#c2410c", "#2a9d8f", "#b45309"]; +export const DAY_COLORS = ["#a21caf", "#1d6fdc", "#c2410c", "#2a9d8f", "#b45309"]; const clock = (ms) => new Date(ms).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); const escapeText = (text) => String(text).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]); const NOTES_URL = "/api/library/notes"; + +// A stop's type: the NPS pictogram shown on its marker and in the list (the +// Design canvas' Plan). The key is the symbol's name, as a library point's icon. +export const STOP_TYPES = { + "point-of-interest": "Sight", + "food-service": "Food", + "coffee": "Break", + "parking": "Parking", + "gas-station": "Fuel", + "vehicle-ferry": "Ferry", + "campground": "Campsite", + "campsite": "Wild night", + "mechanic": "Service", + "residential-building": "Home", +}; +// What a stop keeps in the shared trip (the marker and editing state stay here). +const stopData = ({ lngLat, name, nav, passed, night, stay, note, type, day_note, park, avoid, cost, paid }) => ({ lngLat, name, nav, passed, night, stay, note, type, day_note, park, avoid, cost, paid }); +// what a route can avoid (Routing.costing), the trip's and a day's own +const AVOIDS = { tolls: "Tolls", highways: "Motorways", ferries: "Ferries", unpaved: "Unpaved" }; +const WALK_SOURCE = "route-walks"; +const MAX_DAY_DRIVING_S = 8 * 3600; // the Check: a longer day is a warning +const MAX_WALK_M = 1500; const SOURCE = "route"; const COLOR = "#1d6fdc"; const SAVE_FOLDER = "Routes"; @@ -77,16 +100,38 @@ export class RoutePanelControl { }); onRoutePoint(({ lngLat, name }) => { this._setOpen(true); + // with no + picked: on the leg it lengthens least, not past the end + if (this._insertAt == null && this._points.length >= 2) { + let best = Infinity; + for (let i = 1; i < this._points.length; i++) { + if (this._points[i].passed) continue; + const [a, b] = [this._points[i - 1].lngLat, this._points[i].lngLat]; + const detour = distanceM(a, lngLat) + distanceM(lngLat, b) - distanceM(a, b); + if (detour < best) [best, this._insertAt] = [detour, i]; + } + const end = this._points.at(-1).lngLat; + if (distanceM(end, lngLat) < best) this._insertAt = null; // further on: a new end + } this._addPoint(lngLat, name); }); onRouteEdit(({ key, feature }) => this._edit(key, feature)); map.on("click", (event) => { if (this._panel.hidden || event.originalEvent.altKey) return; + if (this._parkFor) { + // the stop's parking spot picked: the route goes there now + this._parkFor.park = { lngLat: [event.lngLat.lng, event.lngLat.lat] }; + this._parkFor = null; + this._changed(); + return; + } this._addPoint([event.lngLat.lng, event.lngLat.lat]); }); // setStyle() (base map switch) drops custom sources. - map.on("style.load", () => this._draw()); + map.on("style.load", () => { + this._draw(); + this._drawParking(); + }); } mount(sidebar) { @@ -116,8 +161,8 @@ export class RoutePanelControl { for (const [action, icon] of Object.entries(icons)) this._panel.querySelector(`[data-action="${action}"]`).insertAdjacentHTML("afterbegin", icon); this._setupSavedPoints(); this._editingNote = this._panel.querySelector(".route-panel__editing"); - this._itinerary = { name: null, start: null, day_start: null }; - this._tripInputs = [...this._panel.querySelectorAll(".route-panel__trip input")]; + this._itinerary = { name: null, start: null, day_start: null, note: null, budget: null, fuel_price: null }; + this._tripInputs = [...this._panel.querySelectorAll(".route-panel__trip input, .route-panel__trip textarea")]; this._tripInputs.forEach((input) => input.addEventListener("change", () => { this._itinerary[input.name] = input.value.trim() || null; this._itineraryChanged(); @@ -173,7 +218,7 @@ export class RoutePanelControl { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ - points: this._points.map(({ lngLat, name, nav, passed, night, stay, note }) => ({ lngLat, name, nav, passed, night, stay, note })), + points: this._points.map(stopData), vehicle: this._vehicleId, avoid: this._avoid, editing: this._editing, @@ -197,12 +242,12 @@ export class RoutePanelControl { const first = this._version < 0; this._version = trip.version; if (fromElsewhere) { - const before = this._points.map(({ lngLat, name, nav, passed, night, stay, note }) => ({ lngLat, name, nav, passed, night, stay, note })); + const before = this._points.map(stopData); const beforeItinerary = { ...this._itinerary }; this._points.forEach((p) => p.marker.remove()); this._points = []; - trip.points.forEach((p) => this._addPoint(p.lngLat, p.name, { quiet: true, nav: !!p.nav, passed: !!p.passed, night: p.night, stay: p.stay, note: p.note })); - this._itinerary = { name: trip.name || null, start: trip.start || null, day_start: trip.day_start || null }; + trip.points.forEach((p) => this._addPoint(p.lngLat, p.name, { ...p, quiet: true, nav: !!p.nav, passed: !!p.passed })); + this._itinerary = { name: trip.name || null, start: trip.start || null, day_start: trip.day_start || null, note: trip.note || null, budget: trip.budget ?? null, fuel_price: trip.fuel_price ?? null }; this._tripInputs.forEach((input) => (input.value = this._itinerary[input.name] || "")); if (!first) this._showRemoteChange(before, beforeItinerary); // the first load isn't another screen's change this._editing = trip.editing; @@ -233,11 +278,11 @@ export class RoutePanelControl { // A named place (a saved point, a search result) is shown in navigation // by default; a plain map click only shapes the route. - _addPoint(lngLat, name, { quiet = false, nav = !!name && name !== "My position", passed = false, night, stay, note } = {}) { + _addPoint(lngLat, name, { quiet = false, nav = !!name && name !== "My position", passed = false, night, stay, note, type, day_note, park, avoid, cost, paid } = {}) { const element = document.createElement("div"); element.className = "route-marker"; const marker = new Marker({ element, draggable: true }).setLngLat(lngLat).addTo(this._map); - const point = { lngLat, name, nav, marker, night: night || undefined, stay: stay || undefined, note: note || undefined }; + const point = { lngLat, name, nav, marker, night: night || undefined, stay: stay || undefined, note: note || undefined, type: type || undefined, day_note: day_note || undefined, park: park || undefined, avoid: avoid || undefined, cost: cost ?? undefined, paid: paid ?? undefined }; this._setPassed(point, passed); marker.on("dragend", () => { const { lng, lat } = marker.getLngLat(); @@ -245,7 +290,9 @@ export class RoutePanelControl { point.name = null; // no longer that place this._changed(); }); - this._points.push(point); + if (!quiet && this._insertAt != null && this._insertAt < this._points.length) this._points.splice(this._insertAt, 0, point); + else this._points.push(point); + if (!quiet) this._insertAt = null; if (!quiet) this._changed(); } @@ -293,6 +340,19 @@ export class RoutePanelControl { leg: this._leg(i), passed: p.passed, behind: this._behind(i) })); } + // For the driving mode's Today (drive_menus.js): every stop with its plan + // (planned arrive / leave in ms, the day), the leg to it, behind the car or + // not; the trip's itinerary and the Check's items. + plan() { + const schedule = this._schedule(); + return { + stops: this._points.map((p, i) => ({ ...stopData(p), ...schedule[i], index: i, leg: this._leg(i), behind: this._behind(i) })), + days: (schedule.at(-1)?.day ?? 0) + 1, + itinerary: { ...this._itinerary }, + check: this._check(schedule), + }; + } + togglePassed(index) { const point = this._points[index]; if (!point) return; @@ -439,7 +499,7 @@ export class RoutePanelControl { const now = this._points; const keys = new Set(before.map(key)); const added = now.find((p) => !keys.has(key(p))); - const changed = added || now.find((p, i) => JSON.stringify([p.name, p.night, p.stay, p.note]) !== JSON.stringify([before[i]?.name, before[i]?.night, before[i]?.stay, before[i]?.note])); + const changed = added || now.find((p, i) => JSON.stringify(stopData(p)) !== JSON.stringify(before[i])); const removed = now.length < before.length; if (!changed && !removed && JSON.stringify(beforeItinerary) === JSON.stringify(this._itinerary)) return; const at = (changed || now[0] || before[0])?.lngLat; @@ -454,7 +514,7 @@ export class RoutePanelControl { this._remotePopup.remove(); this._points.forEach((p) => p.marker.remove()); this._points = []; - before.forEach((p) => this._addPoint(p.lngLat, p.name, { quiet: true, nav: !!p.nav, passed: !!p.passed, night: p.night, stay: p.stay, note: p.note })); + before.forEach((p) => this._addPoint(p.lngLat, p.name, { ...p, quiet: true, nav: !!p.nav, passed: !!p.passed })); this._itinerary = { ...beforeItinerary }; this._tripInputs.forEach((input) => (input.value = this._itinerary[input.name] || "")); this._changed(); @@ -472,16 +532,28 @@ export class RoutePanelControl { const schedule = this._schedule(); const days = schedule.at(-1)?.day ?? 0; this._points.forEach((point, index) => { - if (days > 0 && (index === 0 || this._points[index - 1].night)) this._list.appendChild(this._dayHeader(schedule[index].day, index, schedule)); + if (days > 0 && (index === 0 || this._points[index - 1].night)) this._dayHeader(schedule[index].day, index, schedule); const letter = String.fromCharCode(65 + (index % 26)); const role = index === 0 ? "Start" : index === last ? "End" : `Via ${index}`; - point.marker.getElement().textContent = letter; + const icon = NPS_SYMBOLS[point.type]; + if (icon) point.marker.getElement().innerHTML = icon; + else point.marker.getElement().textContent = letter; const leg = this._leg(index); - if (leg) { - this._list.appendChild(Object.assign(document.createElement("li"), { - className: "route-panel__leg", - textContent: `${leg.km.toFixed(1)} km${leg.s != null ? ` · ${formatDuration(leg.s)}` : ""}`, - })); + if (index > 0) { + // + inserts the next point added (map click, search, saved point, my position) here + const row = Object.assign(document.createElement("li"), { className: "route-panel__leg" }); + const inserting = this._insertAt === index; + row.append( + Object.assign(document.createElement("span"), { + textContent: inserting ? "Click the map, search or pick a saved point" : leg ? `${leg.km.toFixed(1)} km${leg.s != null ? ` · ${formatDuration(leg.s)}` : ""}` : "", + }), + this._pointButton(inserting ? "×" : "+", inserting ? "Cancel" : "Insert a stop here", true, () => { + this._insertAt = inserting ? null : index; + this._renderPoints(); + }), + ); + row.classList.toggle("route-panel__leg--insert", inserting); + this._list.appendChild(row); } const li = document.createElement("li"); li.className = "route-panel__stop"; @@ -503,7 +575,8 @@ export class RoutePanelControl { this._points.splice(index, 0, ...this._points.splice(from, 1)); this._changed(); }); - const badge = Object.assign(document.createElement("span"), { className: "route-panel__badge", textContent: letter }); + const badge = Object.assign(document.createElement("span"), { className: "route-panel__badge", textContent: letter, title: STOP_TYPES[point.type] || "" }); + if (icon) badge.innerHTML = icon; badge.classList.toggle("route-panel__badge--end", index === last && last > 0); const text = document.createElement("span"); text.className = "route-panel__point"; @@ -514,13 +587,17 @@ export class RoutePanelControl { const { arrive, leave } = schedule[index]; const time = Object.assign(document.createElement("span"), { className: "route-panel__time", textContent: [arrive, point.night ? null : leave].filter((t) => t != null).map(clock).join("–") }); + if (point.park) { + text.appendChild(Object.assign(document.createElement("span"), { className: "route-panel__park", + textContent: `${point.park.name || "Parking"} · ${walk(point)} walk` })); + } if (point.note) text.appendChild(Object.assign(document.createElement("span"), { className: "route-panel__note", textContent: point.note })); const night = this._pointButton("☾", "Night stop: the day ends here", index > 0 && index < last, () => { point.night = point.night ? undefined : true; this._itineraryChanged(); }); night.classList.toggle("route-panel__on", !!point.night); - const edit = this._pointButton("✎", "Stay and note", true, () => { + const edit = this._pointButton("✎", "Type, stay and note", true, () => { point.editingNote = !point.editingNote; this._renderPoints(); }); @@ -531,6 +608,9 @@ export class RoutePanelControl { this._list.appendChild(li); if (point.editingNote) this._list.appendChild(this._noteEditor(point)); }); + this._drawParking(); + this._renderCheck(schedule); + this._renderCosts(); this._stopListeners?.forEach((callback) => callback()); this._editingNote.hidden = !this._editing; if (this._editing) this._editingNote.textContent = `Editing "${this._editing.name}"`; @@ -575,7 +655,96 @@ export class RoutePanelControl { return button; } - // A day's header: its date (from when it leaves), km and driving time. + // Is the trip ready: [{ level: "bad" | "warn" | "info", what, index }] + // (index: the stop it's about, or null), the worst first, then by day. + _check(schedule) { + const out = []; + const last = this._points.length - 1; + if (last < 1) return out; + const days = (schedule.at(-1)?.day ?? 0) + 1; + const dayName = (d) => (days > 1 ? `Day ${d + 1}: ` : ""); + if (!this._itinerary.start) out.push({ level: "info", what: "No leave time: the planned times are unknown", index: null, day: 0 }); + // driving per day + const driving = new Array(days).fill(0); + this._points.forEach((_, i) => { if (i > 0) driving[schedule[i - 1].day] += this._leg(i)?.s || 0; }); + driving.forEach((s, d) => { if (s > MAX_DAY_DRIVING_S) out.push({ level: "warn", what: `${dayName(d)}${formatDuration(s)} driving`, index: null, day: d }); }); + this._points.forEach((p, i) => { + const name = p.name || `Stop ${String.fromCharCode(65 + (i % 26))}`; + const { arrive, day } = schedule[i]; + // a night spot reached after dark + if ((p.night || i === last) && arrive != null && !p.passed) { + const sunset = getTimes(new Date(arrive), p.lngLat[1], p.lngLat[0]).sunset; + if (!Number.isNaN(sunset?.getTime()) && arrive > sunset.getTime()) { + out.push({ level: "warn", what: `${dayName(day)}${name}: arriving ${clock(arrive)}, after sunset (${clock(sunset.getTime())})`, index: i, day }); + } + } + if (p.park && distanceM(p.park.lngLat, p.lngLat) * 1.25 > MAX_WALK_M) out.push({ level: "info", what: `${name}: ${walk(p)} from the parking`, index: i, day }); + }); + // motorways in a country the profile has no vignette / toll unit for + for (const { code, motorway_km: motorway } of this._route?.properties.countries || []) { + const pay = motorwayPayment(code, this._vehicle); + if (pay.how && motorway > 0 && !pay.has) { + out.push({ level: "warn", what: `${code}: ${motorway.toFixed(0)} km of motorway, ${pay.until ? `the ${pay.how} ended ${pay.until}` : `no ${pay.how} in the profile`}`, index: null, day: 0 }); + } + } + const rank = { bad: 0, warn: 1, info: 2 }; + return out.sort((a, b) => rank[a.level] - rank[b.level] || a.day - b.day); + } + + _renderCheck(schedule) { + const fold = this._panel.querySelector(".route-panel__check"); + const items = this._check(schedule); + fold.hidden = this._points.length < 2; + const count = (level) => items.filter((x) => x.level === level).length; + fold.querySelector(".route-panel__fold-meta").textContent = + items.length ? [[count("bad"), "✗"], [count("warn"), "!"], [count("info"), "i"]].filter(([n]) => n).map(([n, m]) => `${n} ${m}`).join(" · ") : "ready ✓"; + fold.classList.toggle("route-panel__check--warn", count("bad") + count("warn") > 0); + fold.querySelector("ul").replaceChildren(...items.map(({ level, what, index }) => { + const li = Object.assign(document.createElement("li"), { className: `route-panel__check-${level}` }); + li.append(Object.assign(document.createElement("span"), { textContent: what })); + if (index != null) { + li.appendChild(this._pointButton("⌖", "Show it", true, () => this._map.easeTo({ center: this._points[index].lngLat, zoom: Math.max(this._map.getZoom(), 13) }))); + } + return li; + })); + } + + // Planned (the fuel from the route's km × the profile's consumption × the + // trip's fuel price, each stop's costs) vs paid, against the budget. + _renderCosts() { + const fold = this._panel.querySelector(".route-panel__costs"); + fold.hidden = this._points.length < 2; + const euro = (n) => `${n.toFixed(n < 100 ? 2 : 0)} €`; + const rows = []; + const km = this._route?.properties.distance_km; + const uses = this._vehicle?.consumption; + const price = Number(this._itinerary.fuel_price) || 0; + let planned = 0; + if (km && uses && price) { + const fuel = (km * uses * price) / 100; + planned += fuel; + rows.push(["Fuel", `${km.toFixed(0)} km × ${uses} /100 km × ${price} €`, `≈ ${euro(fuel)}`]); + } else if (km) { + rows.push(["Fuel", uses ? "set the fuel price above" : "set the consumption in the profile", "–"]); + } + let paid = 0; + this._points.forEach((p, i) => { + if (p.cost == null && p.paid == null) return; + planned += p.cost || 0; + paid += p.paid || 0; + rows.push([p.name || `Stop ${String.fromCharCode(65 + (i % 26))}`, p.paid != null ? `paid ${euro(p.paid)}` : "planned", p.cost != null ? euro(p.cost) : "–"]); + }); + const budget = Number(this._itinerary.budget) || 0; + fold.querySelector(".route-panel__fold-meta").textContent = [planned && `≈ ${euro(planned)} planned`, paid && `${euro(paid)} paid`, budget && `${euro(budget - Math.max(planned, paid))} left`].filter(Boolean).join(" · "); + fold.querySelector("ul").replaceChildren(...rows.map(([what, how, amount]) => { + const li = document.createElement("li"); + li.append(...[what, how, amount].map((textContent) => Object.assign(document.createElement("span"), { textContent }))); + return li; + })); + } + + // A day's header (into the list): its date (from when it leaves), km and + // driving time, ✎ for the day's note, the note under it. _dayHeader(day, from, schedule) { let km = 0; let s = 0; @@ -592,15 +761,90 @@ export class RoutePanelControl { li.style.setProperty("--day", DAY_COLORS[day % DAY_COLORS.length]); li.innerHTML = `${km ? `${km.toFixed(0)} km · ${formatDuration(s)}` : ""}${leaves != null ? ` · leave ${clock(leaves)}` : ""}`; li.querySelector("b").textContent = date; - return li; + // the day's note and avoids live on its first point (the one after the night spot) + const point = this._points[from]; + if (point.avoid) { + const avoided = Object.keys(AVOIDS).filter((k) => point.avoid[k]).map((k) => AVOIDS[k].toLowerCase()); + li.querySelector("span").append(` · ${avoided.length ? `avoids ${avoided.join(", ")}` : "avoids nothing"}`); + } + li.appendChild(this._pointButton("✎", "The day's note", true, () => { + point.editingDay = !point.editingDay; + this._renderPoints(); + })); + this._list.appendChild(li); + if (point.editingDay) { + const editor = Object.assign(document.createElement("li"), { className: "route-panel__note-editor route-panel__day-note" }); + editor.style.setProperty("--day", DAY_COLORS[day % DAY_COLORS.length]); + const text = Object.assign(document.createElement("textarea"), { rows: 2, maxLength: 500, placeholder: "The day's note", value: point.day_note || "" }); + text.addEventListener("change", () => { + point.day_note = text.value.trim() || undefined; + this._itineraryChanged(); + }); + // the day's own avoids (routed apart by the server), else the trip's + const avoid = document.createElement("span"); + avoid.className = "route-panel__day-avoid"; + const own = Object.assign(document.createElement("input"), { type: "checkbox", checked: !!point.avoid }); + const boxes = Object.entries(AVOIDS).map(([key, label]) => { + const box = Object.assign(document.createElement("input"), { type: "checkbox", checked: !!(point.avoid || this._avoid)[key], disabled: !point.avoid }); + box.addEventListener("change", () => { + point.avoid = { ...point.avoid, [key]: box.checked }; + this._changed(); + }); + const wrap = document.createElement("label"); + wrap.append(box, ` ${label}`); + return wrap; + }); + own.addEventListener("change", () => { + point.avoid = own.checked ? Object.fromEntries(Object.keys(AVOIDS).map((k) => [k, !!this._avoid[k]])) : undefined; + this._changed(); + }); + const ownLabel = document.createElement("label"); + ownLabel.append(own, " This day avoids:"); + avoid.append(ownLabel, ...boxes); + editor.append(text, avoid); + this._list.appendChild(editor); + } else if (point.day_note) { + const note = Object.assign(document.createElement("li"), { className: "route-panel__note route-panel__day-note", textContent: point.day_note }); + note.style.setProperty("--day", DAY_COLORS[day % DAY_COLORS.length]); + this._list.appendChild(note); + } } - // A stop's stay (minutes) and note, under it. + // A stop's type, stay (minutes) and note, under it. _noteEditor(point) { const li = document.createElement("li"); li.className = "route-panel__note-editor"; - li.innerHTML = ``; - const [stay, note] = [li.querySelector("input"), li.querySelector("textarea")]; + li.innerHTML = ` + + Parking + `; + li.querySelectorAll(".route-panel__money input").forEach((input) => { + input.value = point[input.name] ?? ""; + input.addEventListener("change", () => { + const value = Number(input.value); + point[input.name] = input.value.trim() !== "" && value >= 0 ? Math.round(value * 100) / 100 : undefined; + this._itineraryChanged(); + }); + }); + const setPark = li.querySelector('[data-park="set"]'); + const clearPark = li.querySelector('[data-park="clear"]'); + setPark.textContent = this._parkFor === point ? "Click the map…" : point.park ? "Move: click the map" : "Set: click the map"; + clearPark.hidden = !point.park; + setPark.addEventListener("click", () => { + this._parkFor = this._parkFor === point ? null : point; + this._renderPoints(); + }); + clearPark.addEventListener("click", () => { + point.park = undefined; + this._changed(); + }); + const [type, stay, note] = [li.querySelector("select"), li.querySelector("input"), li.querySelector("textarea")]; + type.append(...Object.entries(STOP_TYPES).map(([value, label]) => new Option(label, value))); + type.value = point.type || ""; + type.addEventListener("change", () => { + point.type = type.value || undefined; + this._itineraryChanged(); + }); stay.value = point.stay || ""; note.value = point.note || ""; stay.addEventListener("change", () => { @@ -614,6 +858,28 @@ export class RoutePanelControl { return li; } + // The stops' parking spots: a P marker each (drag it to move), a dashed + // line to the place — the walk. + _drawParking() { + this._parkMarkers?.forEach((m) => m.remove()); + const parked = this._points.filter((p) => p.park); + this._parkMarkers = parked.map((point) => { + const element = Object.assign(document.createElement("div"), { className: "route-park", textContent: "P", title: point.park.name || "Parking" }); + const marker = new Marker({ element, draggable: true }).setLngLat(point.park.lngLat).addTo(this._map); + marker.on("dragend", () => { + const { lng, lat } = marker.getLngLat(); + point.park = { lngLat: [lng, lat] }; + this._changed(); + }); + return marker; + }); + if (!this._map.isStyleLoaded() && !this._map.getSource(WALK_SOURCE)) return; + const data = { type: "FeatureCollection", features: parked.map((p) => ({ type: "Feature", properties: {}, geometry: { type: "LineString", coordinates: [p.park.lngLat, p.lngLat] } })) }; + if (this._map.getSource(WALK_SOURCE)) return this._map.getSource(WALK_SOURCE).setData(data); + this._map.addSource(WALK_SOURCE, { type: "geojson", data }); + this._map.addLayer({ id: WALK_SOURCE, type: "line", source: WALK_SOURCE, paint: { "line-color": "#1d4ed8", "line-width": 2.5, "line-dasharray": [1, 1.5] } }); + } + _pointButton(text, title, enabled, onClick) { const button = document.createElement("button"); button.type = "button"; @@ -644,7 +910,7 @@ export class RoutePanelControl { const response = await fetch(ROUTE_URL, { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ locations: this._active().map((p) => p.lngLat), vehicle: this._vehicleId, avoid: this._avoid }), + body: JSON.stringify({ locations: this._active().map((p) => p.park?.lngLat || p.lngLat), vehicle: this._vehicleId, avoid: this._avoid }), }); data = await response.json().catch(() => ({})); if (!response.ok) error = data.error || `routing failed (${response.status})`; @@ -1189,6 +1455,13 @@ function distanceM([lon1, lat1], [lon2, lat2]) { return 12742000 * Math.asin(Math.sqrt(a)); } +// Parking → the place, straight (the real path ~ a quarter longer). +// ponytail: straight line ×1.25, a foot route from Valhalla if it misleads +function walk(point) { + const m = distanceM(point.park.lngLat, point.lngLat) * 1.25; + return m < 1000 ? `${Math.round(m / 10) * 10} m` : `${(m / 1000).toFixed(1)} km`; +} + export function formatDuration(seconds) { const minutes = Math.round(seconds / 60); return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h ${minutes % 60} min`; diff --git a/public/js/search.js b/public/js/search.js index 2a157ad..339a0f5 100644 --- a/public/js/search.js +++ b/public/js/search.js @@ -120,6 +120,23 @@ export class SearchControl { return; } + // A pasted link (Google Maps, park4night, a page with coordinates): + // the server reads the place from it (lib/maptool/link_place.rb) + if (/^(https?:\/\/|geo:)\S+$/i.test(query)) { + this._renderResults([], true); + try { + const response = await fetch(`/api/link?${new URLSearchParams({ url: query })}`); + const place = await response.json(); + if (!response.ok) throw new Error(response.status === 401 ? "log in to read links" : place.error); + let where = "From the link"; + try { where = `From ${new URL(place.url || query).hostname}`; } catch { /* geo: */ } + this._renderResults([{ name: place.name || `${place.lat.toFixed(5)}, ${place.lng.toFixed(5)}`, where, lat: place.lat, lng: place.lng }]); + } catch (err) { + this._renderResults([{ status: `That link: ${err.message}` }]); + } + return; + } + // Every source answers on its own; the list re-renders (nearest first // across all of them) as each one comes in. const searchId = (this._searchId = (this._searchId || 0) + 1); diff --git a/test/test_app.rb b/test/test_app.rb index 3a6923f..5285fc8 100644 --- a/test/test_app.rb +++ b/test/test_app.rb @@ -499,7 +499,7 @@ class AppTest < Minitest::Test def test_plugins_lists_whatever_is_on_disk response = request.get("/api/plugins") assert_equal 200, response.status - assert_equal [{ "name" => "test-plugin", "label" => "Test plugin" }], json_body(response) + assert_equal [{ "name" => "test-plugin", "label" => "Test plugin", "route" => false, "settings" => [], "set" => [] }], json_body(response) end def test_plugins_run_imports_the_output_into_a_folder_of_its_own @@ -516,6 +516,22 @@ class AppTest < Minitest::Test assert_equal "Test POI", saved["features"][0]["properties"]["name"] end + # Along the trip's route: what lies further off than the corridor dropped. + def test_plugins_run_along_the_route_keeps_the_corridor + store = Maptool::App::TRIP_STORE + saved = store.instance_variable_get(:@trip) + run = lambda do |line| + store.instance_variable_set(:@trip, saved.merge(route: { geometry: { coordinates: line } })) + json_body(request.post("/api/plugins/test-plugin/run", params: { route: "1", corridor_km: "2" }, **logged_in_env))["count"] + end + assert_equal 1, run.([[17.0, 47.99], [17.1, 47.99]]) # the POI ~1.1 km off + assert_equal 0, run.([[17.0, 47.95], [17.1, 47.95]]) # ~5.6 km off + store.instance_variable_set(:@trip, saved.merge(route: nil)) + assert_equal 422, request.post("/api/plugins/test-plugin/run", params: { route: "1", corridor_km: "2" }, **logged_in_env).status + ensure + store.instance_variable_set(:@trip, saved) + end + def test_plugins_run_requires_a_bbox response = request.post("/api/plugins/test-plugin/run", **logged_in_env) assert_equal 400, response.status @@ -696,6 +712,32 @@ class AppTest < Minitest::Test latest.clear end + # The recording's days and its export: a GPX with a track per day, or a .zip. + def test_trip_log_days_and_export + log = Maptool::App::TRIP_LOG + log.stop + assert_equal 200, request.post("/api/trip/log", input: JSON.generate(name: "Export test"), "CONTENT_TYPE" => "application/json", **logged_in_env).status + t0 = Time.new(2026, 12, 1, 10).to_f + 10.times { |i| log.record(17.0, 48.0 + i * 0.001, 100.0, t0 + i * 60) } + 10.times { |i| log.record(17.0, 48.1 + i * 0.001, 100.0, t0 + 10 * 3600 + i * 60) } # stood 10 h + log.record(17.0, 48.2, 100.0, t0 + 11 * 3600) + + days = json_body(request.get("/api/trip/log/days?track=1", **logged_in_env)) + assert_equal [true, 2, "auto"], [days["active"], days["days"].size, days["days"][0]["cut"]["kind"]] + assert_equal 21, days["track"].size + gpx = request.get("/api/trip/log/export?pauses=1", **logged_in_env) + assert_equal 2, gpx.body.scan("").size + assert_includes gpx.body, "Stood " + one = request.get("/api/trip/log/export?days=2", **logged_in_env).body + assert_equal 1, one.scan("").size + zip = request.get("/api/trip/log/export?per_day=1", **logged_in_env) + assert_equal "application/zip", zip.content_type + assert_equal 200, request.post("/api/trip/log/days", input: JSON.generate(join: days["track"][10][2]), "CONTENT_TYPE" => "application/json", **logged_in_env).status + assert_equal 1, json_body(request.get("/api/trip/log/days", **logged_in_env))["days"].size + ensure + log.stop + end + # A tunnel: no fix for a while, the position carried along the trip's # route — at the average speed it was entered at, by the CAN speed when there is one. def test_no_fix_on_the_route_is_dead_reckoned_along_it diff --git a/test/test_corridor.rb b/test/test_corridor.rb new file mode 100644 index 0000000..a592a1b --- /dev/null +++ b/test/test_corridor.rb @@ -0,0 +1,28 @@ +require_relative "test_helper" +require "maptool/corridor" + +class CorridorTest < Minitest::Test + C = Maptool::Corridor + # 30 km east along 48° N, as a vertex every ~0.75 km + LINE = (0..40).map { |i| [17.0 + i * 0.01, 48.0] } + + def test_circles_cover_the_corridor_with_no_gap + circles = C.circles(LINE, 2.0) + assert_in_delta 2.5, circles.first[1], 1e-9 + # every point 2 km off the line, all along it, inside a circle + (0..300).each do |i| + lon = 17.0 + i * 0.4 / 300 + edge = [lon, 48.0 + 2.0 / C::KM_PER_DEG] + assert circles.any? { |center, r| C.km(center, edge) <= r + 1e-6 }, "gap at #{lon}" + end + assert_operator circles.size, :<=, (C.km(LINE.first, LINE.last) / 3.0).ceil + 2 + end + + def test_distance_to_the_line_and_thinning + assert_in_delta 1.0, C.distance_km([17.2, 48.0 + 1.0 / C::KM_PER_DEG], LINE), 1e-3 + assert_in_delta C.km([16.99, 48.0], LINE.first), C.distance_km([16.99, 48.0], LINE), 1e-9 # past an end: to the end + thin = C.thin(LINE, 2.0) + assert_equal [LINE.first, LINE.last], [thin.first, thin.last] + assert thin.each_cons(2).to_a[0..-2].all? { |a, b| C.km(a, b) >= 2.0 } + end +end diff --git a/test/test_gnss_sim.rb b/test/test_gnss_sim.rb index f189fd9..e22ca26 100644 --- a/test/test_gnss_sim.rb +++ b/test/test_gnss_sim.rb @@ -22,6 +22,19 @@ class GnssSimTest < Minitest::Test assert_in_delta (1000 / (36 / 3.6) / 2 + 500 / (45 / 3.6)) / Maptool::GnssSim::TICK_S, fixes.size, 3 # a fix every TICK_S end + # A track replayed at its own pace: 100 m in 10 s (10 m/s), a stop of an + # hour cut to MAX_GAP_S, another 100 m in 20 s; ends at its end. + def test_replays_a_track_at_its_own_speed + fixes = [] + step = 100.0 / 111_320 + track = [[17.0, 48.0, 1000], [17.0, 48.0 + step, 1010], [17.0, 48.0 + step, 4610], [17.0, 48.0 + 2 * step, 4630]] + Maptool::GnssSim.new("http://valhalla", sleep: ->(_s) {}).replay(track) { |fix| fixes << fix } + assert_in_delta 10.0, fixes.first[:speed], 0.01 + assert_in_delta 5.0, fixes.last[:speed], 0.01 + assert_in_delta 48.0 + 2 * step, fixes.last[:lat], 1e-9 + assert_in_delta (10 + Maptool::GnssSim::MAX_GAP_S + 20) / Maptool::GnssSim::TICK_S, fixes.size, 2 + end + # Started with the trip's route: from its start along it, before any random trip. def test_starts_along_a_given_route fixes = Queue.new diff --git a/test/test_link_place.rb b/test/test_link_place.rb new file mode 100644 index 0000000..5fa8279 --- /dev/null +++ b/test/test_link_place.rb @@ -0,0 +1,28 @@ +require_relative "test_helper" +require_relative "../lib/maptool/link_place" + +class LinkPlaceTest < Minitest::Test + def test_coordinates_in_the_link + place = Maptool::LinkPlace.from_url("https://www.google.com/maps/place/Hallstatt/@47.5622,13.6493,15z/data=!3m1!4b1!4m6!3m5!1s0x0:0x0!8m2!3d47.5622!4d13.6493") + assert_equal({ name: "Hallstatt", lat: 47.5622, lng: 13.6493, url: place[:url] }, place) + assert_equal [48.15, 17.11], Maptool::LinkPlace.from_url("https://maps.google.com/?q=48.15,17.11").values_at(:lat, :lng) + assert_equal [48.15, 17.11], Maptool::LinkPlace.from_url("geo:48.15,17.11").values_at(:lat, :lng) + assert_nil Maptool::LinkPlace.from_url("https://park4night.com/en/place/313577") + end + + def test_coordinates_in_the_page + meta = %(x) + assert_equal({ name: "Stellplatz & See", lat: 47.7395, lng: 13.4482 }, Maptool::LinkPlace.from_html(meta)) + ld = %( Camp ) + assert_equal({ name: "Camp", lat: 46.1, lng: 14.2 }, Maptool::LinkPlace.from_html(ld)) + link = %(go) + assert_equal [45.5, 13.7], Maptool::LinkPlace.from_html(link).values_at(:lat, :lng) + assert_nil Maptool::LinkPlace.from_html("

nothing

") + end + + def test_no_private_addresses + assert_raises(Maptool::LinkPlace::Error) { Maptool::LinkPlace.fetch("http://127.0.0.1/") } + assert_raises(Maptool::LinkPlace::Error) { Maptool::LinkPlace.fetch("http://192.168.1.1/") } + assert_raises(Maptool::LinkPlace::Error) { Maptool::LinkPlace.fetch("file:///etc/passwd") } + end +end diff --git a/test/test_overpass_pois.rb b/test/test_overpass_pois.rb index 8f179e8..ba19991 100644 --- a/test/test_overpass_pois.rb +++ b/test/test_overpass_pois.rb @@ -120,4 +120,9 @@ class OverpassPoisTest < Minitest::Test assert_includes query, %(["amenity"="drinking_water"]) assert_includes query, %(["natural"="spring"]) end + + def test_build_query_along_a_line_uses_around + query = Maptool::OverpassPois.build_query(nil, around: [5000.0, [[17.1, 48.1], [17.2, 48.15]]]) + assert_includes query, %(node["amenity"="drinking_water"](around:5000,48.1,17.1,48.15,17.2);) + end end diff --git a/test/test_plugins.rb b/test/test_plugins.rb index 901b4b9..fe16185 100644 --- a/test/test_plugins.rb +++ b/test/test_plugins.rb @@ -18,7 +18,7 @@ class PluginsTest < Minitest::Test end def test_list_finds_plugins_by_their_manifest - assert_equal [{ "name" => "hello", "label" => "Hello" }], Maptool::Plugins.list(@dir) + assert_equal [{ "name" => "hello", "label" => "Hello", "route" => false, "settings" => [] }], Maptool::Plugins.list(@dir) end def test_list_is_empty_for_a_directory_with_no_plugins @@ -76,7 +76,7 @@ class PluginsTest < Minitest::Test plugins = Maptool::Plugins.list([@dir, other_dir]) - assert_equal [{ "name" => "hello", "label" => "Hello" }, { "name" => "private", "label" => "Private" }], plugins + assert_equal [{ "name" => "hello", "label" => "Hello", "route" => false, "settings" => [] }, { "name" => "private", "label" => "Private", "route" => false, "settings" => [] }], plugins ensure FileUtils.remove_entry(other_dir) end @@ -88,7 +88,7 @@ class PluginsTest < Minitest::Test plugins = Maptool::Plugins.list([@dir, other_dir]) - assert_equal [{ "name" => "hello", "label" => "Hello" }], plugins + assert_equal [{ "name" => "hello", "label" => "Hello", "route" => false, "settings" => [] }], plugins ensure FileUtils.remove_entry(other_dir) end @@ -97,4 +97,22 @@ class PluginsTest < Minitest::Test result = Maptool::Plugins.run([Dir.mktmpdir, @dir], "hello", [1, 2, 3, 4]) assert_equal({ "type" => "FeatureCollection", "features" => [] }, result) end + + # A route and settings: --route/--corridor-km and the settings as env vars, + # only the keys the plugin.json declares saved. + def test_route_args_and_saved_settings_reach_the_command + File.write(File.join(@plugin_dir, "plugin.json"), JSON.generate(label: "Hello", command: "./run.sh", route: true, + settings: [{ key: "TOKEN", label: "Token" }, { key: "bad key" }])) + File.write(File.join(@plugin_dir, "run.sh"), "#!/bin/sh\necho \"{\\\"type\\\":\\\"FeatureCollection\\\",\\\"features\\\":[],\\\"args\\\":\\\"$5 $6\\\",\\\"token\\\":\\\"$TOKEN\\\"}\"\n") + assert_equal [{ "name" => "hello", "label" => "Hello", "route" => true, "settings" => [{ "key" => "TOKEN", "label" => "Token" }] }], Maptool::Plugins.list(@dir) + + path = File.join(@dir, "settings.json") + assert_equal ["TOKEN"], Maptool::Plugins.save_settings(path, @dir, "hello", { "TOKEN" => " abc ", "OTHER" => "x" }) + assert_equal 0o600, File.stat(path).mode & 0o777 + env = Maptool::Plugins.saved_settings(path)["hello"] + result = Maptool::Plugins.run(@dir, "hello", [1, 2, 3, 4], route: "/tmp/r.geojson", corridor_km: 5.0, env: env) + assert_equal "--route=/tmp/r.geojson --corridor-km=5.0", result["args"] + assert_equal "abc", result["token"] + assert_empty Maptool::Plugins.save_settings(path, @dir, "hello", { "TOKEN" => "" }) + end end diff --git a/test/test_routing.rb b/test/test_routing.rb index 0ac7397..df49db2 100644 --- a/test/test_routing.rb +++ b/test/test_routing.rb @@ -115,13 +115,14 @@ class RoutingTest < Minitest::Test def test_a_car_keeps_its_fuel_euro_class_stickers_and_vignettes Maptool::Routing.save_vehicles(@data, [{ "id" => "van", "name" => "Van", "fuel" => "diesel", "euro" => "6d", "stickers" => " DE green ", + "wheelbase" => "3.45", "track" => 1.75, "ramps" => "9, 3 6,5", "vignettes" => [{ "country" => "sk", "until" => "2027-01-31" }, { "country" => "AT", "kind" => "toll" }] }, { "id" => "b", "name" => "B", "type" => "bicycle", "fuel" => "diesel" }]) - assert_equal({ id: "van", name: "Van", type: "car", fuel: "diesel", euro: "6d", stickers: "DE green", + assert_equal({ id: "van", name: "Van", type: "car", fuel: "diesel", euro: "6d", stickers: "DE green", wheelbase: 3.45, track: 1.75, ramps: "3 6.5 9", vignettes: [{ country: "SK", kind: "vignette", until: "2027-01-31" }, { country: "AT", kind: "toll" }] }, Maptool::Routing.vehicle(@data, "van")) assert_equal({ id: "b", name: "B", type: "bicycle" }, Maptool::Routing.vehicle(@data, "b")) # a bike burns nothing [{ "fuel" => "coal" }, { "euro" => "7" }, { "vignettes" => [{ "country" => "Slovakia" }] }, { "vignettes" => [{ "country" => "SK", "until" => "soon" }] }, - { "vignettes" => [{ "country" => "SK", "kind" => "sticker" }] }].each do |bad| + { "vignettes" => [{ "country" => "SK", "kind" => "sticker" }] }, { "ramps" => "3 60" }, { "track" => "5" }].each do |bad| assert_raises(ArgumentError) { Maptool::Routing.save_vehicles(@data, [{ "id" => "x", "name" => "X", **bad }]) } end end diff --git a/test/test_trip.rb b/test/test_trip.rb index e411546..61d76d5 100644 --- a/test/test_trip.rb +++ b/test/test_trip.rb @@ -33,16 +33,45 @@ class TripTest < Minitest::Test router = ->(*) { calls += 1; { type: "Feature" } } points = [{ lngLat: [17.1, 48.1] }, { lngLat: [17.2, 48.2] }] store.update(points: points, vehicle: nil, avoid: {}, editing: nil, &router) - points[1] = { lngLat: [17.2, 48.2], night: true, stay: "90", note: " call ahead " } - trip = store.update(points: points, vehicle: nil, avoid: {}, editing: nil, name: "Alps", start: "2026-12-12T08:00", day_start: "09:30", &router) + points[1] = { lngLat: [17.2, 48.2], night: true, stay: "90", note: " call ahead ", type: "campground", day_note: "" } + points[0] = { lngLat: [17.1, 48.1], day_note: "leave early" } + trip = store.update(points: points, vehicle: nil, avoid: {}, editing: nil, name: "Alps", start: "2026-12-12T08:00", day_start: "09:30", note: " chains ", &router) assert_equal 1, calls # an itinerary change isn't a route change - assert_equal({ lngLat: [17.2, 48.2], name: nil, nav: false, passed: false, night: true, stay: 90, note: "call ahead" }.compact, trip[:points][1]) - assert_equal ["Alps", "2026-12-12T08:00", "09:30"], trip.values_at(:name, :start, :day_start) + assert_equal({ lngLat: [17.2, 48.2], name: nil, nav: false, passed: false, night: true, stay: 90, note: "call ahead", type: "campground" }.compact, trip[:points][1]) + assert_equal "leave early", trip[:points][0][:day_note] + assert_equal ["Alps", "2026-12-12T08:00", "09:30", "chains"], trip.values_at(:name, :start, :day_start, :note) + assert_raises(ArgumentError) { store.update(points: [{ lngLat: [1, 2], type: "" }], vehicle: nil, avoid: {}, editing: nil, &router) } + assert_raises(ArgumentError) { store.update(points: [{ lngLat: [1, 2], cost: "-1" }], vehicle: nil, avoid: {}, editing: nil, &router) } + trip = store.update(points: [{ lngLat: [1, 2], cost: "32", paid: "" }], vehicle: nil, avoid: {}, editing: nil, budget: "250", fuel_price: "1.619", &router) + assert_equal [32.0, nil, 250.0, 1.62], [trip[:points][0][:cost], trip[:points][0][:paid], trip[:budget], trip[:fuel_price]] + # a parking spot: the route goes there instead of the place + seen = nil + points[1] = points[1].merge(park: { lngLat: [17.21, 48.19], name: "P2" }) + trip = store.update(points: points, vehicle: nil, avoid: {}, editing: nil) { |locations, *| seen = locations; { type: "Feature" } } + assert_equal [[17.1, 48.1], [17.21, 48.19]], seen + assert_equal({ lngLat: [17.21, 48.19], name: "P2" }, trip[:points][1][:park]) assert_raises(ArgumentError) { store.update(points: [{ lngLat: [1, 2], stay: "-5" }], vehicle: nil, avoid: {}, editing: nil, &router) } assert_raises(ArgumentError) { store.update(points: points, vehicle: nil, avoid: {}, editing: nil, start: "tomorrow", &router) } end end + # A day with avoids of its own: its legs routed apart, joined into one route. + def test_a_days_own_avoids_route_it_apart + points = [{ lngLat: [0, 0] }, { lngLat: [1, 0], night: true }, { lngLat: [2, 0], avoid: { highways: true } }, { lngLat: [3, 0] }] + assert_equal [[[[0, 0], [1, 0]], { tolls: true }], [[[1, 0], [2, 0], [3, 0]], { highways: true }]], Maptool::TripStore.pieces(points, { tolls: true }) + assert_equal [[[[0, 0], [1, 0], [2, 0], [3, 0]], {}]], Maptool::TripStore.pieces(points.map { |p| p.except(:avoid) }, {}) + + part = ->(from, to) { { type: "Feature", geometry: { coordinates: [[from, 0], [to, 0]] }, + properties: { distance_km: 10.0, time_s: 600, legs_km: [10.0], legs_s: [600], maneuvers: [{ km: 10 }], + roads: [[0.0, "motorway", "AT"]], signals: [[from, 0, 5.0]], countries: [{ code: "AT", km: 10.0, motorway_km: 10.0, toll_km: 0.0 }] } } } + route = Maptool::Routing.merge([part.(0, 1), part.(1, 2)]) + assert_equal [[0, 0], [1, 0], [2, 0]], route[:geometry][:coordinates] + assert_equal [20.0, 1200, [10.0, 10.0]], route[:properties].values_at(:distance_km, :time_s, :legs_km) + assert_equal [[0.0, "motorway", "AT"], [10.0, "motorway", "AT"]], route[:properties][:roads] + assert_equal [[0, 0, 5.0], [1, 0, 15.0]], route[:properties][:signals] + assert_equal [{ code: "AT", km: 20.0, motorway_km: 20.0, toll_km: 0.0 }], route[:properties][:countries] + end + # Off the route while driving for 3 fixes: routed again from the position # to the points not reached yet (the first via passed: dropped). def test_following_reroutes_from_the_position_off_the_route diff --git a/test/test_trip_days.rb b/test/test_trip_days.rb new file mode 100644 index 0000000..5ca0725 --- /dev/null +++ b/test/test_trip_days.rb @@ -0,0 +1,43 @@ +require_relative "test_helper" +require "maptool/trip_days" + +class TripDaysTest < Minitest::Test + D = Maptool::TripDays + + # A drive: a point a minute from `start` (local time), `n` of them, going north. + def drive(start, n, lat0 = 48.0) + t0 = Time.new(*start).to_f + (0...n).map { |i| [17.0, lat0 + i * 0.01, 100.0 + i, t0 + i * 60] } + end + + def test_a_night_stood_cuts_a_day_and_a_night_drive_cuts_at_three + points = drive([2026, 12, 1, 18, 0], 60) + drive([2026, 12, 2, 8, 0], 30, 49.0) # stood 13 h + assert_equal [[60, "auto"]], D.cuts(points) + night = drive([2026, 12, 1, 23, 0], 300) # through the night, no stop + assert_equal [[240, "night"]], D.cuts(night) # 23:00 + 240 min = 03:00 + end + + def test_cuts_by_hand_and_joined + points = drive([2026, 12, 1, 10, 0], 60) + drive([2026, 12, 1, 20, 0], 10, 49.0) + hand = points[30][3] - 20 # between two points: the day starts at the next one + cuts = D.cuts(points, hand: [hand]) + assert_equal [[30, "hand"], [60, "auto"]], cuts + assert_equal [[30, "hand"]], D.cuts(points, hand: [hand], joined: [points[60][3]]) + + days = D.days(points, cuts) + assert_equal [1, 2, 3], days.map { |d| d[:index] } + assert_equal [0, 30, 60], days.map { |d| d[:from] } + assert_equal "auto", days[1][:cut][:kind] + assert_equal 9 * 3600 + 60, days[1][:cut][:stood_s] # from 10:59 to 20:00 + assert_in_delta 29 * 60, days[0][:driving_s], 1 + assert_nil days.last[:cut] + end + + def test_gpx_has_a_track_per_piece_with_times_and_pauses + points = drive([2026, 12, 1, 10, 0], 3) + drive([2026, 12, 1, 11, 0], 3, 48.1) + gpx = D.gpx([["Day 1", points.first(3)], ["Day 2", points.last(3)]], D.pauses(points)) + assert_equal 2, gpx.scan("").size + assert_includes gpx, "" + assert_includes gpx, "Stood 58 min" + end +end diff --git a/test/test_trip_log.rb b/test/test_trip_log.rb index fd9ccd8..aa575ae 100644 --- a/test/test_trip_log.rb +++ b/test/test_trip_log.rb @@ -65,4 +65,27 @@ class TripLogTest < Minitest::Test refute Maptool::TripLog.new(log_dir, library: lib).active? # ended stays ended end end + + # The days' cuts by hand and the joins go into the journal — while it + # runs and after it ended — and a restart doesn't take them for a trip. + def test_cuts_and_joins_are_journaled_running_or_ended + Dir.mktmpdir do |dir| + log = Maptool::TripLog.new(File.join(dir, "trip_log"), library: library(dir)) + assert_nil log.recording + log.start("Days", now: Time.utc(2026, 12, 1, 8)) + log.record(17.0, 48.0, nil, 1000) + log.record(17.001, 48.0, nil, 1010) + log.mark(:cut, 1005) + rec = log.recording + assert rec[:active] + assert_equal [[1005.0], 2], [rec[:hand], rec[:points].size] + log.stop + log.mark(:join, 1010) + rec = log.recording + refute rec[:active] + assert_equal [[1005.0], [1010.0], "Trips/2026-12-01 Days"], rec.values_at(:hand, :joined, :folder) + refute Maptool::TripLog.new(File.join(dir, "trip_log"), library: library(dir)).active? + assert_raises(ArgumentError) { log.mark(:other, 1) } + end + end end diff --git a/views/index.erb b/views/index.erb index 5b56d96..a776198 100644 --- a/views/index.erb +++ b/views/index.erb @@ -167,12 +167,25 @@
+ when it leaves; a day after a night stop starts at "Days start"; its note -->
+ + +
+ + + +
    @@ -191,6 +204,8 @@ Avoid + +