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
CI / check (push) Successful in 19s
CI / deploy (push) Successful in 17s

This commit is contained in:
randy committed 2026-11-17 16:47:22 +01:00
1 parent 3e487539bc
commit 38368fc801
9 files changed
+292 -101

No files matched your search

+5
View File
@@ -241,6 +241,11 @@ phone can't skip a change.
`PowerInWatts`, TCX `Watts`) go into the profile; the profile panel `PowerInWatts`, TCX `Watts`) go into the profile; the profile panel
computes splits and best efforts (fastest distances, best power over computes splits and best efforts (fastest distances, best power over
5 s–60 min, biggest climb) from it in the browser. 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 `<Lap>`), 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 === FIT course out
+31 -11
View File
@@ -5,7 +5,7 @@ module Maptool
# to a GeoJSON FeatureCollection, in the same shape Gpx.to_geojson produces # to a GeoJSON FeatureCollection, in the same shape Gpx.to_geojson produces
# for a <trk>: one Feature per file, geometry MultiLineString, "kind" => # for a <trk>: one Feature per file, geometry MultiLineString, "kind" =>
# "track". Only "record" messages (the track points) and one "sport"/ # "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 # events, device info, developer fields, none of which this app has
# anywhere to show, so they're skipped by byte-length rather than # anywhere to show, so they're skipped by byte-length rather than
# interpreted. # interpreted.
@@ -16,6 +16,8 @@ module Maptool
RECORD_MESSAGE_NUM = 20 RECORD_MESSAGE_NUM = 20
SPORT_MESSAGE_NUM = 12 SPORT_MESSAGE_NUM = 12
SESSION_MESSAGE_NUM = 18 SESSION_MESSAGE_NUM = 18
LAP_MESSAGE_NUM = 19
FIELD_LAP_START_TIME = 2
FIELD_POSITION_LAT = 0 FIELD_POSITION_LAT = 0
FIELD_POSITION_LONG = 1 FIELD_POSITION_LONG = 1
FIELD_ALTITUDE = 2 FIELD_ALTITUDE = 2
@@ -46,7 +48,7 @@ module Maptool
}.freeze }.freeze
Definition = Struct.new(:global_mesg_num, :little_endian, :fields, :total_size) 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) def self.kinds(path)
to_geojson(path)["features"].empty? ? [] : ["track"] to_geojson(path)["features"].empty? ? [] : ["track"]
@@ -62,6 +64,7 @@ module Maptool
def self.track_feature(result) def self.track_feature(result)
coordinates = result.records.map { |r| r[:coordinate] } 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] } } 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] }, "geometry" => { "type" => "MultiLineString", "coordinates" => [coordinates] },
"properties" => { "kind" => "track", "name" => nil, "activity_type" => result.activity_type } "properties" => { "kind" => "track", "name" => nil, "activity_type" => result.activity_type }
.merge(TrackStats.compute(coordinates, times: result.records.map { |r| r[:time] })) .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 end
private_class_method :track_feature 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) def self.parse(data)
raise ParseError, "not a FIT file" if data.bytesize < 12 || data.byteslice(8, 4) != ".FIT" raise ParseError, "not a FIT file" if data.bytesize < 12 || data.byteslice(8, 4) != ".FIT"
@@ -85,6 +97,7 @@ module Maptool
offset = header_size offset = header_size
definitions = {} definitions = {}
records = [] records = []
lap_starts = []
activity_type = nil activity_type = nil
while offset < data_end while offset < data_end
@@ -94,7 +107,7 @@ module Maptool
if header & 0x80 != 0 if header & 0x80 != 0
local_type = (header >> 5) & 0x3 local_type = (header >> 5) & 0x3
definition = definitions[local_type] or raise ParseError, "data message before its definition" 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 activity_type ||= sport
elsif header & 0x40 != 0 elsif header & 0x40 != 0
local_type = header & 0x0F local_type = header & 0x0F
@@ -103,12 +116,12 @@ module Maptool
else else
local_type = header & 0x0F local_type = header & 0x0F
definition = definitions[local_type] or raise ParseError, "data message before its definition" 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 activity_type ||= sport
end end
end end
ParseResult.new(records, activity_type) ParseResult.new(records, activity_type, lap_starts)
rescue ArgumentError, NoMethodError => e rescue ArgumentError, NoMethodError => e
raise ParseError, e.message raise ParseError, e.message
end end
@@ -143,11 +156,14 @@ module Maptool
# Returns [next_offset, sport_name_or_nil] — the latter only set when # Returns [next_offset, sport_name_or_nil] — the latter only set when
# this message happens to be the one sport/session message carrying it. # 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 sport = nil
if definition.global_mesg_num == RECORD_MESSAGE_NUM if definition.global_mesg_num == RECORD_MESSAGE_NUM
record = extract_record(data, offset, definition) record = extract_record(data, offset, definition)
records << record if record 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]) elsif (field_num = SPORT_FIELD_BY_MESSAGE[definition.global_mesg_num])
sport = extract_sport(data, offset, definition, field_num) sport = extract_sport(data, offset, definition, field_num)
end end
@@ -156,16 +172,20 @@ module Maptool
private_class_method :read_data_message private_class_method :read_data_message
def self.extract_sport(data, offset, definition, target_field_num) 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 pos = offset
definition.fields.each do |field_num, size| definition.fields.each do |field_num, size|
if field_num == target_field_num return unpack_int(data, pos, size, definition.little_endian, signed: false) if field_num == target_field_num
value = unpack_int(data, pos, size, definition.little_endian, signed: false)
return SPORT_NAMES[value]
end
pos += size pos += size
end end
nil nil
end end
private_class_method :field_value
private_class_method :extract_sport private_class_method :extract_sport
# Only reads the fields the map/its properties need; every other field # Only reads the fields the map/its properties need; every other field
+2 -2
View File
@@ -37,7 +37,7 @@ module Maptool
EXTENSIONS = %w[.gpx .fit .tcx .geojson].freeze EXTENSIONS = %w[.gpx .fit .tcx .geojson].freeze
# Bumped when a parser starts reading more (power, temperature, ...): # Bumped when a parser starts reading more (power, temperature, ...):
# tracks imported before get their profile re-read once (reparse). # tracks imported before get their profile re-read once (reparse).
PARSER_VERSION = 1 PARSER_VERSION = 2
def initialize(db_path, gpx_store:, sources_dir:) def initialize(db_path, gpx_store:, sources_dir:)
@path = db_path @path = db_path
@@ -92,7 +92,7 @@ module Maptool
write do |db, rev, now| write do |db, rev, now|
db.execute("UPDATE items SET properties = ?, updated_at = ?, rev = ? WHERE id = ?", 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 end
updated += 1 updated += 1
rescue Gpx::ParseError, Fit::ParseError, Errno::ENOENT, JSON::ParserError, GpxStore::InvalidPath rescue Gpx::ParseError, Fit::ParseError, Errno::ENOENT, JSON::ParserError, GpxStore::InvalidPath
+15 -9
View File
@@ -22,24 +22,30 @@ module Maptool
points = [] points = []
times = [] times = []
extras = [] extras = []
activity.each_element("Lap/Track/Trackpoint") do |pt| laps = [] # index of each lap's first positioned point
lat = text(pt, "Position/LatitudeDegrees") activity.each_element("Lap") do |lap|
lon = text(pt, "Position/LongitudeDegrees") laps << points.size
next unless lat && lon 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") ele = text(pt, "AltitudeMeters")
points << (ele ? [lon.to_f, lat.to_f, ele.to_f] : [lon.to_f, lat.to_f]) 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) 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) extras << extensions(pt).merge({ heart_rate_bpm: text(pt, "HeartRateBpm/Value")&.to_i, cadence_rpm: text(pt, "Cadence")&.to_i }.compact)
end
end end
next if points.empty? next if points.empty?
laps = laps.uniq.reject { |i| i >= points.size }
features << { features << {
"type" => "Feature", "type" => "Feature",
"geometry" => { "type" => "MultiLineString", "coordinates" => [points] }, "geometry" => { "type" => "MultiLineString", "coordinates" => [points] },
"properties" => { "kind" => "track", "name" => nil, "activity_type" => SPORTS.fetch(activity.attributes["Sport"], activity.attributes["Sport"]&.downcase) } "properties" => { "kind" => "track", "name" => nil, "activity_type" => SPORTS.fetch(activity.attributes["Sport"], activity.attributes["Sport"]&.downcase) }
.merge(TrackStats.compute(points, times: times)) .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 end
{ "type" => "FeatureCollection", "features" => features } { "type" => "FeatureCollection", "features" => features }
+44 -3
View File
@@ -2118,11 +2118,52 @@ html, body {
bottom: 2px; bottom: 2px;
} }
.profile-panel__xaxis-toggle { .profile-panel__controls {
display: flex; display: flex;
justify-content: flex-end; flex-wrap: wrap;
gap: 4px; align-items: center;
gap: 4px 8px;
margin-bottom: 4px; 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 { .profile-panel__xaxis-toggle-btn {
+1
View File
@@ -284,6 +284,7 @@ export class RoutePanelControl {
const elevation = this._route.elevation; const elevation = this._route.elevation;
return { return {
name: this._editing?.name || "Route", name: this._editing?.name || "Route",
vehicle_type: this._vehicle?.type || "car", // picks the default split length
distance_meters: km * 1000, distance_meters: km * 1000,
duration_secs: seconds, duration_secs: seconds,
...(elevation && { elevation_gain_meters: elevation.gain, profile: elevation.profile }), ...(elevation && { elevation_gain_meters: elevation.gain, profile: elevation.profile }),
+176 -75
View File
@@ -29,6 +29,7 @@ const SERIES = [
const BEST_DISTANCES_KM = [1, 5, 10, 21.0975, 42.195, 100]; const BEST_DISTANCES_KM = [1, 5, 10, 21.0975, 42.195, 100];
const BEST_POWER_SECS = [5, 60, 300, 1200, 3600]; 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 CLIMB_TOLERANCE_M = 10; // a dip smaller than this doesn't end a climb
const MILEPOST_SOURCE = "profile-mileposts";
export class TrackProfilePanel { export class TrackProfilePanel {
constructor(map) { 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._stats.textContent += ` · ${Math.round(avg)} °C (${Math.round(Math.min(...temperatures))}–${Math.round(Math.max(...temperatures))})`;
} }
this._chartsContainer.innerHTML = ""; this._activityType = properties.activity_type || properties.vehicle_type || (properties.vehicle && (properties.vehicle.type || "car")) || "";
this._tooltip = document.createElement("div"); this._ride = /cycl|bik|ride/i.test(this._activityType);
this._tooltip.className = "profile-panel__tooltip"; this._laps = Array.isArray(properties.laps) && properties.laps.length > 1 ? properties.laps : null;
this._tooltip.hidden = true; this._segmentMode = /driv|motor|car/i.test(this._activityType) ? "10000" : this._ride ? "5000" : "1000";
this._chartsContainer.appendChild(this._tooltip);
// Only offer the toggle when there's actually elapsed-time data to // Only offer the time axis when there's actually elapsed-time data —
// switch to — plenty of GPX files have no <time> at all. // plenty of GPX files have no <time> at all.
this._hasTime = this._profile.some((p) => typeof p.elapsed_secs === "number"); this._hasTime = this._profile.some((p) => typeof p.elapsed_secs === "number");
this._xAxisMode = "distance"; this._xAxisMode = "distance";
if (this._hasTime) this._chartsContainer.appendChild(this._renderXAxisToggle());
this._activeSeries = SERIES.filter((s) => this._profile.some((p) => typeof p[s.key] === "number")); this._activeSeries = SERIES.filter((s) => this._profile.some((p) => typeof p[s.key] === "number"));
this._activeSeries.forEach((series) => this._chartsContainer.appendChild(this._renderChart(series)));
const trails = this._renderTrailBand();
if (trails) this._chartsContainer.appendChild(trails);
// One shared strip below the whole stack, not per-chart — every chart this._chartsContainer.innerHTML = "";
// above uses the same x-scale (distance-position), so a separate axis this._chartsContainer.appendChild(this._renderControls());
// per chart would just repeat itself. // Pointer tracking only over the plots, so the controls above and the
this._xAxisStripEl = document.createElement("div"); // tables below stay uncovered by the tooltip.
this._xAxisStripEl.className = "profile-panel__xaxis"; this._plots = document.createElement("div");
this._chartsContainer.appendChild(this._xAxisStripEl); this._plots.className = "profile-panel__plots";
this._renderXAxisTicks(); this._chartsContainer.appendChild(this._plots);
this._chartsContainer.insertAdjacentHTML("beforeend", statsTables(this._profile, properties.activity_type)); this._tables = document.createElement("div");
this._chartsContainer.appendChild(this._tables);
this._renderSegments();
this._chartsContainer.addEventListener("pointermove", this._onPointerMove); this._plots.addEventListener("pointermove", this._onPointerMove);
this._chartsContainer.addEventListener("pointerleave", this._onPointerLeave); this._plots.addEventListener("pointerleave", this._onPointerLeave);
this._panel.hidden = false; this._panel.hidden = false;
} }
// Everything that depends on the split/lap choice: the charts with their
// shaded segments, the tables and the markers on the map.
_renderSegments() {
this._bounds = this._segmentMode === "laps" ? [...this._laps, this._profile.length - 1] : splitBounds(this._profile, Number(this._segmentMode));
this._plots.innerHTML = "";
this._tooltip = document.createElement("div");
this._tooltip.className = "profile-panel__tooltip";
this._tooltip.hidden = true;
this._plots.appendChild(this._tooltip);
this._plots.appendChild(this._renderSegmentLabels());
this._activeSeries.forEach((series) => this._plots.appendChild(this._renderChart(series)));
const trails = this._renderTrailBand();
if (trails) this._plots.appendChild(trails);
// One shared strip below the whole stack, not per-chart — every chart
// above uses the same x-scale (distance-position).
this._xAxisStripEl = document.createElement("div");
this._xAxisStripEl.className = "profile-panel__xaxis";
this._plots.appendChild(this._xAxisStripEl);
this._renderXAxisTicks();
this._tables.innerHTML = statsTables(this._profile, this._bounds, this._segmentMode === "laps", this._ride);
this._showMileposts();
}
_segmentLabel(n) {
if (this._segmentMode === "laps") return `L${n}`;
const km = this._profile[this._bounds[n]].distance_meters / 1000;
return n === this._bounds.length - 1 ? km.toFixed(1) : String(Math.round(km));
}
// Numbered boxes over the segments, thinned out when they'd crowd.
_renderSegmentLabels() {
const strip = document.createElement("div");
strip.className = "profile-panel__segments";
const count = this._bounds.length - 1;
const every = Math.max(1, Math.ceil(count / 40));
let html = "";
for (let n = 1; n <= count; n++) {
if (n % every && n !== count) continue;
const x1 = this._profile[this._bounds[n - 1]].distance_meters / this._maxDistance;
const x2 = this._profile[this._bounds[n]].distance_meters / this._maxDistance;
html += `<span style="left:${(((x1 + x2) / 2) * 100).toFixed(2)}%">${n}</span>`;
}
strip.innerHTML = html;
return strip;
}
// Split ends (or lap ends) as numbered posts along the track.
_showMileposts() {
const data = {
type: "FeatureCollection",
features: this._bounds.slice(1).map((index, i) => ({
type: "Feature",
geometry: { type: "Point", coordinates: [this._profile[index].lon, this._profile[index].lat] },
properties: { label: this._segmentLabel(i + 1) },
})),
};
const source = this._map.getSource(MILEPOST_SOURCE);
if (source) return source.setData(data);
this._map.addSource(MILEPOST_SOURCE, { type: "geojson", data });
this._map.addLayer({
id: MILEPOST_SOURCE,
type: "circle",
source: MILEPOST_SOURCE,
paint: { "circle-radius": 9, "circle-color": "#fff", "circle-stroke-color": "#0b0b0b", "circle-stroke-width": 1.5 },
});
this._map.addLayer({
id: `${MILEPOST_SOURCE}-label`,
type: "symbol",
source: MILEPOST_SOURCE,
layout: { "text-field": ["get", "label"], "text-font": ["Noto Sans Regular"], "text-size": 10, "text-allow-overlap": true },
paint: { "text-color": "#0b0b0b" },
});
}
_hideMileposts() {
[`${MILEPOST_SOURCE}-label`, MILEPOST_SOURCE].forEach((id) => this._map.getLayer(id) && this._map.removeLayer(id));
if (this._map.getSource(MILEPOST_SOURCE)) this._map.removeSource(MILEPOST_SOURCE);
}
_renderControls() {
const row = document.createElement("div");
row.className = "profile-panel__controls";
const segments = [["1000", "1 km"], ["5000", "5 km"], ["10000", "10 km"], ...(this._laps ? [["laps", `Laps (${this._laps.length})`]] : [])];
const group = (name, options, current) =>
`<span class="profile-panel__toggle" data-group="${name}">${options.map(([value, label]) => `<button type="button" class="profile-panel__xaxis-toggle-btn${value === current ? " active" : ""}" data-value="${value}">${label}</button>`).join("")}</span>`;
row.innerHTML = `<span class="profile-panel__controls-label">Splits</span>${group("segments", segments, this._segmentMode)}<span class="profile-panel__controls-spacer"></span>${this._hasTime ? group("axis", [["distance", "Distance"], ["time", "Time"]], this._xAxisMode) : ""}`;
row.addEventListener("click", (event) => {
const btn = event.target.closest("button");
if (!btn || btn.classList.contains("active")) return;
btn.parentElement.querySelectorAll("button").forEach((b) => b.classList.toggle("active", b === btn));
if (btn.parentElement.dataset.group === "axis") {
this._xAxisMode = btn.dataset.value;
this._renderXAxisTicks();
} else {
this._segmentMode = btn.dataset.value;
this._renderSegments();
}
});
return row;
}
hide() { hide() {
this._panel.hidden = true; this._panel.hidden = true;
this._chartsContainer.removeEventListener("pointermove", this._onPointerMove); this._plots?.removeEventListener("pointermove", this._onPointerMove);
this._chartsContainer.removeEventListener("pointerleave", this._onPointerLeave); this._plots?.removeEventListener("pointerleave", this._onPointerLeave);
this._marker.remove(); this._marker.remove();
this._hideMileposts();
} }
_renderChart(series) { _renderChart(series) {
@@ -116,12 +215,20 @@ export class TrackProfilePanel {
? `${linePath} L${points.at(-1)[0].toFixed(1)},${series.height} L0,${series.height} Z` ? `${linePath} L${points.at(-1)[0].toFixed(1)},${series.height} L0,${series.height} Z`
: ""; : "";
let bands = "";
for (let n = 1; n < this._bounds.length; n += 2) {
const x1 = toX(this._profile[this._bounds[n - 1]].distance_meters);
const x2 = toX(this._profile[this._bounds[n]].distance_meters);
bands += `<rect x="${x1.toFixed(1)}" width="${(x2 - x1).toFixed(1)}" y="0" height="${series.height}" class="profile-chart__segment"></rect>`;
}
const wrapper = document.createElement("div"); const wrapper = document.createElement("div");
wrapper.className = "profile-chart"; wrapper.className = "profile-chart";
wrapper.innerHTML = ` wrapper.innerHTML = `
<div class="profile-chart__label">${escapeHtml(series.label)} <span class="profile-chart__unit">(${escapeHtml(series.unit)})</span></div> <div class="profile-chart__label">${escapeHtml(series.label)} <span class="profile-chart__unit">(${escapeHtml(series.unit)})</span></div>
<div class="profile-chart__plot" style="height:${series.height}px"> <div class="profile-chart__plot" style="height:${series.height}px">
<svg viewBox="0 0 ${VIEWBOX_WIDTH} ${series.height}" preserveAspectRatio="none" class="profile-chart__svg"> <svg viewBox="0 0 ${VIEWBOX_WIDTH} ${series.height}" preserveAspectRatio="none" class="profile-chart__svg">
${bands}
${areaPath ? `<path d="${areaPath}" fill="${series.color}" fill-opacity="0.15" stroke="none"></path>` : ""} ${areaPath ? `<path d="${areaPath}" fill="${series.color}" fill-opacity="0.15" stroke="none"></path>` : ""}
<path d="${linePath}" fill="none" stroke="${series.color}" stroke-width="2" vector-effect="non-scaling-stroke"></path> <path d="${linePath}" fill="none" stroke="${series.color}" stroke-width="2" vector-effect="non-scaling-stroke"></path>
<line class="profile-chart__crosshair" x1="0" x2="0" y1="0" y2="${series.height}" hidden></line> <line class="profile-chart__crosshair" x1="0" x2="0" y1="0" y2="${series.height}" hidden></line>
@@ -165,25 +272,6 @@ export class TrackProfilePanel {
return band; return band;
} }
_renderXAxisToggle() {
const row = document.createElement("div");
row.className = "profile-panel__xaxis-toggle";
row.innerHTML = `
<button type="button" class="profile-panel__xaxis-toggle-btn" data-mode="distance">Distance</button>
<button type="button" class="profile-panel__xaxis-toggle-btn" data-mode="time">Time</button>
`;
row.querySelectorAll("button").forEach((btn) => {
btn.classList.toggle("active", btn.dataset.mode === this._xAxisMode);
btn.addEventListener("click", () => {
if (btn.dataset.mode === this._xAxisMode) return;
this._xAxisMode = btn.dataset.mode;
row.querySelectorAll("button").forEach((b) => b.classList.toggle("active", b === btn));
this._renderXAxisTicks();
});
});
return row;
}
_renderXAxisTicks() { _renderXAxisTicks() {
const TICK_COUNT = 5; const TICK_COUNT = 5;
this._xAxisStripEl.innerHTML = Array.from({ length: TICK_COUNT }, (_, i) => { this._xAxisStripEl.innerHTML = Array.from({ length: TICK_COUNT }, (_, i) => {
@@ -198,7 +286,7 @@ export class TrackProfilePanel {
// Bound once (arrow fields, not prototype methods) so add/removeEventListener see the same reference. // Bound once (arrow fields, not prototype methods) so add/removeEventListener see the same reference.
_onPointerMove = (event) => { _onPointerMove = (event) => {
const rect = this._chartsContainer.getBoundingClientRect(); const rect = this._plots.getBoundingClientRect();
const fraction = Math.min(1, Math.max(0, (event.clientX - rect.left) / rect.width)); const fraction = Math.min(1, Math.max(0, (event.clientX - rect.left) / rect.width));
const targetDistance = fraction * this._maxDistance; const targetDistance = fraction * this._maxDistance;
@@ -211,13 +299,13 @@ export class TrackProfilePanel {
_onPointerLeave = () => { _onPointerLeave = () => {
this._tooltip.hidden = true; this._tooltip.hidden = true;
this._chartsContainer.querySelectorAll(".profile-chart__crosshair, .profile-chart__dot").forEach((el) => (el.hidden = true)); this._plots.querySelectorAll(".profile-chart__crosshair, .profile-chart__dot").forEach((el) => (el.hidden = true));
this._marker.remove(); this._marker.remove();
}; };
_updateCrosshair(point) { _updateCrosshair(point) {
const x = (point.distance_meters / this._maxDistance) * VIEWBOX_WIDTH; const x = (point.distance_meters / this._maxDistance) * VIEWBOX_WIDTH;
this._chartsContainer.querySelectorAll(".profile-chart").forEach((wrapper, i) => { this._plots.querySelectorAll(".profile-chart").forEach((wrapper, i) => {
const series = this._activeSeries[i]; const series = this._activeSeries[i];
const value = point[series.key]; const value = point[series.key];
const svg = wrapper.querySelector("svg"); const svg = wrapper.querySelector("svg");
@@ -250,34 +338,42 @@ export class TrackProfilePanel {
this._tooltip.innerHTML = `<div class="profile-panel__tooltip-distance">${(point.distance_meters / 1000).toFixed(2)} km${timeSuffix}</div>${rows}`; this._tooltip.innerHTML = `<div class="profile-panel__tooltip-distance">${(point.distance_meters / 1000).toFixed(2)} km${timeSuffix}</div>${rows}`;
this._tooltip.hidden = false; this._tooltip.hidden = false;
const containerRect = this._chartsContainer.getBoundingClientRect(); // Beside the pointer, flipped to its left near the right edge, and
const left = Math.min(event.clientX - containerRect.left + 12, containerRect.width - this._tooltip.offsetWidth - 8); // following it vertically so it never parks over one spot.
this._tooltip.style.left = `${Math.max(8, left)}px`; const rect = this._plots.getBoundingClientRect();
const x = event.clientX - rect.left;
const width = this._tooltip.offsetWidth;
this._tooltip.style.left = `${Math.max(0, x + 16 + width > rect.width ? x - 16 - width : x + 16)}px`;
this._tooltip.style.top = `${Math.max(0, Math.min(event.clientY - rect.top - this._tooltip.offsetHeight / 2, rect.height - this._tooltip.offsetHeight))}px`;
} }
} }
// Splits and best efforts under the charts, as two collapsed <details>. // Splits (or laps, open) and best efforts (collapsed) under the charts. A planned route has no times: its splits show climbing only.
// Splits need times (a planned route has none); the biggest climb doesn't. function statsTables(profile, bounds, laps, ride) {
function statsTables(profile, activityType) {
const timed = profile.filter((p) => typeof p.elapsed_secs === "number"); const timed = profile.filter((p) => typeof p.elapsed_secs === "number");
const total = profile.at(-1).distance_meters; const total = profile.at(-1).distance_meters;
const ride = /cycl|bik|ride/i.test(activityType || ""); const hasTime = timed.length > 1;
const hasHr = profile.some((p) => typeof p.heart_rate_bpm === "number"); const hasHr = profile.some((p) => typeof p.heart_rate_bpm === "number");
const hasPower = profile.some((p) => typeof p.power_w === "number"); const hasPower = profile.some((p) => typeof p.power_w === "number");
const hasTemp = profile.some((p) => typeof p.temperature_c === "number"); const hasTemp = profile.some((p) => typeof p.temperature_c === "number");
const pace = (secs, meters) => (ride ? `${((meters / secs) * 3.6).toFixed(1)} km/h` : `${formatPace(secs / (meters / 1000))} /km`); const pace = (secs, meters) => (ride ? `${((meters / secs) * 3.6).toFixed(1)} km/h` : `${formatPace(secs / (meters / 1000))} /km`);
const km = (m) => `${(m / 1000).toFixed(m % 1000 ? 2 : 0)} km`;
let html = ""; let html = "";
if (timed.length > 1) { const rows = segmentStats(profile, bounds).map((s, i) => {
const step = ride || total > 50000 ? 5000 : 1000; const cells = [laps ? `${i + 1}` : km(s.to), ...(laps ? [km(s.meters)] : [])];
const rows = splits(timed, step).map( if (hasTime) cells.push(s.secs ? formatDuration(s.secs) : "", s.secs ? pace(s.secs, s.meters) : "");
(s) => `<tr><td>${(s.to / 1000).toFixed(s.to % 1000 ? 1 : 0)} km</td><td>${formatDuration(s.secs)}</td><td>${pace(s.secs, s.meters)}</td><td>↑ ${Math.round(s.gain)} m</td><td>↓ ${Math.round(s.loss)} m</td>${hasHr ? `<td>${s.hr ? `${Math.round(s.hr)} bpm` : ""}</td>` : ""}${hasPower ? `<td>${s.power ? `${Math.round(s.power)} W` : ""}</td>` : ""}${hasTemp ? `<td>${s.temp != null ? `${Math.round(s.temp)} °C` : ""}</td>` : ""}</tr>`, cells.push(`↑ ${Math.round(s.gain)} m`, `↓ ${Math.round(s.loss)} m`);
); if (hasHr) cells.push(s.hr ? `${Math.round(s.hr)} bpm` : "");
html += `<details class="profile-stats"><summary>Splits (${step / 1000} km)</summary><table><thead><tr><th>At</th><th>Time</th><th>${ride ? "Speed" : "Pace"}</th><th>Ascent</th><th>Descent</th>${hasHr ? "<th>Avg HR</th>" : ""}${hasPower ? "<th>Avg power</th>" : ""}${hasTemp ? "<th>Avg temp</th>" : ""}</tr></thead><tbody>${rows.join("")}</tbody></table></details>`; if (hasPower) cells.push(s.power ? `${Math.round(s.power)} W` : "");
} if (hasTemp) cells.push(s.temp != null ? `${Math.round(s.temp)} °C` : "");
return `<tr>${cells.map((c) => `<td>${c}</td>`).join("")}</tr>`;
});
const head = [laps ? "Lap" : "At", ...(laps ? ["Distance"] : []), ...(hasTime ? ["Time", ride ? "Speed" : "Pace"] : []), "Ascent", "Descent", ...(hasHr ? ["Avg HR"] : []), ...(hasPower ? ["Avg power"] : []), ...(hasTemp ? ["Avg temp"] : [])];
if (rows.length) html += `<details class="profile-stats" open><summary>${laps ? "Laps" : "Splits"}</summary><table><thead><tr>${head.map((h) => `<th>${h}</th>`).join("")}</tr></thead><tbody>${rows.join("")}</tbody></table></details>`;
const best = []; const best = [];
if (timed.length > 1) { if (hasTime) {
BEST_DISTANCES_KM.filter((km) => km * 1000 <= total).forEach((km) => { BEST_DISTANCES_KM.filter((km) => km * 1000 <= total).forEach((km) => {
const secs = fastest(timed, km * 1000); const secs = fastest(timed, km * 1000);
if (secs) best.push([`${km === 21.0975 ? "Half marathon" : km === 42.195 ? "Marathon" : `${km} km`}`, `${formatDuration(secs)} · ${pace(secs, km * 1000)}`]); if (secs) best.push([`${km === 21.0975 ? "Half marathon" : km === 42.195 ? "Marathon" : `${km} km`}`, `${formatDuration(secs)} · ${pace(secs, km * 1000)}`]);
@@ -295,15 +391,22 @@ function statsTables(profile, activityType) {
return html; return html;
} }
// Every `step` meters: time, ascent/descent and average heart rate/power, the last // Profile indices where splits end: the first point at/after every `step`
// split shorter. Points are the first at/after each boundary. // meters, plus the last point (that split shorter).
function splits(profile, step) { function splitBounds(profile, step) {
const out = []; const bounds = [0];
let start = 0;
for (let i = 1; i < profile.length; i++) { for (let i = 1; i < profile.length; i++) {
const last = i === profile.length - 1; if (i === profile.length - 1 || profile[i].distance_meters >= bounds.length * step) bounds.push(i);
if (!last && profile[i].distance_meters < (out.length + 1) * step) continue; }
const part = profile.slice(start, i + 1); return bounds;
}
// Per segment between consecutive bounds: distance, time (null without
// times), ascent/descent and average heart rate/power/temperature.
function segmentStats(profile, bounds) {
return bounds.slice(1).map((end, n) => {
const start = bounds[n];
const part = profile.slice(start, end + 1);
let gain = 0; let gain = 0;
let loss = 0; let loss = 0;
part.forEach((p, j) => { part.forEach((p, j) => {
@@ -311,12 +414,10 @@ function splits(profile, step) {
if (climb > 0) gain += climb; if (climb > 0) gain += climb;
else loss -= climb; else loss -= climb;
}); });
const meters = profile[i].distance_meters - profile[start].distance_meters; const [a, b] = [profile[start].elapsed_secs, profile[end].elapsed_secs];
const secs = profile[i].elapsed_secs - profile[start].elapsed_secs; const secs = typeof a === "number" && typeof b === "number" && b > a ? b - a : null;
if (meters > 0 && secs > 0) out.push({ to: profile[i].distance_meters, meters, secs, gain, loss, hr: average(part, "heart_rate_bpm"), power: average(part, "power_w"), temp: average(part, "temperature_c") }); return { to: profile[end].distance_meters, meters: profile[end].distance_meters - profile[start].distance_meters, secs, gain, loss, hr: average(part, "heart_rate_bpm"), power: average(part, "power_w"), temp: average(part, "temperature_c") };
start = i; });
}
return out;
} }
function average(points, key) { function average(points, key) {
+4 -1
View File
@@ -159,11 +159,14 @@ class AppTest < Minitest::Test
tcx = <<~XML tcx = <<~XML
<TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"><Activities><Activity Sport="Biking"><Lap><Track> <TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"><Activities><Activity Sport="Biking"><Lap><Track>
<Trackpoint><Time>2026-05-01T10:00:00Z</Time><Position><LatitudeDegrees>48.1</LatitudeDegrees><LongitudeDegrees>17.1</LongitudeDegrees></Position><AltitudeMeters>140</AltitudeMeters></Trackpoint> <Trackpoint><Time>2026-05-01T10:00:00Z</Time><Position><LatitudeDegrees>48.1</LatitudeDegrees><LongitudeDegrees>17.1</LongitudeDegrees></Position><AltitudeMeters>140</AltitudeMeters></Trackpoint>
</Track></Lap><Lap><Track>
<Trackpoint><Time>2026-05-01T10:01:00Z</Time><Position><LatitudeDegrees>48.11</LatitudeDegrees><LongitudeDegrees>17.1</LongitudeDegrees></Position><AltitudeMeters>150</AltitudeMeters></Trackpoint> <Trackpoint><Time>2026-05-01T10:01:00Z</Time><Position><LatitudeDegrees>48.11</LatitudeDegrees><LongitudeDegrees>17.1</LongitudeDegrees></Position><AltitudeMeters>150</AltitudeMeters></Trackpoint>
</Track></Lap></Activity></Activities></TrainingCenterDatabase> </Track></Lap></Activity></Activities></TrainingCenterDatabase>
XML XML
key = json_body(upload("ride.tcx", tcx))["paths"].first key = json_body(upload("ride.tcx", tcx))["paths"].first
assert_equal "cycling", json_body(request.get(node_url(key)))["features"][0]["properties"]["activity_type"] properties = json_body(request.get(node_url(key)))["features"][0]["properties"]
assert_equal "cycling", properties["activity_type"]
assert_equal [0, 1], properties["laps"]
fit = request.get("#{node_url(key)}?download=fit&name=Ride", **logged_in_env) fit = request.get("#{node_url(key)}?download=fit&name=Ride", **logged_in_env)
assert_equal 200, fit.status assert_equal 200, fit.status
+14
View File
@@ -101,6 +101,20 @@ class FitTest < Minitest::Test
assert_equal "cycling", geojson["features"][0]["properties"]["activity_type"] assert_equal "cycling", geojson["features"][0]["properties"]["activity_type"]
end end
def test_laps_are_the_first_record_index_of_each_lap
record_def = [0b01000000, 0, 0, 20, 3].pack("CCCS<C") + [253, 4, 0x86, 0, 4, 0x85, 1, 4, 0x85].pack("C*")
lap_def = [0b01000001, 0, 0, 19, 1].pack("CCCS<C") + [2, 4, 0x86].pack("C*")
body = record_def + lap_def
body << [0b00000001].pack("C") << le32(1000) # lap 1 starts at t=1000
body << [0b00000001].pack("C") << le32(1002) # lap 2 at t=1002
4.times { |i| body << [0].pack("C") << le32(1000 + i) << le32(100_000_000 + i * 1000) << le32(200_000_000) }
path = File.join(Dir.mktmpdir, "laps.fit")
File.binwrite(path, [12, 16, 0, 0].pack("C2S<") + le32(body.bytesize) + ".FIT" + body + "\x00\x00")
assert_equal [0, 2], Maptool::Fit.to_geojson(path)["features"][0]["properties"]["laps"]
assert_nil Maptool::Fit.to_geojson(write_fit([[1, 2], [3, 4]]))["features"][0]["properties"]["laps"]
end
def test_activity_type_is_nil_without_a_session_message def test_activity_type_is_nil_without_a_session_message
path = write_activity_fit([{ lat: 100_000_000, lon: 200_000_000 }]) path = write_activity_fit([{ lat: 100_000_000, lon: 200_000_000 }])
geojson = Maptool::Fit.to_geojson(path) geojson = Maptool::Fit.to_geojson(path)