diff --git a/TODO.adoc b/TODO.adoc index 7bc2bc3..2366746 100644 --- a/TODO.adoc +++ b/TODO.adoc @@ -313,9 +313,13 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho (`turn_lanes`), from the same `trace_attributes` pass as the countries; the route's signals drawn on the map from z14. Off the route / with none: `POST /api/road` (map-matched last fixes → the road's name and limit), every 4 s while moving -** [ ] Speed limits that aren't on the edge: `maxspeed:conditional` (time, wet), variable +** [x] Speed limits that aren't on the edge: `maxspeed:conditional` (time, wet), variable signs, `zone:maxspeed` defaults per country (Valhalla leaves untagged roads empty — show - the country's default by road class?), the vehicle's own limits (a camper > 3.5 t: 80/100) + the country's default by road class?), the vehicle's own limits (a camper > 3.5 t: 80/100). Done + for the vehicle: `public/js/speed_limits.js` (14 countries, cars and over 3.5 t, from two camping + guides — see its sources), the route's `roads` (km, road class, country), the limit shown = the + lower of the sign and the profile's; past a border a card in drive mode (the canvas' GridBorder). + Not yet: `maxspeed:conditional`, a car's country default where the edge has none, ES/SE/NO/BE/LU ** [x] Rerouting (after Ferrostar's split of deviation detection and recalculation): off the 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 @@ -365,8 +369,12 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho route once for all screens, not per screen with a dashboard. Done: `TripStore#follow` on every fix (3 fixes > 30 m off while moving, at most every 15 s), the browser's own reroute only without the shared trip -*** [ ] An itinerary view: stops by day/night, notes, planned arrival times (Valhalla's leg - times), "Add to the trip" from search, the library, park4night and other sources +*** [x] An itinerary view: stops by day/night, notes, planned arrival times (Valhalla's leg + times), "Add to the trip" from search, the library, park4night and other sources. Done in the + Route panel (the canvas' Itinerary): the trip's name, leave time, days start; per stop ☾ night + (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 *** [ ] 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 diff --git a/app.rb b/app.rb index 1943d27..9a20de2 100644 --- a/app.rb +++ b/app.rb @@ -825,7 +825,8 @@ module Maptool body = JSON.parse(request.body.read, symbolize_names: true) 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]) do |locations, vehicle, avoid| + 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| Routing.route(VALHALLA_URL, locations, Routing.vehicle(DATA_DIR, vehicle), avoid.transform_keys(&:to_s)) end) rescue JSON::ParserError diff --git a/lib/maptool/routing.rb b/lib/maptool/routing.rb index 7861209..57e4a41 100644 --- a/lib/maptool/routing.rb +++ b/lib/maptool/routing.rb @@ -177,6 +177,11 @@ module Maptool { id: "hike", name: "Hike", type: "foot", speed: 4.5, sac: 3.0 }, ].freeze TYPES = %w[car bicycle foot].freeze + # A car's fuel and emissions (low-emission zones) and what it has paid + # for: vignettes / toll units per country, until a date (YYYY-MM-DD). + FUELS = %w[petrol diesel lpg cng electric hybrid].freeze + EUROS = %w[3 4 5 6 6d].freeze + PAYMENT_KINDS = %w[vignette toll].freeze 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. @@ -228,7 +233,8 @@ module Maptool [key, value] end - { id: id, name: name, type: type, bicycle_type: bicycle_type, **limits }.compact + car = type == "car" ? car_details(name, values) : {} + { id: id, name: name, type: type, bicycle_type: bicycle_type, **limits, **car }.compact end raise ArgumentError, "vehicle ids must be unique" unless vehicles.map { |v| v[:id] }.uniq.size == vehicles.size @@ -236,6 +242,30 @@ module Maptool vehicles end + def self.car_details(name, values) + fuel = values["fuel"].to_s.empty? ? nil : values["fuel"].to_s + euro = values["euro"].to_s.empty? ? nil : values["euro"].to_s + raise ArgumentError, "#{name}: invalid fuel" unless fuel.nil? || FUELS.include?(fuel) + raise ArgumentError, "#{name}: invalid Euro class" unless euro.nil? || EUROS.include?(euro) + + stickers = values["stickers"].to_s.strip[0, 80] + list = values["vignettes"] || [] + raise ArgumentError, "#{name}: invalid vignettes" unless list.is_a?(Array) && list.size <= 30 + + vignettes = list.map do |v| + country = v.is_a?(Hash) && v["country"].to_s.upcase + kind = v.is_a?(Hash) ? (v["kind"] || "vignette").to_s : nil + until_date = v.is_a?(Hash) ? v["until"].to_s : "" + raise ArgumentError, "#{name}: a vignette needs a country code" unless country&.match?(/\A[A-Z]{2}\z/) + raise ArgumentError, "#{name}: invalid vignette kind" unless PAYMENT_KINDS.include?(kind) + raise ArgumentError, "#{name}: invalid date #{until_date}" unless until_date.empty? || until_date.match?(/\A\d{4}-\d{2}-\d{2}\z/) + + { 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?) } + end + private_class_method :car_details + # [[lon, lat], ...] → a GeoJSON Feature (the route line) with distance # (km), time (s), the turn-by-turn instructions and, per country, the # km on motorways and toll roads (for vignettes and tolls). @@ -253,7 +283,7 @@ module Maptool geometry: { type: "LineString", coordinates: legs.flat_map { |leg| decode_polyline(leg["shape"]) } }, properties: { kind: "route", costing: costing, distance_km: data["trip"]["summary"]["length"], time_s: data["trip"]["summary"]["time"], countries: along[:countries], - speed_limits: along[:speed_limits], signals: along[:signals], + speed_limits: along[:speed_limits], signals: along[:signals], roads: along[:roads], legs_km: legs.map { |leg| leg.dig("summary", "length") }, # to each via point, for rerouting legs_s: legs.map { |leg| leg.dig("summary", "time") }, # the time of each, for the stops list # lanes: Valhalla's [{directions:, valid:, active:}] bitmasks, at junctions that have them @@ -275,12 +305,15 @@ module Maptool # order (vignettes, tolls); # speed_limits: [[km from the start, km/h | "unlimited" | nil], ...], an # entry where the limit changes (nil: not tagged); - # signals: [[lon, lat, km from the start], ...], the traffic signals. + # signals: [[lon, lat, km from the start], ...], the traffic signals; + # roads: [[km from the start, road class, country code], ...], an entry + # where either changes (a vehicle's limits by country and road class). # nil if that lookup fails: it's extra. def self.along_route(valhalla_url, legs, costing, options) totals = {} limits = [] signals = [] + roads = [] km = 0.0 legs.each do |leg| shape = decode_polyline(leg["shape"]) @@ -298,13 +331,15 @@ module Maptool row[:toll_km] += edge["length"] if edge["toll"] limit = speed_limit(edge["speed_limit"]) limits << [km.round(3), limit] if limits.empty? || limits.last[1] != limit + road = [km.round(3), edge["road_class"], code] + roads << road if roads.empty? || roads.last.drop(1) != road.drop(1) km += edge["length"] point = shape[edge["end_shape_index"].to_i] if edge.dig("end_node", "traffic_signal") signals << [*point, km.round(3)] if point end end { countries: totals.values.each { |row| row.transform_values! { |v| v.is_a?(Float) ? v.round(1) : v } }, - speed_limits: limits, signals: signals } + speed_limits: limits, signals: signals, roads: roads } rescue RouteError, Unavailable, Net::ReadTimeout, NoMethodError, TypeError nil end @@ -326,9 +361,11 @@ module Maptool data = valhalla(valhalla_url, "/trace_attributes", shape: points.map { |lon, lat| { lon: Float(lon), lat: Float(lat) } }, costing: "auto", shape_match: "map_snap", - filters: { attributes: %w[edge.names edge.road_class edge.speed_limit edge.surface], action: "include" }) + filters: { attributes: %w[edge.names edge.road_class edge.speed_limit edge.surface node.admin_index admin.country_code], + action: "include" }) edge = data["edges"]&.last or raise RouteError, "no road here" - { name: edge["names"]&.first, road_class: edge["road_class"], speed_limit: speed_limit(edge["speed_limit"]), surface: edge["surface"], + country = data["admins"]&.dig(edge.dig("end_node", "admin_index").to_i, "country_code") + { name: edge["names"]&.first, road_class: edge["road_class"], speed_limit: speed_limit(edge["speed_limit"]), surface: edge["surface"], country: country, signals: signals_ahead(valhalla_url, points) }.compact rescue ArgumentError, TypeError raise RouteError, "invalid coordinates" diff --git a/lib/maptool/trip.rb b/lib/maptool/trip.rb index f883310..8c51cf6 100644 --- a/lib/maptool/trip.rb +++ b/lib/maptool/trip.rb @@ -10,6 +10,29 @@ module Maptool # camera. Kept in data/trip.json across restarts. class TripStore 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. + MAX_STAY_MIN = 7 * 24 * 60 + DATE_TIME = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}\z/ + TIME = /\A\d{2}:\d{2}\z/ + + def self.point(p) + 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] + { 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 + end + + def self.itinerary(name:, start:, day_start:) + name = name.to_s.strip[0, 80] + 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?) } + end def initialize(path) @path = path @@ -117,8 +140,9 @@ module Maptool # changed — the old route stays then. Passed points stay in the trip # (shown dimmed, still editable: a stop missed out added afterwards), # just not routed. Last write wins. - def update(points:, vehicle:, avoid:, editing:) - points = points.map { |p| { lngLat: p.fetch(:lngLat).map { |v| Float(v) }, name: p[:name], nav: !!p[:nav], passed: !!p[:passed] } } + def update(points:, vehicle:, avoid:, editing:, name: nil, start: nil, day_start: nil) + points = points.map { |p| self.class.point(p) } + itinerary = self.class.itinerary(name: name, start: start, day_start: day_start) avoid = (avoid || {}).to_h { |k, v| [k.to_sym, !!v] } before = get routed = ->(list) { list.reject { |p| p[:passed] }.map { |p| p[:lngLat] } } @@ -135,7 +159,9 @@ module Maptool end @mutex.synchronize do @trip = { version: @trip[:version] + 1, points: points, vehicle: vehicle, avoid: avoid, editing: editing, - route: route, error: error, updated_at: Time.now.to_f } + **itinerary, route: route, error: error, updated_at: Time.now.to_f }.compact + @trip[:route] = route # nil kept: the client reads it + @trip[:error] = error File.write("#{@path}.tmp", JSON.generate(@trip)) File.rename("#{@path}.tmp", @path) @trip.dup diff --git a/public/css/style.css b/public/css/style.css index faafab3..3c37f39 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -1513,7 +1513,7 @@ button.basemap-panel__link[hidden] { display: none; } .here__position small, .here__position em { color: var(--ui-muted); font-style: normal; font-size: 12px; } .here__actions { display: flex; gap: 6px; padding: 8px 12px; border-bottom: 1px solid var(--ui-line); } .here__actions button { flex: 1; height: 30px; padding: 0 6px; border: 1px solid var(--ui-line); border-radius: 6px; background: none; font-weight: 600; font-size: 12px; white-space: nowrap; } -.here__actions button:hover { background: var(--ui-hover, rgba(0, 0, 0, 0.06)); } +.here__actions button:hover { background: var(--ui-bg-2); } .here__features { padding: 8px 12px 0; } .here__features summary { font-weight: 600; cursor: pointer; } .here__features .debug-popup__feature:first-of-type { margin-top: 6px; } @@ -2912,23 +2912,6 @@ button.basemap-panel__link[hidden] { display: none; } padding-left: 20px; } -.route-panel__vehicle { - display: grid; - grid-template-columns: 1fr 1fr; - gap: 6px; - border: 1px solid var(--ui-line); - border-radius: 4px; -} - -.route-panel__vehicle[hidden] { - display: none; -} - -.route-panel__vehicle input { - width: 4.5em; -} - -.route-panel__vehicle [hidden], .route-panel__avoid[hidden] { display: none; } @@ -2939,32 +2922,55 @@ button.basemap-panel__link[hidden] { display: none; } align-items: center; } -.route-panel__countries { - margin: 0; - padding-left: 1.2em; - font-size: 0.9em; -} +.route-panel__countries { margin: 0; padding: 0; list-style: none; font-size: 0.9em; border: 1px solid var(--ui-line); border-radius: 8px; overflow: hidden; } +.route-panel__countries li { display: flex; align-items: center; gap: 8px; padding: 6px 10px; } +.route-panel__countries li + li { border-top: 1px solid var(--ui-line); } +.route-panel__countries li > span:first-of-type { flex: 1; color: var(--ui-muted); } +.route-panel__country--missing > span:first-of-type { color: var(--inst-caution, #b26a00) !important; font-weight: 600; } +.route-panel__signs { display: flex; gap: 4px; } +.route-panel__sign { display: inline-flex; width: 26px; height: 26px; border-radius: 50%; border: 3px solid #d32f2f; background: #fff; color: #1a1a1a; + align-items: center; justify-content: center; font: 700 10px inherit; box-sizing: border-box; } -.route-panel__vehicle-row { - display: flex; - gap: 6px; - align-items: center; -} - -.route-panel__vehicle-name, -.route-panel__vehicle-hint { - grid-column: 1 / -1; -} - -.route-panel__vehicle-name input { - width: 12em; -} - -.route-panel__vehicle-hint { - margin: 0; - font-size: 0.85em; - color: var(--ui-muted); -} +/* Profiles (route.js, the Design canvas' Vehicle): a dialog set once, the + chip in the map's bottom-left corner picks one. */ +.profiles { width: min(860px, 96vw); max-height: 90vh; padding: 0; border: none; border-radius: 12px; background: var(--ui-bg); color: var(--ui-fg); + box-shadow: 0 8px 40px rgb(0 0 0 / 0.4); display: none; grid-template-columns: 220px 1fr; grid-template-rows: auto 1fr auto; overflow: hidden; } +.profiles[open] { display: grid; } +.profiles::backdrop { background: rgb(0 0 0 / 0.35); } +.profiles__head { grid-column: 1 / -1; display: flex; align-items: center; padding: 12px 18px; border-bottom: 1px solid var(--ui-line); } +.profiles__head h2 { margin: 0; flex: 1; font-size: 17px; } +.profiles__close { border: none; background: none; color: var(--ui-muted); font-size: 18px; cursor: pointer; } +.profiles__list { border-right: 1px solid var(--ui-line); background: var(--ui-bg-2); padding: 6px 0; overflow-y: auto; } +.profiles__list ul, .profile-chip__list { list-style: none; margin: 0; padding: 0; } +.profiles__list li button, .profile-chip__list li button { display: flex; align-items: center; gap: 10px; width: 100%; min-height: 40px; padding: 0 14px; + border: none; border-left: 3px solid transparent; background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; } +.profiles__list li button b, .profile-chip__list li button b { flex: 1; font-weight: 500; } +.profiles__list li button small, .profile-chip__list li button small { color: var(--ui-muted); } +.profiles__list li.is-open button { border-left-color: var(--accent); background: var(--ui-bg); } +.profiles__list li.is-open b, .profile-chip__list li.is-current b { font-weight: 700; } +.profiles__list > button { margin: 6px 14px; border: none; background: none; color: var(--accent); font-weight: 600; cursor: pointer; padding: 0; } +.profiles__form { border: none; margin: 0; padding: 14px 20px; display: grid; grid-template-columns: 1fr 1fr; gap: 8px 16px; align-content: start; overflow-y: auto; } +.profiles__form > label { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--ui-muted); } +.profiles__form > label input, .profiles__form > label select { flex: 1; min-width: 0; height: 30px; color: var(--ui-fg); } +.profiles__form [hidden] { display: none !important; } +.route-panel__vehicle-name, .route-panel__vehicle-hint, .profiles__wide { grid-column: 1 / -1; } +.route-panel__vehicle-hint { margin: 0; font-size: 0.85em; color: var(--ui-muted); } +.profiles__vignettes > span { font-size: 13px; color: var(--ui-muted); } +.profiles__vignettes ul { list-style: none; margin: 6px 0; padding: 0; display: flex; flex-direction: column; gap: 6px; } +.profiles__vignettes li { display: flex; gap: 6px; align-items: center; } +.profiles__vignettes li [name="country"] { width: 3.5em; text-transform: uppercase; } +.profiles__vignettes button, .profiles__delete { border: 1px solid var(--ui-line); border-radius: 6px; background: none; color: inherit; padding: 4px 10px; cursor: pointer; } +.profiles__delete { justify-self: start; } +.profiles__foot { grid-column: 1 / -1; padding: 10px 18px; border-top: 1px solid var(--ui-line); font-size: 12px; color: var(--ui-muted); } +.profile-chip { position: relative; } +.profile-chip__button { height: 32px; padding: 0 12px; border: none; border-radius: 16px; background: var(--ui-bg); color: var(--ui-fg); + box-shadow: 0 1px 6px rgb(0 0 0 / 0.25); font: 600 13px inherit; cursor: pointer; white-space: nowrap; } +.profile-chip__list { position: absolute; left: 0; bottom: calc(100% + 6px); min-width: 230px; border-radius: 10px; background: var(--ui-bg); + box-shadow: 0 2px 12px rgb(0 0 0 / 0.3); overflow: hidden; } +.profile-chip__list[hidden] { display: none; } +.profile-chip__list li.is-current button { background: var(--ui-bg-2); } +.profile-chip__edit { width: 100%; height: 36px; border: none; border-top: 1px solid var(--ui-line); background: none; color: var(--accent); + font-weight: 600; text-align: left; padding: 0 14px; cursor: pointer; } .route-marker { width: 22px; @@ -4795,3 +4801,31 @@ html.driving .drive-cell--field { position: relative; } font-variant-numeric: tabular-nums; } .drive-speed__limit small { font-size: calc(11px * var(--s, 1)); color: var(--drive-muted); white-space: nowrap; } + +/* Drive: past a border, the new country's limits for the profile (the Design canvas' GridBorder) */ +.drive-cell--border { position: relative; z-index: 3; align-self: start; height: calc(var(--cell, 80px) * 3); justify-content: center; gap: calc(10px * var(--s, 1)); padding: calc(12px * var(--s, 1)) calc(16px * var(--s, 1)); cursor: pointer; } +.drive-cell--border[hidden] { display: none; } +.drive-border__head { display: flex; align-items: baseline; gap: 10px; } +.drive-border__head b { font-size: calc(26px * var(--s, 1)); } +.drive-border__signs { display: flex; gap: calc(18px * var(--s, 1)); } +.drive-border__limit { display: flex; flex-direction: column; align-items: center; gap: 4px; } +.drive-border__limit .drive-speed__limit { position: static; transform: none; } +.drive-border__limit small { font-size: calc(12px * var(--s, 1)); color: var(--drive-muted); } +.drive-border__pays { font-size: calc(15px * var(--s, 1)); } + +/* The itinerary in the Route panel (the Design canvas' Itinerary) */ +.route-panel__trip { display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center; font-size: 12px; color: var(--ui-muted); } +.route-panel__trip input[name="name"] { flex: 1 1 100%; font: 600 15px inherit; color: var(--ui-fg); border: none; border-bottom: 1px solid var(--ui-line); background: none; padding: 2px 0; } +.route-panel__trip label { display: flex; gap: 4px; align-items: center; } +.route-panel__day { list-style: none; display: flex; align-items: baseline; gap: 8px; padding: 10px 0 4px; font-size: 13px; } +.route-panel__day::before { content: ""; width: 10px; height: 10px; border-radius: 50%; background: var(--day); align-self: center; } +.route-panel__day b { flex: 1; } +.route-panel__day span { font-size: 12px; color: var(--ui-muted); } +.route-panel__time { font-size: 12px; font-weight: 600; font-variant-numeric: tabular-nums; white-space: nowrap; } +.route-panel__note { display: block; margin-top: 2px; padding: 3px 6px; border-radius: 4px; background: var(--ui-bg-2); font-size: 12px; white-space: pre-wrap; } +.route-panel__on { color: var(--accent) !important; font-weight: 700; } +.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-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; } diff --git a/public/drive/road.json b/public/drive/road.json index 0fffed4..23e7688 100644 --- a/public/drive/road.json +++ b/public/drive/road.json @@ -14,6 +14,7 @@ { "area": "1 / 13 / 2 / 15", "widget": "field", "value": "sun" }, { "area": "1 / 15 / 2 / 17", "widget": "status" }, { "area": "2 / 1 / 3 / 5", "widget": "ahead" }, + { "area": "2 / 1 / 5 / 6", "widget": "border" }, { "area": "2 / 14 / 3 / 17", "widget": "field", "value": "nextStop", "small": true }, { "area": "3 / 14 / 4 / 17", "widget": "field", "value": "toNextStop" }, { "area": "4 / 14 / 5 / 17", "widget": "field", "value": "etaNextStop" }, diff --git a/public/js/dashboard.js b/public/js/dashboard.js index 2951d9c..f93ad00 100644 --- a/public/js/dashboard.js +++ b/public/js/dashboard.js @@ -1,5 +1,6 @@ import { isLoggedIn } from "/js/auth.js"; -import { onRouteChanged, requestReroute, notifyRouteProgress } from "/js/panels.js"; +import { onRouteChanged, requestReroute, notifyRouteProgress, currentVehicle } from "/js/panels.js"; +import { effectiveLimit } from "/js/speed_limits.js"; import { elevationAt } from "/js/dem.js"; // The car's dashboard over the map, off the CAN signals (GET /api/can, @@ -108,7 +109,7 @@ function prepareRoute(route) { const maneuvers = route.properties.maneuvers.map((m) => { const at = start; start += m.km; return { ...m, at }; }); let leg = 0; const viaKm = (route.properties.legs_km || []).slice(0, -1).map((length) => (leg += length)); // km at each via point - return { coords, km, limits: route.properties.speed_limits, signals: route.properties.signals || [], maneuvers, viaKm }; + return { coords, km, limits: route.properties.speed_limits, roads: route.properties.roads || [], signals: route.properties.signals || [], maneuvers, viaKm }; } // Nearest point on the route: [km along it, meters off it]. Near the last @@ -282,9 +283,16 @@ export class DashboardControl { if (fresh && this._route && off > ON_ROUTE_M && (this._values.hdop ?? 0) <= MAX_HDOP) this._offFixes++; else if (off <= ON_ROUTE_M) this._offFixes = 0; if (this._route && this._offFixes < OFF_ROUTE_FIXES) { - const { limits, signals, maneuvers } = this._route; - const current = limits.findLast(([km]) => km <= at); - const next = limits.find(([km, limit]) => km > at && limit !== current?.[1]); + const { limits, roads, signals, maneuvers } = this._route; + // the road's sign capped by the profile's own limit for that country and road class + const limitAt = (k) => { + const road = roads.findLast(([km]) => km <= k); + const sign = limits.findLast(([km]) => km <= k)?.[1] ?? null; + return road ? effectiveLimit(sign, road[2], road[1], currentVehicle) : sign; + }; + const limit = limitAt(at); + 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 maneuver = maneuvers[index]; @@ -295,8 +303,9 @@ export class DashboardControl { this._progress(at); } this._nav = { - limit: current?.[1] ?? null, + limit, 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 }, then: maneuver && then && then.at - maneuver.at <= THEN_M / 1000 ? then : null, @@ -308,7 +317,9 @@ export class DashboardControl { return; } this._progress(null); - this._nav = { limit: this._road?.speed_limit ?? null, offRoute: !!this._route, street: this._road?.name, signal: this._signalAhead(position) }; + const road = this._road; + this._nav = { limit: road ? effectiveLimit(road.speed_limit ?? null, road.country, road.road_class, currentVehicle) : null, + offRoute: !!this._route, street: road?.name, signal: this._signalAhead(position), country: road?.country ?? null }; if (this._route && (speed ?? 0) >= MOVING_MS && Date.now() - this._rerouteAt >= REROUTE_EVERY_MS) { this._rerouteAt = Date.now(); requestReroute(position, this._route.viaKm.filter((km) => km <= this._lastAt).length); diff --git a/public/js/driving.js b/public/js/driving.js index 0bf92c6..21bbf59 100644 --- a/public/js/driving.js +++ b/public/js/driving.js @@ -4,6 +4,8 @@ import { pauseFollow, resumeFollow, isFollowing } from "/js/gnss.js"; import { formatDuration } from "/js/route.js"; import { isLoggedIn } from "/js/auth.js"; import { watchDashboard, maneuverSvg, laneSvg, distance, VOICE_KEY } from "/js/dashboard.js"; +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"; @@ -17,7 +19,8 @@ import { pointsMenu, layersMenu, terrainMenu, elevationHtml, cellButton, bindKey const KEY = "drivingMode"; const PROFILE_URL = "/drive/road.json"; const PITCH_3D = 60; // as map.js's 3D toggle -const RENDER_MS = 1000; // the clock, the follow state; the dashboard's polls render too +const RENDER_MS = 1000; +const BORDER_MS = 20000; // the border card's time on the screen // the clock, the follow state; the dashboard's polls render too const SEARCH_DELAY_MS = 300; // after the last key const LOG_POLL_MS = 5000; // the trip log's state and new points const DRIVEN_SOURCE = "trip-driven"; @@ -105,6 +108,7 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) { + `; // auto: opens off-road and closes back on the road; stay: opens and stays (the inclinometer all along); hand: neither const TERRAIN_MODES = { auto: "opens and closes by itself", stay: "opens by itself, stays", hand: "by hand" }; @@ -127,6 +131,19 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) { renderVoice(); }); renderVoice(); + // the profile: a tap goes to the next one (re-routes); the dialog is the desktop's + const profileButton = menuPanel.querySelector('[data-action="profile"]'); + const renderProfile = () => { + const { current } = routePanel?.profiles() || {}; + profileButton.innerHTML = `Profile: ${escapeHtml(current?.name ?? "—")} tap for the next one`; + }; + profileButton.addEventListener("click", () => { + const { list, current } = routePanel?.profiles() || { list: [] }; + if (!list.length) return; + routePanel.pickProfile(list[(list.indexOf(current) + 1) % list.length].id); + }); + onVehicle(renderProfile); + renderProfile(); menuPanel.querySelector('[data-action="overview"]').addEventListener("click", overview); menuPanel.querySelector('[data-action="leave"]').addEventListener("click", () => set(false)); const crosshair = document.createElement("div"); @@ -479,6 +496,34 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) { (signal != null ? `${distance(signal)}` : ""); }; + // Past a border (the country along the route, or of the road driven): + // the new country's limits for the profile and how its motorways are + // paid, for BORDER_MS or until tapped (the Design canvas' GridBorder). + let country = null; + let border = null; // { code, until } + const renderBorder = (el) => { + const code = dash?.nav?.country; + if (code && code !== country) { + if (country) border = { code, until: Date.now() + BORDER_MS }; + country = code; + } + el.hidden = !border || Date.now() > border.until; + if (el.hidden) return; + if (!el.dataset.wired) { + el.dataset.wired = "1"; + el.addEventListener("click", () => { border = null; el.hidden = true; }); + } + const heavy = isHeavy(currentVehicle); + const row = SPEED_LIMITS[border.code]?.[heavy ? "heavy" : "car"]; + const pay = motorwayPayment(border.code, currentVehicle); + const sign = (v, k) => `${v ?? "–"}${k}`; + let name = border.code; + try { name = COUNTRY_NAMES.of(border.code); } catch { /* not a region code */ } + el.innerHTML = `
${escapeHtml(name)}${border.code}${currentVehicle ? ` · ${escapeHtml(currentVehicle.name)}` : ""}
` + + (row ? `
${sign(row[0], "Motorway")}${sign(row[2], "Outside towns")}${sign(row[3], "In towns")}
` : `No limits known for ${border.code}`) + + (pay.how ? `Motorways: ${pay.how} ${pay.has ? "✓" : "— not in the profile"}` : ""); + }; + const renderManeuver = (el) => { const n = dash?.nav; if (n?.offRoute) { @@ -530,6 +575,7 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) { el.innerHTML = `${extra}${FIELDS[name] || name}${escapeHtml(value)} ${escapeHtml(unit)}`; } else if (cell.widget === "maneuver") renderManeuver(el); else if (cell.widget === "ahead") renderAhead(el); + else if (cell.widget === "border") renderBorder(el); else if (cell.widget === "status") { el.innerHTML = `MAPTOOL● ${navigator.onLine ? "online" : "offline"}${log?.active ? ` · ● rec` : ""}`; } else if (cell.widget === "elevation") renderElevation(el, cell); diff --git a/public/js/panels.js b/public/js/panels.js index c2075c8..c0b9cba 100644 --- a/public/js/panels.js +++ b/public/js/panels.js @@ -123,6 +123,20 @@ export function notifyRouteChanged(route) { document.dispatchEvent(new CustomEvent(ROUTE_CHANGED_EVENT, { detail: route })); } +// The profile in use (route.js; its /api/vehicles entry): the dashboard's +// and the driving grid's limits for it, the border card's "how it pays". +const VEHICLE_EVENT = "vehicle-changed"; +export let currentVehicle = null; + +export function notifyVehicle(vehicle) { + currentVehicle = vehicle; + document.dispatchEvent(new CustomEvent(VEHICLE_EVENT, { detail: vehicle })); +} + +export function onVehicle(callback) { + document.addEventListener(VEHICLE_EVENT, (event) => callback(event.detail)); +} + // How far along the route the position is, while the dashboard follows it // (km, or null once it's off it / not navigating): the route panel draws // the driven part dimmed and the rest as the active route. diff --git a/public/js/route.js b/public/js/route.js index 403c578..efe12b4 100644 --- a/public/js/route.js +++ b/public/js/route.js @@ -1,7 +1,8 @@ -import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs"; +import { Marker, Popup } from "/vendor/maplibre-gl/maplibre-gl.mjs"; import { ROUTE_ICON, REVERSE_ICON, CLEAR_ICON } from "/js/icons.js"; -import { notifySidePanelOpen, onlyOneSidePanelOpen, notifyGpxStoreChanged, onRoutePoint, onRouteEdit, notifyRouteChanged, onReroute, onRouteProgress } from "/js/panels.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"; @@ -18,10 +19,16 @@ const PROFILE_SAMPLES = 400; // elevation lookups per route, at least 50 m apart const GRADE_WINDOW_M = 500; // "max grade" is sustained over this distance, not one noisy pixel const VEHICLES_URL = "/api/vehicles"; const VEHICLE_KEY = "maptool.routeVehicle"; +const PROFILE_ICONS = { car: "🚗", bicycle: "🚲", foot: "🥾" }; +// What the chip and the lists say about a profile, past its name. +const profileMeta = (v) => + (v.type || "car") === "car" + ? [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"; -// Motorways paid by a time-based vignette rather than per section. Not -// reliably tagged as toll in OSM, so every motorway km there counts. -const VIGNETTE_COUNTRIES = new Set(["AT", "BG", "CH", "CZ", "HU", "MD", "RO", "SI", "SK"]); +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"; const SOURCE = "route"; const COLOR = "#1d6fdc"; @@ -109,6 +116,12 @@ 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._tripInputs.forEach((input) => input.addEventListener("change", () => { + this._itinerary[input.name] = input.value.trim() || null; + this._itineraryChanged(); + })); this._saveButton.addEventListener("click", () => this._save()); this._profileButton = this._panel.querySelector(".route-panel__profile"); this._profileButton.addEventListener("click", () => { @@ -160,10 +173,11 @@ export class RoutePanelControl { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ - points: this._points.map(({ lngLat, name, nav, passed }) => ({ lngLat, name, nav, passed })), + points: this._points.map(({ lngLat, name, nav, passed, night, stay, note }) => ({ lngLat, name, nav, passed, night, stay, note })), vehicle: this._vehicleId, avoid: this._avoid, editing: this._editing, + ...this._itinerary, }), }); const trip = await response.json().catch(() => ({})); @@ -180,11 +194,17 @@ export class RoutePanelControl { // vehicle, avoids, the library route being edited) when they came from // another screen. _applyTrip(trip, fromElsewhere) { + 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 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 })); + 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 }; + 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; this._avoid = { ...trip.avoid }; this._panel.querySelectorAll(".route-panel__avoid input").forEach((input) => (input.checked = !!this._avoid[input.name])); @@ -213,11 +233,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 } = {}) { + _addPoint(lngLat, name, { quiet = false, nav = !!name && name !== "My position", passed = false, night, stay, note } = {}) { 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 }; + const point = { lngLat, name, nav, marker, night: night || undefined, stay: stay || undefined, note: note || undefined }; this._setPassed(point, passed); marker.on("dragend", () => { const { lng, lat } = marker.getLngLat(); @@ -331,6 +351,17 @@ export class RoutePanelControl { this._changed(); } + // The profiles and the one in use, for the driving Menu's row; picking + // one re-routes. + profiles() { + return { list: this._vehicles || [], current: this._vehicle || null }; + } + + pickProfile(id) { + this._selectVehicle?.(id); + this._fetchRoute(); + } + // The start moved to where the car is (GNSS, else the browser's position). startHere() { const set = (lngLat) => { @@ -362,13 +393,86 @@ export class RoutePanelControl { this._fetchRoute(); } + // Night / stay / note / the trip's name and start: no new route, the + // shared trip saved (the server doesn't route again for these). + _itineraryChanged() { + this._renderPoints(); + if (this._shared) this._pushTrip(); + } + + // The planned times: leaving at the trip's start, each leg's time, a stay + // where set; a night stop ends the day, the next one leaves at "Days start" + // (09:00). [{ arrive, leave, day }] in ms, null where unknown (no start, a + // leg not routed yet). + _schedule() { + const last = this._points.length - 1; + const [dh, dm] = (this._itinerary.day_start || "09:00").split(":").map(Number); + let t = this._itinerary.start ? new Date(this._itinerary.start).getTime() : null; + let day = 0; + return this._points.map((p, i) => { + if (i > 0 && t != null) { + const leg = this._leg(i); + t = leg?.s != null ? t + leg.s * 1000 : null; + } + const arrive = i > 0 ? t : null; + let leave = null; + if (t != null && i < last) { + if (p.night) { + const next = new Date(t); + next.setDate(next.getDate() + 1); + next.setHours(dh, dm, 0, 0); + leave = next.getTime(); + } else leave = t + (p.stay || 0) * 60000; + } + const out = { arrive, leave, day }; + if (p.night && i < last) day++; + t = leave; + return out; + }); + } + + // Another screen changed the trip: where (the first point added or moved, + // else the first one changed) a popup says so, with Undo (the points and + // the itinerary as they were, saved back). The map isn't moved. + _showRemoteChange(before, beforeItinerary) { + const key = (p) => p.lngLat.join(); + 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 removed = now.length < before.length; + if (!changed && !removed && JSON.stringify(beforeItinerary) === JSON.stringify(this._itinerary)) return; + const at = (changed || now[0] || before[0])?.lngLat; + if (!at) return; + const what = added ? `added ${added.name || "a point"}` : removed ? "removed a point" : changed ? `changed ${changed.name || "a point"}` : "changed the trip"; + const el = document.createElement("div"); + el.className = "route-remote"; + el.innerHTML = `Another screen ${escapeText(what)} `; + this._remotePopup?.remove(); + this._remotePopup = new Popup({ closeButton: false, closeOnClick: true, className: "route-remote-popup" }).setLngLat(at).setDOMContent(el).addTo(this._map); + el.querySelector("button").addEventListener("click", () => { + 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 })); + this._itinerary = { ...beforeItinerary }; + this._tripInputs.forEach((input) => (input.value = this._itinerary[input.name] || "")); + this._changed(); + }); + clearTimeout(this._remoteTimer); + this._remoteTimer = setTimeout(() => this._remotePopup?.remove(), 15000); + } + // The Desktop artboard's list: a grip to drag the point to another place, // its letter (the same on its marker), name and role, then the leg to the // next one as a dashed line between them. _renderPoints() { this._list.innerHTML = ""; const last = this._points.length - 1; + 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)); const letter = String.fromCharCode(65 + (index % 26)); const role = index === 0 ? "Start" : index === last ? "End" : `Via ${index}`; point.marker.getElement().textContent = letter; @@ -405,13 +509,27 @@ export class RoutePanelControl { text.className = "route-panel__point"; text.append( Object.assign(document.createElement("span"), { className: "route-panel__name", textContent: point.name || `${point.lngLat[1].toFixed(5)}, ${point.lngLat[0].toFixed(5)}` }), - Object.assign(document.createElement("small"), { className: "route-panel__role", textContent: role }), + Object.assign(document.createElement("small"), { className: "route-panel__role", textContent: [point.night && index < last ? "☾ night" : role, point.stay && !point.night ? `stay ${formatDuration(point.stay * 60)}` : ""].filter(Boolean).join(" · ") }), ); - li.append(grip, badge, text, this._navButton(point, role), this._pointButton("×", "Remove", true, () => this._removePoint(point))); + 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.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, () => { + point.editingNote = !point.editingNote; + this._renderPoints(); + }); + li.append(grip, badge, text, time, night, edit, this._navButton(point, role), this._pointButton("×", "Remove", true, () => this._removePoint(point))); // Hover/hold previews the point; a click on its name commits. wirePreview(this._map, text, () => ({ lngLat: point.lngLat })); text.addEventListener("click", () => this._map.easeTo({ center: point.lngLat, zoom: Math.max(this._map.getZoom(), 14) })); this._list.appendChild(li); + if (point.editingNote) this._list.appendChild(this._noteEditor(point)); }); this._stopListeners?.forEach((callback) => callback()); this._editingNote.hidden = !this._editing; @@ -457,6 +575,45 @@ export class RoutePanelControl { return button; } + // A day's header: its date (from when it leaves), km and driving time. + _dayHeader(day, from, schedule) { + let km = 0; + let s = 0; + for (let i = from + 1; i < this._points.length; i++) { + const leg = this._leg(i); + km += leg?.km || 0; + s += leg?.s || 0; + if (this._points[i].night) break; + } + const leaves = schedule[from].leave; + const date = leaves != null ? new Date(leaves).toLocaleDateString([], { weekday: "short", day: "numeric", month: "numeric" }) : `Day ${day + 1}`; + const li = document.createElement("li"); + li.className = "route-panel__day"; + 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; + } + + // A stop's 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")]; + stay.value = point.stay || ""; + note.value = point.note || ""; + stay.addEventListener("change", () => { + point.stay = Math.max(0, Math.round(Number(stay.value) || 0)) || undefined; + this._itineraryChanged(); + }); + note.addEventListener("change", () => { + point.note = note.value.trim() || undefined; + this._itineraryChanged(); + }); + return li; + } + _pointButton(text, title, enabled, onClick) { const button = document.createElement("button"); button.type = "button"; @@ -782,15 +939,28 @@ export class RoutePanelControl { }); } - // Where the route needs a vignette or pays tolls, country by country. + // Country by country on the route: the profile's limits there (motorway / + // outside towns / in towns), how its motorways are paid and whether the + // profile has it (a vignette, or a toll unit over 3.5 t), the km driven. + // Motorway km in a vignette country count whole: the vignette isn't + // reliably tagged as toll in OSM. _showCountries(countries) { - const rows = (countries || []).flatMap(({ code, motorway_km: motorway, toll_km: toll }) => { - if (VIGNETTE_COUNTRIES.has(code) && motorway > 0) { - return [`${code}: vignette, ${motorway.toFixed(0)} km motorway${toll > 0 ? ` (${toll.toFixed(0)} km tolled)` : ""}`]; - } - return toll > 0 ? [`${code}: toll, ${toll.toFixed(0)} km`] : []; + this._lastCountries = countries; + const v = this._vehicle; + const sign = (limit) => `${limit ?? "–"}`; + const rows = (countries || []).map(({ code, km, motorway_km: motorway, toll_km: toll }) => { + const row = SPEED_LIMITS[code]?.[isHeavy(v) ? "heavy" : "car"]; + const pay = motorwayPayment(code, v); + const pays = pay.how && motorway > 0 + ? `${pay.how} ${pay.has ? "✓" : pay.has === false && pay.until ? `ended ${pay.until}` : "—"}` + : toll > 0 ? `toll, ${toll.toFixed(0)} km` : ""; + const li = document.createElement("li"); + li.classList.toggle("route-panel__country--missing", pay.how != null && motorway > 0 && !pay.has); + li.innerHTML = `${code}${km.toFixed(0)} km${pays ? ` · ${pays}` : ""}` + + (row ? `${[row[0], row[2], row[3]].map(sign).join("")}` : ""); + return li; }); - this._countries.replaceChildren(...rows.map((text) => Object.assign(document.createElement("li"), { textContent: text }))); + this._countries.replaceChildren(...rows); this._countries.hidden = rows.length === 0; } @@ -815,30 +985,104 @@ export class RoutePanelControl { // --- vehicle -------------------------------------------------------------- - // Profiles (Car, Camper, ...) are shared and edited only when logged in; - // which one is in use is this browser's own choice. A change re-routes. + // Profiles (Car, Camper, Bicycle, ...) are shared and edited only when + // logged in, in a dialog (the Design canvas' Vehicle); which one is in use + // is this browser's own choice (or the shared trip's), picked from the chip + // in the map's bottom-left corner. A change re-routes. async _setupVehicle() { - const select = this._panel.querySelector(".route-panel__vehicle-select"); - const editButton = this._panel.querySelector('[data-action="vehicle-edit"]'); - const fieldset = this._panel.querySelector(".route-panel__vehicle"); - const inputs = [...fieldset.querySelectorAll("input, select")]; + const dialog = document.querySelector("dialog.profiles"); + const fieldset = dialog.querySelector(".profiles__form"); + const inputs = [...fieldset.querySelectorAll(":scope > label input, :scope > label select")]; + const list = dialog.querySelector(".profiles__list ul"); + const vignetteList = dialog.querySelector(".profiles__vignettes ul"); const avoidRow = this._panel.querySelector(".route-panel__avoid"); try { this._vehicles = await (await fetch(VEHICLES_URL)).json(); } catch { return; } + let editId = null; // the profile open in the dialog, apart from the one in use const current = () => this._vehicles.find((v) => v.id === this._vehicleId) || this._vehicles[0]; - const fill = () => { - select.replaceChildren(...this._vehicles.map((v) => new Option(v.name, v.id))); - this._vehicle = current(); - this._vehicleId = select.value = this._vehicle.id; - inputs.forEach((input) => (input.value = this._vehicle[input.name] ?? "")); - // No type: a car (profiles saved before bicycle/foot existed). - const type = (fieldset.querySelector('[name="type"]').value = this._vehicle.type || "car"); - if (type === "bicycle" && !this._vehicle.bicycle_type) fieldset.querySelector('[name="bicycle_type"]').value = "Hybrid"; + const edited = () => this._vehicles.find((v) => v.id === editId) || current(); + const typeOf = (v) => v.type || "car"; + + const chip = document.createElement("div"); + chip.className = "maplibregl-ctrl profile-chip"; + chip.innerHTML = ``; + const chipButton = chip.querySelector(".profile-chip__button"); + const chipList = chip.querySelector(".profile-chip__list"); + this._map.addControl({ onAdd: () => chip, onRemove: () => chip.remove() }, "bottom-left"); + const row = (v, onPick) => { + const li = document.createElement("li"); + const button = Object.assign(document.createElement("button"), { type: "button" }); + button.innerHTML = `${PROFILE_ICONS[typeOf(v)]}`; + button.querySelector("b").textContent = v.name; + button.querySelector("small").textContent = profileMeta(v); + button.addEventListener("click", () => onPick(v)); + li.appendChild(button); + return li; + }; + + const fillForm = () => { + const v = edited(); + list.replaceChildren(...this._vehicles.map((p) => { + const li = row(p, (picked) => { editId = picked.id; fillForm(); }); + li.classList.toggle("is-open", p === v); + return li; + })); + inputs.forEach((input) => (input.value = v[input.name] ?? "")); + const type = (fieldset.querySelector('[name="type"]').value = typeOf(v)); + if (type === "bicycle" && !v.bicycle_type) fieldset.querySelector('[name="bicycle_type"]').value = "Hybrid"; fieldset.querySelectorAll("[data-for]").forEach((el) => (el.hidden = !el.dataset.for.split(" ").includes(type))); - avoidRow.hidden = type !== "car"; // tolls/motorways: a car's choice + vignetteList.replaceChildren(...(v.vignettes || []).map((vignette, i) => { + const li = document.createElement("li"); + li.innerHTML = ` + + `; + li.querySelector('[name="country"]').value = vignette.country || ""; + li.querySelector('[name="kind"]').value = vignette.kind || "vignette"; + li.querySelector('[name="until"]').value = vignette.until || ""; + li.querySelectorAll("input, select").forEach((el) => el.addEventListener("change", () => { + const value = el.value.trim(); + if (value) vignette[el.name] = el.name === "country" ? value.toUpperCase() : value; + else delete vignette[el.name]; + if (vignette.country?.length === 2) save(); + })); + li.querySelector("button").addEventListener("click", () => { + v.vignettes.splice(i, 1); + save(); + }); + return li; + })); + }; + const fill = () => { + this._vehicle = current(); + this._vehicleId = this._vehicle.id; + chipButton.innerHTML = `${PROFILE_ICONS[typeOf(this._vehicle)]} ▴`; + chipButton.children[1].textContent = [this._vehicle.name, typeOf(this._vehicle) === "car" ? profileMeta(this._vehicle) : ""].filter(Boolean).join(" · "); + chipList.replaceChildren(...this._vehicles.map((v) => { + const li = row(v, (picked) => { + chipList.hidden = true; + this._selectVehicle(picked.id); + this._fetchRoute(); + }); + li.classList.toggle("is-current", v === this._vehicle); + return li; + })); + if (isLoggedIn()) { + const edit = Object.assign(document.createElement("button"), { type: "button", className: "profile-chip__edit", textContent: "Edit profiles…" }); + edit.addEventListener("click", () => { + chipList.hidden = true; + editId = this._vehicleId; + fillForm(); + dialog.showModal(); + }); + chipList.appendChild(Object.assign(document.createElement("li"), { className: "profile-chip__edit-row" })).appendChild(edit); + } + avoidRow.hidden = typeOf(this._vehicle) !== "car"; // tolls/motorways: a car's choice + if (this._lastCountries) this._showCountries(this._lastCountries); + if (dialog.open) fillForm(); + notifyVehicle(this._vehicle); }; this._selectVehicle = (id) => { this._vehicleId = id; @@ -853,11 +1097,11 @@ export class RoutePanelControl { if (response.ok) { this._vehicles = data; } else { - window.alert(data.error || "Could not save the vehicles."); + window.alert(data.error || "Could not save the profiles."); this._vehicles = await (await fetch(VEHICLES_URL)).json(); } fill(); - this._fetchRoute(); + if (edited() === current()) this._fetchRoute(); }; try { @@ -865,33 +1109,35 @@ export class RoutePanelControl { this._vehicleId = this._version >= 0 && this._vehicleId ? this._vehicleId : localStorage.getItem(VEHICLE_KEY); } catch {} fill(); - select.addEventListener("change", () => { - this._selectVehicle(select.value); - this._fetchRoute(); - }); - - editButton.hidden = !isLoggedIn(); - editButton.addEventListener("click", () => (fieldset.hidden = !fieldset.hidden)); + chipButton.addEventListener("click", () => (chipList.hidden = !chipList.hidden)); + document.addEventListener("click", (e) => !chip.contains(e.target) && (chipList.hidden = true)); + dialog.querySelector(".profiles__close").addEventListener("click", () => dialog.close()); inputs.forEach((input) => input.addEventListener("change", () => { const value = input.value.trim(); - if (input.name === "name") current().name = value; - else if (value === "") delete current()[input.name]; - else if (input.name === "type" || input.name === "bicycle_type") current()[input.name] = value; - else current()[input.name] = value; + if (input.name === "name") edited().name = value; + else if (value === "") delete edited()[input.name]; + else edited()[input.name] = value; save(); }), ); - fieldset.querySelector('[data-action="vehicle-add"]').addEventListener("click", () => { + dialog.querySelector('[data-action="vignette-add"]').addEventListener("click", () => { + (edited().vignettes ||= []).push({ country: "", kind: "vignette" }); + fillForm(); + vignetteList.lastElementChild?.querySelector("input")?.focus(); + }); + dialog.querySelector('[data-action="vehicle-add"]').addEventListener("click", () => { const id = `v${Date.now().toString(36)}`; - this._vehicles.push({ ...current(), id, name: "New vehicle" }); - this._selectVehicle(id); + this._vehicles.push({ ...edited(), id, name: "New profile" }); + editId = id; save(); }); - fieldset.querySelector('[data-action="vehicle-delete"]').addEventListener("click", () => { - if (this._vehicles.length < 2 || !window.confirm(`Delete the vehicle "${current().name}"?`)) return; - this._vehicles = this._vehicles.filter((v) => v !== current()); - this._selectVehicle(this._vehicles[0].id); + dialog.querySelector('[data-action="vehicle-delete"]').addEventListener("click", () => { + if (this._vehicles.length < 2 || !window.confirm(`Delete the profile "${edited().name}"?`)) return; + const gone = edited(); + this._vehicles = this._vehicles.filter((v) => v !== gone); + editId = null; + if (gone === current()) this._selectVehicle(this._vehicles[0].id); save(); }); } diff --git a/public/js/speed_limits.js b/public/js/speed_limits.js new file mode 100644 index 0000000..5d2379a --- /dev/null +++ b/public/js/speed_limits.js @@ -0,0 +1,71 @@ +// The countries' general speed limits (km/h) for a car / a vehicle up to +// 3.5 t and for a motorhome over 3.5 t: [motorway, expressway, outside towns, +// in towns]; null = no general limit. What a road's own sign says wins when +// it's lower (dashboard.js), these fill in what a vehicle may not exceed. +// +// Sources (read 2026-12-03; both are camping guides built on ADAC's tables, +// not the laws themselves — check before relying on a figure): +// W = womoly.app/wohnmobil-ratgeber/tempolimits-europa (Stand Oktober 2026) +// C = copilot.travel/maps/caravan-speed-limits (read up to 2026-10-31) +// CZ, HU, PL, SK only from C (a secondary source). Left out where the two +// disagree or depend on the registration: ES, SE, NO, BE, LU, and countries +// neither covers (RO, BG, GR). +// ponytail: one figure per road class; night/rain limits, Germany's 100 only for a +// registered Wohnmobil up to 7.5 t, France's 80/90 by département not modelled +export const SPEED_LIMITS = { + AT: { car: [130, 100, 100, 50], heavy: [80, 80, 70, 50], src: "W, C" }, + CH: { car: [120, 100, 80, 50], heavy: [100, 100, 80, 50], src: "W, C" }, + CZ: { car: [130, 110, 90, 50], heavy: [80, 80, 80, 50], src: "C" }, + DE: { car: [null, 100, 100, 50], heavy: [100, 100, 80, 50], src: "W, C; 100 only registered as Wohnmobil, else 80" }, + DK: { car: [130, 80, 80, 50], heavy: [80, 80, 80, 50], src: "W, C" }, + FR: { car: [130, 110, 80, 50], heavy: [110, 100, 80, 50], src: "W, C" }, + HR: { car: [130, 110, 90, 50], heavy: [90, 80, 80, 50], src: "W, C" }, + HU: { car: [130, 110, 90, 50], heavy: [80, 70, 70, 50], src: "C" }, + IT: { car: [130, 110, 90, 50], heavy: [100, 80, 80, 50], src: "W, C" }, + NL: { car: [100, 100, 80, 50], heavy: [80, 80, 80, 50], src: "W, C; 130 at night on some motorways" }, + PL: { car: [140, 120, 90, 50], heavy: [80, 80, 70, 50], src: "C" }, + PT: { car: [120, 100, 90, 50], heavy: [100, 90, 80, 50], src: "W, C" }, + SI: { car: [130, 110, 90, 50], heavy: [80, 80, 80, 50], src: "W, C" }, + SK: { car: [130, 130, 90, 50], heavy: [90, 90, 90, 50], src: "C" }, +}; + +// Motorways paid by a time-based vignette (a car up to 3.5 t); over 3.5 t +// these countries charge by distance (a toll unit) instead. +export const VIGNETTE_COUNTRIES = new Set(["AT", "BG", "CH", "CZ", "HU", "MD", "RO", "SI", "SK"]); + +export const COUNTRY_NAMES = new Intl.DisplayNames(["en"], { type: "region" }); + +// Over 3.5 t: a car profile heavier than that. +export const isHeavy = (vehicle) => (vehicle?.type || "car") === "car" && (vehicle?.weight ?? 0) > 3.5; + +// The column of the four for a Valhalla road class. +const column = (roadClass) => (roadClass === "motorway" ? 0 : roadClass === "trunk" ? 1 : 2); + +// The vehicle's limit on this road: the general one for its class and road +// class (outside towns: Valhalla doesn't say where a town starts, a town's +// own 50 is the road's sign), or null where none is known. +export function vehicleLimit(code, roadClass, vehicle) { + const row = SPEED_LIMITS[code]; + return row ? row[isHeavy(vehicle) ? "heavy" : "car"][column(roadClass)] : null; +} + +// The lower of the road's sign (a number, "unlimited" or null) and the +// vehicle's own limit there. Only for a heavy vehicle: a car's general limit +// is what the road's sign already says, or unknown. +export function effectiveLimit(sign, code, roadClass, vehicle) { + const own = isHeavy(vehicle) ? vehicleLimit(code, roadClass, vehicle) : null; + if (own == null) return sign; + return typeof sign === "number" ? Math.min(sign, own) : own; +} + +// How the motorways are paid there, and whether the profile has it: +// { how: "vignette" | "toll unit" | null, has: true | false | null, until }. +export function motorwayPayment(code, vehicle, today = new Date().toISOString().slice(0, 10)) { + const heavy = isHeavy(vehicle); + const how = VIGNETTE_COUNTRIES.has(code) ? (heavy ? "toll unit" : "vignette") : null; + if (!how) return { how: null, has: null }; + const kind = heavy ? "toll" : "vignette"; + const owned = (vehicle?.vignettes || []).find((v) => v.country === code && (v.kind || "vignette") === kind); + if (!owned) return { how, has: false }; + return { how, has: !owned.until || owned.until >= today, until: owned.until || null }; +} diff --git a/test/test_routing.rb b/test/test_routing.rb index ada0715..0ac7397 100644 --- a/test/test_routing.rb +++ b/test/test_routing.rb @@ -113,6 +113,19 @@ class RoutingTest < Minitest::Test assert_raises(ArgumentError) { Maptool::Routing.save_vehicles(@data, []) } end + 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 ", + "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", + 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| + assert_raises(ArgumentError) { Maptool::Routing.save_vehicles(@data, [{ "id" => "x", "name" => "X", **bad }]) } + end + end + def test_the_old_single_vehicle_becomes_the_camper File.write(File.join(@data, "vehicle.json"), JSON.generate(height: 3.3, width: 2.3, length: 7, weight: 3.5)) assert_equal 3.3, Maptool::Routing.vehicle(@data, "camper")[:height] @@ -156,6 +169,7 @@ class RoutingTest < Minitest::Test assert_equal [{ code: "AT", km: 1.5, motorway_km: 1.0, toll_km: 0.0 }, { code: "SK", km: 1.5, motorway_km: 1.5, toll_km: 1.5 }], properties[:countries] assert_equal [[0.0, 130], [1.0, nil], [1.5, 130]], properties[:speed_limits] assert_equal [[9.521034, 47.140974, 1.5]], properties[:signals] + assert_equal [[0.0, "motorway", "AT"], [1.0, "primary", "AT"], [1.5, "motorway", "SK"]], properties[:roads] end assert_includes request, %("costing_options":{"auto":{"use_tolls":0.0}}) assert_includes request, "/trace_attributes" @@ -163,7 +177,8 @@ class RoutingTest < Minitest::Test def test_the_road_driven_is_the_last_matched_edge reply = JSON.generate(edges: [{ names: ["A"], road_class: "primary", speed_limit: 90 }, { names: ["B"], road_class: "motorway", speed_limit: "unlimited", surface: "paved_smooth" }]) - request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}") do |url| + no_route = "HTTP/1.1 400 Bad Request\r\nContent-Length: 2\r\n\r\n{}" # the signals ahead: none + request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}", no_route) do |url| assert_equal({ name: "B", road_class: "motorway", speed_limit: "unlimited", surface: "paved_smooth" }, Maptool::Routing.road(url, [[17.1, 48.1], [17.2, 48.2]])) end assert_includes request, %("shape_match":"map_snap") diff --git a/test/test_trip.rb b/test/test_trip.rb index 4f015e6..e411546 100644 --- a/test/test_trip.rb +++ b/test/test_trip.rb @@ -26,6 +26,23 @@ class TripTest < Minitest::Test end end + def test_the_itinerary_keeps_nights_stays_notes_and_the_start_without_routing_again + Dir.mktmpdir do |dir| + store = Maptool::TripStore.new(File.join(dir, "trip.json")) + calls = 0 + 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) + 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_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 + # 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/views/importmap.erb b/views/importmap.erb index 8e752ec..552126b 100644 --- a/views/importmap.erb +++ b/views/importmap.erb @@ -40,6 +40,7 @@ "/js/share_import.js": "/js/share_import.js?v=<%= ASSET_VERSION %>", "/js/search.js": "/js/search.js?v=<%= ASSET_VERSION %>", "/js/shadow.js": "/js/shadow.js?v=<%= ASSET_VERSION %>", + "/js/speed_limits.js": "/js/speed_limits.js?v=<%= ASSET_VERSION %>", "/js/sun.js": "/js/sun.js?v=<%= ASSET_VERSION %>", "/js/track_profile.js": "/js/track_profile.js?v=<%= ASSET_VERSION %>", "/vendor/maplibre-gl/maplibre-gl.mjs": "/vendor/maplibre-gl/maplibre-gl.mjs?v=<%= ASSET_VERSION %>", diff --git a/views/index.erb b/views/index.erb index 91d2bfc..5b56d96 100644 --- a/views/index.erb +++ b/views/index.erb @@ -166,6 +166,13 @@ saving at the bottom. -->
+ +
+ + + +
    @@ -180,61 +187,11 @@

    -
    - Vehicle - - -
    Avoid
    -
    + + + +

    Profiles

    +
      +
      + + + + + + + + + + + + + + +
      + Vignettes & toll units +
        + +
        +

        Empty: no limit. Over 3.5 t routes as a truck.

        +

        Empty speed: the usual one for the bike or walking.

        + +
        +
        Stored on this server for every screen; changes save as you go.
        +