Skip to content

Build your personal knowledge base with Trilium Notes

feat(client): preview a GPX file as its stats and an elevation profile

Elian Doraneef8a0961365
diff --git a/apps/client/src/services/gpx.spec.ts b/apps/client/src/services/gpx.spec.ts
new file mode 100644
index 0000000000..46e80abc0e
--- /dev/null
+++ b/apps/client/src/services/gpx.spec.ts
@@ -0,0 +1,137 @@
+import { describe, expect, it } from "vitest";
+
+import { parseGpxStats } from "./gpx";
+
+/** One degree of longitude on the equator, which the distance assertions are stated in. */
+const DEGREE_M = (Math.PI / 180) * 6371000;
+
+function gpx(body: string) {
+ return `<?xml version="1.0" encoding="UTF-8"?>
+<gpx xmlns="http://www.topografix.com/GPX/1/1" version="1.1" creator="test">${body}</gpx>`;
+}
+
+describe("parseGpxStats", () => {
+ it("counts the pieces and sums the distance within segments, not across the gaps", () => {
+ const stats = parseGpxStats(gpx(`
+ <wpt lat="1" lon="1"/>
+ <wpt lon="broken"/>
+ <trk><name>Morning ride</name>
+ <trkseg>
+ <trkpt lat="0" lon="0"/>
+ <trkpt lat="0" lon="0.01"/>
+ <trkpt lat="0" lon="0.02"/>
+ </trkseg>
+ <trkseg>
+ <trkpt lat="0" lon="1"/>
+ <trkpt lat="0" lon="1.01"/>
+ </trkseg>
+ </trk>
+ <rte>
+ <rtept lat="0" lon="2"/>
+ <rtept lat="0" lon="2.01"/>
+ </rte>
+ `));
+
+ expect(stats).not.toBeNull();
+ expect(stats).toMatchObject({
+ trackCount: 1,
+ routeCount: 1,
+ segmentCount: 2,
+ pointCount: 7,
+ // The waypoint without a position is not counted.
+ waypointCount: 1,
+ name: "Morning ride"
+ });
+ // 0.02° within the first segment, 0.01° within the second, 0.01° along the route — and
+ // nothing for the ~1° gaps between them, which were not travelled.
+ expect(stats?.distance).toBeCloseTo(0.04 * DEGREE_M, -1);
+ expect(stats?.elevation).toBeUndefined();
+ expect(stats?.time).toBeUndefined();
+ });
+
+ it("reads elevation extremes and accumulates gain/loss through the noise window", () => {
+ const track = [ 100, 102, 100, 110, 108, 120, 90 ]
+ .map((elevation, i) => `<trkpt lat="0" lon="${i * 0.001}"><ele>${elevation}</ele></trkpt>`)
+ .join("");
+ const stats = parseGpxStats(gpx(`<trk><trkseg>${track}</trkseg></trk>`));
+
+ // The ±2 m wobbles sit inside the 5 m hysteresis window and count for nothing; the real
+ // climbs (100→110→120) and the drop to 90 do.
+ expect(stats?.elevation).toMatchObject({ min: 90, max: 120, gain: 20, loss: 30 });
+
+ const profile = stats?.elevation?.profile ?? [];
+ expect(profile).toHaveLength(7);
+ expect(profile[0]).toEqual({ distance: 0, elevation: 100 });
+ expect(profile[6].elevation).toBe(90);
+ // Distance along the profile grows monotonically.
+ for (let i = 1; i < profile.length; i++) {
+ expect(profile[i].distance).toBeGreaterThan(profile[i - 1].distance);
+ }
+ });
+
+ it("does not carry the elevation anchor across a segment gap", () => {
+ const stats = parseGpxStats(gpx(`<trk>
+ <trkseg>
+ <trkpt lat="0" lon="0"><ele>100</ele></trkpt>
+ <trkpt lat="0" lon="0.001"><ele>110</ele></trkpt>
+ </trkseg>
+ <trkseg>
+ <trkpt lat="0" lon="1"><ele>500</ele></trkpt>
+ <trkpt lat="0" lon="1.001"><ele>510</ele></trkpt>
+ </trkseg>
+ </trk>`));
+
+ // 10 m climbed in each segment; the 390 m between them happened off the record.
+ expect(stats?.elevation).toMatchObject({ gain: 20, loss: 0, min: 100, max: 510 });
+ });
+
+ it("reads the travel time from the points' own timestamps, not from extensions", () => {
+ const stats = parseGpxStats(gpx(`<trk><trkseg>
+ <trkpt lat="0" lon="0"><time>2024-06-01T10:00:00Z</time></trkpt>
+ <trkpt lat="0" lon="0.01"><extensions><time>1999-01-01T00:00:00Z</time></extensions></trkpt>
+ <trkpt lat="0" lon="0.02"><time>2024-06-01T11:30:00Z</time></trkpt>
+ </trkseg></trk>`));
+
+ expect(stats?.time?.start.toISOString()).toBe("2024-06-01T10:00:00.000Z");
+ expect(stats?.time?.end.toISOString()).toBe("2024-06-01T11:30:00.000Z");
+ expect(stats?.time?.duration).toBe(90 * 60 * 1000);
+ });
+
+ it("prefers the metadata name and description over the first track's", () => {
+ const stats = parseGpxStats(gpx(`
+ <metadata><name>The file</name><desc>All of it</desc></metadata>
+ <trk><name>First track</name><desc>Only part</desc><trkseg><trkpt lat="0" lon="0"/></trkseg></trk>
+ `));
+ expect(stats).toMatchObject({ name: "The file", description: "All of it" });
+ });
+
+ it("reads points sitting outside any segment or route, as the map does", () => {
+ 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);
+ });
+
+ it("decimates a long profile while keeping its ends and its extremes", () => {
+ const points = Array.from({ length: 2000 }, (_, i) => {
+ // A gentle slope with one sharp summit in the middle of a bucket.
+ const elevation = i === 1111 ? 9999 : 100 + i * 0.01;
+ return `<trkpt lat="0" lon="${i * 0.0001}"><ele>${elevation}</ele></trkpt>`;
+ }).join("");
+ const stats = parseGpxStats(gpx(`<trk><trkseg>${points}</trkseg></trk>`));
+
+ const profile = stats?.elevation?.profile ?? [];
+ expect(profile.length).toBeLessThan(600);
+ expect(profile[0].elevation).toBe(100);
+ expect(profile[profile.length - 1].elevation).toBeCloseTo(100 + 1999 * 0.01, 5);
+ // The summit survives decimation.
+ expect(profile.some((sample) => sample.elevation === 9999)).toBe(true);
+ for (let i = 1; i < profile.length; i++) {
+ expect(profile[i].distance).toBeGreaterThanOrEqual(profile[i - 1].distance);
+ }
+ });
+
+ it("returns zeroed stats for well-formed XML with no points, and null for junk", () => {
+ expect(parseGpxStats(gpx(""))).toMatchObject({ pointCount: 0, waypointCount: 0, distance: 0 });
+ expect(parseGpxStats("this is not xml at all <")).toBeNull();
+ });
+});
diff --git a/apps/client/src/services/gpx.ts b/apps/client/src/services/gpx.ts
new file mode 100644
index 0000000000..6d39eec608
--- /dev/null
+++ b/apps/client/src/services/gpx.ts
@@ -0,0 +1,284 @@
+/**
+ * Reads a GPX file into the numbers a preview can show: how far it goes, how much it climbs, when
+ * it was travelled and what it is made of. Pure parsing and arithmetic over the XML — nothing here
+ * touches the map or the app, so the whole module is unit-testable.
+ */
+
+/** What marks a note as a GPX track: the mime its file carries. */
+export const GPX_MIME = "application/gpx+xml";
+
+export interface GpxElevationSample {
+ /** Metres travelled from the start of the track to this point. */
+ distance: number;
+ /** Metres of elevation at that point. */
+ elevation: number;
+}
+
+export interface GpxStats {
+ /** What the file calls itself (its metadata, else its first track or route) — which may well
+ * differ from the note's title, typically a file name. */
+ name?: string;
+ description?: string;
+ trackCount: number;
+ routeCount: number;
+ segmentCount: number;
+ /** Track and route points that carry a readable position. */
+ pointCount: number;
+ waypointCount: number;
+ /** Metres travelled, summed within each segment and route. The jumps between segments are not
+ * counted: a track is split exactly where it stopped being recorded, so whatever ground lies
+ * between two segments was not travelled on this track. */
+ distance: number;
+ /** Absent when no point carries an elevation. */
+ elevation?: {
+ min: number;
+ max: number;
+ gain: number;
+ loss: number;
+ /** The track flattened to elevation-over-distance, decimated for drawing. */
+ profile: GpxElevationSample[];
+ };
+ /** Absent when no point carries a timestamp. */
+ time?: {
+ start: Date;
+ end: Date;
+ /** Milliseconds from the first timestamp to the last. */
+ duration: number;
+ };
+}
+
+/**
+ * The numbers a GPX file amounts to, or `null` for input that is not XML at all. A file that
+ * parses but holds no points comes back with zeroed counts — whether that is worth showing is the
+ * caller's call.
+ */
+export function parseGpxStats(xml: string): GpxStats | null {
+ let doc: Document;
+ try {
+ doc = new DOMParser().parseFromString(xml, "application/xml");
+ } catch {
+ return null;
+ }
+ // Browsers report a broken document as a document containing the error, not by throwing.
+ if (doc.querySelector("parsererror")) {
+ return null;
+ }
+
+ const root = doc.documentElement;
+ const segments = readSegments(doc);
+
+ const stats: GpxStats = {
+ name: readMetadataOrFirst(root, "name"),
+ description: readMetadataOrFirst(root, "desc"),
+ trackCount: doc.querySelectorAll("trk").length,
+ routeCount: doc.querySelectorAll("rte").length,
+ segmentCount: doc.querySelectorAll("trkseg").length,
+ pointCount: segments.reduce((count, segment) => count + segment.length, 0),
+ waypointCount: countPositioned(doc.querySelectorAll("wpt")),
+ distance: 0
+ };
+
+ const profile: GpxElevationSample[] = [];
+ let min = Infinity;
+ let max = -Infinity;
+ let gain = 0;
+ let loss = 0;
+ 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 [ index, point ] of segment.entries()) {
+ if (index > 0) {
+ stats.distance += haversine(segment[index - 1], point);
+ }
+
+ 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;
+ }
+ }
+
+ if (point.time !== undefined) {
+ start = Math.min(start, point.time);
+ end = Math.max(end, point.time);
+ }
+ }
+ }
+
+ if (profile.length > 0) {
+ stats.elevation = { min, max, gain, loss, profile: decimate(profile) };
+ }
+ if (start <= end) {
+ stats.time = { start: new Date(start), end: new Date(end), duration: end - start };
+ }
+
+ return stats;
+}
+
+/** How much a point's elevation must move, in metres, before it counts as climbing rather than as
+ * the few metres of jitter GPS elevation always carries. */
+const ELEVATION_NOISE_M = 5;
+
+/** How many buckets the elevation profile is decimated into for drawing. Each bucket keeps its
+ * lowest and its highest point, so a decimated profile can double this in samples — plenty for a
+ * chart, while a summit or a dip is never averaged away. */
+const PROFILE_BUCKETS = 250;
+
+const EARTH_RADIUS_M = 6371000;
+
+interface GpxPoint {
+ lat: number;
+ lon: number;
+ /** Metres, from the point's `<ele>` child when it carries a readable one. */
+ elevation?: number;
+ /** Epoch milliseconds, from the point's `<time>` child when it carries a readable one. */
+ time?: number;
+}
+
+/**
+ * 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.
+ */
+function readSegments(doc: Document): GpxPoint[][] {
+ const segments: GpxPoint[][] = [];
+
+ for (const container of doc.querySelectorAll("trkseg, rte")) {
+ const points = readPoints(container.querySelectorAll("trkpt, rtept"));
+ if (points.length > 0) {
+ segments.push(points);
+ }
+ }
+
+ if (segments.length === 0) {
+ const points = readPoints(doc.querySelectorAll("trkpt, rtept"));
+ if (points.length > 0) {
+ segments.push(points);
+ }
+ }
+
+ return segments;
+}
+
+/** Each point that carries a readable position; one that cannot say where it is is skipped. */
+function readPoints(elements: Iterable<Element>): GpxPoint[] {
+ const points: GpxPoint[] = [];
+
+ for (const element of elements) {
+ const lat = parseFloat(element.getAttribute("lat") ?? "");
+ const lon = parseFloat(element.getAttribute("lon") ?? "");
+ if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;
+
+ const point: GpxPoint = { lat, lon };
+
+ const elevation = parseFloat(childText(element, "ele") ?? "");
+ if (Number.isFinite(elevation)) {
+ point.elevation = elevation;
+ }
+
+ const time = Date.parse(childText(element, "time") ?? "");
+ if (Number.isFinite(time)) {
+ point.time = time;
+ }
+
+ points.push(point);
+ }
+
+ return points;
+}
+
+function countPositioned(elements: Iterable<Element>): number {
+ return readPoints(elements).length;
+}
+
+/** What the file calls the given field: its metadata's, else its first track's or route's. */
+function readMetadataOrFirst(root: Element, name: string): string | undefined {
+ for (const container of [ childNamed(root, "metadata"), childNamed(root, "trk"), childNamed(root, "rte") ]) {
+ const text = container && childText(container, name)?.trim();
+ if (text) {
+ return text;
+ }
+ }
+ return undefined;
+}
+
+/**
+ * A direct child's text, matched by local name so a namespaced document reads the same as a bare
+ * one — and only a direct child, so a `<time>` buried in a point's `<extensions>` (heart rate and
+ * the like travel there) is not mistaken for the point's own.
+ */
+function childText(element: Element, name: string): string | undefined {
+ return childNamed(element, name)?.textContent ?? undefined;
+}
+
+function childNamed(element: Element, name: string): Element | undefined {
+ for (const child of element.children) {
+ if (child.localName === name) {
+ return child;
+ }
+ }
+ return undefined;
+}
+
+/** The great-circle metres between two points, which is what "distance travelled" sums. */
+function haversine(a: GpxPoint, b: GpxPoint): number {
+ const toRadians = Math.PI / 180;
+ const dLat = (b.lat - a.lat) * toRadians;
+ const dLon = (b.lon - a.lon) * toRadians;
+ const h = Math.sin(dLat / 2) ** 2
+ + Math.cos(a.lat * toRadians) * Math.cos(b.lat * toRadians) * Math.sin(dLon / 2) ** 2;
+ return 2 * EARTH_RADIUS_M * Math.asin(Math.sqrt(h));
+}
+
+/**
+ * The profile thinned to what a chart can use, by keeping each bucket's lowest and highest sample
+ * rather than every Nth: a stride would average a summit away, and a chart of thousands of points
+ * buys no more pixels than one of hundreds. The first and last samples always survive, so the
+ * profile still spans the whole track.
+ */
+function decimate(profile: GpxElevationSample[]): GpxElevationSample[] {
+ if (profile.length <= PROFILE_BUCKETS * 2) {
+ return profile;
+ }
+
+ const out: GpxElevationSample[] = [ profile[0] ];
+ const bucketSize = profile.length / PROFILE_BUCKETS;
+
+ for (let bucket = 0; bucket < PROFILE_BUCKETS; bucket++) {
+ const from = Math.max(1, Math.floor(bucket * bucketSize));
+ const to = Math.min(profile.length - 1, Math.floor((bucket + 1) * bucketSize));
+
+ let lowest = -1;
+ let highest = -1;
+ for (let i = from; i < to; i++) {
+ if (lowest < 0 || profile[i].elevation < profile[lowest].elevation) lowest = i;
+ if (highest < 0 || profile[i].elevation > profile[highest].elevation) highest = i;
+ }
+
+ if (lowest >= 0) {
+ for (const index of lowest === highest ? [ lowest ] : [ Math.min(lowest, highest), Math.max(lowest, highest) ]) {
+ out.push(profile[index]);
+ }
+ }
+ }
+
+ out.push(profile[profile.length - 1]);
+ return out;
+}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index cf8a5e0547..bc1f5d5686 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1532,6 +1532,28 @@
"file_preview_not_available": "File preview is not available for this file format.",
"too_big": "The preview only shows the first {{maxNumChars}} characters of the file for performance reasons. Download the file and open it externally to be able to see the entire content."
},
+ "gpx_preview": {
+ "distance": "Distance",
+ "duration": "Duration",
+ "avg_speed": "Avg. speed",
+ "elevation_gain": "Elevation gain",
+ "elevation_loss": "Elevation loss",
+ "max_elevation": "Max. elevation",
+ "points": "Points",
+ "segments": "Segments",
+ "tracks": "Tracks",
+ "routes": "Routes",
+ "waypoints": "Waypoints",
+ "elevation_profile": "Elevation profile",
+ "duration_minutes": "{{minutes}} min",
+ "duration_hours_minutes": "{{hours}} h {{minutes}} min",
+ "unit_m": "{{value}} m",
+ "unit_km": "{{value}} km",
+ "unit_mi": "{{value}} mi",
+ "unit_ft": "{{value}} ft",
+ "unit_kmh": "{{value}} km/h",
+ "unit_mph": "{{value}} mph"
+ },
"media": {
"play": "Play",
"activate": "Play {{- title}}",
diff --git a/apps/client/src/widgets/collections/geomap/GpxTrack.tsx b/apps/client/src/widgets/collections/geomap/GpxTrack.tsx
index 627e8598d3..be8489a219 100644
--- a/apps/client/src/widgets/collections/geomap/GpxTrack.tsx
+++ b/apps/client/src/widgets/collections/geomap/GpxTrack.tsx
@@ -1,11 +1,13 @@
import type { FilterSpecification, Map as MapLibreGLMap } from "maplibre-gl";
import { useContext, useEffect } from "preact/hooks";
+import { GPX_MIME } from "../../../services/gpx";
import { MapStyleLoaded, ParentMap } from "./map";
import { buildMarkerImage, LABEL_LAYOUT, LABEL_PAINT, MARKER_SHADOW_PADDING, markerImageId } from "./Markers";
-/** What marks a note as a GPX track: the mime its file carries. */
-export const GPX_MIME = "application/gpx+xml";
+// Re-exported from the leaf module it moved to (the file preview reads it too, and importing it
+// from here would drag the whole map into that bundle), so the map-side consumers keep one home.
+export { GPX_MIME };
export interface GpxTrackProps {
/** The note the track belongs to, which is what its layers are named after and what a click on
@@ -83,7 +85,7 @@ export function GpxTrack({ noteId, title, gpxXmlString, trackColor, pinColor, ic
// Named after the note rather than at random. A random name is a different name on every run
// of this effect, so every track used to churn through a handful of sources and layers on
// its way onto the map, leaving nothing an outside observer could have recognised it by.
- const sourceId = `gpx-source-${noteId}`;
+ const sourceId = trackSourceId(noteId);
const layerId = `gpx-layer-${noteId}`;
const labelLayerId = `gpx-label-${noteId}`;
const hitLayerId = `${HIT_LAYER_PREFIX}${noteId}`;
@@ -293,6 +295,14 @@ export function GpxTrack({ noteId, title, gpxXmlString, trackColor, pinColor, ic
return <div />;
}
+/**
+ * The one source a track's layers draw from, named here for whoever needs to read the track back
+ * off the map — the pane fits the viewport around it when the track is opened (see DetailPane).
+ */
+export function trackSourceId(noteId: string) {
+ return `gpx-source-${noteId}`;
+}
+
/**
* The layers standing in for the tracks currently on the map, for whatever wants to hit-test them:
* each track's widened hit line, and the marks that flag it — a flag is as much the track as the
diff --git a/apps/client/src/widgets/type_widgets/File.tsx b/apps/client/src/widgets/type_widgets/File.tsx
index 2038ee171f..0f1737e35f 100644
--- a/apps/client/src/widgets/type_widgets/File.tsx
+++ b/apps/client/src/widgets/type_widgets/File.tsx
@@ -2,10 +2,12 @@ import "./File.css";
import { isOfficeMimeType } from "@triliumnext/commons";
+import { GPX_MIME } from "../../services/gpx";
import { t } from "../../services/i18n";
import Alert from "../react/Alert";
import CodeBlock from "../react/CodeBlock";
import { useNoteBlob } from "../react/hooks";
+import GpxPreview from "./file/GpxPreview";
import MediaPreview from "./file/MediaPreview";
import OfficePreview from "./file/Office";
import PdfPreview from "./file/Pdf";
@@ -23,6 +25,8 @@ export default function FileTypeWidget({ note, parentComponent, noteContext, isV
// would otherwise be caught by the blob.content branch below and shown as raw markup.
if (isOffice) {
return <OfficePreview note={note} />;
+ } else if (note.mime === GPX_MIME) {
+ return <GpxPreview note={note} blob={blob} />;
} else if (blob?.content) {
return <TextPreview content={blob.content} mime={note.mime} />;
} else if (note.mime === "application/pdf") {
diff --git a/apps/client/src/widgets/type_widgets/file/GpxPreview.css b/apps/client/src/widgets/type_widgets/file/GpxPreview.css
new file mode 100644
index 0000000000..1955d3ce26
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/GpxPreview.css
@@ -0,0 +1,124 @@
+.gpx-preview {
+ max-width: 1000px;
+
+ .gpx-preview-name {
+ margin: 0 0 4px;
+ }
+
+ .gpx-preview-description {
+ margin: 0 0 12px;
+ color: var(--muted-text-color);
+ }
+
+ .gpx-preview-stats {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
+ gap: 10px;
+ margin-bottom: 20px;
+ }
+
+ .gpx-stat {
+ padding: 10px 12px;
+ border-radius: 8px;
+ background: var(--accented-background-color);
+ }
+
+ .gpx-stat-value {
+ font-size: 1.3em;
+ font-weight: 600;
+ /* The digits of neighbouring tiles line up instead of jittering by glyph width. */
+ font-variant-numeric: tabular-nums;
+ }
+
+ .gpx-stat-label {
+ margin-top: 2px;
+ font-size: 0.85em;
+ color: var(--muted-text-color);
+ }
+
+ .gpx-profile-heading {
+ margin-bottom: 6px;
+ font-size: 0.85em;
+ color: var(--muted-text-color);
+ }
+
+ .gpx-profile-plot {
+ position: relative;
+ height: 160px;
+ /* What the line and its fill are drawn in when the note carries no colour of its own —
+ the note's own colour, set inline, wins over this. */
+ color: var(--link-color);
+ border-bottom: 1px solid var(--main-border-color);
+ }
+
+ .gpx-profile-plot svg {
+ display: block;
+ width: 100%;
+ height: 100%;
+ }
+
+ .gpx-profile-area {
+ fill: currentColor;
+ fill-opacity: 0.15;
+ stroke: none;
+ }
+
+ .gpx-profile-line {
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 2px;
+ }
+
+ .gpx-profile-gridline {
+ stroke: var(--main-border-color);
+ stroke-width: 1px;
+ stroke-dasharray: 4 4;
+ opacity: 0.6;
+ }
+
+ .gpx-profile-crosshair {
+ stroke: var(--muted-text-color);
+ stroke-width: 1px;
+ }
+
+ .gpx-profile-max,
+ .gpx-profile-min {
+ position: absolute;
+ left: 6px;
+ font-size: 0.8em;
+ color: var(--muted-text-color);
+ pointer-events: none;
+ }
+
+ .gpx-profile-max {
+ top: 2px;
+ }
+
+ .gpx-profile-min {
+ bottom: 2px;
+ }
+
+ .gpx-profile-tooltip {
+ position: absolute;
+ top: 6px;
+ transform: translateX(-50%);
+ padding: 2px 8px;
+ border-radius: 4px;
+ /* The plain surface pair rather than the tooltip variables: the legacy themes carry no
+ tooltip foreground, and a dark tooltip background with inherited dark text is unreadable. */
+ background: var(--main-background-color);
+ color: var(--main-text-color);
+ border: 1px solid var(--main-border-color);
+ font-size: 0.85em;
+ white-space: nowrap;
+ pointer-events: none;
+ }
+
+ .gpx-profile-axis {
+ display: flex;
+ justify-content: space-between;
+ margin-top: 2px;
+ font-size: 0.8em;
+ color: var(--muted-text-color);
+ }
+}
diff --git a/apps/client/src/widgets/type_widgets/file/GpxPreview.spec.tsx b/apps/client/src/widgets/type_widgets/file/GpxPreview.spec.tsx
new file mode 100644
index 0000000000..e9b4c6600c
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/GpxPreview.spec.tsx
@@ -0,0 +1,132 @@
+import { render } from "preact";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const serverGet = vi.fn<(url: string) => Promise<string | Uint8Array>>();
+
+vi.mock("../../../services/server", () => ({
+ default: { get: (url: string) => serverGet(url) }
+}));
+
+// 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"
+}));
+
+// i18next is never initialized under test, so t() is rendered deterministic instead: the key with
+// the interpolated values appended, e.g. "gpx_preview.unit_km|11.1".
+vi.mock("../../../services/i18n", () => ({
+ t: (key: string, opts?: Record<string, unknown>) => [ key, ...Object.values(opts ?? {}) ].join("|")
+}));
+
+const { default: GpxPreview } = await import("./GpxPreview");
+
+type PreviewProps = Parameters<typeof GpxPreview>[0];
+
+const GPX = `<?xml version="1.0" encoding="UTF-8"?>
+<gpx xmlns="http://www.topografix.com/GPX/1/1" version="1.1" creator="test">
+ <metadata><name>Ridge loop</name><desc>Up and back down</desc></metadata>
+ <trk><trkseg>
+ <trkpt lat="0" lon="0"><ele>100</ele><time>2024-06-01T10:00:00Z</time></trkpt>
+ <trkpt lat="0" lon="0.05"><ele>150</ele><time>2024-06-01T10:30:00Z</time></trkpt>
+ <trkpt lat="0" lon="0.1"><ele>120</ele><time>2024-06-01T11:00:00Z</time></trkpt>
+ </trkseg></trk>
+</gpx>`;
+
+let container: HTMLDivElement;
+
+beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+});
+
+afterEach(() => {
+ render(null, container);
+ container.remove();
+ vi.clearAllMocks();
+});
+
+function mount({ noteId = "gpx1", title = "hike.gpx", color = null as string | null, blob = { blobId: "blobA" } } = {}) {
+ const note = {
+ noteId,
+ title,
+ mime: "application/gpx+xml",
+ getLabelValue: () => color
+ } as unknown as PreviewProps["note"];
+ render(<GpxPreview note={note} blob={blob as PreviewProps["blob"]} />, container);
+}
+
+function tileValue(label: string): string | undefined {
+ for (const tile of container.querySelectorAll(".gpx-stat")) {
+ if (tile.querySelector(".gpx-stat-label")?.textContent === label) {
+ return tile.querySelector(".gpx-stat-value")?.textContent ?? undefined;
+ }
+ }
+ return undefined;
+}
+
+describe("GpxPreview", () => {
+ it("fetches the file raw and lays the track's numbers out as tiles", async () => {
+ serverGet.mockResolvedValue(GPX);
+
+ mount();
+ await vi.waitFor(() => expect(container.querySelector(".gpx-preview")).not.toBeNull());
+ expect(serverGet).toHaveBeenCalledWith("notes/gpx1/open");
+
+ // 0.1° along the equator ≈ 11.1 km, walked in an hour. The decimal separator is the
+ // machine's, so the fraction is matched rather than spelled.
+ expect(tileValue("gpx_preview.distance")).toMatch(/^gpx_preview\.unit_km\|11[.,]1$/);
+ expect(tileValue("gpx_preview.duration")).toBe("gpx_preview.duration_hours_minutes|1|0");
+ expect(tileValue("gpx_preview.avg_speed")).toMatch(/^gpx_preview\.unit_kmh\|11[.,]1$/);
+ 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.points")).toBe("3");
+ expect(tileValue("gpx_preview.segments")).toBe("1");
+ // A single track and no routes/waypoints say nothing worth a tile.
+ expect(tileValue("gpx_preview.tracks")).toBeUndefined();
+ expect(tileValue("gpx_preview.routes")).toBeUndefined();
+ expect(tileValue("gpx_preview.waypoints")).toBeUndefined();
+
+ // The file's own name and description are shown (the note is titled differently).
+ expect(container.querySelector(".gpx-preview-name")?.textContent).toBe("Ridge loop");
+ expect(container.querySelector(".gpx-preview-description")?.textContent).toBe("Up and back down");
+
+ // The elevation profile is drawn, spanning the track's extremes.
+ expect(container.querySelector(".gpx-profile-line")).not.toBeNull();
+ expect(container.querySelector(".gpx-profile-max")?.textContent).toBe("gpx_preview.unit_m|150");
+ expect(container.querySelector(".gpx-profile-min")?.textContent).toBe("gpx_preview.unit_m|100");
+ });
+
+ it("decodes a binary response and paints the profile in the note's own colour", async () => {
+ serverGet.mockResolvedValue(new TextEncoder().encode(GPX));
+
+ mount({ color: "#ff7700" });
+ await vi.waitFor(() => expect(container.querySelector(".gpx-preview")).not.toBeNull());
+
+ const plot = container.querySelector<HTMLElement>(".gpx-profile-plot");
+ expect(plot?.style.color).toBe("#ff7700");
+ });
+
+ it("hides the file's name when it just repeats the note's title", async () => {
+ serverGet.mockResolvedValue(GPX);
+
+ mount({ title: "Ridge loop" });
+ await vi.waitFor(() => expect(container.querySelector(".gpx-preview")).not.toBeNull());
+ expect(container.querySelector(".gpx-preview-name")).toBeNull();
+ });
+
+ it("falls back to the not-available notice for a file that is not readable GPX", async () => {
+ serverGet.mockResolvedValue("not gpx <at all");
+
+ mount();
+ await vi.waitFor(() => expect(container.querySelector(".file-preview-not-available")).not.toBeNull());
+ expect(container.querySelector(".gpx-preview")).toBeNull();
+ });
+
+ it("shows nothing until the blob has arrived", () => {
+ mount({ blob: null as unknown as { blobId: string } });
+ expect(container.innerHTML).toBe("");
+ expect(serverGet).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/file/GpxPreview.tsx b/apps/client/src/widgets/type_widgets/file/GpxPreview.tsx
new file mode 100644
index 0000000000..2f2b5eb3a4
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/GpxPreview.tsx
@@ -0,0 +1,262 @@
+import "./GpxPreview.css";
+
+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 { t } from "../../../services/i18n";
+import server from "../../../services/server";
+import { getMeasurementSystem } from "../../../utils/formatters";
+import Alert from "../../react/Alert";
+
+type MeasurementSystem = ReturnType<typeof getMeasurementSystem>;
+
+interface GpxPreviewProps {
+ note: FNote;
+ /** The note's blob, fetched by the file widget. Not read for its content — a GPX blob arrives
+ * contentless, the XML is fetched raw below — but watched, so an edited file re-reads. */
+ blob: FBlob | null | undefined;
+}
+
+/**
+ * Main-view preview for GPX files: what the track amounts to — distance, climb, time, and the
+ * pieces it is made of — with an elevation profile under it when the points carry elevation. The
+ * numbers stand where "no preview available" used to; the track itself is drawn by the geo map
+ * (see the geomap collection), not here.
+ */
+export default function GpxPreview({ note, blob }: GpxPreviewProps) {
+ const [ stats, setStats ] = useState<GpxStats | null>();
+
+ useEffect(() => {
+ if (!blob) return;
+ let cancelled = false;
+
+ // Fetched raw rather than read off the blob: the server returns no inline content for a
+ // GPX blob — the same road the geo map takes to draw the track.
+ server.get<string | Uint8Array>(`notes/${note.noteId}/open`, undefined, true).then((response) => {
+ if (cancelled) return;
+ const xml = response instanceof Uint8Array ? new TextDecoder().decode(response) : response;
+ setStats(parseGpxStats(xml));
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [ note.noteId, blob ]);
+
+ if (stats === undefined) {
+ return null;
+ }
+ if (!stats || (stats.pointCount === 0 && stats.waypointCount === 0)) {
+ // A file that is not readable GPX gets the notice any other unpreviewable file gets.
+ return (
+ <Alert className="file-preview-not-available" type="info">
+ {t("file.file_preview_not_available")}
+ </Alert>
+ );
+ }
+
+ const system = getMeasurementSystem();
+ const tiles = buildTiles(stats, system);
+ const trackColor = note.getLabelValue("color");
+
+ return (
+ <div className="gpx-preview selectable-text">
+ {stats.name && stats.name !== note.title && <h4 className="gpx-preview-name">{stats.name}</h4>}
+ {stats.description && <p className="gpx-preview-description">{stats.description}</p>}
+
+ <div className="gpx-preview-stats">
+ {tiles.map(({ label, value }) => (
+ <div key={label} className="gpx-stat">
+ <div className="gpx-stat-value">{value}</div>
+ <div className="gpx-stat-label">{label}</div>
+ </div>
+ ))}
+ </div>
+
+ {stats.elevation && stats.elevation.profile.length > 1 && stats.distance > 0 && (
+ <ElevationProfile
+ elevation={stats.elevation}
+ totalDistance={stats.distance}
+ system={system}
+ trackColor={trackColor}
+ />
+ )}
+ </div>
+ );
+}
+
+/** The tiles worth showing for this particular file: a value that would read "0" or restate an
+ * obvious default (one track, no routes) says nothing, so it is left out. */
+function buildTiles(stats: GpxStats, system: MeasurementSystem) {
+ const tiles: { label: string; value: string }[] = [];
+
+ if (stats.distance > 0) {
+ tiles.push({ label: t("gpx_preview.distance"), value: formatDistance(stats.distance, system) });
+ }
+ if (stats.time && stats.time.duration > 0) {
+ tiles.push({ label: t("gpx_preview.duration"), value: formatTravelDuration(stats.time.duration) });
+ if (stats.distance > 0) {
+ const kmh = (stats.distance / 1000) / (stats.time.duration / 3_600_000);
+ tiles.push({ label: t("gpx_preview.avg_speed"), value: formatSpeed(kmh, system) });
+ }
+ }
+ if (stats.elevation) {
+ tiles.push(
+ { label: t("gpx_preview.elevation_gain"), value: formatElevation(stats.elevation.gain, system) },
+ { label: t("gpx_preview.elevation_loss"), value: formatElevation(stats.elevation.loss, system) },
+ { label: t("gpx_preview.max_elevation"), value: formatElevation(stats.elevation.max, system) }
+ );
+ }
+ if (stats.pointCount > 0) {
+ tiles.push({ label: t("gpx_preview.points"), value: stats.pointCount.toLocaleString() });
+ }
+ if (stats.segmentCount > 0) {
+ tiles.push({ label: t("gpx_preview.segments"), value: stats.segmentCount.toLocaleString() });
+ }
+ if (stats.trackCount > 1) {
+ tiles.push({ label: t("gpx_preview.tracks"), value: stats.trackCount.toLocaleString() });
+ }
+ if (stats.routeCount > 0) {
+ tiles.push({ label: t("gpx_preview.routes"), value: stats.routeCount.toLocaleString() });
+ }
+ if (stats.waypointCount > 0) {
+ tiles.push({ label: t("gpx_preview.waypoints"), value: stats.waypointCount.toLocaleString() });
+ }
+
+ return tiles;
+}
+
+/** 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;
+const CHART_HEIGHT = 150;
+/** Air above the highest point, so the line's crest is not cut by the chart's edge. */
+const CHART_TOP_PAD = 10;
+
+function ElevationProfile({ elevation, totalDistance, system, trackColor }: {
+ elevation: NonNullable<GpxStats["elevation"]>;
+ totalDistance: number;
+ system: MeasurementSystem;
+ /** The note's own colour — the same one its track wears on the map — or null for the theme's. */
+ trackColor: string | null;
+}) {
+ const [ hover, setHover ] = useState<GpxElevationSample | null>(null);
+ const { min, max, profile } = elevation;
+
+ // A flat track still gets a visible line rather than a division by zero.
+ const span = Math.max(max - min, 1);
+ const x = (distance: number) => (distance / totalDistance) * CHART_WIDTH;
+ const y = (sampleElevation: number) => CHART_TOP_PAD + (1 - (sampleElevation - min) / span) * (CHART_HEIGHT - CHART_TOP_PAD);
+
+ const linePath = useMemo(
+ () => profile.map((sample, i) => `${i === 0 ? "M" : "L"}${x(sample.distance).toFixed(1)} ${y(sample.elevation).toFixed(1)}`).join(" "),
+ [ profile, totalDistance, min, max ]
+ );
+ const areaPath = `${linePath} L${x(profile[profile.length - 1].distance).toFixed(1)} ${CHART_HEIGHT} L${x(profile[0].distance).toFixed(1)} ${CHART_HEIGHT} Z`;
+
+ function onPointerMove(event: PointerEvent) {
+ const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
+ if (rect.width === 0) return;
+ const fraction = Math.min(1, Math.max(0, (event.clientX - rect.left) / rect.width));
+ setHover(nearestSample(profile, fraction * totalDistance));
+ }
+
+ return (
+ <div className="gpx-profile">
+ <div className="gpx-profile-heading">{t("gpx_preview.elevation_profile")}</div>
+ <div
+ className="gpx-profile-plot"
+ style={trackColor ? { color: trackColor } : undefined}
+ onPointerMove={onPointerMove}
+ onPointerLeave={() => setHover(null)}
+ >
+ <svg viewBox={`0 0 ${CHART_WIDTH} ${CHART_HEIGHT}`} preserveAspectRatio="none">
+ <line className="gpx-profile-gridline" x1={0} y1={y(max)} x2={CHART_WIDTH} y2={y(max)} vector-effect="non-scaling-stroke" />
+ <line className="gpx-profile-gridline" x1={0} y1={y((min + max) / 2)} x2={CHART_WIDTH} y2={y((min + max) / 2)} vector-effect="non-scaling-stroke" />
+ <path className="gpx-profile-area" d={areaPath} />
+ <path className="gpx-profile-line" d={linePath} vector-effect="non-scaling-stroke" />
+ {hover && (
+ <line
+ className="gpx-profile-crosshair"
+ x1={x(hover.distance)} y1={0}
+ x2={x(hover.distance)} y2={CHART_HEIGHT}
+ vector-effect="non-scaling-stroke"
+ />
+ )}
+ </svg>
+ <span className="gpx-profile-max">{formatElevation(max, system)}</span>
+ <span className="gpx-profile-min">{formatElevation(min, system)}</span>
+ {hover && (
+ <div className="gpx-profile-tooltip" style={{ left: `${(hover.distance / totalDistance) * 100}%` }}>
+ {formatDistance(hover.distance, system)} · {formatElevation(hover.elevation, system)}
+ </div>
+ )}
+ </div>
+ <div className="gpx-profile-axis">
+ <span>0</span>
+ <span>{formatDistance(totalDistance, system)}</span>
+ </div>
+ </div>
+ );
+}
+
+/** The profile point nearest to the given distance along the track, found by bisection — the
+ * profile is ordered by distance, and the pointer asks on every move. */
+function nearestSample(profile: GpxElevationSample[], distance: number): GpxElevationSample {
+ let lo = 0;
+ let hi = profile.length - 1;
+ while (hi - lo > 1) {
+ const mid = (lo + hi) >> 1;
+ if (profile[mid].distance < distance) {
+ lo = mid;
+ } else {
+ hi = mid;
+ }
+ }
+ return distance - profile[lo].distance <= profile[hi].distance - distance ? profile[lo] : profile[hi];
+}
+
+const METERS_PER_MILE = 1609.344;
+const FEET_PER_METER = 3.28084;
+
+function formatDistance(meters: number, system: MeasurementSystem): string {
+ if (system === "imperial") {
+ return t("gpx_preview.unit_mi", { value: round(meters / METERS_PER_MILE) });
+ }
+ if (meters < 1000) {
+ return t("gpx_preview.unit_m", { value: Math.round(meters).toLocaleString() });
+ }
+ return t("gpx_preview.unit_km", { value: round(meters / 1000) });
+}
+
+function formatElevation(meters: number, system: MeasurementSystem): string {
+ if (system === "imperial") {
+ return t("gpx_preview.unit_ft", { value: Math.round(meters * FEET_PER_METER).toLocaleString() });
+ }
+ return t("gpx_preview.unit_m", { value: Math.round(meters).toLocaleString() });
+}
+
+function formatSpeed(kmh: number, system: MeasurementSystem): string {
+ if (system === "imperial") {
+ return t("gpx_preview.unit_mph", { value: round(kmh * 1000 / METERS_PER_MILE) });
+ }
+ return t("gpx_preview.unit_kmh", { value: round(kmh) });
+}
+
+function formatTravelDuration(milliseconds: number): string {
+ const totalMinutes = Math.round(milliseconds / 60_000);
+ const hours = Math.floor(totalMinutes / 60);
+ const minutes = totalMinutes % 60;
+ if (hours === 0) {
+ return t("gpx_preview.duration_minutes", { minutes });
+ }
+ return t("gpx_preview.duration_hours_minutes", { hours, minutes });
+}
+
+/** A magnitude-appropriate rounding: two decimals close up, none once they would say nothing. */
+function round(value: number): string {
+ const decimals = value >= 100 ? 0 : value >= 10 ? 1 : 2;
+ return value.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: decimals });
+}