Files
maptool/public/js/track_profile.js
T

566 lines
27 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { trailColorsAlong } from "/js/hiking_trails.js";
// Small-multiples profile chart: one row per metric the track actually has
// (elevation always, speed/cadence/heart rate/power only when present — plenty of
// GPX files have none of those), sharing one x-axis (distance) and one
// crosshair. Elevation/speed/cadence/heart rate live on wildly different
// scales, so this is deliberately several single-series charts stacked
// rather than one chart with several y-axes (see dataviz skill: no
// dual-axis charts).
//
// SVG viewBox is a fixed 1000-unit-wide coordinate space (not real pixels)
// stretched to the container via CSS — mouse interaction converts
// clientX through the container's current bounding rect on every move, so
// this stays correct across container width without redrawing, but a
// browser window resize while the panel is open won't reflow the drawn
// paths until it's reopened. Acceptable for a detail panel that's normally
// open briefly; add a resize listener if that turns out to matter.
const VIEWBOX_WIDTH = 1000;
const SERIES = [
{ key: "elevation_meters", label: "Elevation", unit: "m", color: "#2a78d6", height: 110, area: true },
{ key: "speed_kmh", label: "Speed", unit: "km/h", color: "#1baf7a", height: 70, area: false },
{ key: "cadence_rpm", label: "Cadence", unit: "rpm", color: "#eda100", height: 70, area: false },
{ key: "heart_rate_bpm", label: "Heart rate", unit: "bpm", color: "#e34948", height: 70, area: false },
{ key: "power_w", label: "Power", unit: "W", color: "#7b4fd6", height: 70, area: false },
{ key: "temperature_c", label: "Temperature", unit: "°C", color: "#d9730d", height: 70, area: false },
];
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";
const MOVING_MPS = 0.3; // slower counts as a pause on the time axis
export class TrackProfilePanel {
constructor(map) {
this._map = map;
this._profile = null;
this._marker = new Marker({ color: "#7209b7" });
}
mount() {
this._panel = document.getElementById("profile-panel");
this._title = this._panel.querySelector(".profile-panel__title");
this._stats = this._panel.querySelector(".profile-panel__stats");
this._chartsContainer = this._panel.querySelector(".profile-panel__charts");
this._panel.querySelector(".profile-panel__close").addEventListener("click", () => this.hide());
}
show(properties) {
const profile = properties.profile;
if (!profile || profile.length === 0) return;
this._profile = profile.map((point) => ({ ...point, speed_kmh: typeof point.speed_mps === "number" ? point.speed_mps * 3.6 : null }));
addMovingTime(this._profile);
this._title.textContent = properties.name || "Track";
this._stats.textContent = statsText(properties);
const temperatures = this._profile.map((p) => p.temperature_c).filter((t) => typeof t === "number");
if (temperatures.length) {
const avg = temperatures.reduce((a, b) => a + b, 0) / temperatures.length;
this._stats.textContent += ` · ${Math.round(avg)} °C (${Math.round(Math.min(...temperatures))}–${Math.round(Math.max(...temperatures))})`;
}
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 time axis when there's actually elapsed-time data —
// plenty of GPX files have no <time> at all.
this._hasTime = this._profile.some((p) => typeof p.elapsed_secs === "number");
this._setXAxis("distance");
this._activeSeries = SERIES.filter((s) => this._profile.some((p) => typeof p[s.key] === "number"));
this._chartsContainer.innerHTML = "";
this._chartsContainer.appendChild(this._renderControls());
// Pointer tracking only over the plots, so the controls above and the
// tables below stay uncovered by the tooltip.
this._plots = document.createElement("div");
this._plots.className = "profile-panel__plots";
this._chartsContainer.appendChild(this._plots);
this._tables = document.createElement("div");
this._chartsContainer.appendChild(this._tables);
this._renderSegments();
this._plots.addEventListener("pointermove", this._onPointerMove);
this._plots.addEventListener("pointerleave", this._onPointerLeave);
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();
}
// Distance, or moving time: pauses (auto-pause gaps, standing at a
// crossing) take no width, so the line doesn't jump or go flat there.
_setXAxis(mode) {
this._xAxisMode = mode;
this._xKey = mode === "time" ? "moving_secs" : "distance_meters";
this._maxX = this._profile.at(-1)[this._xKey] || 1;
}
_fx(point) {
return point[this._xKey] / this._maxX;
}
_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._fx(this._profile[this._bounds[n - 1]]);
const x2 = this._fx(this._profile[this._bounds[n]]);
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", "Moving 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._setXAxis(btn.dataset.value);
this._renderSegments();
} else {
this._segmentMode = btn.dataset.value;
this._renderSegments();
}
});
return row;
}
hide() {
this._panel.hidden = true;
this._plots?.removeEventListener("pointermove", this._onPointerMove);
this._plots?.removeEventListener("pointerleave", this._onPointerLeave);
this._marker.remove();
this._hideMileposts();
}
_renderChart(series) {
const values = this._profile.map((p) => p[series.key]).filter((v) => typeof v === "number");
const min = Math.min(...values);
const max = Math.max(...values);
const range = max - min || 1;
const toX = (p) => this._fx(p) * VIEWBOX_WIDTH;
const toY = (v) => series.height - 6 - ((v - min) / range) * (series.height - 12);
const points = this._profile
.map((p) => (typeof p[series.key] === "number" ? [toX(p), toY(p[series.key])] : null))
.filter(Boolean);
const linePath = points.map(([x, y], i) => `${i === 0 ? "M" : "L"}${x.toFixed(1)},${y.toFixed(1)}`).join(" ");
const areaPath = series.area && points.length > 0
? `${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]]);
const x2 = toX(this._profile[this._bounds[n]]);
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");
wrapper.className = "profile-chart";
wrapper.innerHTML = `
<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">
<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>` : ""}
<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>
<circle class="profile-chart__dot" r="4" fill="${series.color}" stroke="#fff" stroke-width="1.5" hidden></circle>
</svg>
<span class="profile-chart__axis-value profile-chart__axis-value--max">${formatValue(max, series)}</span>
<span class="profile-chart__axis-value profile-chart__axis-value--min">${formatValue(min, series)}</span>
</div>
`;
wrapper.dataset.min = min;
wrapper.dataset.max = max;
return wrapper;
}
// A strip under the charts in the color of each marked hiking trail the
// track follows (several stacked where trails share the path), blank off
// trail. Point i's colors span from it to the next point.
_renderTrailBand() {
const colors = trailColorsAlong(this._profile);
if (!colors) return null;
const HEIGHT = 10;
const toX = (p) => this._fx(p) * VIEWBOX_WIDTH;
let rects = "";
let start = 0;
for (let i = 1; i < this._profile.length; i++) {
const run = colors[start];
if (i < this._profile.length - 1 && colors[i].join() === run.join()) continue;
const [x1, x2] = [toX(this._profile[start]), toX(this._profile[i])];
run.forEach((color, j) => {
rects += `<rect x="${x1.toFixed(1)}" width="${(x2 - x1).toFixed(1)}" y="${((j * HEIGHT) / run.length).toFixed(2)}" height="${(HEIGHT / run.length).toFixed(2)}" fill="${color}"></rect>`;
});
start = i;
}
const band = document.createElement("div");
band.className = "profile-trails"; // not .profile-chart: those are the series rows _updateCrosshair walks
// Colors are normalizedTrailColor's (hiking_trails.js): known words or hex only.
band.innerHTML = `
<div class="profile-chart__label">Marked trails</div>
<svg viewBox="0 0 ${VIEWBOX_WIDTH} ${HEIGHT}" preserveAspectRatio="none" class="profile-chart__trails">${rects}</svg>
`;
return band;
}
_renderXAxisTicks() {
const TICK_COUNT = 5;
this._xAxisStripEl.innerHTML = Array.from({ length: TICK_COUNT }, (_, i) => {
const fraction = i / (TICK_COUNT - 1);
const value = fraction * this._maxX;
const label = this._xAxisMode === "time" ? formatDuration(value) : `${(value / 1000).toFixed(1)} km`;
return `<span class="profile-panel__xaxis-tick" style="left:${(fraction * 100).toFixed(2)}%">${escapeHtml(label)}</span>`;
}).join("");
}
// Bound once (arrow fields, not prototype methods) so add/removeEventListener see the same reference.
_onPointerMove = (event) => {
const rect = this._plots.getBoundingClientRect();
const fraction = Math.min(1, Math.max(0, (event.clientX - rect.left) / rect.width));
const index = nearestIndex(this._profile, this._xKey, fraction * this._maxX);
const point = this._profile[index];
this._updateCrosshair(point);
this._updateTooltip(point, event);
this._marker.setLngLat([point.lon, point.lat]).addTo(this._map);
};
_onPointerLeave = () => {
this._tooltip.hidden = true;
this._plots.querySelectorAll(".profile-chart__crosshair, .profile-chart__dot").forEach((el) => (el.hidden = true));
this._marker.remove();
};
_updateCrosshair(point) {
const x = this._fx(point) * VIEWBOX_WIDTH;
this._plots.querySelectorAll(".profile-chart").forEach((wrapper, i) => {
const series = this._activeSeries[i];
const value = point[series.key];
const svg = wrapper.querySelector("svg");
const crosshair = wrapper.querySelector(".profile-chart__crosshair");
const dot = wrapper.querySelector(".profile-chart__dot");
crosshair.setAttribute("x1", x.toFixed(1));
crosshair.setAttribute("x2", x.toFixed(1));
crosshair.hidden = false;
if (typeof value === "number") {
const min = Number(wrapper.dataset.min);
const max = Number(wrapper.dataset.max);
const range = max - min || 1;
const y = series.height - 6 - ((value - min) / range) * (series.height - 12);
dot.setAttribute("cx", x.toFixed(1));
dot.setAttribute("cy", y.toFixed(1));
dot.hidden = false;
} else {
dot.hidden = true;
}
void svg; // svg itself needs no direct update, its children were mutated above
});
}
_updateTooltip(point, event) {
const rows = this._activeSeries
.filter((s) => typeof point[s.key] === "number")
.map((s) => `<div><span class="profile-panel__tooltip-label">${escapeHtml(s.label)}</span> <strong>${formatValue(point[s.key], s)}</strong></div>`)
.join("");
const timeSuffix = typeof point.elapsed_secs === "number" ? ` · ${formatDuration(point.elapsed_secs)}` : "";
this._tooltip.innerHTML = `<div class="profile-panel__tooltip-distance">${(point.distance_meters / 1000).toFixed(2)} km${timeSuffix}</div>${rows}`;
this._tooltip.hidden = false;
// Beside the pointer, flipped to its left near the right edge, and
// following it vertically so it never parks over one spot.
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 (or laps, open) and best efforts (collapsed) under the charts. A planned route has no times: its splits show climbing only.
function statsTables(profile, bounds, laps, ride) {
const timed = profile.filter((p) => typeof p.elapsed_secs === "number");
const total = profile.at(-1).distance_meters;
const hasTime = timed.length > 1;
const hasHr = profile.some((p) => typeof p.heart_rate_bpm === "number");
const hasPower = profile.some((p) => typeof p.power_w === "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 km = (m) => `${(m / 1000).toFixed(m % 1000 ? 2 : 0)} km`;
let html = "";
const rows = segmentStats(profile, bounds).map((s, i) => {
const cells = [laps ? `${i + 1}` : km(s.to), ...(laps ? [km(s.meters)] : [])];
if (hasTime) cells.push(s.secs ? formatClock(s.secs) : "", s.secs ? pace(s.secs, s.meters) : "");
cells.push(`↑ ${Math.round(s.gain)} m`, `↓ ${Math.round(s.loss)} m`);
if (hasHr) cells.push(s.hr ? `${Math.round(s.hr)} bpm` : "");
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 = [];
if (hasTime) {
BEST_DISTANCES_KM.filter((km) => km * 1000 <= total).forEach((km) => {
const secs = fastest(timed, km * 1000);
if (secs) best.push([`${km === 21.0975 ? "Half marathon" : km === 42.195 ? "Marathon" : `${km} km`}`, `${formatClock(secs)} · ${pace(secs, km * 1000)}`]);
});
}
if (hasPower) {
BEST_POWER_SECS.forEach((secs) => {
const watts = bestPower(timed, secs);
if (watts) best.push([`Power ${secs < 60 ? `${secs} s` : `${secs / 60} min`}`, `${Math.round(watts)} W`]);
});
}
const climb = biggestClimb(profile);
if (climb) best.push(["Biggest climb", `↑ ${Math.round(climb.gain)} m over ${(climb.meters / 1000).toFixed(1)} km (${((climb.gain / climb.meters) * 100).toFixed(1)} %)`]);
if (best.length) html += `<details class="profile-stats"><summary>Best efforts</summary><table>${best.map(([k, v]) => `<tr><td>${k}</td><td>${v}</td></tr>`).join("")}</table></details>`;
return html;
}
// Profile indices where splits end: the first point at/after every `step`
// meters, plus the last point (that split shorter).
function splitBounds(profile, step) {
const bounds = [0];
for (let i = 1; i < profile.length; i++) {
if (i === profile.length - 1 || profile[i].distance_meters >= bounds.length * step) bounds.push(i);
}
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 loss = 0;
part.forEach((p, j) => {
const climb = j > 0 && p.elevation_meters != null && part[j - 1].elevation_meters != null ? p.elevation_meters - part[j - 1].elevation_meters : 0;
if (climb > 0) gain += climb;
else loss -= climb;
});
const [a, b] = [profile[start].elapsed_secs, profile[end].elapsed_secs];
const secs = typeof a === "number" && typeof b === "number" && b > a ? b - a : null;
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") };
});
}
function average(points, key) {
const values = points.map((p) => p[key]).filter((v) => typeof v === "number");
return values.length ? values.reduce((a, b) => a + b, 0) / values.length : null;
}
// Shortest time over any stretch of at least `meters` (two pointers).
function fastest(profile, meters) {
let best = null;
let j = 0;
for (let i = 0; i < profile.length; i++) {
while (j < profile.length && profile[j].distance_meters - profile[i].distance_meters < meters) j++;
if (j === profile.length) break;
const secs = profile[j].elapsed_secs - profile[i].elapsed_secs;
if (secs > 0 && (best === null || secs < best)) best = secs;
}
return best;
}
// Highest average power over any `secs` window, time-weighted (samples
// aren't evenly spaced); a missing reading counts as 0 W.
function bestPower(profile, secs) {
const energy = [0];
for (let i = 1; i < profile.length; i++) energy.push(energy[i - 1] + (profile[i].power_w || 0) * (profile[i].elapsed_secs - profile[i - 1].elapsed_secs));
let best = null;
let j = 0;
for (let i = 0; i < profile.length; i++) {
while (j < profile.length && profile[j].elapsed_secs - profile[i].elapsed_secs < secs) j++;
if (j === profile.length) break;
const watts = (energy[j] - energy[i]) / (profile[j].elapsed_secs - profile[i].elapsed_secs);
if (best === null || watts > best) best = watts;
}
return best;
}
// The largest rise from a low to a later high without a dip of more than
// CLIMB_TOLERANCE_M in between.
function biggestClimb(profile) {
const points = profile.filter((p) => typeof p.elevation_meters === "number");
if (points.length < 2) return null;
let best = null;
let low = points[0];
let high = points[0];
const finish = () => {
const gain = high.elevation_meters - low.elevation_meters;
if (gain >= CLIMB_TOLERANCE_M && gain > (best?.gain ?? 0)) best = { gain, meters: high.distance_meters - low.distance_meters };
};
for (const p of points) {
if (p.elevation_meters > high.elevation_meters) high = p;
else if (high.elevation_meters - p.elevation_meters > CLIMB_TOLERANCE_M) {
finish();
low = high = p;
}
if (p.elevation_meters < low.elevation_meters) low = high = p;
}
finish();
return best;
}
function formatPace(secsPerKm) {
const minutes = Math.floor(secsPerKm / 60);
return `${minutes}:${String(Math.round(secsPerKm % 60)).padStart(2, "0")}`;
}
// Cumulative time spent moving (over MOVING_MPS), for the time axis.
function addMovingTime(profile) {
let moving = 0;
profile.forEach((p, i) => {
const prev = profile[i - 1];
const dt = prev && typeof p.elapsed_secs === "number" && typeof prev.elapsed_secs === "number" ? p.elapsed_secs - prev.elapsed_secs : 0;
if (dt > 0 && (p.distance_meters - prev.distance_meters) / dt >= MOVING_MPS) moving += dt;
p.moving_secs = moving;
});
}
function nearestIndex(profile, key, target) {
// Distances are monotonically non-decreasing (see TrackStats.build_profile),
// so a binary search would work too — linear is simpler and profiles here
// top out in the low thousands of points, not worth the complexity.
let closest = 0;
let closestDiff = Infinity;
profile.forEach((p, i) => {
const diff = Math.abs(p[key] - target);
if (diff < closestDiff) {
closestDiff = diff;
closest = i;
}
});
return closest;
}
function formatValue(value, series) {
if (series.key === "elevation_meters") return `${Math.round(value)} ${series.unit}`;
if (series.key === "speed_kmh") return `${value.toFixed(1)} ${series.unit}`;
return `${Math.round(value)} ${series.unit}`;
}
function statsText({ activity_type, distance_meters, elevation_gain_meters, duration_secs }) {
const parts = [];
if (activity_type) parts.push(formatActivityType(activity_type));
if (typeof distance_meters === "number") parts.push(`${(distance_meters / 1000).toFixed(1)} km`);
if (typeof elevation_gain_meters === "number") parts.push(`↑ ${Math.round(elevation_gain_meters)} m`);
if (typeof duration_secs === "number") parts.push(formatDuration(duration_secs));
return parts.join(" · ");
}
// FIT gives snake_case ("cross_country_skiing"); GPX's free-text <type> can
// be anything a device/app chose to write ("VirtualRide", "running", ...) —
// this reads reasonably for both without needing to know which format the
// track came from.
export function formatActivityType(text) {
return text
.split("_")
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(" ");
}
function formatDuration(totalSeconds) {
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
return hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
}
// 4:32, 1:02:05 — with seconds, for splits and best efforts.
function formatClock(totalSeconds) {
const s = Math.round(totalSeconds);
const mmss = `${String(Math.floor((s % 3600) / 60)).padStart(s >= 3600 ? 2 : 1, "0")}:${String(s % 60).padStart(2, "0")}`;
return s >= 3600 ? `${Math.floor(s / 3600)}:${mmss}` : mmss;
}
function escapeHtml(text) {
const div = document.createElement("div");
div.textContent = text;
return div.innerHTML;
}