Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(client): list a GPX file's waypoints under its preview
Elian Dorand715cb22351f
diff --git a/apps/client/src/services/gpx.spec.ts b/apps/client/src/services/gpx.spec.tsindex 4444059666..6124826ef1 100644--- a/apps/client/src/services/gpx.spec.ts+++ b/apps/client/src/services/gpx.spec.ts@@ -76,10 +76,10 @@ describe("parseGpxStats", () => {routeCount: 1,segmentCount: 2,pointCount: 7,- // The waypoint without a position is not counted.- waypointCount: 1,name: "Morning ride"});+ // The waypoint without a position is not counted.+ expect(stats?.waypoints).toHaveLength(1);// 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);@@ -163,7 +163,21 @@ describe("parseGpxStats", () => {<name>Fells loop</name><desc>A ramble</desc><wpt lat="42.4" lon="-71.1"><name>Crossing</name></wpt></gpx>`);- expect(stats).toMatchObject({ name: "Fells loop", description: "A ramble", waypointCount: 1 });+ expect(stats).toMatchObject({ name: "Fells loop", description: "A ramble", waypoints: [ { name: "Crossing" } ] });+ });++ it("lists the waypoints — a desc kept only where it says more than the name", () => {+ const stats = parseGpxStats(gpx(`+ <wpt lat="1" lon="1"><name>5236BRIDGE</name><desc>Bridge</desc><ele>89.9</ele></wpt>+ <wpt lat="2" lon="2"><name>5066</name><desc>5066</desc></wpt>+ <wpt lat="3" lon="3"/>+ `));+ expect(stats?.waypoints).toEqual([+ { name: "5236BRIDGE", description: "Bridge", elevation: 89.9 },+ // The desc repeating the name is dropped; a bare point still counts as a waypoint.+ { name: "5066" },+ {}+ ]);});it("reads points sitting outside any segment or route, as the map does", () => {@@ -192,7 +206,7 @@ describe("parseGpxStats", () => {});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(gpx(""))).toMatchObject({ pointCount: 0, waypoints: [], 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.tsindex ef004f0b4c..4e36f7dae0 100644--- a/apps/client/src/services/gpx.ts+++ b/apps/client/src/services/gpx.ts@@ -15,6 +15,16 @@ export interface GpxElevationSample {elevation: number;}+/** A named place the file marks beside its lines — only what a listing shows of one. */+export interface GpxWaypoint {+ name?: string;+ /** The `<desc>`, kept only where it says more than the name — tools often write the name into+ * both, and a listing that repeats each name twice says nothing. */+ description?: string;+ /** Metres, when the waypoint carries one. */+ 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. */@@ -25,7 +35,8 @@ export interface GpxStats {segmentCount: number;/** Track and route points that carry a readable position. */pointCount: number;- waypointCount: number;+ /** 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* counted: a track is split exactly where it stopped being recorded, so whatever ground lies* between two segments was not travelled on this track. */@@ -78,7 +89,7 @@ export function parseGpxStats(xml: string): GpxStats | null {routeCount: doc.querySelectorAll("rte").length,segmentCount: doc.querySelectorAll("trkseg").length,pointCount: segments.reduce((count, segment) => count + segment.length, 0),- waypointCount: countPositioned(doc.querySelectorAll("wpt")),+ waypoints: readWaypoints(doc),distance: 0};@@ -312,8 +323,30 @@ function readPoints(elements: Iterable<Element>, { withTime = true } = {}): GpxPreturn points;}-function countPositioned(elements: Iterable<Element>): number {- return readPoints(elements).length;+/** The file's waypoints as a listing shows them, skipping any that cannot say where they are. */+function readWaypoints(doc: Document): GpxWaypoint[] {+ const waypoints: GpxWaypoint[] = [];++ for (const element of doc.querySelectorAll("wpt")) {+ const [ point ] = readPoints([ element ], { withTime: false });+ if (!point) continue;++ const waypoint: GpxWaypoint = {};+ const name = childText(element, "name")?.trim();+ if (name) {+ waypoint.name = name;+ }+ const description = childText(element, "desc")?.trim();+ if (description && description !== name) {+ waypoint.description = description;+ }+ if (point.elevation !== undefined) {+ waypoint.elevation = point.elevation;+ }+ waypoints.push(waypoint);+ }++ return waypoints;}/** What the file calls the given field: its metadata's (kept directly on the root in GPX 1.0,diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 1d678068ea..e77e657b69 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1544,6 +1544,8 @@"tracks": "Tracks","routes": "Routes","waypoints": "Waypoints",+ "waypoints_with_count": "Waypoints ({{count}})",+ "unnamed_waypoint": "(unnamed)","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.cssindex 25d04cc47f..b070d89970 100644--- a/apps/client/src/widgets/type_widgets/file/GpxPreview.css+++ b/apps/client/src/widgets/type_widgets/file/GpxPreview.css@@ -130,6 +130,43 @@color: var(--muted-text-color);}+ .gpx-waypoints {+ margin-top: 12px;+ }++ .gpx-waypoint-list {+ list-style: none;+ margin: 0;+ padding: 2px 0 0;++ > li {+ display: flex;+ align-items: baseline;+ gap: 6px;+ padding: 2px 0;++ > .bx {+ color: var(--muted-text-color);+ /* An icon has no baseline worth aligning to; centred it sits on the text's height. */+ align-self: center;+ }+ }+ }++ .gpx-waypoint-description {+ color: var(--muted-text-color);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .gpx-waypoint-elevation {+ margin-left: auto;+ color: var(--muted-text-color);+ font-variant-numeric: tabular-nums;+ white-space: nowrap;+ }+.gpx-preview-map-hint {display: flex;align-items: center;diff --git a/apps/client/src/widgets/type_widgets/file/GpxPreview.spec.tsx b/apps/client/src/widgets/type_widgets/file/GpxPreview.spec.tsxindex 89b1dc6267..6e4b12bb8e 100644--- a/apps/client/src/widgets/type_widgets/file/GpxPreview.spec.tsx+++ b/apps/client/src/widgets/type_widgets/file/GpxPreview.spec.tsx@@ -19,6 +19,13 @@ vi.mock("../../../services/i18n", () => ({t: (key: string, opts?: Record<string, unknown>) => [ key, ...Object.values(opts ?? {}) ].join("|")}));+// Collapsible pulls the real hooks module, which imports half the app (app_context, keyboard+// actions) at module scope; only the two hooks it actually uses are stood in for.+vi.mock("../../react/hooks", () => ({+ useElementSize: () => ({ width: 100, height: 100 }),+ useUniqueName: () => "test-collapsible"+}));+const { default: GpxPreview } = await import("./GpxPreview");type PreviewProps = Parameters<typeof GpxPreview>[0];@@ -102,6 +109,27 @@ describe("GpxPreview", () => {expect(container.querySelector(".gpx-preview-map-hint")?.textContent).toContain("gpx_preview.map_hint");});+ 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>+ <wpt lat="0" lon="0.01"><name>5066</name><desc>5066</desc></wpt>+ <trk>`));++ mount();+ await vi.waitFor(() => expect(container.querySelector(".gpx-waypoints")).not.toBeNull());++ expect(container.querySelector(".gpx-waypoints .collapsible-title")?.textContent)+ .toContain("gpx_preview.waypoints_with_count|2");++ const rows = [ ...container.querySelectorAll(".gpx-waypoint-list > li") ];+ expect(rows.map((row) => row.querySelector(".gpx-waypoint-name")?.textContent)).toEqual([ "GATE16", "5066" ]);+ // The desc shows only where it says more than the name; the elevation only where there is one.+ expect(rows[0].querySelector(".gpx-waypoint-description")?.textContent).toBe("Gate 16");+ expect(rows[0].querySelector(".gpx-waypoint-elevation")?.textContent).toBe("gpx_preview.unit_m|78");+ expect(rows[1].querySelector(".gpx-waypoint-description")).toBeNull();+ expect(rows[1].querySelector(".gpx-waypoint-elevation")).toBeNull();+ });+it("decodes a binary response and paints the profile in the note's own colour", async () => {serverGet.mockResolvedValue(new TextEncoder().encode(GPX));diff --git a/apps/client/src/widgets/type_widgets/file/GpxPreview.tsx b/apps/client/src/widgets/type_widgets/file/GpxPreview.tsxindex 300a0aa927..bf97758c56 100644--- a/apps/client/src/widgets/type_widgets/file/GpxPreview.tsx+++ b/apps/client/src/widgets/type_widgets/file/GpxPreview.tsx@@ -9,6 +9,7 @@ import { t } from "../../../services/i18n";import server from "../../../services/server";import { getMeasurementSystem } from "../../../utils/formatters";import Alert from "../../react/Alert";+import Collapsible from "../../react/Collapsible";type MeasurementSystem = ReturnType<typeof getMeasurementSystem>;@@ -48,7 +49,7 @@ export default function GpxPreview({ note, blob }: GpxPreviewProps) {if (stats === undefined) {return null;}- if (!stats || (stats.pointCount === 0 && stats.waypointCount === 0)) {+ if (!stats || (stats.pointCount === 0 && stats.waypoints.length === 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">@@ -92,6 +93,28 @@ export default function GpxPreview({ note, blob }: GpxPreviewProps) {/>)}+ {/* 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 && (+ <Collapsible+ className="gpx-waypoints"+ title={t("gpx_preview.waypoints_with_count", { count: stats.waypoints.length })}+ >+ <ul className="gpx-waypoint-list">+ {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>+ {waypoint.description && <span className="gpx-waypoint-description">{waypoint.description}</span>}+ {waypoint.elevation !== undefined && (+ <span className="gpx-waypoint-elevation">{formatElevation(waypoint.elevation, system)}</span>+ )}+ </li>+ ))}+ </ul>+ </Collapsible>+ )}+{/* Where the track itself can be seen — hidden when this preview already sits in a geomap's own pane (see the note in GpxPreview.css), where the track is right there. */}<div className="gpx-preview-map-hint">@@ -136,8 +159,8 @@ function buildTiles(stats: GpxStats, system: MeasurementSystem) {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() });+ if (stats.waypoints.length > 0) {+ tiles.push({ label: t("gpx_preview.waypoints"), value: stats.waypoints.length.toLocaleString() });}return tiles;