Skip to content

Build your personal knowledge base with Trilium Notes

feat(client): say when a GPX track was recorded, and list its journeys

Elian Doran0b4bcb4e3a98
diff --git a/apps/client/src/services/gpx.spec.ts b/apps/client/src/services/gpx.spec.ts
index 6124826ef1..f944013d26 100644
--- a/apps/client/src/services/gpx.spec.ts
+++ b/apps/client/src/services/gpx.spec.ts
@@ -85,6 +85,14 @@ describe("parseGpxStats", () => {
expect(stats?.distance).toBeCloseTo(0.04 * DEGREE_M, -1);
expect(stats?.elevation).toBeUndefined();
expect(stats?.time).toBeUndefined();
+
+ // Each journey also answers for itself: the track with both its segments, the route alone.
+ expect(stats?.journeys).toHaveLength(2);
+ expect(stats?.journeys[0]).toMatchObject({ kind: "track", name: "Morning ride" });
+ expect(stats?.journeys[0].distance).toBeCloseTo(0.03 * DEGREE_M, -1);
+ expect(stats?.journeys[1].kind).toBe("route");
+ expect(stats?.journeys[1].name).toBeUndefined();
+ expect(stats?.journeys[1].distance).toBeCloseTo(0.01 * DEGREE_M, -1);
});
it("reads elevation extremes and accumulates gain/loss through the noise window", () => {
@@ -184,6 +192,8 @@ describe("parseGpxStats", () => {
const stats = parseGpxStats(gpx(`<trkpt lat="0" lon="0"/><trkpt lat="0" lon="0.01"/>`));
expect(stats?.pointCount).toBe(2);
expect(stats?.distance).toBeCloseTo(0.01 * DEGREE_M, -1);
+ expect(stats?.journeys).toHaveLength(1);
+ expect(stats?.journeys[0].kind).toBe("track");
});
it("decimates a long profile while keeping its ends and its extremes", () => {
diff --git a/apps/client/src/services/gpx.ts b/apps/client/src/services/gpx.ts
index 4e36f7dae0..edddf31da3 100644
--- a/apps/client/src/services/gpx.ts
+++ b/apps/client/src/services/gpx.ts
@@ -15,6 +15,15 @@ export interface GpxElevationSample {
elevation: number;
}
+/** One of the journeys a GPX file holds — a track or a route — as a listing shows it. */
+export interface GpxJourney {
+ kind: "track" | "route";
+ /** What the file calls this journey, where it names one. */
+ name?: string;
+ /** Metres along this journey's lines alone. */
+ distance: number;
+}
+
/** A named place the file marks beside its lines — only what a listing shows of one. */
export interface GpxWaypoint {
name?: string;
@@ -35,6 +44,8 @@ export interface GpxStats {
segmentCount: number;
/** Track and route points that carry a readable position. */
pointCount: number;
+ /** The file's tracks and routes in file order, each with the metres it draws. */
+ journeys: GpxJourney[];
/** The file's waypoints that carry a readable position, in file order. */
waypoints: GpxWaypoint[];
/** Metres travelled, summed within each segment and route. The jumps between segments are not
@@ -80,7 +91,7 @@ export function parseGpxStats(xml: string): GpxStats | null {
}
const root = doc.documentElement;
- const segments = readSegments(doc);
+ const journeys = readJourneys(doc);
const stats: GpxStats = {
name: readMetadataOrFirst(root, "name"),
@@ -88,7 +99,8 @@ export function parseGpxStats(xml: string): GpxStats | null {
trackCount: doc.querySelectorAll("trk").length,
routeCount: doc.querySelectorAll("rte").length,
segmentCount: doc.querySelectorAll("trkseg").length,
- pointCount: segments.reduce((count, segment) => count + segment.length, 0),
+ pointCount: journeys.reduce((count, journey) => count + journey.segments.reduce((n, segment) => n + segment.length, 0), 0),
+ journeys: [],
waypoints: readWaypoints(doc),
distance: 0
};
@@ -101,40 +113,47 @@ export function parseGpxStats(xml: string): GpxStats | null {
let start = Infinity;
let end = -Infinity;
- for (const segment of segments) {
- // The reference an elevation change is measured against, reset per segment: climbing that
- // happened in the gap between two segments was not climbed on this track.
- let anchor: number | undefined;
+ for (const journey of journeys) {
+ let journeyDistance = 0;
- for (const [ index, point ] of segment.entries()) {
- if (index > 0) {
- stats.distance += haversine(segment[index - 1], point);
- }
+ for (const segment of journey.segments) {
+ // The reference an elevation change is measured against, reset per segment: climbing
+ // that happened in the gap between two segments was not climbed on this track.
+ let anchor: number | undefined;
- if (point.elevation !== undefined) {
- profile.push({ distance: stats.distance, elevation: point.elevation });
- min = Math.min(min, point.elevation);
- max = Math.max(max, point.elevation);
-
- // Gain and loss accumulate through a hysteresis window rather than point to point:
- // GPS elevation jitters by a few metres either way, and summing every wobble
- // reports a mountain climbed on a walk around the block.
- if (anchor === undefined) {
- anchor = point.elevation;
- } else if (point.elevation - anchor >= ELEVATION_NOISE_M) {
- gain += point.elevation - anchor;
- anchor = point.elevation;
- } else if (anchor - point.elevation >= ELEVATION_NOISE_M) {
- loss += anchor - point.elevation;
- anchor = point.elevation;
+ for (const [ index, point ] of segment.entries()) {
+ if (index > 0) {
+ journeyDistance += haversine(segment[index - 1], point);
+ }
+
+ if (point.elevation !== undefined) {
+ profile.push({ distance: stats.distance + journeyDistance, elevation: point.elevation });
+ min = Math.min(min, point.elevation);
+ max = Math.max(max, point.elevation);
+
+ // Gain and loss accumulate through a hysteresis window rather than point to
+ // point: GPS elevation jitters by a few metres either way, and summing every
+ // wobble reports a mountain climbed on a walk around the block.
+ if (anchor === undefined) {
+ anchor = point.elevation;
+ } else if (point.elevation - anchor >= ELEVATION_NOISE_M) {
+ gain += point.elevation - anchor;
+ anchor = point.elevation;
+ } else if (anchor - point.elevation >= ELEVATION_NOISE_M) {
+ loss += anchor - point.elevation;
+ anchor = point.elevation;
+ }
}
- }
- if (point.time !== undefined) {
- start = Math.min(start, point.time);
- end = Math.max(end, point.time);
+ if (point.time !== undefined) {
+ start = Math.min(start, point.time);
+ end = Math.max(end, point.time);
+ }
}
}
+
+ stats.journeys.push({ kind: journey.kind, ...(journey.name ? { name: journey.name } : {}), distance: journeyDistance });
+ stats.distance += journeyDistance;
}
if (profile.length > 0) {
@@ -265,29 +284,42 @@ interface GpxPoint {
time?: number;
}
+/** A journey's points still grouped by segment, which is what the stats walk. */
+interface GpxJourneyPoints {
+ kind: "track" | "route";
+ name?: string;
+ segments: GpxPoint[][];
+}
+
/**
- * The point runs a GPX file is made of, one array per track segment and one per route — split the
- * same way {@link GpxTrack} draws them, including the fallback for schema-less files whose points
- * sit outside any segment or route.
+ * The point runs a GPX file is made of, one entry per track and per route with the track's
+ * segments kept apart — grouped the same way {@link readTrackLines} groups the drawn lines,
+ * including the fallback for schema-less files whose points sit outside any track or route.
*/
-function readSegments(doc: Document): GpxPoint[][] {
- const segments: GpxPoint[][] = [];
+function readJourneys(doc: Document): GpxJourneyPoints[] {
+ const journeys: GpxJourneyPoints[] = [];
- for (const container of doc.querySelectorAll("trkseg, rte")) {
- const points = readPoints(container.querySelectorAll("trkpt, rtept"), { withTime: container.localName !== "rte" });
- if (points.length > 0) {
- segments.push(points);
+ for (const container of doc.querySelectorAll("trk, rte")) {
+ const kind = container.localName === "rte" ? "route" : "track";
+ const segments = (kind === "route"
+ ? [ readPoints(container.querySelectorAll("rtept"), { withTime: false }) ]
+ : [ ...container.querySelectorAll("trkseg") ].map((segment) => readPoints(segment.querySelectorAll("trkpt")))
+ ).filter((segment) => segment.length > 0);
+
+ if (segments.length > 0) {
+ const name = childText(container, "name")?.trim();
+ journeys.push({ kind, ...(name ? { name } : {}), segments });
}
}
- if (segments.length === 0) {
+ if (journeys.length === 0) {
const points = readPoints(doc.querySelectorAll("trkpt, rtept"));
if (points.length > 0) {
- segments.push(points);
+ journeys.push({ kind: "track", segments: [ points ] });
}
}
- return segments;
+ return journeys;
}
/**
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index e77e657b69..a69c296736 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1545,7 +1545,11 @@
"routes": "Routes",
"waypoints": "Waypoints",
"waypoints_with_count": "Waypoints ({{count}})",
- "unnamed_waypoint": "(unnamed)",
+ "tracks_with_count": "Tracks ({{count}})",
+ "routes_with_count": "Routes ({{count}})",
+ "journeys_with_count": "Tracks & routes ({{count}})",
+ "unnamed": "(unnamed)",
+ "recorded_on": "Recorded on",
"map_hint": "Place this note in a Geo Map collection to see the track drawn on a map.",
"elevation_profile": "Elevation profile",
"duration_minutes": "{{minutes}} min",
diff --git a/apps/client/src/widgets/type_widgets/file/GpxPreview.css b/apps/client/src/widgets/type_widgets/file/GpxPreview.css
index b070d89970..b3cd942d0c 100644
--- a/apps/client/src/widgets/type_widgets/file/GpxPreview.css
+++ b/apps/client/src/widgets/type_widgets/file/GpxPreview.css
@@ -130,10 +130,12 @@
color: var(--muted-text-color);
}
+ .gpx-journeys,
.gpx-waypoints {
margin-top: 12px;
}
+ .gpx-journey-list,
.gpx-waypoint-list {
list-style: none;
margin: 0;
@@ -160,7 +162,8 @@
white-space: nowrap;
}
- .gpx-waypoint-elevation {
+ .gpx-waypoint-elevation,
+ .gpx-journey-distance {
margin-left: auto;
color: var(--muted-text-color);
font-variant-numeric: tabular-nums;
diff --git a/apps/client/src/widgets/type_widgets/file/GpxPreview.spec.tsx b/apps/client/src/widgets/type_widgets/file/GpxPreview.spec.tsx
index 6e4b12bb8e..4b8fb90b87 100644
--- a/apps/client/src/widgets/type_widgets/file/GpxPreview.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/file/GpxPreview.spec.tsx
@@ -10,7 +10,8 @@ vi.mock("../../../services/server", () => ({
// Pinned rather than read from the environment: the tiles' units are what the assertions read,
// and the host machine's locale must not decide whether they say km or mi.
vi.mock("../../../utils/formatters", () => ({
- getMeasurementSystem: () => "metric"
+ getMeasurementSystem: () => "metric",
+ formatDateTime: (date: Date) => date.toISOString().slice(0, 10)
}));
// i18next is never initialized under test, so t() is rendered deterministic instead: the key with
@@ -88,12 +89,15 @@ describe("GpxPreview", () => {
expect(tileValue("gpx_preview.elevation_gain")).toBe("gpx_preview.unit_m|50");
expect(tileValue("gpx_preview.elevation_loss")).toBe("gpx_preview.unit_m|30");
expect(tileValue("gpx_preview.max_elevation")).toBe("gpx_preview.unit_m|150");
+ expect(tileValue("gpx_preview.recorded_on")).toBe("2024-06-01");
expect(tileValue("gpx_preview.points")).toBe("3");
expect(tileValue("gpx_preview.segments")).toBe("1");
- // A single track and no routes/waypoints say nothing worth a tile.
+ // A single track and no routes/waypoints say nothing worth a tile — and one journey is
+ // nothing to list either.
expect(tileValue("gpx_preview.tracks")).toBeUndefined();
expect(tileValue("gpx_preview.routes")).toBeUndefined();
expect(tileValue("gpx_preview.waypoints")).toBeUndefined();
+ expect(container.querySelector(".gpx-journeys")).toBeNull();
// The file's own name and description are shown (the note is titled differently).
expect(container.querySelector(".gpx-preview-name")?.textContent).toBe("Ridge loop");
@@ -109,6 +113,32 @@ describe("GpxPreview", () => {
expect(container.querySelector(".gpx-preview-map-hint")?.textContent).toContain("gpx_preview.map_hint");
});
+ it("lists the journeys when the file holds more than one, each with its own distance", async () => {
+ serverGet.mockResolvedValue(`<?xml version="1.0" encoding="UTF-8"?>
+<gpx xmlns="http://www.topografix.com/GPX/1/1" version="1.1" creator="test">
+ <trk><name>Day one</name><trkseg>
+ <trkpt lat="0" lon="0"/><trkpt lat="0" lon="0.01"/>
+ </trkseg></trk>
+ <rte>
+ <rtept lat="0" lon="1"/><rtept lat="0" lon="1.02"/>
+ </rte>
+</gpx>`);
+
+ mount();
+ await vi.waitFor(() => expect(container.querySelector(".gpx-journeys")).not.toBeNull());
+
+ // A track and a route together are headed as neither alone would be.
+ expect(container.querySelector(".gpx-journeys .collapsible-title")?.textContent)
+ .toContain("gpx_preview.journeys_with_count|2");
+
+ const rows = [ ...container.querySelectorAll(".gpx-journey-list > li") ];
+ expect(rows.map((row) => row.querySelector(".gpx-journey-name")?.textContent))
+ .toEqual([ "Day one", "gpx_preview.unnamed" ]);
+ // 0.01° and 0.02° along the equator: ~1.11 km and ~2.22 km.
+ expect(rows[0].querySelector(".gpx-journey-distance")?.textContent).toMatch(/^gpx_preview\.unit_km\|1[.,]11$/);
+ expect(rows[1].querySelector(".gpx-journey-distance")?.textContent).toMatch(/^gpx_preview\.unit_km\|2[.,]22$/);
+ });
+
it("lists the waypoints under a collapsed section, one row apiece", async () => {
serverGet.mockResolvedValue(GPX.replace("<trk>", `
<wpt lat="0" lon="0"><name>GATE16</name><desc>Gate 16</desc><ele>77.7</ele></wpt>
diff --git a/apps/client/src/widgets/type_widgets/file/GpxPreview.tsx b/apps/client/src/widgets/type_widgets/file/GpxPreview.tsx
index bf97758c56..02d920b4cf 100644
--- a/apps/client/src/widgets/type_widgets/file/GpxPreview.tsx
+++ b/apps/client/src/widgets/type_widgets/file/GpxPreview.tsx
@@ -4,10 +4,10 @@ import { useEffect, useMemo, useState } from "preact/hooks";
import type FBlob from "../../../entities/fblob";
import type FNote from "../../../entities/fnote";
-import { GpxElevationSample, GpxStats, parseGpxStats } from "../../../services/gpx";
+import { GpxElevationSample, GpxJourney, GpxStats, parseGpxStats } from "../../../services/gpx";
import { t } from "../../../services/i18n";
import server from "../../../services/server";
-import { getMeasurementSystem } from "../../../utils/formatters";
+import { formatDateTime, getMeasurementSystem } from "../../../utils/formatters";
import Alert from "../../react/Alert";
import Collapsible from "../../react/Collapsible";
@@ -93,6 +93,29 @@ export default function GpxPreview({ note, blob }: GpxPreviewProps) {
/>
)}
+ {/* Only when there is more than one journey to tell apart — a single-track file is
+ already summed up by the stats above. Expanded, unlike the waypoints: a file
+ rarely holds more than a handful. */}
+ {stats.journeys.length > 1 && (
+ <Collapsible
+ className="gpx-journeys"
+ title={journeysTitle(stats.journeys)}
+ initiallyExpanded
+ >
+ <ul className="gpx-journey-list">
+ {stats.journeys.map((journey, index) => (
+ <li key={index}>
+ <span className={journey.kind === "route" ? "bx bx-directions" : "bx bx-trip"} aria-hidden="true" />
+ <span className="gpx-journey-name">{journey.name ?? t("gpx_preview.unnamed")}</span>
+ {journey.distance > 0 && (
+ <span className="gpx-journey-distance">{formatDistance(journey.distance, system)}</span>
+ )}
+ </li>
+ ))}
+ </ul>
+ </Collapsible>
+ )}
+
{/* Collapsed by default: a file can carry dozens (the GPX spec's sample has 86), and
the numbers above should not have to be scrolled back to over a directory. */}
{stats.waypoints.length > 0 && (
@@ -104,7 +127,7 @@ export default function GpxPreview({ note, blob }: GpxPreviewProps) {
{stats.waypoints.map((waypoint, index) => (
<li key={index}>
<span className="bx bx-pin" aria-hidden="true" />
- <span className="gpx-waypoint-name">{waypoint.name ?? t("gpx_preview.unnamed_waypoint")}</span>
+ <span className="gpx-waypoint-name">{waypoint.name ?? t("gpx_preview.unnamed")}</span>
{waypoint.description && <span className="gpx-waypoint-description">{waypoint.description}</span>}
{waypoint.elevation !== undefined && (
<span className="gpx-waypoint-elevation">{formatElevation(waypoint.elevation, system)}</span>
@@ -140,6 +163,11 @@ function buildTiles(stats: GpxStats, system: MeasurementSystem) {
tiles.push({ label: t("gpx_preview.avg_speed"), value: formatSpeed(kmh, system) });
}
}
+ if (stats.time) {
+ // The date alone: the day a track was ridden is the fact worth a glance, and the start
+ // time is implied well enough by the duration beside it.
+ tiles.push({ label: t("gpx_preview.recorded_on"), value: formatDateTime(stats.time.start, "medium", "none") });
+ }
if (stats.elevation) {
tiles.push(
{ label: t("gpx_preview.elevation_gain"), value: formatElevation(stats.elevation.gain, system) },
@@ -166,6 +194,18 @@ function buildTiles(stats: GpxStats, system: MeasurementSystem) {
return tiles;
}
+/** What the journey listing is headed with — named by what the file actually holds, since a file
+ * of routes headed "Tracks" would contradict the very rows under it. */
+function journeysTitle(journeys: GpxJourney[]): string {
+ if (journeys.every((journey) => journey.kind === "track")) {
+ return t("gpx_preview.tracks_with_count", { count: journeys.length });
+ }
+ if (journeys.every((journey) => journey.kind === "route")) {
+ return t("gpx_preview.routes_with_count", { count: journeys.length });
+ }
+ return t("gpx_preview.journeys_with_count", { count: journeys.length });
+}
+
/** The drawing space the profile is projected into. Stretched to the container by the SVG itself
* (`preserveAspectRatio="none"`); strokes carry `non-scaling-stroke` so only the shape stretches. */
const CHART_WIDTH = 1000;