Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): name the place under the pointer

Elian Doran4d496c12f889
diff --git a/apps/client/src/widgets/collections/geomap/Pois.css b/apps/client/src/widgets/collections/geomap/Pois.css
new file mode 100644
index 0000000000..0a34fd9860
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/Pois.css
@@ -0,0 +1,27 @@
+/* The name of a place under the pointer (see Pois). MapLibre puts its popups inside the map's own
+ container, so these are scoped as everything else over the map is; the box is MapLibre's, dressed
+ in the same tokens the app's own tooltips wear, with what the older themes can be asked for. */
+.geo-map-container .place-tooltip .maplibregl-popup-content {
+ padding: var(--tooltip-padding, 4px 9px);
+ border-radius: var(--tooltip-border-radius, 5px);
+ background: var(--tooltip-background-color);
+ backdrop-filter: var(--tooltip-backdrop-filter);
+ box-shadow: var(--tooltip-box-shadow, 2px 2px 8px rgba(0, 0, 0, 0.2));
+ color: var(--tooltip-foreground-color, var(--main-text-color));
+ font-family: var(--main-font-family);
+ font-size: var(--tooltip-font-size, 0.9rem);
+ /* A name is read, not reached: left under the pointer it would take the place's own click. */
+ pointer-events: none;
+}
+
+/* Drawn in a hard white by MapLibre, which is not the colour of the box above it on every theme. */
+.geo-map-container .place-tooltip .maplibregl-popup-tip {
+ display: none;
+}
+
+.geo-map-container .place-tooltip .place-tooltip-label {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ white-space: nowrap;
+}
diff --git a/apps/client/src/widgets/collections/geomap/Pois.spec.tsx b/apps/client/src/widgets/collections/geomap/Pois.spec.tsx
index c3ffe0a9ae..f6db030c4e 100644
--- a/apps/client/src/widgets/collections/geomap/Pois.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/Pois.spec.tsx
@@ -6,7 +6,7 @@
import type { Map as MapLibreGLMap, MapGeoJSONFeature } from "maplibre-gl";
import { render } from "preact";
import { act } from "preact/test-utils";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { CLUSTER_LAYER } from "./clusters";
import type { GeoSearchResult } from "./geocoding";
@@ -14,6 +14,41 @@ import { MapStyleLoaded, ParentMap } from "./map";
import { MARKER_LAYER } from "./Markers";
import Pois, { poiFromFeature, poiLayers } from "./Pois";
+/**
+ * The popup MapLibre would draw, recording what it was shown and whether it is up. Hoisted because
+ * the module mock below it is, and that mock is what hands the class to the component.
+ */
+const { FakePopup } = vi.hoisted(() => {
+ class FakePopup {
+ static open: FakePopup[] = [];
+
+ content: HTMLElement | null = null;
+ lngLat: unknown;
+
+ setLngLat(lngLat: unknown) { this.lngLat = lngLat; return this; }
+ setDOMContent(content: HTMLElement) { this.content = content; return this; }
+
+ addTo() {
+ if (!FakePopup.open.includes(this)) FakePopup.open.push(this);
+ return this;
+ }
+
+ remove() {
+ FakePopup.open = FakePopup.open.filter((popup) => popup !== this);
+ return this;
+ }
+ }
+
+ return { FakePopup };
+});
+
+vi.mock("maplibre-gl", () => ({ Popup: FakePopup }));
+
+/** What the tooltip currently reads, or `null` where none is up. */
+function tooltipText() {
+ return FakePopup.open[0]?.content?.textContent ?? null;
+}
+
type Listener = (e?: unknown) => void;
/** A place as a tile carries one: named, classified by its OSM tags, standing at a point. */
@@ -51,18 +86,21 @@ function fakeMap({ poiLayerIds = [ "poi-amenity", "poi-shop" ], ownLayerIds = [
click() {
for (const fn of listeners.get("click") ?? []) fn({ point: { x: 0, y: 0 } });
},
- /** The pointer arriving over one of the layers the cursor is bound to, and leaving it again. */
- hover(layer: string) {
- for (const fn of listeners.get(`mouseenter:${layer}`) ?? []) fn();
+ /** The pointer coming to rest on a place of the base map, as MapLibre reports it. */
+ hover(feature: unknown) {
+ for (const fn of listeners.get(`mousemove:${poiLayerIds}`) ?? []) {
+ fn({ point: { x: 0, y: 0 }, features: [ feature ] });
+ }
},
- unhover(layer: string) {
- for (const fn of listeners.get(`mouseleave:${layer}`) ?? []) fn();
+ /** The pointer leaving the layers the places are drawn on. */
+ unhover() {
+ for (const fn of listeners.get(`mouseleave:${poiLayerIds}`) ?? []) fn();
},
- /** Which layers the cursor is currently bound to, as a style switch has to put back. */
+ /** Which layers the hover is currently bound to, as a style switch has to put back. */
boundLayers() {
return [ ...listeners.keys() ]
- .filter((key) => key.startsWith("mouseenter:") && (listeners.get(key)?.size ?? 0) > 0)
- .map((key) => key.slice("mouseenter:".length));
+ .filter((key) => key.startsWith("mousemove:") && (listeners.get(key)?.size ?? 0) > 0)
+ .flatMap((key) => key.slice("mousemove:".length).split(",").filter(Boolean));
},
fireStyleLoad() {
for (const fn of listeners.get("style.load") ?? []) fn();
@@ -214,17 +252,19 @@ describe("geo map Pois", () => {
// The styles fade their places in over the zoom above 16, and what cannot be seen is not
// what a click was aimed at.
+ const place = poiFeature({ name: "Café Kranzler", amenity: "cafe" });
+
map.setZoom(16);
- map.setUnderPointer({ poi: [ poiFeature({ name: "Café Kranzler", amenity: "cafe" }) ] });
+ map.setUnderPointer({ poi: [ place ] });
await act(async () => { map.click(); });
- map.hover("poi-amenity");
+ map.hover(place);
expect(picked).toEqual([]);
expect(map.cursor).toBe("");
map.setZoom(17);
await act(async () => { map.click(); });
- map.hover("poi-amenity");
+ map.hover(place);
expect(picked).toHaveLength(1);
expect(map.cursor).toBe("pointer");
@@ -244,20 +284,46 @@ describe("geo map Pois", () => {
it("says a place can be clicked, and puts the pointer back when it goes", async () => {
const map = fakeMap();
const { unmount } = await renderPois(map);
+ const place = poiFeature({ name: "Café Kranzler", amenity: "cafe" });
- map.hover("poi-amenity");
+ map.hover(place);
expect(map.cursor).toBe("pointer");
- map.unhover("poi-amenity");
+ map.unhover();
expect(map.cursor).toBe("");
- map.hover("poi-shop");
+ map.hover(place);
await unmount();
// Torn down with the pointer sitting on a place, the `mouseleave` no longer being listened for.
expect(map.cursor).toBe("");
expect(map.boundLayers()).toEqual([]);
});
+ it("offers no pointer over a place that has no name to keep", async () => {
+ const map = fakeMap();
+ await renderPois(map);
+
+ map.hover(poiFeature({ amenity: "bench" }));
+
+ expect(map.cursor).toBe("");
+ });
+
+ it("leaves the pointer to a marker standing over a place", async () => {
+ const map = fakeMap();
+ await renderPois(map);
+ const place = poiFeature({ name: "Café Kranzler", amenity: "cafe" });
+
+ map.hover(place);
+ expect(map.cursor).toBe("pointer");
+
+ // The marker sets its own pointer and clears it again, so this leaves the cursor alone
+ // rather than clearing what the marker has just set.
+ map.setUnderPointer({ own: [ { properties: { id: "note1" } } ] });
+ map.hover(place);
+
+ expect(map.cursor).toBe("pointer");
+ });
+
it("puts the pointer back on the layers a style switch brought in", async () => {
const map = fakeMap();
await renderPois(map);
@@ -268,7 +334,116 @@ describe("geo map Pois", () => {
await act(async () => { map.fireStyleLoad(); });
expect(map.boundLayers()).toEqual([ "poi-amenity", "poi-shop" ]);
- map.hover("poi-amenity");
+ map.hover(poiFeature({ name: "Café Kranzler", amenity: "cafe" }));
expect(map.cursor).toBe("pointer");
});
});
+
+describe("geo map place tooltips", () => {
+ /** Long enough for the rest the name is held back for, whatever that rest is set to. */
+ const RESTED = 500;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ FakePopup.open = [];
+ });
+
+ afterEach(() => { vi.useRealTimers(); });
+
+ it("names the place the pointer has come to rest on", async () => {
+ const map = fakeMap();
+ await renderPois(map);
+
+ map.hover(poiFeature({ name: "Café Kranzler", amenity: "cafe" }));
+ // Not while the pointer is merely passing over it.
+ expect(tooltipText()).toBeNull();
+
+ vi.advanceTimersByTime(RESTED);
+
+ expect(tooltipText()).toBe("Café Kranzler");
+ // Where the place stands, so the name follows it as the map is moved.
+ expect(FakePopup.open[0]?.lngLat).toEqual([ 13.4, 52.5 ]);
+ });
+
+ it("names the place with the icon it would wear as a marker", async () => {
+ const map = fakeMap();
+ await renderPois(map);
+
+ map.hover(poiFeature({ name: "Edeka", shop: "supermarket" }));
+ vi.advanceTimersByTime(RESTED);
+
+ expect(FakePopup.open[0]?.content?.querySelector("i")?.className).toBe("bx bx-cart");
+ });
+
+ it("says nothing of a place with no name, nor of one a marker stands over", async () => {
+ const map = fakeMap();
+ await renderPois(map);
+
+ map.hover(poiFeature({ amenity: "bench" }));
+ vi.advanceTimersByTime(RESTED);
+ expect(tooltipText()).toBeNull();
+
+ map.setUnderPointer({ own: [ { properties: { id: "note1" } } ] });
+ map.hover(poiFeature({ name: "Café Kranzler", amenity: "cafe" }));
+ vi.advanceTimersByTime(RESTED);
+ expect(tooltipText()).toBeNull();
+ });
+
+ it("carries the name across to the next place the pointer reaches", async () => {
+ const map = fakeMap();
+ await renderPois(map);
+
+ map.hover(poiFeature({ name: "Café Kranzler", amenity: "cafe" }));
+ vi.advanceTimersByTime(RESTED);
+ expect(tooltipText()).toBe("Café Kranzler");
+
+ // A different place, which never leaves the layer the two are drawn on.
+ map.hover({ ...poiFeature({ name: "Edeka", shop: "supermarket" }), id: 43 });
+ // The name just left goes at once rather than standing over its neighbour.
+ expect(tooltipText()).toBeNull();
+
+ vi.advanceTimersByTime(RESTED);
+ expect(tooltipText()).toBe("Edeka");
+ });
+
+ it("takes the name down when the place is clicked, until the pointer has been away", async () => {
+ const map = fakeMap();
+ const place = poiFeature({ name: "Café Kranzler", amenity: "cafe" });
+ map.setUnderPointer({ poi: [ place ] });
+ await renderPois(map);
+
+ map.hover(place);
+ vi.advanceTimersByTime(RESTED);
+ expect(tooltipText()).toBe("Café Kranzler");
+
+ // The panel the click opens says the name at length, and the pin now carries it too.
+ map.click();
+ expect(tooltipText()).toBeNull();
+
+ map.hover(place);
+ vi.advanceTimersByTime(RESTED);
+ expect(tooltipText()).toBeNull();
+
+ map.unhover();
+ map.hover(place);
+ vi.advanceTimersByTime(RESTED);
+ expect(tooltipText()).toBe("Café Kranzler");
+ });
+
+ it("takes the name down as the pointer leaves the place", async () => {
+ const map = fakeMap();
+ const { unmount } = await renderPois(map);
+
+ map.hover(poiFeature({ name: "Café Kranzler", amenity: "cafe" }));
+ vi.advanceTimersByTime(RESTED);
+ map.unhover();
+ expect(tooltipText()).toBeNull();
+
+ // Nor is one left standing over a map that is no longer on the screen.
+ map.hover(poiFeature({ name: "Café Kranzler", amenity: "cafe" }));
+ vi.advanceTimersByTime(RESTED);
+ await unmount();
+
+ expect(tooltipText()).toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/collections/geomap/Pois.tsx b/apps/client/src/widgets/collections/geomap/Pois.tsx
index 588f7df98f..2b8362ea76 100644
--- a/apps/client/src/widgets/collections/geomap/Pois.tsx
+++ b/apps/client/src/widgets/collections/geomap/Pois.tsx
@@ -1,4 +1,6 @@
-import type { Map as MapLibreGLMap, MapGeoJSONFeature, MapMouseEvent } from "maplibre-gl";
+import "./Pois.css";
+
+import { type Map as MapLibreGLMap, type MapGeoJSONFeature, type MapMouseEvent, Popup } from "maplibre-gl";
import { useContext, useEffect } from "preact/hooks";
import { CLUSTER_LAYERS } from "./clusters";
@@ -18,6 +20,18 @@ const POI_SOURCE_LAYER = "pois";
*/
const MIN_POI_ZOOM = 17;
+/**
+ * How long the pointer has to rest on a place before its name is shown.
+ *
+ * Shorter than the wait a marker's preview sits out, that one reading a note from the server while
+ * this is already in hand — but long enough that sweeping the pointer down a high street does not
+ * name every shop on the way past.
+ */
+const TOOLTIP_DELAY = 200;
+
+/** How far the name stands above the place's icon, which is drawn at half size by the styles. */
+const TOOLTIP_OFFSET = 10;
+
/**
* The OSM keys a tile classifies a place by, in the order the styles draw them. A feature carries at
* most a few of these, and the first one present is what the place is.
@@ -65,15 +79,11 @@ export default function Pois({ placing, onPick }: PoisProps) {
const map = parentMap;
const onClick = (e: MapMouseEvent) => {
- if (map.getZoom() < MIN_POI_ZOOM) return;
+ if (map.getZoom() < MIN_POI_ZOOM || isOwnUnderPointer(map, e.point)) return;
const layers = poiLayers(map);
if (!layers.length) return;
- // A marker, a cluster or a track stands above the base map and answers the click first.
- const own = ownLayers(map);
- if (own.length && map.queryRenderedFeatures(e.point, { layers: own }).length) return;
-
const place = poiFromFeature(map.queryRenderedFeatures(e.point, { layers })[0]);
if (place) {
onPick(place);
@@ -84,26 +94,95 @@ export default function Pois({ placing, onPick }: PoisProps) {
return () => { map.off("click", onClick); };
}, [ parentMap, placing, onPick ]);
- // The pointer is what says a place can be clicked: the base map draws it as an icon like any
- // other, and nothing else about it invites a click.
+ /**
+ * The name of the place under the pointer, and the pointer itself saying it can be clicked.
+ *
+ * The styles draw a place as a bare icon: they carry its name but put no label on the map for it,
+ * and turning those labels on would set them against the titles of the map's own markers, which
+ * give way to whatever is placed before them (see `text-optional` in Markers). Shown on hover
+ * instead, the name costs the map nothing until it is asked for.
+ */
useEffect(() => {
if (!parentMap || placing) return;
// Aliased so the narrowing above carries into the functions below.
const map = parentMap;
+
+ const tooltip = new Popup({
+ closeButton: false,
+ closeOnClick: false,
+ // Otherwise MapLibre puts the caret in the popup as it opens, taking the focus out of
+ // whatever the user was typing in (see Tooltips).
+ focusAfterOpen: false,
+ offset: TOOLTIP_OFFSET,
+ className: "place-tooltip"
+ });
+
let bound: string[] = [];
+ // The place under the pointer, which is what keeps a name from being shown twice over and
+ // from coming back after a click until the pointer has left and returned.
+ let hovered: string | null = null;
+ let showTimer: ReturnType<typeof setTimeout> | undefined;
const setCursor = (cursor: string) => { map.getCanvas().style.cursor = cursor; };
- const onEnter = () => {
- if (map.getZoom() >= MIN_POI_ZOOM) {
- setCursor("pointer");
+
+ function hide() {
+ clearTimeout(showTimer);
+ tooltip.remove();
+ }
+
+ function onMouseMove(e: MapMouseEvent & { features?: MapGeoJSONFeature[] }) {
+ // A marker, a cluster or a track stands above the base map, and owns the pointer along
+ // with the click while it does.
+ if (map.getZoom() < MIN_POI_ZOOM || isOwnUnderPointer(map, e.point)) {
+ hovered = null;
+ hide();
+ return;
}
- };
- const onLeave = () => setCursor("");
+
+ const place = poiFromFeature(e.features?.[0]);
+ if (!place) {
+ // A place with no name answers no click either, so the pointer offers none.
+ hovered = null;
+ setCursor("");
+ hide();
+ return;
+ }
+
+ setCursor("pointer");
+ // Watched by the move rather than by `mouseenter`, which fires on entering the layer
+ // rather than the place: the pointer crossing from one place to the next never leaves
+ // the layer, and the first name would stay up over the second.
+ if (place.id === hovered) return;
+
+ hovered = place.id;
+ hide();
+ showTimer = setTimeout(() => {
+ tooltip
+ .setLngLat([ place.lng, place.lat ])
+ .setDOMContent(placeLabel(place))
+ .addTo(map);
+ }, TOOLTIP_DELAY);
+ }
+
+ function onMouseLeave() {
+ hovered = null;
+ setCursor("");
+ hide();
+ }
+
+ /**
+ * Puts the name away because the map was clicked, whatever the click was for. `hovered` is
+ * kept rather than cleared, which is what stops the name coming back over the panel the
+ * click has just opened: the place stays the one under the pointer until the pointer leaves.
+ */
+ function dismiss() {
+ hide();
+ }
function unbind() {
- for (const layer of bound) {
- map.off("mouseenter", layer, onEnter);
- map.off("mouseleave", layer, onLeave);
+ if (bound.length) {
+ map.off("mousemove", bound, onMouseMove);
+ map.off("mouseleave", bound, onMouseLeave);
}
bound = [];
}
@@ -111,19 +190,22 @@ export default function Pois({ placing, onPick }: PoisProps) {
function bind() {
unbind();
bound = poiLayers(map);
- for (const layer of bound) {
- map.on("mouseenter", layer, onEnter);
- map.on("mouseleave", layer, onLeave);
+ if (bound.length) {
+ map.on("mousemove", bound, onMouseMove);
+ map.on("mouseleave", bound, onMouseLeave);
}
}
bind();
// Switching the style replaces every layer the handlers were bound to.
map.on("style.load", bind);
+ map.on("click", dismiss);
return () => {
map.off("style.load", bind);
+ map.off("click", dismiss);
unbind();
+ hide();
// The pointer is put back by hand, since this can be torn down while it sits on a place
// and the `mouseleave` that would have cleared it is no longer listened for.
setCursor("");
@@ -176,8 +258,32 @@ export function poiLayers(map: MapLibreGLMap) {
return map.getLayersOrder().filter((id) => map.getLayer(id)?.sourceLayer === POI_SOURCE_LAYER);
}
-/** The layers the map draws its own notes and tracks on, which stand above the base map. */
-function ownLayers(map: MapLibreGLMap) {
- return [ MARKER_LAYER, PLACE_LAYER, ...CLUSTER_LAYERS, ...trackHitLayers(map) ]
+/**
+ * Whether the map has something of its own under the pointer — a marker, a cluster, a track or the
+ * pin of a place already in hand. Those stand above the base map and answer for it.
+ */
+function isOwnUnderPointer(map: MapLibreGLMap, point: MapMouseEvent["point"]) {
+ const own = [ MARKER_LAYER, PLACE_LAYER, ...CLUSTER_LAYERS, ...trackHitLayers(map) ]
.filter((id) => map.getLayer(id));
+
+ return own.length > 0 && map.queryRenderedFeatures(point, { layers: own }).length > 0;
+}
+
+/** The name of a place and the icon it would wear as a marker, as the tooltip shows them. */
+function placeLabel(place: GeoSearchResult) {
+ const label = document.createElement("span");
+ label.className = "place-tooltip-label";
+
+ if (place.icon) {
+ const icon = document.createElement("i");
+ icon.className = place.icon;
+ label.appendChild(icon);
+ }
+
+ const name = document.createElement("span");
+ // A place is named by whatever OpenStreetMap holds, which is not ours to read as markup.
+ name.textContent = place.name;
+ label.appendChild(name);
+
+ return label;
}
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Geo Map.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Geo Map.html
index ad28d5d04b..e8ae794e1a 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Geo Map.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Geo Map.html
@@ -180,10 +180,12 @@
museums and other places around the area being viewed. Once the map is
zoomed in far enough for these to be drawn, they can be clicked:</p>
<ol>
- <li>Click one of the place icons drawn by the map. The mouse cursor turns
- into a pointer over the ones that can be clicked.</li>
- <li>The same panel used for a searched place appears, showing the place's
- name and its coordinates, and a pin is placed on it.</li>
+ <li>Rest the mouse on one of the place icons drawn by the map. Its name
+ appears above it, and the cursor turns into a pointer. The map draws these
+ places as bare icons, so hovering is how their names are read — showing
+ them all at once would crowd out the titles of your own markers.</li>
+ <li>Click it. The same panel used for a searched place appears, showing the
+ place's name and its coordinates, and a pin is placed on it.</li>
<li>Press <em>Add as marker</em> to keep it. The note is created with the
place's name as its title, and the icon matching the kind of place it
is.</li>
@@ -193,8 +195,8 @@
<p>Some things to keep in mind:</p>
<ul>
<li>Places that have no name in the map data, such as benches or parking
- spaces, are not clickable. Clicking them does nothing, as clicking the
- map elsewhere.</li>
+ spaces, show no name and are not clickable. Clicking them does nothing, as
+ clicking the map elsewhere.</li>
<li>The markers of the map take precedence: where one stands over a place,
clicking it opens the note, not the place.</li>
<li>This does not work with the raster (OpenStreetMap) style, whose places
diff --git a/docs/User Guide/User Guide/Collections/Geo Map.md b/docs/User Guide/User Guide/Collections/Geo Map.md
index 5f9ec07218..dc737772c2 100644
--- a/docs/User Guide/User Guide/Collections/Geo Map.md
+++ b/docs/User Guide/User Guide/Collections/Geo Map.md
@@ -128,15 +128,15 @@ This works for:
When a vector map style is used, the map itself draws the shops, cafés, museums and other places around the area being viewed. Once the map is zoomed in far enough for these to be drawn, they can be clicked:
-1. Click one of the place icons drawn by the map. The mouse cursor turns into a pointer over the ones that can be clicked.
-2. The same panel used for a searched place appears, showing the place's name and its coordinates, and a pin is placed on it.
+1. Rest the mouse on one of the place icons drawn by the map. Its name appears above it, and the cursor turns into a pointer. The map draws these places as bare icons, so hovering is how their names are read — showing them all at once would crowd out the titles of your own markers.
+2. Click it. The same panel used for a searched place appears, showing the place's name and its coordinates, and a pin is placed on it.
3. Press _Add as marker_ to keep it. The note is created with the place's name as its title, and the icon matching the kind of place it is.
Places are read from the map data that has already been downloaded, so clicking one does not send anything to the internet.
Some things to keep in mind:
-* Places that have no name in the map data, such as benches or parking spaces, are not clickable. Clicking them does nothing, as clicking the map elsewhere.
+* Places that have no name in the map data, such as benches or parking spaces, show no name and are not clickable. Clicking them does nothing, as clicking the map elsewhere.
* The markers of the map take precedence: where one stands over a place, clicking it opens the note, not the place.
* This does not work with the raster (OpenStreetMap) style, whose places are part of the map image, nor with the _Neutrino_ style, which draws no places.
* In read-only mode a place can still be clicked and read, but not kept as a marker.