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
fix(geomap): draw the line of a GPX track, not just its ends
Elian Doran88c5d53f3f04
diff --git a/apps/client/src/widgets/collections/geomap/GpxTrack.spec.tsx b/apps/client/src/widgets/collections/geomap/GpxTrack.spec.tsxnew file mode 100644index 0000000000..062a6170b1--- /dev/null+++ b/apps/client/src/widgets/collections/geomap/GpxTrack.spec.tsx@@ -0,0 +1,288 @@+/**+ * The GPX track: the line between the flags.+ *+ * Two things kept it from being drawn. It was added only if `map.isStyleLoaded()` said so, or else on+ * the next `style.load` — but `style.load` fires once per style and this component mounts late (it+ * waits on the note's content to be fetched and on three icons to be drawn), so the event was+ * routinely long gone by the time it listened; and `isStyleLoaded()` answers for the tiles as much as+ * for the style, so it is false while they are still arriving. Missing both, the line was never added+ * at all, while the markers — elements of the page, added unconditionally — went up as usual. What+ * the user saw was a start and an end with nothing in between.+ *+ * The second was that every point in the file was strung into one line, so a track recorded in+ * segments was drawn with a straight line across each gap between them.+ */+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++/** The markers MapLibre was asked to put on the page, in the order they were added. */+const addedMarkers: { lngLat: [number, number]; html: string }[] = [];++vi.mock("maplibre-gl", () => ({+ Marker: class {+ private lngLat: [number, number] = [ 0, 0 ];++ constructor(private options: { element: HTMLElement }) {}++ setLngLat(lngLat: [number, number]) {+ this.lngLat = lngLat;+ return this;+ }++ addTo() {+ addedMarkers.push({ lngLat: this.lngLat, html: this.options.element.innerHTML });+ return this;+ }++ remove() {}+ }+}));++/**+ * A map as MapLibre behaves, in the one respect that matters here: a source or a layer can only be+ * added to a style that has finished loading, and asking for one before then throws.+ */+function fakeMap() {+ const sources = new Map<string, unknown>();+ const layers = new Map<string, unknown>();+ const listeners = new Map<string, (() => void)[]>();+ let loaded = false;++ return {+ sources,+ layers,+ /** What `map.isStyleLoaded()` answers — false while the tiles are still coming in. */+ tilesLoaded: false,++ on(type: string, listener: () => void) {+ listeners.set(type, [ ...(listeners.get(type) ?? []), listener ]);+ },+ off(type: string, listener: () => void) {+ listeners.set(type, (listeners.get(type) ?? []).filter((l) => l !== listener));+ },+ isStyleLoaded() {+ return loaded && this.tilesLoaded;+ },+ getSource(id: string) {+ return sources.get(id);+ },+ getLayer(id: string) {+ return layers.get(id);+ },+ addSource(id: string, source: unknown) {+ if (!loaded) throw new Error("Style is not done loading");+ sources.set(id, source);+ },+ addLayer(layer: { id: string }) {+ if (!loaded) throw new Error("Style is not done loading");+ layers.set(layer.id, layer);+ },+ removeSource(id: string) {+ sources.delete(id);+ },+ removeLayer(id: string) {+ layers.delete(id);+ },++ /** The style finishing, which is what `style.load` announces. */+ loadStyle() {+ loaded = true;+ for (const listener of listeners.get("style.load") ?? []) {+ listener();+ }+ }+ };+}++/** A track of two segments, a good way apart, plus a waypoint between them. */+const TWO_SEGMENT_GPX = `<?xml version="1.0" encoding="UTF-8"?>+<gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1">+ <wpt lat="45.9" lon="24.1"><name>A rest</name></wpt>+ <trk>+ <trkseg>+ <trkpt lat="45.79" lon="24.13" />+ <trkpt lat="45.81" lon="24.14" />+ </trkseg>+ <trkseg>+ <trkpt lat="45.96" lon="24.16" />+ <trkpt lat="45.89" lon="24.08" />+ </trkseg>+ </trk>+</gpx>`;++describe("GpxTrack", () => {+ let container: HTMLElement;+ let map: ReturnType<typeof fakeMap>;+ let GpxTrack: typeof import("./GpxTrack").GpxTrack;+ let ParentMap: typeof import("./map").ParentMap;+ let MapStyleLoaded: typeof import("./map").MapStyleLoaded;++ beforeEach(async () => {+ ({ GpxTrack } = await import("./GpxTrack"));+ ({ ParentMap, MapStyleLoaded } = await import("./map"));+ addedMarkers.length = 0;+ map = fakeMap();+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ });++ /** Mounts the track under a map whose style has loaded (or not), as the context reports it. */+ function renderTrack({ styleLoaded, gpx = TWO_SEGMENT_GPX }: { styleLoaded: boolean; gpx?: string }) {+ act(() => {+ render(+ <ParentMap.Provider value={map as never}>+ <MapStyleLoaded.Provider value={styleLoaded}>+ <GpxTrack+ gpxXmlString={gpx}+ trackColor="red"+ startIconHtml="<i>start</i>"+ endIconHtml="<i>end</i>"+ waypointIconHtml="<i>waypoint</i>"+ />+ </MapStyleLoaded.Provider>+ </ParentMap.Provider>,+ container+ );+ });+ }++ /** The one line layer the track added, whatever its generated id. */+ function trackLayer() {+ return [ ...map.layers.values() ][0] as { paint: Record<string, unknown> } | undefined;+ }++ /** The coordinates of the one source the track added. */+ function trackCoordinates() {+ const source = [ ...map.sources.values() ][0] as+ { data: { geometry: { type: string; coordinates: [number, number][][] } } } | undefined;+ return source?.data.geometry;+ }++ it("draws the line when it mounts after the style loaded, with the tiles still coming in", () => {+ // The style is long since loaded and `style.load` is spent — the case that used to lose.+ map.loadStyle();+ expect(map.isStyleLoaded()).toBe(false);++ renderTrack({ styleLoaded: true });++ expect(trackLayer()?.paint["line-color"]).toBe("red");+ expect(trackCoordinates()?.type).toBe("MultiLineString");+ });++ it("draws the line once the style loads, when it mounts before that", () => {+ renderTrack({ styleLoaded: false });++ // Nothing yet: there is no style to add to.+ expect(map.layers.size).toBe(0);++ act(() => map.loadStyle());++ expect(map.layers.size).toBe(1);+ expect(trackCoordinates()?.coordinates).toHaveLength(2);+ });++ it("keeps the segments apart, rather than joining them across the gap", () => {+ map.loadStyle();+ renderTrack({ styleLoaded: true });++ expect(trackCoordinates()).toEqual({+ type: "MultiLineString",+ coordinates: [+ [ [ 24.13, 45.79 ], [ 24.14, 45.81 ] ],+ [ [ 24.16, 45.96 ], [ 24.08, 45.89 ] ]+ ]+ });+ });++ it("flags where the whole track begins and ends, not every segment", () => {+ map.loadStyle();+ renderTrack({ styleLoaded: true });++ const flags = addedMarkers.filter((marker) => marker.html !== "<i>waypoint</i>");+ expect(flags).toEqual([+ { lngLat: [ 24.13, 45.79 ], html: "<i>start</i>" },+ { lngLat: [ 24.08, 45.89 ], html: "<i>end</i>" }+ ]);+ });++ it("marks the waypoints", () => {+ map.loadStyle();+ renderTrack({ styleLoaded: true });++ expect(addedMarkers.filter((marker) => marker.html === "<i>waypoint</i>"))+ .toEqual([ { lngLat: [ 24.1, 45.9 ], html: "<i>waypoint</i>" } ]);+ });++ it("draws a route as it draws a track", () => {+ map.loadStyle();+ renderTrack({+ styleLoaded: true,+ gpx: `<?xml version="1.0" encoding="UTF-8"?>+<gpx version="1.1" xmlns="http://www.topografix.com/GPX/1/1">+ <rte><rtept lat="1" lon="2" /><rtept lat="3" lon="4" /></rte>+</gpx>`+ });++ expect(trackCoordinates()?.coordinates).toEqual([ [ [ 2, 1 ], [ 4, 3 ] ] ]);+ });++ it("skips a point that does not say where it is, rather than placing it at zero", () => {+ map.loadStyle();+ renderTrack({+ styleLoaded: true,+ gpx: `<?xml version="1.0" encoding="UTF-8"?>+<gpx version="1.1" xmlns="http://www.topografix.com/GPX/1/1">+ <trk><trkseg>+ <trkpt lat="45.79" lon="24.13" />+ <trkpt lon="24.14" />+ <trkpt lat="45.81" lon="24.15" />+ </trkseg></trk>+</gpx>`+ });++ expect(trackCoordinates()?.coordinates).toEqual([ [ [ 24.13, 45.79 ], [ 24.15, 45.81 ] ] ]);+ });++ it("puts the line back when the style is switched under it", () => {+ map.loadStyle();+ renderTrack({ styleLoaded: true });+ expect(map.layers.size).toBe(1);++ // A style is a world of its own: switching one takes everything on it away.+ map.layers.clear();+ map.sources.clear();+ act(() => map.loadStyle());++ expect(map.layers.size).toBe(1);+ expect(trackCoordinates()?.type).toBe("MultiLineString");+ });++ it("draws nothing for a file with no points, and does not throw over it", () => {+ map.loadStyle();+ renderTrack({+ styleLoaded: true,+ gpx: `<?xml version="1.0" encoding="UTF-8"?><gpx version="1.1" xmlns="http://www.topografix.com/GPX/1/1" />`+ });++ expect(map.layers.size).toBe(0);+ expect(map.sources.size).toBe(0);+ expect(addedMarkers).toHaveLength(0);+ });++ it("takes the line off the map when it goes", () => {+ map.loadStyle();+ renderTrack({ styleLoaded: true });+ expect(map.layers.size).toBe(1);++ act(() => render(null, container));++ expect(map.layers.size).toBe(0);+ expect(map.sources.size).toBe(0);+ });+});diff --git a/apps/client/src/widgets/collections/geomap/GpxTrack.tsx b/apps/client/src/widgets/collections/geomap/GpxTrack.tsxindex ca9a9a47d1..5ff204ebee 100644--- a/apps/client/src/widgets/collections/geomap/GpxTrack.tsx+++ b/apps/client/src/widgets/collections/geomap/GpxTrack.tsx@@ -1,7 +1,7 @@import { Marker as MapLibreMarker } from "maplibre-gl";import { useContext, useEffect } from "preact/hooks";-import { ParentMap } from "./map";+import { MapStyleLoaded, ParentMap } from "./map";export interface GpxTrackProps {gpxXmlString: string;@@ -20,6 +20,7 @@ export interface GpxTrackProps {*/export function GpxTrack({ gpxXmlString, trackColor, startIconHtml, endIconHtml, waypointIconHtml }: GpxTrackProps) {const parentMap = useContext(ParentMap);+ const styleLoaded = useContext(MapStyleLoaded);useEffect(() => {if (!parentMap) return;@@ -31,14 +32,9 @@ export function GpxTrack({ gpxXmlString, trackColor, startIconHtml, endIconHtml,const layerId = `gpx-layer-${sourceId}`;const gpxDoc = new DOMParser().parseFromString(gpxXmlString, "application/xml");-- // Parse tracks and routes.- const coordinates: [number, number][] = [];- for (const point of gpxDoc.querySelectorAll("trkpt, rtept")) {- const lat = parseFloat(point.getAttribute("lat") ?? "0");- const lon = parseFloat(point.getAttribute("lon") ?? "0");- coordinates.push([ lon, lat ]);- }+ const lines = readLines(gpxDoc);+ const firstLine = lines[0] ?? [];+ const lastLine = lines[lines.length - 1] ?? [];function addMarker(lngLat: [number, number], html: string) {const element = document.createElement("div");@@ -51,52 +47,76 @@ export function GpxTrack({ gpxXmlString, trackColor, startIconHtml, endIconHtml,}// Markers are elements of the page rather than of the style, so they are added only once.- if (coordinates.length > 0) {+ // Where the track goes and where it stops, which is the first point of its first line and the+ // last of its last — not one pair per line, since a track broken into segments is still one+ // journey, and a flag at every pause would be a flag at every traffic light.+ if (firstLine.length > 0) {if (startIconHtml) {- addMarker(coordinates[0], startIconHtml);+ addMarker(firstLine[0], startIconHtml);}- if (endIconHtml && coordinates.length > 1) {- addMarker(coordinates[coordinates.length - 1], endIconHtml);+ const end = lastLine[lastLine.length - 1];+ if (endIconHtml && end && end !== firstLine[0]) {+ addMarker(end, endIconHtml);}}if (waypointIconHtml) {- for (const waypoint of gpxDoc.querySelectorAll("wpt")) {- const lat = parseFloat(waypoint.getAttribute("lat") ?? "0");- const lon = parseFloat(waypoint.getAttribute("lon") ?? "0");- addMarker([ lon, lat ], waypointIconHtml);+ for (const waypoint of readPoints(gpxDoc.querySelectorAll("wpt"))) {+ addMarker(waypoint, waypointIconHtml);}}// The track line lives in the map style, which setStyle() wipes (the async vector style// arriving, the layer being switched), so it has to be added again on every style load.+ //+ // Each half is put back on its own, and only if it is missing, so that a call made while the+ // map is between two styles leaves nothing half-done: adding the source can succeed and the+ // layer then fail, and a run that took "the source is there" to mean "so is the line" would+ // never draw it. Failing is expected in that window — the style load that follows calls this+ // again, against a style that will have it.function addTrackLayer() {- if (coordinates.length === 0 || map.getSource(sourceId)) return;-- map.addSource(sourceId, {- type: "geojson",- data: {- type: "Feature",- properties: {},- geometry: {- type: "LineString",- coordinates- }+ if (lines.length === 0) return;++ try {+ if (!map.getSource(sourceId)) {+ map.addSource(sourceId, {+ type: "geojson",+ data: {+ type: "Feature",+ properties: {},+ // One line per segment rather than every point strung together: a track+ // is broken into segments exactly where it stopped being recorded, so+ // joining them drew a straight line across each gap — through whatever+ // happened to lie between the end of one segment and the start of the+ // next.+ geometry: {+ type: "MultiLineString",+ coordinates: lines+ }+ }+ });+ }++ if (!map.getLayer(layerId)) {+ map.addLayer({+ id: layerId,+ type: "line",+ source: sourceId,+ paint: {+ "line-color": trackColor ?? "blue",+ "line-width": 3+ }+ });}- });-- map.addLayer({- id: layerId,- type: "line",- source: sourceId,- paint: {- "line-color": trackColor ?? "blue",- "line-width": 3+ } catch (e) {+ // Only worth a word if the style was ready and it still would not take the line.+ if (styleLoaded) {+ console.warn("Geo map: could not draw a GPX track —", e);}- });+ }}- if (map.isStyleLoaded()) {+ if (styleLoaded) {addTrackLayer();}map.on("style.load", addTrackLayer);@@ -117,7 +137,56 @@ export function GpxTrack({ gpxXmlString, trackColor, startIconHtml, endIconHtml,// The map may already have been removed.}};- }, [ parentMap, gpxXmlString, trackColor, startIconHtml, endIconHtml, waypointIconHtml ]);+ }, [ parentMap, styleLoaded, gpxXmlString, trackColor, startIconHtml, endIconHtml, waypointIconHtml ]);return <div />;}++/**+ * The lines a GPX file draws, one per track segment and one per route.+ *+ * A track is split into segments precisely where the recording stopped and picked up again — a lost+ * signal, a paused watch, a drive home nobody logged — so the segments are kept apart rather than+ * strung together. Routes are lines of the same kind and are read alongside them.+ *+ * Points that name no readable position are dropped. A line of one point is kept: it draws nothing,+ * but it is still where the track began or ended, which is what the markers are placed from.+ */+function readLines(gpxDoc: Document): [number, number][][] {+ const lines: [number, number][][] = [];++ for (const container of gpxDoc.querySelectorAll("trkseg, rte")) {+ const points = readPoints(container.querySelectorAll("trkpt, rtept"));+ if (points.length > 0) {+ lines.push(points);+ }+ }++ // A file whose points sit outside any segment or route is not one the GPX schema allows, but it+ // used to draw as a single line here and there is no reason to stop drawing it. Only reached when+ // the reading above found nothing, so a well-formed file never takes this path.+ if (lines.length === 0) {+ const points = readPoints(gpxDoc.querySelectorAll("trkpt, rtept"));+ if (points.length > 0) {+ lines.push(points);+ }+ }++ return lines;+}++/** The `[lng, lat]` GeoJSON wants, for each point that carries a readable pair. */+function readPoints(points: Iterable<Element>): [number, number][] {+ const coordinates: [number, number][] = [];++ for (const point of points) {+ const lat = parseFloat(point.getAttribute("lat") ?? "");+ const lon = parseFloat(point.getAttribute("lon") ?? "");+ // A point that cannot say where it is is skipped rather than defaulted: falling back to zero+ // put it in the Gulf of Guinea and ran the line out to it and back.+ if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;+ coordinates.push([ lon, lat ]);+ }++ return coordinates;+}diff --git a/apps/client/src/widgets/collections/geomap/map.tsx b/apps/client/src/widgets/collections/geomap/map.tsxindex 2a3c83e8d4..e4c45753bd 100644--- a/apps/client/src/widgets/collections/geomap/map.tsx+++ b/apps/client/src/widgets/collections/geomap/map.tsx@@ -19,6 +19,21 @@ export interface GeoMouseEvent {export const ParentMap = createContext<MapLibreGLMap | null>(null);+/**+ * Whether the map's style has finished loading, and so whether a source or a layer can be added to it.+ *+ * Offered here rather than left to each child to work out, because neither of the two things MapLibre+ * says about it can be asked after the fact. `style.load` fires once per style, so a child that mounts+ * late — one waiting on the note's content to be fetched, say — attaches its listener to an event that+ * has already gone by. And `isStyleLoaded()` is no fallback, since it answers for the tiles as much as+ * for the style: it stays false while they are still arriving, and forever on a map whose tile server+ * is slow or refuses us. A child that misses both never gets to add anything at all.+ *+ * Latched beside the map's own creation instead (see below), where the event cannot be missed, and+ * handed down as context so a child that mounts at any time reads the same answer.+ */+export const MapStyleLoaded = createContext(false);+interface MapProps {apiRef?: RefObject<MapLibreGLMap | null>;containerRef?: RefObject<HTMLDivElement>;@@ -95,6 +110,8 @@ export default function Map({ coordinates, zoom, layerData, viewportChanged, chiconst appliedStyle = useRef<StyleContents>();// Whether there is no map to be had here at all — see the catch below.const [ unsupported, setUnsupported ] = useState(false);+ // See MapStyleLoaded.+ const [ styleLoaded, setStyleLoaded ] = useState(false);// Initialize the map.useEffect(() => {@@ -119,6 +136,12 @@ export default function Map({ coordinates, zoom, layerData, viewportChanged, chi}setUnsupported(false);+ // Listened for here, in the same breath as the map is built, rather than in an effect of its+ // own: a style begins loading inside the constructor and `style.load` fires once, so a+ // listener attached even one render later can already be too late. Never unlatched — a style+ // that has loaded is followed only by another style loading, and each of those fires again.+ mapInstance.on("style.load", () => setStyleLoaded(true));+// The attribution stands at the foot of the map beside its scale, rather than in the corner// where the zoom buttons now are (see MapToolbar): a bar of buttons is reached for, and it// would otherwise sit on top of a line of small print that is itself made of links.@@ -145,6 +168,7 @@ export default function Map({ coordinates, zoom, layerData, viewportChanged, chireturn () => {mapInstance.remove();setMap(null);+ setStyleLoaded(false);};}, []);@@ -235,7 +259,9 @@ export default function Map({ coordinates, zoom, layerData, viewportChanged, chi? <NoItems icon="bx bx-error-circle" text={t("geo-map.webgl-unavailable")} />: (<ParentMap.Provider value={map}>- {children}+ <MapStyleLoaded.Provider value={styleLoaded}>+ {children}+ </MapStyleLoaded.Provider></ParentMap.Provider>)}</div>