Skip to content

Build your personal knowledge base with Trilium Notes

Merge remote-tracking branch 'origin/copilot/switch-to-mapbox-gl' into feat/geomap-maplibre

Elian Doran4718e02aefbd
diff --cc apps/client/src/widgets/collections/geomap/ContextMenus.ts
index 2fcb2d7305,1326af9fa1..3662ef6822
--- a/apps/client/src/widgets/collections/geomap/ContextMenus.ts
+++ b/apps/client/src/widgets/collections/geomap/ContextMenus.ts
@@@ -9,8 -10,42 +10,42 @@@ import { copyTextWithToast } from "../.
import { t } from "../../../services/i18n.js";
import link from "../../../services/link.js";
import { createNewNote } from "./api.js";
-import { type GeoMouseEvent,ParentMap, toMapLibreEvent } from "./map.js";
++import { type GeoMouseEvent, ParentMap, toGeoMouseEvent } from "./map.js";
+ import { MARKER_LAYER } from "./Markers.js";
- export default function openContextMenu(noteId: string, e: GeoMouseEvent, isEditable: boolean) {
+ export default function ContextMenus({ note, isReadOnly }: { note: FNote, isReadOnly: boolean }) {
+ const map = useContext(ParentMap);
+
+ const onContextMenu = useCallback((e: GeoMouseEvent) => {
+ if (!map) return;
+ const features = map.queryRenderedFeatures(e.point, {
+ layers: [ MARKER_LAYER ]
+ });
+
+ if (features.length > 0) {
+ // Marker context menu.
+ openContextMenu(features[0].properties.id, e, !isReadOnly);
+ } else {
+ // Empty area context menu.
+ openMapContextMenu(note, e, !isReadOnly);
+ }
+ }, [ map, note, isReadOnly ]);
+
+ useEffect(() => {
+ if (!onContextMenu || !map) return;
+
+ const handler = (e: MapMouseEvent) => {
+ e.preventDefault();
- onContextMenu(toMapLibreEvent(e));
++ onContextMenu(toGeoMouseEvent(e));
+ };
+ map.on("contextmenu", handler);
+ return () => { map.off("contextmenu", handler); };
+ }, [ map, onContextMenu ]);
+
+ return null;
+ }
+
+ export function openContextMenu(noteId: string, e: GeoMouseEvent, isEditable: boolean) {
let items: MenuItem<keyof CommandMappings>[] = [
...buildGeoLocationItem(e),
{ kind: "separator" },
diff --cc apps/client/src/widgets/collections/geomap/GpxTrack.tsx
index 0000000000,0000000000..ca9a9a47d1
new file mode 100644
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/GpxTrack.tsx
@@@ -1,0 -1,0 +1,123 @@@
++import { Marker as MapLibreMarker } from "maplibre-gl";
++import { useContext, useEffect } from "preact/hooks";
++
++import { ParentMap } from "./map";
++
++export interface GpxTrackProps {
++ gpxXmlString: string;
++ trackColor?: string;
++ startIconHtml?: string;
++ endIconHtml?: string;
++ waypointIconHtml?: string;
++}
++
++/**
++ * A GPX file, drawn as a line with a marker 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).
++ */
++export function GpxTrack({ gpxXmlString, trackColor, startIconHtml, endIconHtml, waypointIconHtml }: GpxTrackProps) {
++ const parentMap = useContext(ParentMap);
++
++ useEffect(() => {
++ if (!parentMap) return;
++ // Aliased so the narrowing above carries into the nested functions below.
++ const map = parentMap;
++
++ const markers: MapLibreMarker[] = [];
++ const sourceId = `gpx-source-${Math.random().toString(36).slice(2)}`;
++ 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 ]);
++ }
++
++ function addMarker(lngLat: [number, number], html: string) {
++ const element = document.createElement("div");
++ element.className = "geo-marker";
++ element.innerHTML = html;
++
++ markers.push(new MapLibreMarker({ element, anchor: "bottom" })
++ .setLngLat(lngLat)
++ .addTo(map));
++ }
++
++ // Markers are elements of the page rather than of the style, so they are added only once.
++ if (coordinates.length > 0) {
++ if (startIconHtml) {
++ addMarker(coordinates[0], startIconHtml);
++ }
++ if (endIconHtml && coordinates.length > 1) {
++ addMarker(coordinates[coordinates.length - 1], 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);
++ }
++ }
++
++ // 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.
++ function addTrackLayer() {
++ if (coordinates.length === 0 || map.getSource(sourceId)) return;
++
++ map.addSource(sourceId, {
++ type: "geojson",
++ data: {
++ type: "Feature",
++ properties: {},
++ geometry: {
++ type: "LineString",
++ coordinates
++ }
++ }
++ });
++
++ map.addLayer({
++ id: layerId,
++ type: "line",
++ source: sourceId,
++ paint: {
++ "line-color": trackColor ?? "blue",
++ "line-width": 3
++ }
++ });
++ }
++
++ if (map.isStyleLoaded()) {
++ addTrackLayer();
++ }
++ map.on("style.load", addTrackLayer);
++
++ return () => {
++ map.off("style.load", addTrackLayer);
++ for (const marker of markers) {
++ marker.remove();
++ }
++ try {
++ if (map.getLayer(layerId)) {
++ map.removeLayer(layerId);
++ }
++ if (map.getSource(sourceId)) {
++ map.removeSource(sourceId);
++ }
++ } catch {
++ // The map may already have been removed.
++ }
++ };
++ }, [ parentMap, gpxXmlString, trackColor, startIconHtml, endIconHtml, waypointIconHtml ]);
++
++ return <div />;
++}
diff --cc apps/client/src/widgets/collections/geomap/Markers.tsx
index 0000000000,dac1dbc2bb..148e40ad6a
mode 000000,100644..100644
--- a/apps/client/src/widgets/collections/geomap/Markers.tsx
+++ b/apps/client/src/widgets/collections/geomap/Markers.tsx
@@@ -1,0 -1,250 +1,258 @@@
+ import { AddLayerObject, type GeoJSONSource } from "maplibre-gl";
-import { useCallback, useContext, useEffect } from "preact/hooks";
++import { useContext, useEffect, useState } from "preact/hooks";
+
+ import FNote from "../../../entities/fnote";
-import { useChildNotes } from "../../react/hooks";
++import { renderIconImage } from "../../../services/icon_glyphs";
++import { useTriliumEvent } from "../../react/hooks";
+ import { ParentMap } from "./map";
+
+ export const LOCATION_ATTRIBUTE = "geolocation";
+ export const MARKER_LAYER = "points-layer";
+ const MARKER_SOURCE = "points";
+ const DEFAULT_MARKER_COLOR = "#2A81CB";
+
-// SVG marker pin shape (replaces the Leaflet marker PNG).
-export const MARKER_SVG = "foo"; // TODO: Fix
-const iconSvgCache = new Map<string, string>();
-const iconClassToBitmapCache = new Map<string, string | undefined>();
++/** The pin, in the coordinates its SVG is drawn in. */
++const MARKER_WIDTH = 25;
++const MARKER_HEIGHT = 41;
++const MARKER_ICON_SIZE = 20;
++const MARKER_ICON_X = (MARKER_WIDTH - MARKER_ICON_SIZE) / 2;
++const MARKER_ICON_Y = 4;
+
-const LABEL_LAYOUT: Extract<AddLayerObject, { type: "symbol"}>["layout"] = {
- "text-field": ["get", "name"],
- "text-font": ["Open Sans Regular"],
++const LABEL_LAYOUT: Extract<AddLayerObject, { type: "symbol" }>["layout"] = {
++ "text-field": [ "get", "name" ],
++ "text-font": [ "Open Sans Regular" ],
+ "text-size": 12,
+ "text-anchor": "top",
- "text-allow-overlap": true,
++ "text-allow-overlap": true
+ };
+
-const MARKER_WIDTH = 25;
-const MARKER_ICON_SIZE = 20;
-const MARKER_ICON_X = (MARKER_WIDTH / 2) - (MARKER_ICON_SIZE / 2);
-
-export default function Markers({ note, hideLabels }: { note: FNote, hideLabels: boolean }) {
++/**
++ * Every note that carries a location, drawn as one symbol layer.
++ *
++ * A layer rather than an element apiece: the map is meant to hold thousands of notes, and a DOM node
++ * per note is what made that slow. The pin is rasterized once per colour and icon and handed to the
++ * map as an image, which the layer then stamps on the GPU.
++ */
++export default function Markers({ notes, hideLabels }: { notes: FNote[], hideLabels: boolean }) {
+ const map = useContext(ParentMap);
- const childNotes = useChildNotes(note?.noteId);
++ const version = useNoteChangeVersion(notes);
+
- // Add the source and layer.
+ useEffect(() => {
+ if (!map) return;
+
- // Wait for styles to be loaded.
- map.on("style.load", () => {
- map.addSource(MARKER_SOURCE, {
- type: "geojson",
- data: {
- type: "FeatureCollection",
- features: []
++ let cancelled = false;
++ let stopListening: (() => void) | undefined;
++
++ async function render() {
++ const { features, images } = await buildMarkerData(notes);
++ if (cancelled || !map) return;
++
++ /**
++ * Puts the layer and its data back on the map. A style is a world of its own — switching
++ * one wipes every source, layer and image added to the last — so this has to run again
++ * after each style load, not only when the notes change.
++ */
++ function install() {
++ if (!map) return;
++
++ for (const [ id, image ] of images) {
++ if (!map.hasImage(id)) {
++ map.addImage(id, image, { pixelRatio: window.devicePixelRatio || 1 });
++ }
++ }
++
++ if (!map.getSource(MARKER_SOURCE)) {
++ map.addSource(MARKER_SOURCE, {
++ type: "geojson",
++ data: { type: "FeatureCollection", features: [] }
++ });
+ }
- });
- map.addLayer({
- id: MARKER_LAYER,
- type: "symbol",
- source: MARKER_SOURCE,
- layout: {
- "icon-image": [ "get", "icon" ],
- "icon-size": 1,
- "icon-anchor": "bottom",
- "icon-allow-overlap": true,
- ...hideLabels ? [] : LABEL_LAYOUT
- },
- paint: {
- "text-color": "#333",
- "text-halo-color": "#fff",
- "text-halo-width": 1,
++
++ if (!map.getLayer(MARKER_LAYER)) {
++ map.addLayer({
++ id: MARKER_LAYER,
++ type: "symbol",
++ source: MARKER_SOURCE,
++ layout: {
++ "icon-image": [ "get", "icon" ],
++ "icon-size": 1,
++ "icon-anchor": "bottom",
++ "icon-allow-overlap": true,
++ ...(hideLabels ? {} : LABEL_LAYOUT)
++ },
++ paint: {
++ // Archived notes are drawn faintly, as they were when each marker was an
++ // element of its own wearing an `archived` class.
++ "icon-opacity": [ "case", [ "get", "archived" ], 0.5, 1 ],
++ "text-opacity": [ "case", [ "get", "archived" ], 0.5, 1 ],
++ "text-color": "#333",
++ "text-halo-color": "#fff",
++ "text-halo-width": 1
++ }
++ });
+ }
- });
- });
++
++ map.getSource<GeoJSONSource>(MARKER_SOURCE)?.setData({
++ type: "FeatureCollection",
++ features
++ });
++ }
++
++ if (map.isStyleLoaded()) {
++ install();
++ }
++ map.on("style.load", install);
++ stopListening = () => map.off("style.load", install);
++ }
++
++ render();
+
+ return () => {
++ cancelled = true;
++ stopListening?.();
+ if (map.getLayer(MARKER_LAYER)) {
+ map.removeLayer(MARKER_LAYER);
+ }
+ if (map.getSource(MARKER_SOURCE)) {
+ map.removeSource(MARKER_SOURCE);
+ }
+ };
- }, [ map ]);
++ }, [ map, notes, hideLabels, version ]);
+
- const refresh = useCallback(async () => {
- if (!map) return;
++ return null;
++}
+
- async function ensureIcon(color: string, iconClass: string) {
- const key = `marker-${color}-${iconClass}`;
++/** A GeoJSON feature per located note, and the pin image each of them asks for. */
++async function buildMarkerData(notes: FNote[]) {
++ const features: GeoJSON.Feature[] = [];
++ const images = new Map<string, HTMLImageElement>();
+
- if (!iconSvgCache.has(key)) {
- const svg = await buildMarkerIcon(color, iconClass);
- iconSvgCache.set(key, svg);
- }
++ for (const note of notes) {
++ const latLng = parseLocation(note.getLabelValue(LOCATION_ATTRIBUTE));
++ if (!latLng) continue;
+
- return key;
- }
++ const color = note.getLabelValue("color") ?? DEFAULT_MARKER_COLOR;
++ const iconClass = note.getIcon();
++ const id = markerImageId(color, iconClass);
+
- const features: GeoJSON.Feature[] = [];
- for (const childNote of childNotes) {
- const location = childNote.getLabelValue(LOCATION_ATTRIBUTE);
- const latLng = location?.split(",", 2).map((el) => parseFloat(el)) as [ number, number ] | undefined;
- if (!latLng) continue;
- latLng.reverse();
-
- const color = childNote.getLabelValue("color") ?? DEFAULT_MARKER_COLOR;
- features.push({
- type: "Feature",
- geometry: {
- type: "Point",
- coordinates: latLng
- },
- properties: {
- id: childNote.noteId,
- name: childNote.title,
- icon: await ensureIcon(color, childNote.getIcon())
- }
- });
++ if (!images.has(id)) {
++ const image = await buildMarkerImage(color, iconClass);
++ if (image) {
++ images.set(id, image);
++ }
+ }
+
- // Build all the icons.
- await Promise.all(iconSvgCache.entries().map(async ([ key, svg ]) => {
- const image = await svgToImage(svg);
- map.addImage(key, image, {
- pixelRatio: window.devicePixelRatio
- });
- }));
-
- // Update the source
- const source = map.getSource<GeoJSONSource>(MARKER_SOURCE);
- source?.setData({
- type: "FeatureCollection",
- features
++ features.push({
++ type: "Feature",
++ geometry: { type: "Point", coordinates: latLng },
++ properties: {
++ id: note.noteId,
++ name: note.title,
++ archived: note.isLabelTruthy("archived"),
++ icon: id
++ }
+ });
- }, [ childNotes, map ]);
++ }
+
- // Refresh the data.
- useEffect(() => {
- refresh();
- }, [ refresh ]);
- return null;
++ return { features, images };
+ }
+
-//#region Renderer
-async function buildMarkerIcon(color: string, iconClass: string, scale = window.devicePixelRatio || 1) {
- const iconUrl = iconClassToBitmapCache.get(iconClass) ?? await snapshotIcon(iconClass, MARKER_ICON_SIZE * scale);
- return `\
-<svg width="${MARKER_WIDTH * scale}" height="${41 * scale}" viewBox="0 0 ${MARKER_WIDTH} 41" xmlns="http://www.w3.org/2000/svg">
-<defs>
- <filter id="shadow" x="-50%" y="-50%" width="200%" height="200%">
- <feDropShadow dx="0" dy="2" stdDeviation="3" flood-color="black" flood-opacity="0.4" />
- </filter>
-</defs>
-<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" filter="url(#shadow)" fill="${color}" />
-<image href="${iconUrl}" x="${MARKER_ICON_X}" y="4" width="${MARKER_ICON_SIZE}" height="${MARKER_ICON_SIZE}" preserveAspectRatio="xMidYMid meet" />
-</svg>
- `;
-}
++/** `lat,lng` as the label stores it, as the `[lng, lat]` GeoJSON wants, or `null` if unreadable. */
++export function parseLocation(location: string | null | undefined): [number, number] | null {
++ if (!location) return null;
+
-async function snapshotIcon(iconClass: string, size: number) {
- const cachedIcon = iconClassToBitmapCache.get(iconClass);
- if (cachedIcon) return cachedIcon;
++ const [ lat, lng ] = location.split(",", 2).map((part) => parseFloat(part));
++ if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
+
- await document.fonts.ready;
- const glyph = getGlyphFromClass(iconClass);
- const rendered = renderMarkerCanvas({
- color: "black",
- glyph,
- size
- });
- const dataUrl = rendered?.toDataURL();
- iconClassToBitmapCache.set(iconClass, dataUrl);
- return dataUrl;
++ return [ lng, lat ];
+ }
+
-function renderMarkerCanvas({
- color,
- glyph, // e.g. "\uf123"
- size = 32,
- scale = window.devicePixelRatio || 1
-}) {
- const canvas = document.createElement("canvas");
-
- // High-DPI canvas
- canvas.width = size * scale;
- canvas.height = size * scale;
-
- const ctx = canvas.getContext("2d");
- if (!ctx) return null;
-
- // Scale for retina
- ctx.scale(scale, scale);
-
- ctx.clearRect(0, 0, size, size);
-
- // Set font
- ctx.font = `${size}px ${glyph.fontFamily}`;
- ctx.fillStyle = color;
-
- // Measure glyph
- const metrics = ctx.measureText(glyph.content);
-
- const glyphWidth =
- metrics.actualBoundingBoxLeft +
- metrics.actualBoundingBoxRight;
-
- const glyphHeight =
- metrics.actualBoundingBoxAscent +
- metrics.actualBoundingBoxDescent;
-
- // Center position
- const x = (size - glyphWidth) / 2 + metrics.actualBoundingBoxLeft;
- const y = (size - glyphHeight) / 2 + metrics.actualBoundingBoxAscent;
-
- // Draw
- ctx.fillText(glyph.content, x, y);
-
- return canvas;
++function markerImageId(color: string, iconClass: string) {
++ return `marker|${color}|${iconClass}`;
+ }
+
-function getGlyphFromClass(iconClass: string) {
- const el = document.createElement("span");
- el.className = 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>>();
+
- document.body.appendChild(el);
++function buildMarkerImage(color: string, iconClass: string) {
++ const id = markerImageId(color, iconClass);
+
- const style = window.getComputedStyle(el, "::before");
- const content = style.getPropertyValue("content");
- const fontFamily = style.getPropertyValue("font-family");
-
- document.body.removeChild(el);
-
- if (!content || content === "none") {
- return null;
++ let image = markerImages.get(id);
++ if (!image) {
++ image = drawMarkerImage(color, iconClass);
++ markerImages.set(id, image);
+ }
++ return image;
++}
+
- // content is usually quoted like: '"\f123"'
- return {
- fontFamily,
- content: content.replace(/^["']|["']$/g, "")
- };
++async function drawMarkerImage(color: string, iconClass: string) {
++ // Drawn through the shared icon service, so a marker wears the icon its note wears everywhere
++ // else — including one from a pack the user brought along.
++ const scale = window.devicePixelRatio || 1;
++ const icon = await renderIconImage(`bx ${iconClass}`, {
++ size: MARKER_ICON_SIZE,
++ color: "black",
++ scale
++ });
++
++ const badge = icon
++ ? `<circle cx="${MARKER_WIDTH / 2}" cy="${MARKER_ICON_Y + MARKER_ICON_SIZE / 2}" r="${MARKER_ICON_SIZE / 2}" fill="white" />
++ <image href="${icon}" x="${MARKER_ICON_X}" y="${MARKER_ICON_Y}" width="${MARKER_ICON_SIZE}" height="${MARKER_ICON_SIZE}" preserveAspectRatio="xMidYMid meet" />`
++ : "";
++
++ return svgToImage(`\
++<svg xmlns="http://www.w3.org/2000/svg" width="${MARKER_WIDTH * scale}" height="${MARKER_HEIGHT * scale}" viewBox="0 0 ${MARKER_WIDTH} ${MARKER_HEIGHT}">
++ <defs>
++ <filter id="shadow" x="-50%" y="-50%" width="200%" height="200%">
++ <feDropShadow dx="0" dy="2" stdDeviation="3" flood-color="black" flood-opacity="0.4" />
++ </filter>
++ </defs>
++ <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" filter="url(#shadow)" fill="${escapeXmlAttribute(color)}" />
++ ${badge}
++</svg>`);
+ }
+
-function svgToImage(svgString: string){
- return new Promise<HTMLImageElement>(resolve => {
- const svgBlob = new Blob([svgString], { type: "image/svg+xml" });
- const url = URL.createObjectURL(svgBlob);
++/** A colour comes from a label the user typed, and lands in an attribute of a document we build. */
++function escapeXmlAttribute(value: string) {
++ return value.replace(/[<>&"']/g, (character) => `&#${character.charCodeAt(0)};`);
++}
+
- const img = new Image();
++function svgToImage(svgString: string) {
++ return new Promise<HTMLImageElement | null>((resolve) => {
++ const url = URL.createObjectURL(new Blob([ svgString ], { type: "image/svg+xml" }));
++ const image = new Image();
+
- img.onload = () => {
++ image.onload = () => {
+ URL.revokeObjectURL(url);
- resolve(img);
++ resolve(image);
+ };
++ image.onerror = () => {
++ URL.revokeObjectURL(url);
++ resolve(null);
++ };
++ image.src = url;
++ });
++}
+
- img.src = url;
++/**
++ * A number that changes whenever something a marker is drawn from does.
++ *
++ * The notes are drawn into one layer rather than a component apiece, so there are no per-note hooks
++ * to notice a title, colour, icon or location changing. Without this, moving a marker or taking one
++ * off the map would leave the old drawing in place until the collection itself reloaded.
++ */
++function useNoteChangeVersion(notes: FNote[]) {
++ const [ version, setVersion ] = useState(0);
++
++ useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
++ const noteIds = new Set(notes.map((note) => note.noteId));
++ const touched = loadResults.getAttributeRows().some((attribute) => !!attribute.noteId && noteIds.has(attribute.noteId))
++ || loadResults.getNoteIds().some((noteId) => noteIds.has(noteId));
++
++ if (touched) {
++ setVersion((current) => current + 1);
++ }
+ });
++
++ return version;
+ }
-//#endregion
diff --cc apps/client/src/widgets/collections/geomap/index.tsx
index f4148ca14b,de1761d7cf..f2ddad473b
--- a/apps/client/src/widgets/collections/geomap/index.tsx
+++ b/apps/client/src/widgets/collections/geomap/index.tsx
@@@ -1,9 -1,8 +1,8 @@@
import "./index.css";
-import type { Map as MapLibreGL } from "maplibre-gl";
++import type { Map as MapLibreGLMap } from "maplibre-gl";
import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
- import type maplibregl from "maplibre-gl";
- import appContext from "../../../components/app_context";
import FNote from "../../../entities/fnote";
import branches from "../../../services/branches";
import froca from "../../../services/froca";
@@@ -15,18 -11,18 +14,21 @@@ import { escapeHtml } from "../../../se
import CollectionProperties from "../../note_bars/CollectionProperties";
import ActionButton from "../../react/ActionButton";
import { ButtonOrActionButton } from "../../react/Button";
-import { useCollectionTreeDrag, useNoteLabel, useNoteLabelBoolean, useSpacedUpdate, useTriliumEvent } from "../../react/hooks";
+import { useCollectionTreeDrag, useNoteBlob, useNoteLabel, useNoteLabelBoolean, useNoteProperty, useSpacedUpdate, useTriliumEvent } from "../../react/hooks";
import { ViewModeProps } from "../interface";
import { createNewNote, moveMarker } from "./api";
- import openContextMenu, { openMapContextMenu } from "./context_menu";
+ import ContextMenus from "./ContextMenus";
++import { GpxTrack } from "./GpxTrack";
import Map, { GeoMouseEvent } from "./map";
import { DEFAULT_MAP_LAYER_NAME, MAP_LAYERS, MapLayer } from "./map_layer";
- import Marker, { GpxTrack } from "./marker";
-import Markers from "./Markers";
++import Markers, { LOCATION_ATTRIBUTE } from "./Markers";
+ import Tooltips from "./Tooltips";
const DEFAULT_COORDINATES: [number, number] = [3.878638227135724, 446.6630455551659];
const DEFAULT_ZOOM = 2;
- export const LOCATION_ATTRIBUTE = "geolocation";
+
++export { LOCATION_ATTRIBUTE };
+
interface MapData {
view?: {
center?: { lat: number; lng: number } | [number, number];
@@@ -108,13 -101,9 +110,9 @@@ export default function GeoView({ note
}
}, [ note, state ]);
- const onContextMenu = useCallback((e: GeoMouseEvent) => {
- openMapContextMenu(note, e, !isReadOnly);
- }, [ note, isReadOnly ]);
-
// Dragging
const containerRef = useRef<HTMLDivElement>(null);
- const apiRef = useRef<maplibregl.Map>(null);
- const apiRef = useRef<MapLibreGL | null>(null);
++ const apiRef = useRef<MapLibreGLMap>(null);
useCollectionTreeDrag(containerRef, {
dragEnabled: !isReadOnly,
includeArchived,
@@@ -171,10 -159,11 +169,12 @@@
spacedUpdate.scheduleUpdate();
}}
onClick={onClick}
- onContextMenu={onContextMenu}
scale={hasScale}
>
- {notes.map(note => <NoteWrapper note={note} isReadOnly={isReadOnly} hideLabels={hideLabels} />)}
+ <Tooltips />
+ <ContextMenus note={note} isReadOnly={isReadOnly} />
- <Markers note={note} hideLabels={hideLabels} />
++ <Markers notes={notes} hideLabels={hideLabels} />
++ {notes.map(note => <NoteGpxTrackWrapper note={note} hideLabels={hideLabels} />)}
</Map>}
</div>
);
@@@ -211,175 -200,3 +211,131 @@@ function ToggleReadOnlyButton({ note }
onClick={() => setReadOnly(!isReadOnly)}
/>;
}
+
- function NoteWrapper({ note, isReadOnly, hideLabels }: {
- note: FNote,
- isReadOnly: boolean,
- hideLabels: boolean
- }) {
++/**
++ * A GPX note's track, where the note is one.
++ *
++ * Only tracks are rendered a component apiece: a note that merely carries a location is drawn into
++ * the shared symbol layer instead (see {@link Markers}).
++ */
++function NoteGpxTrackWrapper({ note, hideLabels }: { note: FNote, hideLabels: boolean }) {
+ const mime = useNoteProperty(note, "mime");
- const [ location ] = useNoteLabel(note, LOCATION_ATTRIBUTE);
+
- if (mime === "application/gpx+xml") {
- return <NoteGpxTrack note={note} hideLabels={hideLabels} />;
++ if (mime !== "application/gpx+xml") {
++ return null;
+ }
+
- if (location) {
- const latLng = location?.split(",", 2).map((el) => parseFloat(el)) as [ number, number ] | undefined;
- if (!latLng) return;
- return <NoteMarker note={note} editable={!isReadOnly} latLng={latLng} hideLabels={hideLabels} />;
- }
- }
-
- function NoteMarker({ note, editable, latLng, hideLabels }: { note: FNote, editable: boolean, latLng: [number, number], hideLabels: boolean }) {
- // Subscribed for re-rendering only: the icon and colour reach useIconHtml through the values
- // derived from them (note.getIcon(), note.getColorClass()).
- useNoteLabel(note, "color");
- useNoteLabel(note, "iconClass");
- const [ archived ] = useNoteLabelBoolean(note, "archived");
-
- const title = useNoteProperty(note, "title");
- const iconHtml = useIconHtml(note.getIcon(), note.getColorClass() ?? undefined, hideLabels ? undefined : title, note.noteId, archived);
-
- const onClick = useCallback(() => {
- appContext.triggerCommand("openInPopup", { noteIdOrPath: note.noteId });
- }, [ note.noteId ]);
-
- // Middle click to open in new tab
- const onMouseDown = useCallback((e: MouseEvent) => {
- if (e.button === 1) {
- const hoistedNoteId = appContext.tabManager.getActiveContext()?.hoistedNoteId;
- appContext.tabManager.openInNewTab(note.noteId, hoistedNoteId);
- return true;
- }
- }, [ note.noteId ]);
-
- const onDragged = useCallback((newCoordinates: { lat: number; lng: number }) => {
- moveMarker(note.noteId, newCoordinates);
- }, [ note.noteId ]);
-
- const onContextMenu = useCallback((e: GeoMouseEvent) => openContextMenu(note.noteId, e, editable), [ note.noteId, editable ]);
-
- return latLng && iconHtml && <Marker
- coordinates={latLng}
- iconHtml={iconHtml}
- iconSize={[25, 41]}
- draggable={editable}
- onMouseDown={onMouseDown}
- onDragged={editable ? onDragged : undefined}
- onClick={!editable ? onClick : undefined}
- onContextMenu={onContextMenu}
- />;
++ return <NoteGpxTrack note={note} hideLabels={hideLabels} />;
+}
+
+function NoteGpxTrack({ note, hideLabels }: { note: FNote, hideLabels?: boolean }) {
+ const [ xmlString, setXmlString ] = useState<string>();
+ const blob = useNoteBlob(note);
+
+ useEffect(() => {
+ if (!blob) return;
+ server.get<string | Uint8Array>(`notes/${note.noteId}/open`, undefined, true).then(xmlResponse => {
+ if (xmlResponse instanceof Uint8Array) {
+ setXmlString(new TextDecoder().decode(xmlResponse));
+ } else {
+ setXmlString(xmlResponse);
+ }
+ });
+ }, [ blob ]);
+
+ // React to changes
+ const color = useNoteLabel(note, "color");
+ useNoteLabel(note, "iconClass");
+
+ const trackColor = useMemo(() => note.getLabelValue("color") ?? "blue", [ color ]);
+ const startIconHtml = useIconHtml(note.getIcon(), note.getColorClass() ?? undefined, hideLabels ? undefined : note.title);
+ const endIconHtml = useIconHtml("bxs-flag-checkered");
+ const waypointIconHtml = useIconHtml("bx bx-pin");
+
+ return xmlString && <GpxTrack
+ gpxXmlString={xmlString}
+ trackColor={trackColor}
+ startIconHtml={startIconHtml}
+ endIconHtml={endIconHtml}
+ waypointIconHtml={waypointIconHtml}
+ />;
+}
+
+// SVG marker pin shape (replaces the Leaflet marker PNG).
+const MARKER_SVG = `<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="#2A81CB" />` +
+ `<circle cx="12.5" cy="12.5" r="8" fill="white" />` +
+ `</svg>`;
+
+/** The size the icon badge 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(bxIconClass: string, colorClass?: string, title?: string, noteIdLink?: string, archived?: boolean) {
+ const [ html, setHtml ] = useState<string>();
+
+ useEffect(() => {
+ let cancelled = false;
+ buildIconHtml(bxIconClass, colorClass, title, noteIdLink, archived).then((result) => {
+ if (!cancelled) {
+ setHtml(result);
+ }
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [ bxIconClass, colorClass, title, noteIdLink, archived ]);
+
+ return html;
+}
+
+async function buildIconHtml(bxIconClass: string, colorClass?: string, title?: string, noteIdLink?: string, archived?: boolean) {
+ // 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.
+ const image = await renderIconImage(`bx ${bxIconClass}`, {
+ size: MARKER_ICON_SIZE,
+ color: resolveIconColor(colorClass)
+ });
+ const icon = image
+ ? `<img class="tn-icon" src="${image}" alt="" />`
+ : `<span class="bx ${escapeHtml(bxIconClass)} tn-icon ${escapeHtml(colorClass ?? "")}"></span>`;
+
+ let html = /*html*/`\
+ <div class="marker-pin">${MARKER_SVG}</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 the marker icon is drawn in: the light-theme variant of the note's colour —
+ * the same value the CSS-styled span read from `--light-theme-custom-color` — or black without
+ * one. Only the stylesheet knows the adjusted value, so it is read off an element wearing the
+ * colour class, the way the icon service reads its glyphs.
+ */
+function resolveIconColor(colorClass?: string) {
+ if (!colorClass) {
+ return "black";
+ }
+
+ const probe = document.createElement("span");
+ probe.className = colorClass;
+ document.body.appendChild(probe);
+ try {
+ return getComputedStyle(probe).getPropertyValue("--light-theme-custom-color").trim() || "black";
+ } finally {
+ probe.remove();
+ }
+}
+
diff --cc apps/client/src/widgets/collections/geomap/map.tsx
index 6b27f80fb6,d5a5a35439..e6230f44f8
--- a/apps/client/src/widgets/collections/geomap/map.tsx
+++ b/apps/client/src/widgets/collections/geomap/map.tsx
@@@ -1,19 -1,22 +1,23 @@@
- import { useEffect, useImperativeHandle, useRef } from "preact/hooks";
- import maplibregl from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";
- import { type MapLayer } from "./map_layer";
+
-import { Map as MapLibreGLMap, MapMouseEvent, NavigationControl, type Point, ScaleControl, StyleSpecification } from "maplibre-gl";
++import { Map as MapLibreGLMap, MapMouseEvent, NavigationControl, type Point, ScaleControl, type StyleSpecification } from "maplibre-gl";
import { ComponentChildren, createContext, RefObject } from "preact";
+ import { useEffect, useImperativeHandle, useState } from "preact/hooks";
+
import { useElementSize, useSyncedRef } from "../../react/hooks";
-import { MapLayer } from "./map_layer";
++import { type MapLayer } from "./map_layer";
export interface GeoMouseEvent {
latlng: { lat: number; lng: number };
originalEvent: MouseEvent;
++ /** Where the event landed in the container, for hit-testing against the rendered layers. */
+ point: Point;
}
- export const ParentMap = createContext<maplibregl.Map | null>(null);
+ export const ParentMap = createContext<MapLibreGLMap | null>(null);
interface MapProps {
- apiRef?: RefObject<maplibregl.Map | null>;
+ apiRef?: RefObject<MapLibreGLMap | null>;
containerRef?: RefObject<HTMLDivElement>;
coordinates: { lat: number; lng: number } | [number, number];
zoom: number;
@@@ -21,122 -24,137 +25,128 @@@
viewportChanged: (coordinates: { lat: number; lng: number }, zoom: number) => void;
children: ComponentChildren;
onClick?: (e: GeoMouseEvent) => void;
-- onContextMenu?: (e: GeoMouseEvent) => void;
-- onZoom?: () => void;
scale: boolean;
}
- function toGeoMouseEvent(e: maplibregl.MapMouseEvent): GeoMouseEvent {
-export function toMapLibreEvent(e: MapMouseEvent): GeoMouseEvent {
++export function toGeoMouseEvent(e: MapMouseEvent): GeoMouseEvent {
return {
latlng: { lat: e.lngLat.lat, lng: e.lngLat.lng },
- originalEvent: e.originalEvent
+ originalEvent: e.originalEvent,
+ point: e.point
};
}
-export default function Map({ coordinates, zoom, layerData, viewportChanged, children, onClick, scale, apiRef, containerRef: _containerRef, onZoom }: MapProps) {
+/** Builds the style that can be applied synchronously: the raster style spec, a vector style URL
+ * or the vector fallback style used as a placeholder until the real style loads asynchronously. */
- function buildSyncStyle(layerData: MapLayer): maplibregl.StyleSpecification | string {
++function buildSyncStyle(layerData: MapLayer): StyleSpecification | string {
+ if (layerData.type === "vector") {
+ return typeof layerData.style === "string"
+ ? layerData.style
- : layerData.styleFallback as maplibregl.StyleSpecification;
++ : layerData.styleFallback;
+ }
+
+ return {
+ version: 8,
+ sources: {
+ "raster-tiles": {
+ type: "raster",
+ tiles: [ layerData.url ],
+ tileSize: 256,
+ attribution: layerData.attribution
+ }
+ },
+ layers: [
+ {
+ id: "raster-layer",
+ type: "raster",
+ source: "raster-tiles"
+ }
+ ]
+ };
+}
+
+function toCenter(coordinates: { lat: number; lng: number } | [number, number]): [number, number] {
+ return Array.isArray(coordinates)
+ ? [ coordinates[1], coordinates[0] ]
+ : [ coordinates.lng, coordinates.lat ];
+}
+
- export default function Map({ coordinates, zoom, layerData, viewportChanged, children, onClick, onContextMenu, scale, apiRef, containerRef: _containerRef, onZoom }: MapProps) {
- const mapRef = useRef<maplibregl.Map>(null);
++export default function Map({ coordinates, zoom, layerData, viewportChanged, children, onClick, scale, apiRef, containerRef: _containerRef }: MapProps) {
++ // State rather than a ref: the children below read the map off the context, so its creation has
++ // to produce a render or they would only ever see the null it started as.
+ const [ map, setMap ] = useState<MapLibreGLMap | null>(null);
const containerRef = useSyncedRef<HTMLDivElement>(_containerRef);
- useImperativeHandle(apiRef ?? null, () => mapRef.current);
+ useImperativeHandle(apiRef ?? null, () => map);
// Initialize the map.
useEffect(() => {
if (!containerRef.current) return;
- const mapInstance = new maplibregl.Map({
- let style: StyleSpecification | string;
-
- if (layerData.type === "vector") {
- style = typeof layerData.style === "string"
- ? layerData.style
- : layerData.styleFallback;
- } else {
- style = {
- version: 8,
- sources: {
- "raster-tiles": {
- type: "raster",
- tiles: [layerData.url],
- tileSize: 256,
- attribution: layerData.attribution
- }
- },
- layers: [
- {
- id: "raster-layer",
- type: "raster",
- source: "raster-tiles"
- }
- ]
- };
- }
-
- const center = Array.isArray(coordinates)
- ? [coordinates[1], coordinates[0]] as [number, number]
- : [coordinates.lng, coordinates.lat] as [number, number];
-
+ const mapInstance = new MapLibreGLMap({
container: containerRef.current,
- style,
- center,
+ style: buildSyncStyle(layerData),
+ center: toCenter(coordinates),
zoom,
- minZoom: 1,
+ minZoom: 2,
+ // No explicit maxBounds: a bounds whose longitude range spans the full world
+ // (-180..180) crashes MapLibre — the east edge wraps to -180, collapsing the range
+ // to zero width and making the constrain zoom infinite (a singular-matrix null
+ // deref). With renderWorldCopies disabled, MapLibre itself constrains panning to a
+ // single world (substituting an almost-full-world longitude range that avoids the
+ // collapse) and clamps latitude to the Mercator limit, which is the Leaflet-parity
+ // behavior we want.
renderWorldCopies: false
});
- mapRef.current = mapInstance;
- // Add navigation buttons.
++ // Zoom buttons, which Leaflet added of its own accord. No compass: nothing here persists a
++ // bearing, so the button would offer to undo a rotation the map never remembers.
+ mapInstance.addControl(new NavigationControl({
+ showCompass: false,
+ showZoom: true
+ }), "top-left");
+
+ setMap(mapInstance);
- // Load async vector style if needed.
- if (layerData.type === "vector" && typeof layerData.style !== "string") {
- layerData.style().then(asyncStyle => {
- mapInstance.setStyle(asyncStyle as StyleSpecification);
- });
- }
-
return () => {
mapInstance.remove();
- mapRef.current = null;
+ setMap(null);
};
}, []);
- // React to layer changes.
+ // React to layer changes. Also runs after the initial map creation, which is a no-op for the
+ // synchronous styles (setStyle diffs against the current style) but loads the asynchronous
+ // vector styles for the first time.
useEffect(() => {
- const map = mapRef.current;
if (!map) return;
- if (layerData.type === "vector") {
- if (typeof layerData.style === "string") {
- map.setStyle(layerData.style);
- } else {
- layerData.style().then(asyncStyle => {
- map.setStyle(asyncStyle as StyleSpecification);
- });
- }
- } else {
- map.setStyle({
- version: 8,
- sources: {
- "raster-tiles": {
- type: "raster",
- tiles: [layerData.url],
- tileSize: 256,
- attribution: layerData.attribution
- }
- },
- layers: [
- {
- id: "raster-layer",
- type: "raster",
- source: "raster-tiles"
- }
- ]
+ let cancelled = false;
+
+ if (layerData.type === "vector" && typeof layerData.style !== "string") {
+ layerData.style().then(asyncStyle => {
+ // Guard against the layer changing again or the map being torn down while the
+ // style was still loading.
- if (cancelled || mapRef.current !== map) return;
- map.setStyle(asyncStyle as maplibregl.StyleSpecification);
++ if (cancelled) return;
++ map.setStyle(asyncStyle);
});
+ } else {
+ map.setStyle(buildSyncStyle(layerData));
}
+
+ return () => {
+ cancelled = true;
+ };
- }, [ layerData ]);
+ }, [ map, layerData ]);
// React to coordinate changes.
useEffect(() => {
- if (!mapRef.current) return;
- mapRef.current.setCenter(toCenter(coordinates));
- mapRef.current.setZoom(zoom);
- }, [ coordinates, zoom ]);
+ if (!map) return;
- const center = Array.isArray(coordinates)
- ? [coordinates[1], coordinates[0]] as [number, number]
- : [coordinates.lng, coordinates.lat] as [number, number];
-
- map.setCenter(center);
++ map.setCenter(toCenter(coordinates));
+ map.setZoom(zoom);
+ }, [ map, coordinates, zoom ]);
- // Viewport callback.
+ // Viewport callback. MapLibre fires "moveend" for every camera change, including zooming.
useEffect(() => {
- const map = mapRef.current;
if (!map) return;
const updateFn = () => {
@@@ -148,45 -166,30 +158,23 @@@
return () => {
map.off("moveend", updateFn);
};
- }, [ viewportChanged ]);
+ }, [ map, viewportChanged ]);
useEffect(() => {
- const map = mapRef.current;
if (!onClick || !map) return;
- const handler = (e: maplibregl.MapMouseEvent) => onClick(toGeoMouseEvent(e));
- const handler = (e: MapMouseEvent) => onClick(toMapLibreEvent(e));
++ const handler = (e: MapMouseEvent) => onClick(toGeoMouseEvent(e));
map.on("click", handler);
return () => { map.off("click", handler); };
- }, [ onClick ]);
-
- useEffect(() => {
- const map = mapRef.current;
- if (!onContextMenu || !map) return;
-
- const handler = (e: maplibregl.MapMouseEvent) => {
- e.preventDefault();
- onContextMenu(toGeoMouseEvent(e));
- };
- map.on("contextmenu", handler);
- return () => { map.off("contextmenu", handler); };
- }, [ onContextMenu ]);
-
- useEffect(() => {
- const map = mapRef.current;
- if (!onZoom || !map) return;
-
- map.on("zoom", onZoom);
- return () => { map.off("zoom", onZoom); };
- }, [ onZoom ]);
+ }, [ map, onClick ]);
- useEffect(() => {
- if (!onZoom || !map) return;
-
- map.on("zoom", onZoom);
- return () => { map.off("zoom", onZoom); };
- }, [ map, onZoom ]);
-
// Scale
useEffect(() => {
- const map = mapRef.current;
if (!scale || !map) return;
- const scaleControl = new maplibregl.ScaleControl();
+ const scaleControl = new ScaleControl();
map.addControl(scaleControl);
return () => { map.removeControl(scaleControl); };
- }, [ scale ]);
+ }, [ map, scale ]);
// Adapt to container size changes.
const size = useElementSize(containerRef);
diff --cc apps/client/src/widgets/collections/geomap/marker.tsx
index 510722576d,039345cbd2..0000000000
deleted file mode 100644,100644
--- a/apps/client/src/widgets/collections/geomap/marker.tsx
+++ /dev/null
@@@ -1,196 -1,211 +1,0 @@@
-import { Marker as MapLibreMarker } from "maplibre-gl";
--import { useContext, useEffect, useRef } from "preact/hooks";
- import { ParentMap, GeoMouseEvent } from "./map";
- import maplibregl from "maplibre-gl";
-
-import { GeoMouseEvent,ParentMap } from "./map";
--
--export interface MarkerProps {
-- coordinates: [ number, number ];
-- iconHtml?: string;
-- iconSize?: [number, number];
- iconAnchor?: [number, number];
-- onClick?: () => void;
-- onMouseDown?: (e: MouseEvent) => void;
-- onDragged?: ((newCoordinates: { lat: number; lng: number }) => void);
-- onContextMenu: (e: GeoMouseEvent) => void;
-- draggable?: boolean;
--}
--
--export default function Marker({ coordinates, iconHtml, iconSize, draggable, onClick, onDragged, onMouseDown, onContextMenu }: MarkerProps) {
-- const parentMap = useContext(ParentMap);
- const markerRef = useRef<maplibregl.Marker>(null);
- const markerRef = useRef<MapLibreMarker>(null);
--
-- useEffect(() => {
-- if (!parentMap) return;
--
-- const el = document.createElement("div");
-- el.className = "geo-marker";
-- if (iconHtml) {
-- el.innerHTML = iconHtml;
-- }
-- if (iconSize) {
-- el.style.width = `${iconSize[0]}px`;
-- el.style.height = `${iconSize[1]}px`;
-- }
--
- const newMarker = new maplibregl.Marker({
- const newMarker = new MapLibreMarker({
-- element: el,
-- draggable: !!draggable,
-- anchor: "bottom"
-- })
- .setLngLat([coordinates[1], coordinates[0]])
- .addTo(parentMap);
- .setLngLat([coordinates[1], coordinates[0]])
- .addTo(parentMap);
--
-- markerRef.current = newMarker;
--
-- if (onClick) {
-- el.addEventListener("click", (e) => {
-- e.stopPropagation();
-- onClick();
-- });
-- }
--
-- if (onMouseDown) {
-- el.addEventListener("mousedown", (e) => {
-- if (e.button === 1) {
-- e.stopPropagation();
-- onMouseDown(e);
-- }
-- });
-- }
--
-- if (onDragged) {
-- newMarker.on("dragend", () => {
-- const lngLat = newMarker.getLngLat();
-- onDragged({ lat: lngLat.lat, lng: lngLat.lng });
-- });
-- }
--
-- if (onContextMenu) {
-- el.addEventListener("contextmenu", (e) => {
-- e.stopPropagation();
-- e.preventDefault();
-- const lngLat = newMarker.getLngLat();
-- onContextMenu({
-- latlng: { lat: lngLat.lat, lng: lngLat.lng },
- originalEvent: e
- originalEvent: e,
- point: parentMap.project(lngLat)
-- });
-- });
-- }
--
-- return () => {
-- newMarker.remove();
-- markerRef.current = null;
-- };
-- }, [ parentMap, coordinates, onMouseDown, onDragged, iconHtml ]);
--
-- return (<div />);
--}
--
--export interface GpxTrackProps {
-- gpxXmlString: string;
-- trackColor?: string;
-- startIconHtml?: string;
-- endIconHtml?: string;
-- waypointIconHtml?: string;
--}
--
--export function GpxTrack({ gpxXmlString, trackColor, startIconHtml, endIconHtml, waypointIconHtml }: GpxTrackProps) {
-- const parentMap = useContext(ParentMap);
--
-- useEffect(() => {
-- if (!parentMap) return;
- // Non-null alias: the narrowing above doesn't carry into the nested function.
- const map = parentMap;
--
- const markers: maplibregl.Marker[] = [];
- const markers: MapLibreMarker[] = [];
-- const sourceId = `gpx-source-${Math.random().toString(36).slice(2)}`;
-- const layerId = `gpx-layer-${sourceId}`;
-
- const parser = new DOMParser();
- const gpxDoc = parser.parseFromString(gpxXmlString, "application/xml");
-
- // Parse tracks and routes.
- const coordinates: [number, number][] = [];
- for (const pt of gpxDoc.querySelectorAll("trkpt, rtept")) {
- const lat = parseFloat(pt.getAttribute("lat") ?? "0");
- const lon = parseFloat(pt.getAttribute("lon") ?? "0");
- coordinates.push([lon, lat]);
- }
-
- function addMarker(lngLat: [number, number], html: string) {
- const el = document.createElement("div");
- el.className = "geo-marker";
- el.innerHTML = html;
- const marker = new maplibregl.Marker({ element: el, anchor: "bottom" })
- .setLngLat(lngLat)
- .addTo(parentMap!);
- markers.push(marker);
- }
--
- // Markers are DOM-based and independent of the map style, so they are added only once.
- if (coordinates.length > 0) {
- if (startIconHtml) {
- addMarker(coordinates[0], startIconHtml);
- }
- if (endIconHtml && coordinates.length > 1) {
- addMarker(coordinates[coordinates.length - 1], endIconHtml);
- }
- }
- function addGpxToMap() {
- const parser = new DOMParser();
- const gpxDoc = parser.parseFromString(gpxXmlString, "application/xml");
--
- if (waypointIconHtml) {
- for (const wpt of gpxDoc.querySelectorAll("wpt")) {
- const lat = parseFloat(wpt.getAttribute("lat") ?? "0");
- const lon = parseFloat(wpt.getAttribute("lon") ?? "0");
- addMarker([lon, lat], waypointIconHtml);
- // Parse tracks.
- const coordinates: [number, number][] = [];
- const trackPoints = gpxDoc.querySelectorAll("trkpt, rtept");
- for (const pt of trackPoints) {
- const lat = parseFloat(pt.getAttribute("lat") ?? "0");
- const lon = parseFloat(pt.getAttribute("lon") ?? "0");
- coordinates.push([lon, lat]);
-- }
- }
--
- // The track line lives in the map style, which setStyle() wipes (async vector style
- // arrival, layer switching), so it must be re-added on every style load.
- function addTrackLayer() {
- if (coordinates.length === 0 || parentMap!.getSource(sourceId)) return;
- // Add GeoJSON line for the track.
- if (coordinates.length > 0) {
- map.addSource(sourceId, {
- type: "geojson",
- data: {
- type: "Feature",
- properties: {},
- geometry: {
- type: "LineString",
- coordinates
- }
- }
- });
--
- parentMap!.addSource(sourceId, {
- type: "geojson",
- data: {
- type: "Feature",
- properties: {},
- geometry: {
- type: "LineString",
- coordinates
- map.addLayer({
- id: layerId,
- type: "line",
- source: sourceId,
- paint: {
- "line-color": trackColor ?? "blue",
- "line-width": 3
-- }
- });
-
- // Start marker
- if (startIconHtml) {
- const startEl = document.createElement("div");
- startEl.className = "geo-marker";
- startEl.innerHTML = startIconHtml;
- const startMarker = new MapLibreMarker({ element: startEl, anchor: "bottom" })
- .setLngLat(coordinates[0])
- .addTo(map);
- markers.push(startMarker);
-- }
- });
--
- parentMap!.addLayer({
- id: layerId,
- type: "line",
- source: sourceId,
- paint: {
- "line-color": trackColor ?? "blue",
- "line-width": 3
- // End marker
- if (endIconHtml && coordinates.length > 1) {
- const endEl = document.createElement("div");
- endEl.className = "geo-marker";
- endEl.innerHTML = endIconHtml;
- const endMarker = new MapLibreMarker({ element: endEl, anchor: "bottom" })
- .setLngLat(coordinates[coordinates.length - 1])
- .addTo(map);
- markers.push(endMarker);
-- }
- });
- }
-
- // Parse waypoints.
- const waypoints = gpxDoc.querySelectorAll("wpt");
- for (const wpt of waypoints) {
- const lat = parseFloat(wpt.getAttribute("lat") ?? "0");
- const lon = parseFloat(wpt.getAttribute("lon") ?? "0");
- if (waypointIconHtml) {
- const wptEl = document.createElement("div");
- wptEl.className = "geo-marker";
- wptEl.innerHTML = waypointIconHtml;
- const wptMarker = new MapLibreMarker({ element: wptEl, anchor: "bottom" })
- .setLngLat([lon, lat])
- .addTo(map);
- markers.push(wptMarker);
- }
- }
-- }
--
-- if (parentMap.isStyleLoaded()) {
- addTrackLayer();
- addGpxToMap();
- } else {
- parentMap.once("style.load", addGpxToMap);
-- }
- parentMap.on("style.load", addTrackLayer);
--
-- return () => {
- parentMap.off("style.load", addTrackLayer);
-- for (const m of markers) {
-- m.remove();
-- }
-- try {
-- if (parentMap.getLayer(layerId)) {
-- parentMap.removeLayer(layerId);
-- }
-- if (parentMap.getSource(sourceId)) {
-- parentMap.removeSource(sourceId);
-- }
-- } catch {
-- // Map may be already removed.
-- }
-- };
-- }, [ parentMap, gpxXmlString, trackColor, startIconHtml, endIconHtml, waypointIconHtml ]);
--
-- return <div />;
--}