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
This commit is contained in:
1 parent
3e487539bc
commit
38368fc801
9 files changed
+292
-101
No files matched your search
@@ -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 }),
|
||||
|
||||
+176
-75
@@ -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 <time> at all.
|
||||
// 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._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.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
|
||||
// above uses the same x-scale (distance-position), so a separate axis
|
||||
// per chart would just repeat itself.
|
||||
this._xAxisStripEl = document.createElement("div");
|
||||
this._xAxisStripEl.className = "profile-panel__xaxis";
|
||||
this._chartsContainer.appendChild(this._xAxisStripEl);
|
||||
this._renderXAxisTicks();
|
||||
this._chartsContainer.insertAdjacentHTML("beforeend", statsTables(this._profile, properties.activity_type));
|
||||
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._chartsContainer.addEventListener("pointermove", this._onPointerMove);
|
||||
this._chartsContainer.addEventListener("pointerleave", this._onPointerLeave);
|
||||
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();
|
||||
}
|
||||
|
||||
_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() {
|
||||
this._panel.hidden = true;
|
||||
this._chartsContainer.removeEventListener("pointermove", this._onPointerMove);
|
||||
this._chartsContainer.removeEventListener("pointerleave", this._onPointerLeave);
|
||||
this._plots?.removeEventListener("pointermove", this._onPointerMove);
|
||||
this._plots?.removeEventListener("pointerleave", this._onPointerLeave);
|
||||
this._marker.remove();
|
||||
this._hideMileposts();
|
||||
}
|
||||
|
||||
_renderChart(series) {
|
||||
@@ -116,12 +215,20 @@ export class TrackProfilePanel {
|
||||
? `${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");
|
||||
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>
|
||||
@@ -165,25 +272,6 @@ export class TrackProfilePanel {
|
||||
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() {
|
||||
const TICK_COUNT = 5;
|
||||
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.
|
||||
_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 targetDistance = fraction * this._maxDistance;
|
||||
|
||||
@@ -211,13 +299,13 @@ export class TrackProfilePanel {
|
||||
|
||||
_onPointerLeave = () => {
|
||||
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();
|
||||
};
|
||||
|
||||
_updateCrosshair(point) {
|
||||
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 value = point[series.key];
|
||||
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.hidden = false;
|
||||
|
||||
const containerRect = this._chartsContainer.getBoundingClientRect();
|
||||
const left = Math.min(event.clientX - containerRect.left + 12, containerRect.width - this._tooltip.offsetWidth - 8);
|
||||
this._tooltip.style.left = `${Math.max(8, left)}px`;
|
||||
// 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 and best efforts under the charts, as two collapsed <details>.
|
||||
// Splits need times (a planned route has none); the biggest climb doesn't.
|
||||
function statsTables(profile, activityType) {
|
||||
// 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 ride = /cycl|bik|ride/i.test(activityType || "");
|
||||
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 = "";
|
||||
|
||||
if (timed.length > 1) {
|
||||
const step = ride || total > 50000 ? 5000 : 1000;
|
||||
const rows = splits(timed, step).map(
|
||||
(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>`,
|
||||
);
|
||||
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>`;
|
||||
}
|
||||
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 ? formatDuration(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 (timed.length > 1) {
|
||||
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`}`, `${formatDuration(secs)} · ${pace(secs, km * 1000)}`]);
|
||||
@@ -295,15 +391,22 @@ function statsTables(profile, activityType) {
|
||||
return html;
|
||||
}
|
||||
|
||||
// Every `step` meters: time, ascent/descent and average heart rate/power, the last
|
||||
// split shorter. Points are the first at/after each boundary.
|
||||
function splits(profile, step) {
|
||||
const out = [];
|
||||
let start = 0;
|
||||
// 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++) {
|
||||
const last = i === profile.length - 1;
|
||||
if (!last && profile[i].distance_meters < (out.length + 1) * step) continue;
|
||||
const part = profile.slice(start, i + 1);
|
||||
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) => {
|
||||
@@ -311,12 +414,10 @@ function splits(profile, step) {
|
||||
if (climb > 0) gain += climb;
|
||||
else loss -= climb;
|
||||
});
|
||||
const meters = profile[i].distance_meters - profile[start].distance_meters;
|
||||
const secs = profile[i].elapsed_secs - profile[start].elapsed_secs;
|
||||
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") });
|
||||
start = i;
|
||||
}
|
||||
return out;
|
||||
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) {
|
||||
|
||||
Reference in new issue
Block a user