Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): fit the viewport around a track when it is opened or brought in

Elian Doran4746dcf14579
diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx
index 6304167aee..ed1ff848c4 100644
--- a/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx
@@ -16,7 +16,7 @@ import { buildNote } from "../../../test/easy-froca";
import { useLegacyImperativeHandlers, useNoteContext, useTriliumEvent } from "../../react/hooks";
import { ParentComponent } from "../../react/react_utils";
import DetailPane, { OTHER_WAYS_TO_OPEN, PaneSelection } from "./DetailPane";
-import { GPX_MIME } from "./GpxTrack";
+import { GPX_MIME, trackSourceId } from "./GpxTrack";
import { ParentMap } from "./map";
import { MARKER_LAYER } from "./Markers";
@@ -77,11 +77,22 @@ const MAP_WIDTH = 1200;
function fakeMap({ width = MAP_WIDTH, features = [] as unknown[] } = {}) {
const listeners = new Map<string, Set<Listener>>();
const eased: unknown[] = [];
+ const fitted: unknown[] = [];
+ const sources = new Map<string, unknown>();
let under: unknown[] = features;
return {
/** Every camera move the pane has asked for, which is how it holds a marker clear of itself. */
get eased() { return eased; },
+ /** Every fit the pane has asked for, which is how it brings a whole track into view. */
+ get fitted() { return fitted; },
+ /** Registers a GeoJSON source as a track's layers would have added it, for the pane to read back. */
+ addSource(id: string, data: unknown) { sources.set(id, { getData: async () => data }); },
+ getSource(id: string) { return sources.get(id); },
+ /** A source announcing itself, as MapLibre does — repeatedly, for as long as it lives. */
+ fireSourceData(sourceId: string) {
+ for (const fn of listeners.get("sourcedata") ?? []) fn({ sourceId });
+ },
/** What the next click will land on: a marker's feature, or nothing at all. */
setUnderPointer(hit: unknown[]) { under = hit; },
/** A click on the map, wherever `setUnderPointer` says it landed. */
@@ -101,7 +112,8 @@ function fakeMap({ width = MAP_WIDTH, features = [] as unknown[] } = {}) {
return layers.includes(MARKER_LAYER) ? under : [];
},
easeTo(options: unknown) { eased.push(options); },
- getContainer: () => ({ clientWidth: width }),
+ fitBounds(bounds: unknown, options: unknown) { fitted.push({ bounds, options }); },
+ getContainer: () => ({ clientWidth: width, clientHeight: 800 }),
// Asked for by `trackHitLayers`, which reads the current GPX hit layers off the style.
getLayersOrder: () => [] as string[]
};
@@ -236,11 +248,78 @@ describe("DetailPane", () => {
await settle();
expect(pane()?.querySelector<HTMLInputElement>(".title-row input")?.value).toBe("A hike");
- // Nothing to pan to and no place to write out, there being no location label to read.
+ // No place to write out, there being no location label to read — and nothing to move the
+ // camera for either, this map not carrying the track's source to fit the viewport around.
expect(map.eased).toEqual([]);
+ expect(map.fitted).toEqual([]);
expect(pane()?.querySelector(".geo-detail-pane-location")).toBeNull();
});
+ /**
+ * A track is not a point but a shape, so opening one does not centre a coordinate: the camera
+ * is solved for the track's corners — pan and zoom both — held clear of the pane on its side
+ * and given a rim of air on the others. The corners are read back off the track's own source,
+ * so the pane never parses the file itself.
+ */
+ it("fits the whole track into what the pane leaves uncovered", async () => {
+ buildNote({ id: "root", title: "root", children: [ { id: "hikefit", title: "A hike", mime: GPX_MIME } ] });
+ const note = froca.notes["hikefit"];
+ const map = fakeMap();
+ map.addSource(trackSourceId(note.noteId), {
+ type: "FeatureCollection",
+ features: [
+ { type: "Feature", properties: {}, geometry: { type: "MultiLineString", coordinates: [ [ [ 24.13, 45.79 ], [ 24.16, 45.96 ] ] ] } },
+ { type: "Feature", properties: {}, geometry: { type: "Point", coordinates: [ 24.08, 45.89 ] } }
+ ]
+ });
+ await mount([ note ], map);
+
+ map.setUnderPointer([ trackFeature(note) ]);
+ await act(async () => map.click());
+ await settle();
+
+ expect(map.eased).toEqual([]);
+ expect(map.fitted).toEqual([ {
+ // The westmost point is the mark's, not the line's: everything the source holds counts.
+ bounds: [ [ 24.08, 45.79 ], [ 24.16, 45.96 ] ],
+ options: { padding: { top: 60, bottom: 60, left: 60, right: 460 }, maxZoom: 16 }
+ } ]);
+ });
+
+ /**
+ * A track selected the moment it was brought onto the map (see `addGpxTrack` in index.tsx) has
+ * no line yet — the note's content is still being fetched, so the source the bounds are read
+ * from is not there to be asked. The fit waits for the source to announce itself rather than
+ * giving up, and takes only the first announcement: they repeat for as long as the source
+ * lives, and a map re-fitted under the reader on each would never stay where it was put.
+ */
+ it("fits a track whose line arrives after it was selected, and only once", async () => {
+ buildNote({ id: "root", title: "root", children: [ { id: "hikelate", title: "A hike", mime: GPX_MIME } ] });
+ const note = froca.notes["hikelate"];
+ const map = fakeMap();
+
+ // Selected before any source exists, as the map view selects a track it has just imported.
+ await mount([ note ], map, false, false, { noteId: note.noteId });
+ await settle();
+ expect(map.fitted).toEqual([]);
+
+ // The track's layers go up once the content has arrived (see GpxTrack), source first.
+ map.addSource(trackSourceId(note.noteId), {
+ type: "FeatureCollection",
+ features: [ { type: "Feature", properties: {}, geometry: { type: "MultiLineString", coordinates: [ [ [ 24.13, 45.79 ], [ 24.16, 45.96 ] ] ] } } ]
+ });
+ await act(async () => { map.fireSourceData(trackSourceId(note.noteId)); });
+
+ expect(map.fitted).toEqual([ {
+ bounds: [ [ 24.13, 45.79 ], [ 24.16, 45.96 ] ],
+ options: { padding: { top: 60, bottom: 60, left: 60, right: 460 }, maxZoom: 16 }
+ } ]);
+
+ // Announced again — a repaint, a tile settling — the map stays where it was put.
+ await act(async () => { map.fireSourceData(trackSourceId(note.noteId)); });
+ expect(map.fitted).toHaveLength(1);
+ });
+
/**
* Regression test for a click on a marker whiting out the map and losing its WebGL context.
*
diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.tsx
index d1f4cd0b92..cab77fbf4e 100644
--- a/apps/client/src/widgets/collections/geomap/DetailPane.tsx
+++ b/apps/client/src/widgets/collections/geomap/DetailPane.tsx
@@ -1,7 +1,7 @@
import "./DetailPane.css";
import clsx from "clsx";
-import type { Map as MapLibreGLMap, MapMouseEvent } from "maplibre-gl";
+import type { GeoJSONSource, Map as MapLibreGLMap, MapMouseEvent, MapSourceDataEvent } from "maplibre-gl";
import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "preact/hooks";
import appContext from "../../../components/app_context";
@@ -23,7 +23,7 @@ import { useLegacyComponentElement, useNoteColorClass, useNoteContext, useNoteLa
import OverlayPanel, { OverlayPanelBody } from "../../react/OverlayPanel";
import { NoteContextContext, ParentComponent } from "../../react/react_utils";
import { moveMarker } from "./api";
-import { GPX_MIME, trackHitLayers } from "./GpxTrack";
+import { GPX_MIME, trackHitLayers, trackSourceId } from "./GpxTrack";
import { ParentMap } from "./map";
import { formatLocation, LOCATION_ATTRIBUTE, MARKER_LAYER, parseLocation } from "./Markers";
@@ -145,9 +145,44 @@ export default function DetailPane({ notes, placing, isReadOnly, selection, onSe
// rather than in the click handler, so a marker the map opened by hand — the note it has just
// created — is held clear of the pane the same way as one that was clicked; and off the
// location too, so a marker that has just been put somewhere else is followed there.
+ //
+ // A GPX track is not a point but a shape, so it is fitted rather than centred: panned and
+ // zoomed until the whole of it stands in the part of the map the pane leaves uncovered.
useEffect(() => {
if (!map || !note) return;
+ if (note.mime === GPX_MIME) {
+ const sourceId = trackSourceId(note.noteId);
+ // Reading the track back off the map is asynchronous, and the answer may arrive after
+ // the pane has moved on — to another note, or to nothing at all — or after another
+ // asking of it has already fitted the map.
+ let done = false;
+
+ const fit = async () => {
+ const bounds = await trackBounds(map, note.noteId);
+ if (done || !bounds) return;
+ done = true;
+ map.off("sourcedata", onSourceData);
+ map.fitBounds(bounds, { padding: trackFitPadding(map), maxZoom: TRACK_FIT_MAX_ZOOM });
+ };
+
+ // A track selected the moment it was brought onto the map has no line yet: its content
+ // is still being fetched (see NoteGpxTrackWrapper), so the source the bounds are read
+ // from is not there to be asked. The source announces itself when it goes up, and the
+ // fit follows — once, the announcement repeating for as long as the source lives.
+ const onSourceData = (e: MapSourceDataEvent) => {
+ if (e.sourceId === sourceId) void fit();
+ };
+
+ map.on("sourcedata", onSourceData);
+ void fit();
+
+ return () => {
+ done = true;
+ map.off("sourcedata", onSourceData);
+ };
+ }
+
const coordinates = parseLocation(location);
if (!coordinates) return;
@@ -240,6 +275,66 @@ function paneOffset(map: MapLibreGLMap): [number, number] {
return [ glob.isRtl ? shift : -shift, 0 ];
}
+/** Air kept around a fitted track, so its ends stand clear of the pane and the map's own edges. */
+const TRACK_FIT_AIR = 60;
+
+/** How close fitting a track may zoom: a stroll around the block is still shown as a map of the
+ * neighbourhood, not of somebody's garden. */
+const TRACK_FIT_MAX_ZOOM = 16;
+
+/**
+ * The corners of the selected track, as `fitBounds` wants them, read back off the map itself — the
+ * source already holds every point of the line and its marks, so the file is not parsed twice.
+ * `null` for a track that is not on this map, or holds nothing with a place.
+ */
+async function trackBounds(map: MapLibreGLMap, noteId: string): Promise<[[number, number], [number, number]] | null> {
+ const data = await map.getSource<GeoJSONSource>(trackSourceId(noteId))?.getData();
+ if (!data || data.type !== "FeatureCollection") return null;
+
+ let west = Infinity, south = Infinity, east = -Infinity, north = -Infinity;
+ const extend = ([ lng, lat ]: number[]) => {
+ west = Math.min(west, lng);
+ south = Math.min(south, lat);
+ east = Math.max(east, lng);
+ north = Math.max(north, lat);
+ };
+
+ for (const { geometry } of data.features) {
+ if (geometry.type === "Point") {
+ extend(geometry.coordinates);
+ } else if (geometry.type === "MultiLineString") {
+ for (const line of geometry.coordinates) {
+ for (const point of line) {
+ extend(point);
+ }
+ }
+ }
+ }
+
+ return Number.isFinite(west) ? [ [ west, south ], [ east, north ] ] : null;
+}
+
+/**
+ * What a fitted track has to keep clear of: the pane on its side of the map, and a rim of air all
+ * round, so the line reads as standing in the viewport rather than pinned to its corners.
+ *
+ * The air gives way on a map too small to spare it, and the pane's reach is only counted where
+ * there is room left over — the same bargain {@link paneOffset} strikes — since padding wider than
+ * the map does not clip the fit but forfeits it: MapLibre cannot solve the camera and leaves it
+ * where it stands.
+ */
+function trackFitPadding(map: MapLibreGLMap) {
+ const { clientWidth, clientHeight } = map.getContainer();
+ const air = Math.max(0, Math.min(TRACK_FIT_AIR, Math.floor(Math.min(clientWidth, clientHeight) / 4)));
+ const padding = { top: air, bottom: air, left: air, right: air };
+
+ if (clientWidth > PANE_REACH + 2 * air) {
+ padding[glob.isRtl ? "left" : "right"] += PANE_REACH;
+ }
+
+ return padding;
+}
+
/** The pane itself, for a marker there is one to draw. */
function MarkerDetails({ note, isReadOnly, onClose, onRelocate, onFollowLink }: {
note: FNote;
diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsx
index ba2a3d0b4a..2d2f772ae9 100644
--- a/apps/client/src/widgets/collections/geomap/index.tsx
+++ b/apps/client/src/widgets/collections/geomap/index.tsx
@@ -119,8 +119,12 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
/**
* Asks for a GPX file and brings it onto the map as a child note (see importGpxTrack). The
* note is put among the map's own straight away, as a created note is, so the track is drawn
- * the moment the file is read rather than after the collection reloads around it. No pane
- * opens: a track is not a marker, and the file's name already names it.
+ * the moment the file is read rather than after the collection reloads around it.
+ *
+ * The pane opens on it too, as it opens on a note just placed — and it is the pane's own fit
+ * that brings the track into view (see DetailPane), waiting on the line if it has not been
+ * drawn yet, so a file from the other side of the world does not land off-screen. Unlike a
+ * placed note the title is not offered for typing over: the file's name already names it.
*/
const addGpxTrack = useCallback(async () => {
const file = await pickGpxFile();
@@ -130,6 +134,7 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
if (!created) return;
setNotes((current) => current.some((n) => n.noteId === created.noteId) ? current : [ ...current, created ]);
+ setSelection({ noteId: created.noteId });
}, [ note ]);
// Placement mode is armed by the button or by the context menu. Tying the instruction toast and