From 38368fc8010cbcadc34a05b3daf2f1a2f40693b8 Mon Sep 17 00:00:00 2001 From: Roman Priesol Date: Tue, 17 Nov 2026 16:47:22 +0100 Subject: [PATCH] Profile: 1/5/10 km splits or laps (FIT/TCX) shaded in the charts, in the table and as numbered posts on the map; tooltip follows the pointer over the plots only --- docs/library-design.adoc | 5 + lib/maptool/fit.rb | 42 +++++-- lib/maptool/library.rb | 4 +- lib/maptool/tcx.rb | 24 ++-- public/css/style.css | 47 ++++++- public/js/route.js | 1 + public/js/track_profile.js | 251 ++++++++++++++++++++++++++----------- test/test_app.rb | 5 +- test/test_fit.rb | 14 +++ 9 files changed, 292 insertions(+), 101 deletions(-) diff --git a/docs/library-design.adoc b/docs/library-design.adoc index 9be7706..d713d1c 100644 --- a/docs/library-design.adoc +++ b/docs/library-design.adoc @@ -241,6 +241,11 @@ phone can't skip a change. `PowerInWatts`, TCX `Watts`) go into the profile; the profile panel computes splits and best efforts (fastest distances, best power over 5 s–60 min, biggest climb) from it in the browser. +* Laps: `laps` holds each lap's first profile index (FIT lap + `start_time`, TCX ``), only with two or more. The panel switches + splits between 1/5/10 km (default by activity: run/hike 1, bike 5, + car 10) and laps; the segments are shaded in the charts, listed in the + table and marked as numbered posts on the map. === FIT course out diff --git a/lib/maptool/fit.rb b/lib/maptool/fit.rb index f1c0048..36a53e8 100644 --- a/lib/maptool/fit.rb +++ b/lib/maptool/fit.rb @@ -5,7 +5,7 @@ module Maptool # to a GeoJSON FeatureCollection, in the same shape Gpx.to_geojson produces # for a : one Feature per file, geometry MultiLineString, "kind" => # "track". Only "record" messages (the track points) and one "sport"/ - # "session" field (the activity type) are read — FIT also carries laps, + # "session" field (the activity type) and lap start times are read — FIT also carries # events, device info, developer fields, none of which this app has # anywhere to show, so they're skipped by byte-length rather than # interpreted. @@ -16,6 +16,8 @@ module Maptool RECORD_MESSAGE_NUM = 20 SPORT_MESSAGE_NUM = 12 SESSION_MESSAGE_NUM = 18 + LAP_MESSAGE_NUM = 19 + FIELD_LAP_START_TIME = 2 FIELD_POSITION_LAT = 0 FIELD_POSITION_LONG = 1 FIELD_ALTITUDE = 2 @@ -46,7 +48,7 @@ module Maptool }.freeze Definition = Struct.new(:global_mesg_num, :little_endian, :fields, :total_size) - ParseResult = Struct.new(:records, :activity_type) + ParseResult = Struct.new(:records, :activity_type, :lap_starts) def self.kinds(path) to_geojson(path)["features"].empty? ? [] : ["track"] @@ -62,6 +64,7 @@ module Maptool def self.track_feature(result) coordinates = result.records.map { |r| r[:coordinate] } + laps = lap_indices(result) extras = result.records.map { |r| { speed_mps: r[:speed_mps], cadence_rpm: r[:cadence], heart_rate_bpm: r[:heart_rate], power_w: r[:power], temperature_c: r[:temperature] } } { @@ -69,11 +72,20 @@ module Maptool "geometry" => { "type" => "MultiLineString", "coordinates" => [coordinates] }, "properties" => { "kind" => "track", "name" => nil, "activity_type" => result.activity_type } .merge(TrackStats.compute(coordinates, times: result.records.map { |r| r[:time] })) - .merge("profile" => TrackStats.build_profile(coordinates, times: result.records.map { |r| r[:time] }, extras: extras)), + .merge("profile" => TrackStats.build_profile(coordinates, times: result.records.map { |r| r[:time] }, extras: extras)) + .merge(laps ? { "laps" => laps } : {}), } end private_class_method :track_feature + # Index of the first record of each lap, nil for a single lap. + def self.lap_indices(result) + indices = result.lap_starts.sort.map { |t| result.records.index { |r| r[:time] && r[:time].to_i >= t } }.compact.uniq + indices[0] = 0 if indices.any? + indices.size > 1 ? indices : nil + end + private_class_method :lap_indices + def self.parse(data) raise ParseError, "not a FIT file" if data.bytesize < 12 || data.byteslice(8, 4) != ".FIT" @@ -85,6 +97,7 @@ module Maptool offset = header_size definitions = {} records = [] + lap_starts = [] activity_type = nil while offset < data_end @@ -94,7 +107,7 @@ module Maptool if header & 0x80 != 0 local_type = (header >> 5) & 0x3 definition = definitions[local_type] or raise ParseError, "data message before its definition" - offset, sport = read_data_message(data, offset, definition, records) + offset, sport = read_data_message(data, offset, definition, records, lap_starts) activity_type ||= sport elsif header & 0x40 != 0 local_type = header & 0x0F @@ -103,12 +116,12 @@ module Maptool else local_type = header & 0x0F definition = definitions[local_type] or raise ParseError, "data message before its definition" - offset, sport = read_data_message(data, offset, definition, records) + offset, sport = read_data_message(data, offset, definition, records, lap_starts) activity_type ||= sport end end - ParseResult.new(records, activity_type) + ParseResult.new(records, activity_type, lap_starts) rescue ArgumentError, NoMethodError => e raise ParseError, e.message end @@ -143,11 +156,14 @@ module Maptool # Returns [next_offset, sport_name_or_nil] — the latter only set when # this message happens to be the one sport/session message carrying it. - def self.read_data_message(data, offset, definition, records) + def self.read_data_message(data, offset, definition, records, lap_starts) sport = nil if definition.global_mesg_num == RECORD_MESSAGE_NUM record = extract_record(data, offset, definition) records << record if record + elsif definition.global_mesg_num == LAP_MESSAGE_NUM + start = field_value(data, offset, definition, FIELD_LAP_START_TIME) + lap_starts << FIT_EPOCH + start if start && !invalid?(start, 4) elsif (field_num = SPORT_FIELD_BY_MESSAGE[definition.global_mesg_num]) sport = extract_sport(data, offset, definition, field_num) end @@ -156,16 +172,20 @@ module Maptool private_class_method :read_data_message def self.extract_sport(data, offset, definition, target_field_num) + value = field_value(data, offset, definition, target_field_num) + value && SPORT_NAMES[value] + end + + def self.field_value(data, offset, definition, target_field_num) pos = offset definition.fields.each do |field_num, size| - if field_num == target_field_num - value = unpack_int(data, pos, size, definition.little_endian, signed: false) - return SPORT_NAMES[value] - end + return unpack_int(data, pos, size, definition.little_endian, signed: false) if field_num == target_field_num + pos += size end nil end + private_class_method :field_value private_class_method :extract_sport # Only reads the fields the map/its properties need; every other field diff --git a/lib/maptool/library.rb b/lib/maptool/library.rb index 3a9d4b6..7e157a2 100644 --- a/lib/maptool/library.rb +++ b/lib/maptool/library.rb @@ -37,7 +37,7 @@ module Maptool EXTENSIONS = %w[.gpx .fit .tcx .geojson].freeze # Bumped when a parser starts reading more (power, temperature, ...): # tracks imported before get their profile re-read once (reparse). - PARSER_VERSION = 1 + PARSER_VERSION = 2 def initialize(db_path, gpx_store:, sources_dir:) @path = db_path @@ -92,7 +92,7 @@ module Maptool write do |db, rev, now| db.execute("UPDATE items SET properties = ?, updated_at = ?, rev = ? WHERE id = ?", - [JSON.generate(JSON.parse(props).merge("profile" => feature["properties"]["profile"])), now, rev, id]) + [JSON.generate(JSON.parse(props).merge(feature["properties"].slice("profile", "laps"))), now, rev, id]) end updated += 1 rescue Gpx::ParseError, Fit::ParseError, Errno::ENOENT, JSON::ParserError, GpxStore::InvalidPath diff --git a/lib/maptool/tcx.rb b/lib/maptool/tcx.rb index a9048de..b6e76ab 100644 --- a/lib/maptool/tcx.rb +++ b/lib/maptool/tcx.rb @@ -22,24 +22,30 @@ module Maptool points = [] times = [] extras = [] - activity.each_element("Lap/Track/Trackpoint") do |pt| - lat = text(pt, "Position/LatitudeDegrees") - lon = text(pt, "Position/LongitudeDegrees") - next unless lat && lon + laps = [] # index of each lap's first positioned point + activity.each_element("Lap") do |lap| + laps << points.size + lap.each_element("Track/Trackpoint") do |pt| + lat = text(pt, "Position/LatitudeDegrees") + lon = text(pt, "Position/LongitudeDegrees") + next unless lat && lon - ele = text(pt, "AltitudeMeters") - points << (ele ? [lon.to_f, lat.to_f, ele.to_f] : [lon.to_f, lat.to_f]) - times << (Time.iso8601(text(pt, "Time")) rescue nil) - extras << extensions(pt).merge({ heart_rate_bpm: text(pt, "HeartRateBpm/Value")&.to_i, cadence_rpm: text(pt, "Cadence")&.to_i }.compact) + ele = text(pt, "AltitudeMeters") + points << (ele ? [lon.to_f, lat.to_f, ele.to_f] : [lon.to_f, lat.to_f]) + times << (Time.iso8601(text(pt, "Time")) rescue nil) + extras << extensions(pt).merge({ heart_rate_bpm: text(pt, "HeartRateBpm/Value")&.to_i, cadence_rpm: text(pt, "Cadence")&.to_i }.compact) + end end next if points.empty? + laps = laps.uniq.reject { |i| i >= points.size } features << { "type" => "Feature", "geometry" => { "type" => "MultiLineString", "coordinates" => [points] }, "properties" => { "kind" => "track", "name" => nil, "activity_type" => SPORTS.fetch(activity.attributes["Sport"], activity.attributes["Sport"]&.downcase) } .merge(TrackStats.compute(points, times: times)) - .merge("profile" => TrackStats.build_profile(points, times: times, extras: extras)), + .merge("profile" => TrackStats.build_profile(points, times: times, extras: extras)) + .merge(laps.size > 1 ? { "laps" => laps } : {}), } end { "type" => "FeatureCollection", "features" => features } diff --git a/public/css/style.css b/public/css/style.css index 8d71dc2..20edf9c 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -2118,11 +2118,52 @@ html, body { bottom: 2px; } -.profile-panel__xaxis-toggle { +.profile-panel__controls { display: flex; - justify-content: flex-end; - gap: 4px; + flex-wrap: wrap; + align-items: center; + gap: 4px 8px; margin-bottom: 4px; + font-size: 11px; + color: #898781; +} + +.profile-panel__controls-spacer { + flex: 1; +} + +.profile-panel__toggle { + display: inline-flex; + gap: 4px; +} + +.profile-panel__plots { + position: relative; +} + +/* Segment numbers over the charts, centred on their segment. */ +.profile-panel__segments { + position: relative; + height: 16px; +} + +.profile-panel__segments span { + position: absolute; + transform: translateX(-50%); + min-width: 14px; + padding: 0 3px; + border: 1px solid #e1e0d9; + border-radius: 3px; + background: #fcfcfb; + color: #52514e; + font-size: 10px; + line-height: 13px; + text-align: center; +} + +.profile-chart__segment { + fill: #0b0b0b; + fill-opacity: 0.05; } .profile-panel__xaxis-toggle-btn { diff --git a/public/js/route.js b/public/js/route.js index 38aa423..3ec3b64 100644 --- a/public/js/route.js +++ b/public/js/route.js @@ -284,6 +284,7 @@ export class RoutePanelControl { const elevation = this._route.elevation; return { name: this._editing?.name || "Route", + vehicle_type: this._vehicle?.type || "car", // picks the default split length distance_meters: km * 1000, duration_secs: seconds, ...(elevation && { elevation_gain_meters: elevation.gain, profile: elevation.profile }), diff --git a/public/js/track_profile.js b/public/js/track_profile.js index ccf5416..4687e2d 100644 --- a/public/js/track_profile.js +++ b/public/js/track_profile.js @@ -29,6 +29,7 @@ const SERIES = [ const BEST_DISTANCES_KM = [1, 5, 10, 21.0975, 42.195, 100]; const BEST_POWER_SECS = [5, 60, 300, 1200, 3600]; const CLIMB_TOLERANCE_M = 10; // a dip smaller than this doesn't end a climb +const MILEPOST_SOURCE = "profile-mileposts"; export class TrackProfilePanel { constructor(map) { @@ -60,43 +61,141 @@ export class TrackProfilePanel { this._stats.textContent += ` · ${Math.round(avg)} °C (${Math.round(Math.min(...temperatures))}–${Math.round(Math.max(...temperatures))})`; } - this._chartsContainer.innerHTML = ""; - this._tooltip = document.createElement("div"); - this._tooltip.className = "profile-panel__tooltip"; - this._tooltip.hidden = true; - this._chartsContainer.appendChild(this._tooltip); + this._activityType = properties.activity_type || properties.vehicle_type || (properties.vehicle && (properties.vehicle.type || "car")) || ""; + this._ride = /cycl|bik|ride/i.test(this._activityType); + this._laps = Array.isArray(properties.laps) && properties.laps.length > 1 ? properties.laps : null; + this._segmentMode = /driv|motor|car/i.test(this._activityType) ? "10000" : this._ride ? "5000" : "1000"; - // Only offer the toggle when there's actually elapsed-time data to - // switch to — plenty of GPX files have no