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
refactor(geomap): draw a GPX track's flags into the map, not the DOM
Elian Doran5890f0beb181
diff --git a/apps/client/src/widgets/collections/geomap/GpxTrack.spec.tsx b/apps/client/src/widgets/collections/geomap/GpxTrack.spec.tsxindex 62f421557a..4a1b465c72 100644--- a/apps/client/src/widgets/collections/geomap/GpxTrack.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/GpxTrack.spec.tsx@@ -1,42 +1,30 @@/**- * The GPX track: the line between the flags.+ * The GPX track: the line between the flags, and the flags themselves.*- * 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.+ * Two things kept the line 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), 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.** 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.+ *+ * The marks used to be DOM elements apiece — a leftover of the Leaflet map — which nothing+ * hit-testing the style could see. They are features of the track's own source now, stamped by a+ * symbol layer with pins from the shared rasterizer (see Markers), and only that layer waits on the+ * rasterizing: the line must go up at once, as it always has.*/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;- }+import { GpxTrack, trackHitLayers } from "./GpxTrack";+import { MapStyleLoaded, ParentMap } from "./map";+import { LABEL_PAINT, markerImageId } from "./Markers";- remove() {}- }+vi.mock("../../../services/icon_glyphs", () => ({+ renderIconImage: vi.fn(async () => "data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=")}));/**@@ -46,12 +34,14 @@ vi.mock("maplibre-gl", () => ({function fakeMap() {const sources = new Map<string, unknown>();const layers = new Map<string, unknown>();+ const images = new Map<string, unknown>();const listeners = new Map<string, (() => void)[]>();let loaded = false;return {sources,layers,+ images,/** What `map.isStyleLoaded()` answers — false while the tiles are still coming in. */tilesLoaded: false,@@ -81,6 +71,12 @@ function fakeMap() {getLayersOrder() {return [ ...layers.keys() ];},+ hasImage(id: string) {+ return images.has(id);+ },+ addImage(id: string, image: unknown) {+ images.set(id, image);+ },removeSource(id: string) {sources.delete(id);},@@ -117,25 +113,38 @@ const TWO_SEGMENT_GPX = `<?xml version="1.0" encoding="UTF-8"?>/** The note the track belongs to, which every one of its layers is named after. */const NOTE_ID = "gpxNoteId1";+/** What the marks are drawn with, under the ids the shared rasterizer files pins by (see Markers). */+const PIN_COLOR = "purple";+const NOTE_ICON = "bx bx-cycling";+const START_IMAGE = markerImageId(PIN_COLOR, NOTE_ICON);+const END_IMAGE = markerImageId(PIN_COLOR, "bx bxs-flag-checkered");+const WAYPOINT_IMAGE = markerImageId(PIN_COLOR, "bx bx-pin");+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;++ beforeEach(() => {map = fakeMap();container = document.createElement("div");document.body.appendChild(container);++ // A pin is drawn by handing an SVG blob to an <img> and waiting for it to load, which no DOM+ // stand-in actually does. Without this the build never resolves and the marks never go up.+ vi.stubGlobal("Image", class {+ onload: (() => void) | null = null;+ onerror: (() => void) | null = null;+ set src(_value: string) {+ setTimeout(() => this.onload?.());+ }+ });+ vi.stubGlobal("URL", { ...URL, createObjectURL: () => "blob:pin", revokeObjectURL: () => {} });});afterEach(() => {render(null, container);container.remove();+ vi.unstubAllGlobals();});/** Mounts the track under a map whose style has loaded (or not), as the context reports it. */@@ -151,9 +160,8 @@ describe("GpxTrack", () => {title="A Sunday ride"gpxXmlString={gpx}trackColor="red"- startIconHtml="<i>start</i>"- endIconHtml="<i>end</i>"- waypointIconHtml="<i>waypoint</i>"+ pinColor={PIN_COLOR}+ iconClass={NOTE_ICON}hideLabels={hideLabels}isDarkTheme={isDarkTheme}/>@@ -164,24 +172,41 @@ describe("GpxTrack", () => {});}+ /** Drains the pin rasterizing (icon render → svg decode → marks layer). */+ async function settle() {+ await act(async () => {+ for (let i = 0; i < 20; i++) await new Promise((resolve) => setTimeout(resolve));+ });+ }+/** A layer the track added, by the id it is named after the note with. */- function layer(kind: "layer" | "hit" | "label") {+ function layer(kind: "layer" | "hit" | "label" | "marks") {return map.layers.get(`gpx-${kind}-${NOTE_ID}`) as- { layout?: Record<string, unknown>; paint: Record<string, unknown> } | undefined;+ { filter?: unknown; layout?: Record<string, unknown>; paint: Record<string, unknown> } | undefined;}- /** The coordinates of the one source the track added. */- function trackCoordinates() {+ /** Everything the one source carries: the line, and a mark per flag. */+ function features() {const source = map.sources.get(`gpx-source-${NOTE_ID}`) as- { data: { geometry: { type: string; coordinates: [number, number][][] } } } | undefined;- return source?.data.geometry;+ { data: GeoJSON.FeatureCollection } | undefined;+ return source?.data.features ?? [];+ }++ /** The marks alone, in the order they were read out of the file. */+ function marks() {+ return features().filter((feature) => feature.geometry.type === "Point") as+ (GeoJSON.Feature & { geometry: GeoJSON.Point })[];+ }++ /** The geometry of the line the track drew. */+ function trackCoordinates() {+ const line = features().find((feature) => feature.geometry.type === "MultiLineString");+ return line?.geometry as GeoJSON.MultiLineString | undefined;}/** What the source says the line stands for. */function trackProperties() {- const source = map.sources.get(`gpx-source-${NOTE_ID}`) as- { data: { properties: Record<string, unknown> } } | undefined;- return source?.data.properties;+ return features().find((feature) => feature.geometry.type === "MultiLineString")?.properties;}it("draws the line when it mounts after the style loaded, with the tiles still coming in", () => {@@ -224,10 +249,12 @@ describe("GpxTrack", () => {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>" }+ // The start wears the note's own pin and says its name; the end wears the chequered flag.+ // Both carry the note, so whatever the pointer lands on can be traced back to it.+ const flags = marks().filter((mark) => mark.properties?.icon !== WAYPOINT_IMAGE);+ expect(flags.map((mark) => ({ ...mark.properties, at: mark.geometry.coordinates }))).toEqual([+ { id: NOTE_ID, icon: START_IMAGE, name: "A Sunday ride", at: [ 24.13, 45.79 ] },+ { id: NOTE_ID, icon: END_IMAGE, name: "", at: [ 24.08, 45.89 ] }]);});@@ -235,8 +262,44 @@ describe("GpxTrack", () => {map.loadStyle();renderTrack({ styleLoaded: true });- expect(addedMarkers.filter((marker) => marker.html === "<i>waypoint</i>"))- .toEqual([ { lngLat: [ 24.1, 45.9 ], html: "<i>waypoint</i>" } ]);+ expect(marks().filter((mark) => mark.properties?.icon === WAYPOINT_IMAGE).map((mark) => mark.geometry))+ .toEqual([ { type: "Point", coordinates: [ 24.1, 45.9 ] } ]);+ });++ it("marks the waypoints of a file that draws no line at all", async () => {+ 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"><wpt lat="1" lon="2" /></gpx>`+ });+ await settle();++ expect(layer("layer")).toBeUndefined();+ expect(layer("marks")).toBeDefined();+ expect(marks()).toHaveLength(1);+ });++ /**+ * The marks are the second half of the track to go up: their pins come out of the shared+ * rasterizer (see Markers), which is asynchronous, and the line must not wait on them — it used+ * to, back when the icons were resolved before anything was drawn at all.+ */+ it("stamps the marks once their pins are drawn, without holding the line back", async () => {+ map.loadStyle();+ renderTrack({ styleLoaded: true });++ // The line is up at once; the marks are still waiting on their pins.+ expect(layer("layer")).toBeDefined();+ expect(layer("marks")).toBeUndefined();++ await settle();++ expect(layer("marks")?.layout?.["icon-image"]).toEqual([ "get", "icon" ]);+ // Stamped with the very pins the note markers stamp, filed under the same names.+ for (const id of [ START_IMAGE, END_IMAGE, WAYPOINT_IMAGE ]) {+ expect(map.images.has(id)).toBe(true);+ }});it("draws a route as it draws a track", () => {@@ -269,17 +332,21 @@ describe("GpxTrack", () => {expect(trackCoordinates()?.coordinates).toEqual([ [ [ 24.13, 45.79 ], [ 24.15, 45.81 ] ] ]);});- it("puts the line back when the style is switched under it", () => {+ it("puts the line and its marks back when the style is switched under it", async () => {map.loadStyle();renderTrack({ styleLoaded: true });- expect(map.layers.size).toBe(3);+ await settle();+ expect(map.layers.size).toBe(4);- // A style is a world of its own: switching one takes everything on it away.+ // A style is a world of its own: switching one takes everything on it away, images included.map.layers.clear();map.sources.clear();- act(() => map.loadStyle());+ map.images.clear();+ await act(async () => map.loadStyle());+ await settle();- expect(map.layers.size).toBe(3);+ expect(map.layers.size).toBe(4);+ expect(map.images.has(START_IMAGE)).toBe(true);expect(trackCoordinates()?.type).toBe("MultiLineString");});@@ -294,16 +361,14 @@ describe("GpxTrack", () => {expect(trackProperties()).toEqual({ id: NOTE_ID, name: "A Sunday ride" });});- it("draws the name the way the marker titles are drawn, light map or dark", async () => {- const { LABEL_PAINT } = await import("./Markers");-+ it("draws the name the way the marker titles are drawn, light map or dark", () => {map.loadStyle();renderTrack({ styleLoaded: true, isDarkTheme: true });expect(layer("label")?.paint).toMatchObject(LABEL_PAINT.dark);});- it("leaves the name off when the map's titles are hidden", () => {+ it("leaves the names off when the map's titles are hidden", async () => {map.loadStyle();renderTrack({ styleLoaded: true, hideLabels: true });@@ -311,6 +376,10 @@ describe("GpxTrack", () => {// The line and the target for pointing at it are still there.expect(layer("layer")).toBeDefined();expect(layer("hit")).toBeDefined();++ // The marks keep their pins and lose only their words.+ await settle();+ expect(layer("marks")?.layout?.["text-field"]).toBe("");});it("gives the line a target wide enough to be pointed at, without drawing it", () => {@@ -323,14 +392,14 @@ describe("GpxTrack", () => {expect(hit?.paint["line-width"]).toBeGreaterThan(layer("layer")?.paint["line-width"] as number);});- it("offers its target to whatever hit-tests the tracks", async () => {- const { trackHitLayers } = await import("./GpxTrack");-+ it("offers its target and its marks to whatever hit-tests the tracks", async () => {map.loadStyle();renderTrack({ styleLoaded: true });+ await settle();- // The line and the label are not offered: only the target is meant to be pointed at.- expect(trackHitLayers(map as never)).toEqual([ `gpx-hit-${NOTE_ID}` ]);+ // The line and the label are not offered: what is pointable is the widened target and the+ // flags — a flag is as much the track as the line is.+ expect(trackHitLayers(map as never)).toEqual([ `gpx-hit-${NOTE_ID}`, `gpx-marks-${NOTE_ID}` ]);act(() => render(null, container));@@ -339,34 +408,37 @@ describe("GpxTrack", () => {expect(trackHitLayers(map as never)).toEqual([]);});- it("names its layers after the note, so a rerun does not churn through fresh ones", () => {+ it("names its layers after the note, so a rerun does not churn through fresh ones", async () => {map.loadStyle();renderTrack({ styleLoaded: true });+ await settle();const first = [ ...map.layers.keys() ];- // The same track drawn again — as it is each time one of its icons resolves.+ // The same track drawn again.renderTrack({ styleLoaded: true });+ await settle();expect([ ...map.layers.keys() ]).toEqual(first);- expect(first).toEqual([ `gpx-layer-${NOTE_ID}`, `gpx-hit-${NOTE_ID}`, `gpx-label-${NOTE_ID}` ]);+ expect(first).toEqual([ `gpx-layer-${NOTE_ID}`, `gpx-hit-${NOTE_ID}`, `gpx-label-${NOTE_ID}`, `gpx-marks-${NOTE_ID}` ]);});- it("draws nothing for a file with no points, and does not throw over it", () => {+ it("draws nothing for a file with no points, and does not throw over it", async () => {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" />`});+ await settle();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", () => {+ it("takes the track off the map when it goes", async () => {map.loadStyle();renderTrack({ styleLoaded: true });- expect(map.layers.size).toBe(3);+ await settle();+ expect(map.layers.size).toBe(4);act(() => render(null, container));diff --git a/apps/client/src/widgets/collections/geomap/GpxTrack.tsx b/apps/client/src/widgets/collections/geomap/GpxTrack.tsxindex 70f2d27eb8..627e8598d3 100644--- a/apps/client/src/widgets/collections/geomap/GpxTrack.tsx+++ b/apps/client/src/widgets/collections/geomap/GpxTrack.tsx@@ -1,50 +1,68 @@-import { type Map as MapLibreGLMap, Marker as MapLibreMarker } from "maplibre-gl";+import type { FilterSpecification, Map as MapLibreGLMap } from "maplibre-gl";import { useContext, useEffect } from "preact/hooks";import { MapStyleLoaded, ParentMap } from "./map";-import { LABEL_PAINT } from "./Markers";+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";export interface GpxTrackProps {/** The note the track belongs to, which is what its layers are named after and what a click on- * one of them resolves to. */+ * any of them resolves to. */noteId: string;- /** What the line is named along its length. */+ /** What the line is named along its length, and what the start mark wears under its pin. */title: string;gpxXmlString: string;trackColor?: string;- startIconHtml?: string;- endIconHtml?: string;- waypointIconHtml?: string;- /** Whether the map is a dark one, which decides how the name is drawn over it (see Markers). */+ /** What the marks' pins are filled with — the note's own colour, as its marker would wear it. */+ pinColor: string;+ /** The note's icon, which the start mark wears; the end and the waypoints have icons of their own. */+ iconClass: string;+ /** Whether the map is a dark one, which decides how the names are drawn over it (see Markers). */isDarkTheme?: boolean;- /** Whether the map's titles are hidden (`#map:hideLabels`), the track's name among them. */+ /** Whether the map's titles are hidden (`#map:hideLabels`), the track's names among them. */hideLabels?: boolean;}-/** What marks a note as a GPX track: the mime its file carries. */-export const GPX_MIME = "application/gpx+xml";-/**- * What a track's layers are named with.+ * What a track's hit line is named with.** A prefix rather than a fixed name, because every track has layers of its own — see the note on ids* below. Anything hit-testing tracks finds the current set by asking the style for its layers and- * keeping the ones that start with this (see {@link trackHitLayers}).+ * keeping the ones under the pointable prefixes (see {@link trackHitLayers}).*/const HIT_LAYER_PREFIX = "gpx-hit-";+/** What a track's marks layer is named with — the flags are as pointable as the line is. */+const MARKS_LAYER_PREFIX = "gpx-marks-";+/** How wide a track is to the pointer, as against the three pixels it is drawn with. */const HIT_WIDTH = 20;/** How far apart the name is repeated along the line, in pixels. */const LABEL_SPACING = 250;+/** What the end of a track is flagged with, and what marks a waypoint along it. */+const END_ICON = "bx bxs-flag-checkered";+const WAYPOINT_ICON = "bx bx-pin";+/**- * A GPX file, drawn as a line with a marker at either end and one at every waypoint.+ * Each layer takes its kind out of the shared source: the line layers draw the lines and the marks+ * layer the points, and neither may pick up the other's features.+ */+const LINES_ONLY: FilterSpecification = [ "==", [ "geometry-type" ], "LineString" ];+const MARKS_ONLY: FilterSpecification = [ "==", [ "geometry-type" ], "Point" ];++/**+ * A GPX file, drawn as a line with a mark at either end and one at every waypoint.*- * The line is a layer of the map's style and the markers are elements of their own: there are a- * handful of them per file at most, and each carries the note's own icon as HTML — unlike the note- * markers, which are drawn in their thousands and so are rasterized into one layer (see Markers).+ * The line and the marks alike are layers of the map's style, drawing from one source — the marks+ * used to be DOM elements apiece, a leftover of the Leaflet map, which nothing hit-testing the+ * style could see. As features they are found by the same query that finds the line and the note+ * pins, so clicking or right-clicking a flag means what it means on the track itself; and their+ * pins come out of the shared rasterizer (see Markers), so the start of a track wears exactly the+ * pin its note would wear as a marker.** The line says which note it belongs to in two ways. It is named along its length, the way a map* names a road or a river, so the answer is wherever the reader happens to be looking rather than@@ -53,7 +71,7 @@ const LABEL_SPACING = 250;* the note's own menu (see ContextMenus) — a line three pixels wide being nearly impossible to hit* otherwise.*/-export function GpxTrack({ noteId, title, gpxXmlString, trackColor, startIconHtml, endIconHtml, waypointIconHtml, isDarkTheme, hideLabels }: GpxTrackProps) {+export function GpxTrack({ noteId, title, gpxXmlString, trackColor, pinColor, iconClass, isDarkTheme, hideLabels }: GpxTrackProps) {const parentMap = useContext(ParentMap);const styleLoaded = useContext(MapStyleLoaded);@@ -62,175 +80,203 @@ export function GpxTrack({ noteId, title, gpxXmlString, trackColor, startIconHtm// Aliased so the narrowing above carries into the nested functions below.const map = parentMap;- const markers: MapLibreMarker[] = [];// Named after the note rather than at random. A random name is a different name on every run- // of this effect — and it runs again for each of the three icons resolving — 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.+ // 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 layerId = `gpx-layer-${noteId}`;const labelLayerId = `gpx-label-${noteId}`;const hitLayerId = `${HIT_LAYER_PREFIX}${noteId}`;+ const marksLayerId = `${MARKS_LAYER_PREFIX}${noteId}`;const gpxDoc = new DOMParser().parseFromString(gpxXmlString, "application/xml");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");- element.className = "geo-marker";- element.innerHTML = html;+ const marks = readMarks(gpxDoc, lines, { noteId, title, pinColor, iconClass });- markers.push(new MapLibreMarker({ element, anchor: "bottom" })- .setLngLat(lngLat)- .addTo(map));- }+ // The pins the marks stamp, rasterized off this path: the line must not wait on them, so+ // the layers go up in two halves — the line at once, the marks when their images arrive.+ let images: Map<string, HTMLImageElement> | undefined;+ let cancelled = false;- // Markers are elements of the page rather than of the style, so they are added only once.- // 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(firstLine[0], startIconHtml);- }- const end = lastLine[lastLine.length - 1];- if (endIconHtml && end && end !== firstLine[0]) {- addMarker(end, endIconHtml);- }- }-- if (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+ // The track 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 (lines.length === 0) return;+ // Each piece 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+ // a 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 addTrackLayers() {+ if (lines.length === 0 && marks.length === 0) return;try {if (!map.getSource(sourceId)) {map.addSource(sourceId, {type: "geojson",data: {- type: "Feature",- // The note the line stands for, carried by the feature so that whatever- // the pointer lands on can be traced back to it — `id` is what the- // context menu opens, and `name` is what the line is labelled with.- properties: { id: noteId, name: title },- // 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- }+ type: "FeatureCollection",+ features: [+ // 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.+ //+ // The note the line stands for is carried by the feature, so that+ // whatever the pointer lands on can be traced back to it — `id` is+ // what a click or the context menu opens, and `name` is what the+ // line is labelled with. The marks carry the same (see readMarks).+ ...(lines.length > 0 ? [ {+ type: "Feature",+ properties: { id: noteId, name: title },+ geometry: {+ type: "MultiLineString",+ coordinates: lines+ }+ } satisfies GeoJSON.Feature ] : []),+ ...marks+ ]}});}- if (!map.getLayer(layerId)) {- map.addLayer({- id: layerId,- type: "line",- source: sourceId,- layout: {- // Otherwise a track doubling back on itself meets its own corners as- // spikes, and every segment ends in a flat stub.- "line-join": "round",- "line-cap": "round"- },- paint: {- "line-color": trackColor ?? "blue",- "line-width": 3- }- });- }+ if (lines.length > 0) {+ if (!map.getLayer(layerId)) {+ map.addLayer({+ id: layerId,+ type: "line",+ source: sourceId,+ filter: LINES_ONLY,+ layout: {+ // Otherwise a track doubling back on itself meets its own corners as+ // spikes, and every segment ends in a flat stub.+ "line-join": "round",+ "line-cap": "round"+ },+ paint: {+ "line-color": trackColor ?? "blue",+ "line-width": 3+ }+ });+ }- // What the pointer is actually aiming at. Transparent and far wider than the line is- // drawn, because three pixels is not something anyone can reliably hit — and left- // queryable by being transparent rather than hidden, since MapLibre drops a layer- // from a query for `visibility: none` but not for being invisible.- if (!map.getLayer(hitLayerId)) {- map.addLayer({- id: hitLayerId,- type: "line",- source: sourceId,- paint: {- "line-color": trackColor ?? "blue",- "line-opacity": 0,- "line-width": HIT_WIDTH- }- });+ // What the pointer is actually aiming at. Transparent and far wider than the+ // line is drawn, because three pixels is not something anyone can reliably hit —+ // and left queryable by being transparent rather than hidden, since MapLibre+ // drops a layer from a query for `visibility: none` but not for being invisible.+ if (!map.getLayer(hitLayerId)) {+ map.addLayer({+ id: hitLayerId,+ type: "line",+ source: sourceId,+ filter: LINES_ONLY,+ paint: {+ "line-color": trackColor ?? "blue",+ "line-opacity": 0,+ "line-width": HIT_WIDTH+ }+ });+ }++ // The name, written along the line the way a map writes the name of a road or a+ // river: repeated as the line runs, so which track this is can be read wherever+ // the reader is looking rather than only back at the pin it started from.+ if (!hideLabels && title && !map.getLayer(labelLayerId)) {+ map.addLayer({+ id: labelLayerId,+ type: "symbol",+ source: sourceId,+ filter: LINES_ONLY,+ layout: {+ "symbol-placement": "line",+ "text-field": [ "get", "name" ],+ // The fontstack the styles carry glyphs for — the same one the+ // marker titles are set in, so a map reads as one map (see Markers,+ // and the note on `glyphs` in map.tsx).+ "text-font": [ "Open Sans Regular" ],+ "text-size": 12,+ "symbol-spacing": LABEL_SPACING,+ // Lifted just clear of the line, so the line does not strike through+ // its own name.+ "text-offset": [ 0, -0.8 ],+ // A name is dropped rather than bent around a hairpin, and rather+ // than laid over a marker's title: every symbol layer shares one+ // collision index, so the two are placed against each other.+ "text-max-angle": 30,+ "text-padding": 4+ },+ paint: {+ ...LABEL_PAINT[isDarkTheme ? "dark" : "light"],+ "text-halo-width": 2,+ "text-halo-blur": 1+ }+ });+ }}- // The name, written along the line the way a map writes the name of a road or a- // river: repeated as the line runs, so which track this is can be read wherever the- // reader is looking rather than only back at the pin it started from.- if (!hideLabels && title && !map.getLayer(labelLayerId)) {- map.addLayer({- id: labelLayerId,- type: "symbol",- source: sourceId,- layout: {- "symbol-placement": "line",- "text-field": [ "get", "name" ],- // The fontstack the styles carry glyphs for — the same one the marker- // titles are set in, so a map reads as one map (see Markers, and the- // note on `glyphs` in map.tsx).- "text-font": [ "Open Sans Regular" ],- "text-size": 12,- "symbol-spacing": LABEL_SPACING,- // Lifted just clear of the line, so the line does not strike through- // its own name.- "text-offset": [ 0, -0.8 ],- // A name is dropped rather than bent around a hairpin, and rather than- // laid over a marker's title: every symbol layer shares one collision- // index, so the two are placed against each other.- "text-max-angle": 30,- "text-padding": 4- },- paint: {- ...LABEL_PAINT[isDarkTheme ? "dark" : "light"],- "text-halo-width": 2,- "text-halo-blur": 1+ // The marks, held back until their pins have been drawn: a symbol layer added+ // before its images would stamp nothing and warn over each one it cannot find.+ if (images) {+ for (const [ id, image ] of images) {+ if (!map.hasImage(id)) {+ map.addImage(id, image, { pixelRatio: window.devicePixelRatio || 1 });}- });+ }++ if (marks.length > 0 && !map.getLayer(marksLayerId)) {+ map.addLayer({+ id: marksLayerId,+ type: "symbol",+ source: sourceId,+ filter: MARKS_ONLY,+ layout: {+ "icon-image": [ "get", "icon" ],+ "icon-size": 1,+ "icon-anchor": "bottom",+ // The image carries padding for its shadow, pushed back down by+ // exactly that much so a mark stands on its coordinate — as the+ // note pins are (see Markers).+ "icon-offset": [ 0, MARKER_SHADOW_PADDING ],+ // A track keeps its flags however crowded the map: a flag dropped+ // for colliding is a start or an end that has silently left it.+ "icon-allow-overlap": true,+ ...LABEL_LAYOUT,+ ...(hideLabels ? { "text-field": "" } : {})+ },+ paint: {+ ...LABEL_PAINT[isDarkTheme ? "dark" : "light"],+ "text-halo-width": 2,+ "text-halo-blur": 1+ }+ });+ }}} catch (e) {- // Only worth a word if the style was ready and it still would not take the line.+ // Only worth a word if the style was ready and it still would not take the track.if (styleLoaded) {console.warn("Geo map: could not draw a GPX track —", e);}}}+ buildMarkImages(pinColor, iconClass).then((built) => {+ if (cancelled) return;+ images = built;+ if (styleLoaded) {+ addTrackLayers();+ }+ });+if (styleLoaded) {- addTrackLayer();+ addTrackLayers();}- map.on("style.load", addTrackLayer);+ map.on("style.load", addTrackLayers);return () => {- map.off("style.load", addTrackLayer);- for (const marker of markers) {- marker.remove();- }+ cancelled = true;+ map.off("style.load", addTrackLayers);try {// Every layer drawing from the source before the source itself: one still in use// cannot be removed.- for (const layer of [ layerId, hitLayerId, labelLayerId ]) {+ for (const layer of [ layerId, hitLayerId, labelLayerId, marksLayerId ]) {if (map.getLayer(layer)) {map.removeLayer(layer);}@@ -242,13 +288,15 @@ export function GpxTrack({ noteId, title, gpxXmlString, trackColor, startIconHtm// The map may already have been removed.}};- }, [ parentMap, styleLoaded, noteId, title, gpxXmlString, trackColor, startIconHtml, endIconHtml, waypointIconHtml, isDarkTheme, hideLabels ]);+ }, [ parentMap, styleLoaded, noteId, title, gpxXmlString, trackColor, pinColor, iconClass, isDarkTheme, hideLabels ]);return <div />;}/**- * The layers standing in for the tracks currently on the map, for whatever wants to hit-test them.+ * 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+ * line is, and answers with the same note.** Asked of the style each time rather than remembered, because a track is a component of its own and* comes and goes with the note it belongs to: a list built once would name layers that have since@@ -256,7 +304,63 @@ export function GpxTrack({ noteId, title, gpxXmlString, trackColor, startIconHtm* rather than skipping the one it cannot find — if a single named layer is missing.*/export function trackHitLayers(map: MapLibreGLMap) {- return map.getLayersOrder().filter((id) => id.startsWith(HIT_LAYER_PREFIX));+ return map.getLayersOrder().filter((id) => id.startsWith(HIT_LAYER_PREFIX) || id.startsWith(MARKS_LAYER_PREFIX));+}++/**+ * The marks a track is flagged with, as features of the same source its line is drawn from: where+ * the whole track begins and where it ends — not one pair per segment, since a track broken into+ * segments is still one journey, and a flag at every pause would be a flag at every traffic light —+ * and one at every waypoint. Only the start says the note's name; the pin says the rest.+ */+function readMarks(gpxDoc: Document, lines: [number, number][][], { noteId, title, pinColor, iconClass }: {+ noteId: string; title: string; pinColor: string; iconClass: string;+}) {+ const marks: GeoJSON.Feature[] = [];++ function addMark(coordinates: [number, number], icon: string, name = "") {+ marks.push({+ type: "Feature",+ geometry: { type: "Point", coordinates },+ properties: { id: noteId, icon: markerImageId(pinColor, icon), name }+ });+ }++ const firstLine = lines[0] ?? [];+ const lastLine = lines[lines.length - 1] ?? [];++ if (firstLine.length > 0) {+ addMark(firstLine[0], iconClass, title);+ const end = lastLine[lastLine.length - 1];+ if (end && end !== firstLine[0]) {+ addMark(end, END_ICON);+ }+ }++ for (const waypoint of readPoints(gpxDoc.querySelectorAll("wpt"))) {+ addMark(waypoint, WAYPOINT_ICON);+ }++ return marks;+}++/**+ * The pins the marks stamp, drawn through the shared rasterizer (see Markers) so the start of a+ * track wears exactly the pin its note would wear as a marker, and the end and the waypoints wear+ * flags of their own in the note's colour. A pin that cannot be drawn is left out, and its mark+ * stamps nothing rather than keeping the rest from going up.+ */+async function buildMarkImages(pinColor: string, iconClass: string) {+ const images = new Map<string, HTMLImageElement>();++ await Promise.all([ iconClass, END_ICON, WAYPOINT_ICON ].map(async (icon) => {+ const image = await buildMarkerImage(pinColor, icon);+ if (image) {+ images.set(markerImageId(pinColor, icon), image);+ }+ }));++ return images;}/**@@ -267,7 +371,7 @@ export function trackHitLayers(map: MapLibreGLMap) {* 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.+ * but it is still where the track began or ended, which is what the marks are placed from.*/function readLines(gpxDoc: Document): [number, number][][] {const lines: [number, number][][] = [];diff --git a/apps/client/src/widgets/collections/geomap/Markers.tsx b/apps/client/src/widgets/collections/geomap/Markers.tsxindex 27f86806ff..3793a0ac16 100644--- a/apps/client/src/widgets/collections/geomap/Markers.tsx+++ b/apps/client/src/widgets/collections/geomap/Markers.tsx@@ -32,13 +32,13 @@ export const MARKER_HEIGHT = 41;* reads as a grey box behind the pin rather than as a shadow. Wide enough for the blur (about three* times its deviation) plus the distance it is pushed down.*/-const MARKER_SHADOW_PADDING = 6;+export const MARKER_SHADOW_PADDING = 6;const MARKER_ICON_SIZE = 20;// Centred on the pin's round head, which is a circle of the pin's own width sitting at the top.const MARKER_ICON_X = (MARKER_WIDTH - MARKER_ICON_SIZE) / 2;const MARKER_ICON_Y = (MARKER_WIDTH - MARKER_ICON_SIZE) / 2;-const LABEL_LAYOUT: Extract<AddLayerObject, { type: "symbol" }>["layout"] = {+export const LABEL_LAYOUT: Extract<AddLayerObject, { type: "symbol" }>["layout"] = {"text-field": [ "get", "name" ],"text-font": [ "Open Sans Regular" ],"text-size": 12,@@ -538,14 +538,16 @@ export function formatLocation([ lng, lat ]: [number, number], precision = 6) {return `${lat.toFixed(precision)}, ${lng.toFixed(precision)}`;}-function markerImageId(color: string, iconClass: string) {+export function markerImageId(color: string, iconClass: string) {return `marker|${color}|${iconClass}`;}/** What has been rasterized already, since the same few pins are asked for over and over. */const markerImages = new Map<string, Promise<HTMLImageElement | null>>();-function buildMarkerImage(color: string, iconClass: string) {+/** The pin for a colour and icon, through the cache — what everything stamping pins should call,+ * the GPX marks included (see GpxTrack), so a map never draws the same pin twice. */+export function buildMarkerImage(color: string, iconClass: string) {const id = markerImageId(color, iconClass);let image = markerImages.get(id);diff --git a/apps/client/src/widgets/collections/geomap/index.css b/apps/client/src/widgets/collections/geomap/index.cssindex bed7ad8d1f..c21a18f7c3 100644--- a/apps/client/src/widgets/collections/geomap/index.css+++ b/apps/client/src/widgets/collections/geomap/index.css@@ -228,72 +228,3 @@position: relative;}-/* No `position` here: MapLibre positions markers itself with `.maplibregl-marker`'s- `position: absolute` + a transform, and this more specific selector would override it back to- `relative`, dropping every marker into the canvas container's normal flow — each one then sits- 41px (a marker height) lower than the previous, so the marker added last lands furthest below its- coordinate. `absolute` is a positioned box too, so the badge and label below still anchor here. */-.geo-map-container .geo-marker {- cursor: pointer;- overflow: visible;-}--.geo-map-container .geo-marker .marker-pin {- position: relative;-}--/* The same shadow the pins in the symbol layer are drawn with (see drawMarkerImage), expressed the- CSS way — its blur radius is twice the filter's standard deviation. */-.geo-map-container .geo-marker .marker-pin svg {- display: block;- filter: drop-shadow(0 1.5px 3px rgba(0, 0, 0, 0.35));-}--/* Cut straight out of the pin — no disc behind it, so only the note's colour is seen. */-.geo-map-container .geo-marker .tn-icon {- position: absolute;- top: 4px;- inset-inline-start: 4px;- color: white;- font-size: 17px;-}--/* The icon drawn as a picture (see buildIconHtml): sized as the span's glyph was. */-.geo-map-container .geo-marker img.tn-icon {- width: 17px;- height: 17px;- display: block;-}--.geo-map-container .geo-marker .title-label {- display: block;- position: absolute;- top: 100%;- inset-inline-start: 50%;- transform: translateX(-50%);- font-size: 0.75rem;- height: 1rem;- --label-halo: rgba(255, 255, 255, 0.8);- color: #333;- width: 100px;- text-align: center;- text-overflow: ellipsis;- /* The soft glow the titles in the symbol layer are haloed with (see Markers), stacked because one- blurred shadow alone is too faint to hold the text apart from a busy map. */- text-shadow: 0 0 2px var(--label-halo), 0 0 2px var(--label-halo), 0 0 4px var(--label-halo);- white-space: nowrap;- overflow: hidden;-}--body[dir=rtl] .geo-map-container .geo-marker .title-label {- transform: translateX(50%);-}--.geo-map-container .geo-marker .archived {- opacity: 0.5;-}--.geo-map-container.dark .geo-marker .title-label {- --label-halo: rgba(0, 0, 0, 0.8);- color: white;-}diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsxindex c8e7aa6863..ba2a3d0b4a 100644--- a/apps/client/src/widgets/collections/geomap/index.tsx+++ b/apps/client/src/widgets/collections/geomap/index.tsx@@ -5,13 +5,10 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks"import FNote from "../../../entities/fnote";import branches from "../../../services/branches";-import { getReadableTextColor } from "../../../services/css_class_manager";import froca from "../../../services/froca";import { t } from "../../../services/i18n";-import { renderIconImage } from "../../../services/icon_glyphs";import server from "../../../services/server";import toast from "../../../services/toast";-import { escapeHtml } from "../../../services/utils";import CollectionProperties from "../../note_bars/CollectionProperties";import ActionButton from "../../react/ActionButton";import { useCollectionTreeDrag, useNoteBlob, useNoteLabel, useNoteLabelBoolean, useNoteProperty, useSpacedUpdate, useTriliumEvent } from "../../react/hooks";@@ -25,7 +22,7 @@ import { GPX_MIME, GpxTrack } from "./GpxTrack";import Map, { DEFAULT_ZOOM, GeoMouseEvent } from "./map";import { DEFAULT_MAP_LAYER_NAME, MAP_LAYERS, MapLayer } from "./map_layer";import MapToolbar from "./MapToolbar";-import Markers, { LOCATION_ATTRIBUTE } from "./Markers";+import Markers, { DEFAULT_MARKER_COLOR, LOCATION_ATTRIBUTE } from "./Markers";import Tooltips from "./Tooltips";const DEFAULT_COORDINATES: [number, number] = [3.878638227135724, 446.6630455551659];@@ -358,118 +355,24 @@ function NoteGpxTrack({ note, hideLabels, isDarkTheme }: { note: FNote, hideLabe}, [ blob ]);// React to changes- const color = useNoteLabel(note, "color");+ const [ color ] = useNoteLabel(note, "color");useNoteLabel(note, "iconClass");// The line is named after the note along its whole length, so a note being renamed has to reach// the map rather than leaving the old name written across the track.const title = useNoteProperty(note, "title") ?? "";- const trackColor = useMemo(() => note.getLabelValue("color") ?? "blue", [ color ]);- const startIconHtml = useIconHtml(note.getIcon(), note.getColorClass() ?? undefined, hideLabels ? undefined : title);- const endIconHtml = useIconHtml("bx bxs-flag-checkered");- const waypointIconHtml = useIconHtml("bx bx-pin");-return xmlString && <GpxTracknoteId={note.noteId}title={title}gpxXmlString={xmlString}- trackColor={trackColor}- startIconHtml={startIconHtml}- endIconHtml={endIconHtml}- waypointIconHtml={waypointIconHtml}+ trackColor={color ?? "blue"}+ // The colour and icon rather than anything built from them: the marks are rasterized into+ // the track's own symbol layer through the shared pin rasterizer (see GpxTrack), so the+ // start of a track wears exactly the pin its note would wear as a marker.+ pinColor={color ?? DEFAULT_MARKER_COLOR}+ iconClass={note.getIcon()}isDarkTheme={isDarkTheme}hideLabels={hideLabels}/>;}-/** The pin shape, filled with whatever colour the note asks for. Replaces the Leaflet marker PNG. */-function buildMarkerSvg(color: string) {- return `<svg width="25" height="41" viewBox="0 0 25 41" xmlns="http://www.w3.org/2000/svg">` +- `<path d="M12.5 0C5.6 0 0 5.6 0 12.5C0 21.9 12.5 41 12.5 41S25 21.9 25 12.5C25 5.6 19.4 0 12.5 0Z" fill="${escapeHtml(color)}" />` +- `</svg>`;-}--/** What a pin is filled with where its note asks for no colour of its own. */-const DEFAULT_MARKER_COLOR = "#2A81CB";--/** The size the icon is drawn at, matching the font size the CSS-styled span used. */-const MARKER_ICON_SIZE = 17;--/**- * The marker HTML for {@link buildIconHtml}, built asynchronously because the icon inside it is- * drawn through the shared icon-rendering service. Undefined until the first build resolves; the- * service caches each icon/colour pair, so every marker after the first with the same icon gets- * its HTML in a single tick.- */-function useIconHtml(iconClass: string, colorClass?: string, title?: string, noteIdLink?: string, archived?: boolean) {- const [ html, setHtml ] = useState<string>();-- useEffect(() => {- let cancelled = false;- buildIconHtml(iconClass, colorClass, title, noteIdLink, archived).then((result) => {- if (!cancelled) {- setHtml(result);- }- });- return () => {- cancelled = true;- };- }, [ iconClass, colorClass, title, noteIdLink, archived ]);-- return html;-}--async function buildIconHtml(iconClass: string, colorClass?: string, title?: string, noteIdLink?: string, archived?: boolean) {- // The note's colour fills the pin, as it does for the note markers drawn into the symbol layer,- // and the icon is cut out of it in whichever of black or white stands out against that.- const pinColor = resolveNoteColor(colorClass) ?? DEFAULT_MARKER_COLOR;-- // Drawn as a picture through the shared icon service (icon_glyphs.ts) rather than styled by- // CSS, so the marker renders any icon pack's icon the way the rest of the app draws it. A- // class the service cannot resolve falls back to the CSS-styled span.- //- // The class is passed on whole, as callers give it — a complete one, family and all. The- // service resolves a class by wearing it and reading back what the stylesheet made of it, so- // every class handed over is one more voice in that cascade: a `bx` of our own would have the- // built-in pack's font competing with the pack the icon actually belongs to.- const image = await renderIconImage(iconClass, {- size: MARKER_ICON_SIZE,- color: getReadableTextColor(pinColor)- });- const icon = image- ? `<img class="tn-icon" src="${image}" alt="" />`- : `<span class="${escapeHtml(iconClass)} tn-icon"></span>`;-- let html = /*html*/`\- <div class="marker-pin">${buildMarkerSvg(pinColor)}</div>- ${icon}- <span class="title-label">${escapeHtml(title ?? "")}</span>`;-- if (noteIdLink) {- html = `<div data-href="#root/${escapeHtml(noteIdLink)}" class="${archived ? "archived" : ""}">${html}</div>`;- }-- return html;-}--/**- * The concrete colour a note's colour class stands for — the light-theme variant, the same value- * the CSS-styled span used to read from `--light-theme-custom-color`, or `null` for a note that- * asks for no colour. Only the stylesheet knows the adjusted value, so it is read off an element- * wearing the class, the way the icon service reads its glyphs.- */-function resolveNoteColor(colorClass?: string) {- if (!colorClass) {- return null;- }-- const probe = document.createElement("span");- probe.className = colorClass;- document.body.appendChild(probe);- try {- return getComputedStyle(probe).getPropertyValue("--light-theme-custom-color").trim() || null;- } finally {- probe.remove();- }-}-