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
feat(geomap): display a simple tooltip for shapes
Elian Doranc9ad0c4ecb9e
diff --git a/apps/client/src/widgets/collections/geomap/Pois.tsx b/apps/client/src/widgets/collections/geomap/Pois.tsxindex dcacde56ad..0271839bda 100644--- a/apps/client/src/widgets/collections/geomap/Pois.tsx+++ b/apps/client/src/widgets/collections/geomap/Pois.tsx@@ -1,11 +1,10 @@-import "./Pois.css";--import { type AllPaintProperties, type ExpressionSpecification, type InterpolationSpecification, type Map as MapLibreGLMap, type MapGeoJSONFeature, type MapMouseEvent, Popup } from "maplibre-gl";+import { type AllPaintProperties, type ExpressionSpecification, type InterpolationSpecification, type Map as MapLibreGLMap, type MapGeoJSONFeature, type MapMouseEvent } from "maplibre-gl";import { useContext, useEffect } from "preact/hooks";import { CLUSTER_LAYERS } from "./clusters";import type { GeoSearchResult } from "./geocoding";import { trackHitLayers } from "./GpxTrack";+import { useHoverName } from "./hover_name";import { MapStyleLoaded, ParentMap } from "./map";import { isLocationDot } from "./MapToolbar";import { MARKER_LAYER } from "./Markers";@@ -28,18 +27,6 @@ const MIN_POI_ZOOM = 17;*/const CLICKABLE_OPACITY = 0.95;-/**- * 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.@@ -113,115 +100,23 @@ export default function Pois({ placing, onPick }: PoisProps) {* 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; };-- 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;+ useHoverName(parentMap, {+ disabled: placing,+ layers: poiLayers,+ answer: (e) => {+ // A marker, a cluster, a track or a drawn shape stands above the base map, and owns the+ // pointer along with the click while it does.+ if (!parentMap || parentMap.getZoom() < MIN_POI_ZOOM || isOwnUnderPointer(parentMap, e.point)) {+ return "deferred";}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);- }+ // A place with no name answers no click either, so the pointer offers none.+ if (!place) return null;- function onMouseLeave() {- hovered = null;- setCursor("");- hide();+ return { id: place.id, lngLat: [ place.lng, place.lat ], icon: place.icon, text: place.name };}-- /**- * 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() {- if (bound.length) {- map.off("mousemove", bound, onMouseMove);- map.off("mouseleave", bound, onMouseLeave);- }- bound = [];- }-- function bind() {- unbind();- bound = poiLayers(map);- 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("");- };- }, [ parentMap, placing, styleLoaded ]);+ });/*** Draws the places that answer a click in the colour a place is pinned in, so which of them do@@ -455,21 +350,3 @@ function readRamp(value: unknown) {return { stops: read, interpolation };}-/** 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/client/src/widgets/collections/geomap/ShapeLayer.spec.tsx b/apps/client/src/widgets/collections/geomap/ShapeLayer.spec.tsxindex 7d7b9ab0d6..c557064038 100644--- a/apps/client/src/widgets/collections/geomap/ShapeLayer.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/ShapeLayer.spec.tsx@@ -1,15 +1,43 @@/*** The hand-drawn shape (see ShapeLayer.tsx): that it goes onto a loaded style and not before, that* a line is a stroke alone while an area wears a wash under the same stroke, that it is put back- * after a style switch wipes the map, and that it leaves nothing behind when it goes.+ * after a style switch wipes the map, and that it leaves nothing behind when it goes. Then the name+ * a shape answers a hover with, which is the only thing on the map that says what it is.*/import { render } from "preact";import { act } from "preact/test-utils";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { buildNote } from "../../../test/easy-froca";import type { GeoShape } from "./shapes";-import { shapeHitLayers, ShapeLayer, shapeSourceId } from "./ShapeLayer";+import { shapeHitLayers, ShapeLayer, ShapeNames, shapeSourceId } from "./ShapeLayer";import { MapStyleLoaded, ParentMap } from "./map";+import { MARKER_LAYER } from "./Markers";++/** The popup MapLibre would draw, recording what it was shown and whether it is up. */+const { FakePopup } = vi.hoisted(() => {+ class FakePopup {+ static open: FakePopup[] = [];++ content: HTMLElement | null = null;++ setLngLat() { 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 };+});++// map.ts reaches for these at load; only the popup is exercised here.+vi.mock("maplibre-gl", () => ({ GeolocateControl: class {}, Popup: FakePopup, setWorkerUrl: vi.fn() }));/*** A map as MapLibre behaves, in the one respect that matters here: a source or a layer can only be@@ -203,3 +231,151 @@ describe("ShapeLayer", () => {expect(map.layers.has(`shape-stroke-${NOTE_ID}`)).toBe(true);});});++/**+ * A map that reports what is under the pointer and takes listeners bound to named layers, which is+ * what a hover is read through (see `useHoverName`).+ */+function hoverMap(shapeLayers = [ `shape-hit-${NOTE_ID}` ]) {+ const listeners = new Map<string, Set<(e?: unknown) => void>>();+ const canvas = { style: { cursor: "" } };+ let layers = shapeLayers;+ let marker: string | null = null;+ let shape: string | null = NOTE_ID;++ function fire(key: string, event?: unknown) {+ for (const fn of listeners.get(key) ?? []) fn(event);+ }++ return {+ get cursor() { return canvas.style.cursor; },+ /** The pointer another layer's own hover has set, which this one must not clear. */+ setCursor(cursor: string) { canvas.style.cursor = cursor; },+ /** Which of the map's notes the pointer is really over, the marker being the smaller target. */+ setUnderPointer({ markerNoteId = null as string | null, shapeNoteId = null as string | null }) {+ marker = markerNoteId;+ shape = shapeNoteId;+ },+ /** A shape drawn while the map is up, which MapLibre announces as a change to the style. */+ addShapeLayer(id: string) {+ layers = [ ...layers, id ];+ fire("styledata");+ },+ /** The layers the pointer is currently watched on. */+ boundLayers() {+ return [ ...listeners.keys() ]+ .filter((key) => key.startsWith("mousemove:") && (listeners.get(key)?.size ?? 0) > 0)+ .flatMap((key) => key.slice("mousemove:".length).split(",").filter(Boolean));+ },+ /** The pointer coming to rest, as MapLibre reports it to a layer-bound listener. */+ hover() {+ for (const key of [ ...listeners.keys() ].filter((k) => k.startsWith("mousemove:"))) {+ fire(key, { point: { x: 10, y: 20 }, lngLat: { lng: 24.13, lat: 45.79 } });+ }+ },+ click() { fire("click"); },+ on(event: string, fnOrLayers: unknown, fn?: (e?: unknown) => void) {+ const key = fn ? `${event}:${fnOrLayers}` : event;+ if (!listeners.has(key)) listeners.set(key, new Set());+ listeners.get(key)?.add((fn ?? fnOrLayers) as (e?: unknown) => void);+ },+ off(event: string, fnOrLayers: unknown, fn?: (e?: unknown) => void) {+ listeners.get(fn ? `${event}:${fnOrLayers}` : event)?.delete((fn ?? fnOrLayers) as () => void);+ },+ getLayersOrder: () => layers,+ getCanvas: () => canvas,+ queryRenderedFeatures(_point: unknown, { layers: queried }: { layers: string[] }) {+ if (queried.includes(MARKER_LAYER)) {+ return marker ? [ { properties: { id: marker }, layer: { id: MARKER_LAYER } } ] : [];+ }+ return shape && queried.length+ ? [ { properties: { id: shape }, layer: { id: queried[0] } } ]+ : [];+ }+ };+}++describe("ShapeNames", () => {+ /** Long enough for the rest the name is held back for, whatever that rest is set to. */+ const RESTED = 500;+ let container: HTMLElement;++ beforeEach(() => {+ vi.useFakeTimers();+ FakePopup.open = [];+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ vi.useRealTimers();+ });++ function renderNames(map: ReturnType<typeof hoverMap>) {+ act(() => {+ render(+ <ParentMap.Provider value={map as never}>+ <ShapeNames />+ </ParentMap.Provider>,+ container+ );+ });+ }++ /** What the name currently reads, or `null` where none is up. */+ function nameText() {+ return FakePopup.open[0]?.content?.textContent ?? null;+ }++ it("names the shape the pointer has come to rest on", () => {+ buildNote({ id: NOTE_ID, title: "The lot", "#geoShape": "polygon:45.79,24.13 45.81,24.16 45.89,24.08" });+ const map = hoverMap();+ renderNames(map);++ map.hover();+ // Not while the pointer is merely passing over it.+ expect(nameText()).toBeNull();++ vi.advanceTimersByTime(RESTED);+ expect(nameText()).toBe("The lot");+ expect(map.cursor).toBe("pointer");++ // A click is always something being done, whose result the name would otherwise stand over.+ act(() => map.click());+ expect(nameText()).toBeNull();+ });++ /**+ * A pin standing inside a polygon is the smaller target and the one a click means, and it sets+ * a pointer of its own — so the shape neither names itself nor clears what the marker has set.+ */+ it("says nothing while a marker standing on the shape is what the pointer is on", () => {+ buildNote({ id: NOTE_ID, title: "The lot", "#geoShape": "polygon:45.79,24.13 45.81,24.16 45.89,24.08" });+ buildNote({ id: "markerNoteId1", title: "The well", "#geolocation": "45.8,24.14" });+ const map = hoverMap();+ renderNames(map);+ map.setUnderPointer({ markerNoteId: "markerNoteId1", shapeNoteId: NOTE_ID });+ // The pointer the marker's own hover has just set (see Markers).+ map.setCursor("pointer");++ map.hover();+ vi.advanceTimersByTime(RESTED);++ // Neither the shape's name nor the marker's: the marker answers for itself.+ expect(nameText()).toBeNull();+ expect(map.cursor).toBe("pointer");+ });++ /** A shape drawn while the map is up adds a layer, which nothing was watching until now. */+ it("watches a shape drawn after it was bound", () => {+ const map = hoverMap();+ renderNames(map);++ expect(map.boundLayers()).toEqual([ `shape-hit-${NOTE_ID}` ]);++ act(() => map.addShapeLayer("shape-fill-shapeNoteId2"));+ expect(map.boundLayers()).toEqual([ `shape-hit-${NOTE_ID}`, "shape-fill-shapeNoteId2" ]);+ });+});diff --git a/apps/client/src/widgets/collections/geomap/ShapeLayer.tsx b/apps/client/src/widgets/collections/geomap/ShapeLayer.tsxindex 04541fdaa5..a8ed3eedc8 100644--- a/apps/client/src/widgets/collections/geomap/ShapeLayer.tsx+++ b/apps/client/src/widgets/collections/geomap/ShapeLayer.tsx@@ -1,7 +1,9 @@import type { MapGeoJSONFeature, Map as MapLibreGLMap, Point } from "maplibre-gl";import { useContext, useEffect } from "preact/hooks";+import froca from "../../../services/froca";import { trackHitLayers } from "./GpxTrack";+import { useHoverName } from "./hover_name";import { MapStyleLoaded, ParentMap } from "./map";import { MARKER_LAYER } from "./Markers";import { circleRing, closeRing, type GeoShape, serializeGeoShape } from "./shapes";@@ -161,6 +163,50 @@ export function ShapeLayer({ noteId, shape, color }: ShapeLayerProps) {return <div />;}+/**+ * The name of the drawn shape under the pointer, shown once the pointer has rested on it.+ *+ * A shape carries nothing on the map to say what it is: a marker's title hangs under its pin and a+ * track's is written along its line, but a shape is drawn bare. Named on hover rather than labelled+ * outright, which is how the base map's places are named as well (see Pois) — a title written across+ * every shape would set the stock name of each unnamed one against the map, and a name over an area+ * covers the very thing it names.+ *+ * Mounted once for the whole map rather than once per shape, every shape's layers being watched in+ * the one binding.+ */+export function ShapeNames() {+ const map = useContext(ParentMap);++ useHoverName(map, {+ layers: shapeHitLayers,+ answer: (e) => {+ if (!map) return null;++ // A marker or a track standing on the shape is the smaller target and the one a click+ // means (see featureAt), and it sets a pointer of its own — so the shape says nothing+ // while one of them is what the pointer is really on.+ const feature = featureAt(map, e.point);+ if (!feature) return null;+ if (!isShapeFeature(feature)) return "deferred";++ const note = froca.getNoteFromCache(String(feature.properties.id));+ if (!note) return null;++ return {+ id: note.noteId,+ // Where the pointer came to rest, an area having no one point to stand at. Held+ // there while the pointer stays on the same shape rather than following it.+ lngLat: [ e.lngLat.lng, e.lngLat.lat ],+ icon: note.getIcon(),+ text: note.title+ };+ }+ });++ return null;+}+/*** The one source a shape's layers draw from, named for whoever needs to read the shape back off* the map — as a track's is (see `trackSourceId`).@@ -193,3 +239,8 @@ export function featureAt(map: MapLibreGLMap, point: Point): MapGeoJSONFeature |return map.queryRenderedFeatures(point, { layers: [ MARKER_LAYER, ...trackHitLayers(map) ] })[0]?? map.queryRenderedFeatures(point, { layers: shapeHitLayers(map) })[0];}++/** Whether {@link featureAt} answered with a shape rather than with a marker or a track. */+function isShapeFeature(feature: MapGeoJSONFeature) {+ return feature.layer.id.startsWith(HIT_LAYER_PREFIX) || feature.layer.id.startsWith(FILL_LAYER_PREFIX);+}diff --git a/apps/client/src/widgets/collections/geomap/Pois.css b/apps/client/src/widgets/collections/geomap/hover_name.csssimilarity index 55%rename from apps/client/src/widgets/collections/geomap/Pois.cssrename to apps/client/src/widgets/collections/geomap/hover_name.cssindex 0a34fd9860..ebfb70551f 100644--- a/apps/client/src/widgets/collections/geomap/Pois.css+++ b/apps/client/src/widgets/collections/geomap/hover_name.css@@ -1,7 +1,8 @@-/* 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 {+/* The name of whatever the pointer is resting on — a place of the base map, a drawn shape (see+ hover_name.ts). 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 .geo-hover-name .maplibregl-popup-content {padding: var(--tooltip-padding, 4px 9px);border-radius: var(--tooltip-border-radius, 5px);background: var(--tooltip-background-color);@@ -10,16 +11,17 @@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. */+ /* A name is read, not reached: left under the pointer it would take the click of the very+ thing it names. */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 {+.geo-map-container .geo-hover-name .maplibregl-popup-tip {display: none;}-.geo-map-container .place-tooltip .place-tooltip-label {+.geo-map-container .geo-hover-name .geo-hover-name-label {display: flex;align-items: center;gap: 5px;diff --git a/apps/client/src/widgets/collections/geomap/hover_name.ts b/apps/client/src/widgets/collections/geomap/hover_name.tsnew file mode 100644index 0000000000..bfe2a43db4--- /dev/null+++ b/apps/client/src/widgets/collections/geomap/hover_name.ts@@ -0,0 +1,191 @@+import "./hover_name.css";++import {+ type Map as MapLibreGLMap, type MapGeoJSONFeature, type MapMouseEvent, Popup+} from "maplibre-gl";+import { useEffect, useRef } from "preact/hooks";++/**+ * How long the pointer has to rest on something before its name is shown.+ *+ * Shorter than the wait a marker's preview sits out, that one reading a note from the server while+ * these names are already in hand — but long enough that sweeping the pointer across a crowded+ * map does not name everything on the way past.+ */+const REST_DELAY = 200;++/** How far the name stands off what it names, be that a place's icon or the pointer itself. */+const NAME_OFFSET = 10;++/** A name to show, and with it the pointer saying the thing under it answers a click. */+export interface HoverName {+ /** Tells one thing from the next, so the pointer crossing between them replaces the name. */+ id: string;+ /** Where the name stands. */+ lngLat: [number, number];+ /** The boxicons classes of the mark beside the name, where the thing wears one. */+ icon?: string | null;+ text: string;+}++/**+ * What the pointer is resting on: a name to show, nothing at all, or something drawn above that+ * answers for it. The last is not the same as nothing — whatever stands above has set its own+ * cursor, so this leaves the cursor alone rather than clearing what that has just set.+ */+export type HoverAnswer = HoverName | null | "deferred";++interface HoverNameOptions {+ /** The layers the pointer is watched on, read afresh whenever the style changes. */+ layers: (map: MapLibreGLMap) => string[];+ /** What the pointer is resting on, given the features those layers reported under it. */+ answer: (e: MapMouseEvent & { features?: MapGeoJSONFeature[] }) => HoverAnswer;+ /** Held off entirely, for a map busy with something the pointer means instead. */+ disabled?: boolean;+}++/**+ * The name of the thing under the pointer, shown in a small popup once the pointer has rested.+ *+ * What every hovered name over this map has in common, the caller saying only which layers to watch+ * and what it finds there: the base map's places (see Pois) and the shapes drawn onto it (see+ * ShapeLayer). Both are named from something already in hand, so neither waits on the server the+ * way a marker's preview does (see Tooltips).+ *+ * The name is put away on a click, whatever the click was for, and does not come back until the+ * pointer has left and returned — a click is always something being done, whose result the name+ * would otherwise stand over.+ */+export function useHoverName(+ parentMap: MapLibreGLMap | null, { layers, answer, disabled }: HoverNameOptions) {+ // Read through a ref so a caller can hand over plain arrows without the handlers being bound+ // again on every render.+ const latest = useRef({ layers, answer });+ latest.current = { layers, answer };++ useEffect(() => {+ if (!parentMap || disabled) return;+ // Aliased so the narrowing above carries into the functions below.+ const map = parentMap;++ const popup = 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: NAME_OFFSET,+ className: "geo-hover-name"+ });++ let bound: string[] = [];+ /** What the name belongs to, or what the last click was on until the pointer leaves it. */+ let named: string | null = null;+ let showTimer: ReturnType<typeof setTimeout> | undefined;++ const setCursor = (cursor: string) => { map.getCanvas().style.cursor = cursor; };++ function hide() {+ clearTimeout(showTimer);+ popup.remove();+ }++ function onMouseMove(e: MapMouseEvent & { features?: MapGeoJSONFeature[] }) {+ const answered = latest.current.answer(e);++ if (answered === "deferred") {+ named = null;+ hide();+ return;+ }++ if (!answered) {+ named = null;+ setCursor("");+ hide();+ return;+ }++ setCursor("pointer");+ // Watched by the move rather than by `mouseenter`, which fires on entering the layer+ // rather than the thing: the pointer crossing from one to the next never leaves the+ // layer, and the first name would stay up over the second.+ if (answered.id === named) return;++ named = answered.id;+ hide();+ showTimer = setTimeout(() => {+ popup.setLngLat(answered.lngLat).setDOMContent(nameLabel(answered)).addTo(map);+ }, REST_DELAY);+ }++ function onMouseLeave() {+ named = null;+ setCursor("");+ hide();+ }++ function unbind() {+ if (bound.length) {+ map.off("mousemove", bound, onMouseMove);+ map.off("mouseleave", bound, onMouseLeave);+ }+ bound = [];+ }++ function bind() {+ const wanted = latest.current.layers(map);+ if (wanted.length === bound.length && wanted.every((id, i) => id === bound[i])) return;++ unbind();+ bound = wanted;+ if (bound.length) {+ map.on("mousemove", bound, onMouseMove);+ map.on("mouseleave", bound, onMouseLeave);+ }+ }++ bind();+ // Two ways the layers under the pointer change: a style switch replaces every one of them,+ // and a layer added or taken away within a style, a shape drawn or removed, changes which+ // of them there are. `bind` does nothing where they turn out to be the same, so the second,+ // which MapLibre reports freely, costs a comparison.+ map.on("style.load", bind);+ map.on("styledata", bind);+ // `named` is left standing rather than cleared, which is what keeps the name from coming+ // back over whatever the click has just opened: the thing under the pointer stays the one+ // already named until the pointer leaves it.+ map.on("click", hide);++ return () => {+ map.off("style.load", bind);+ map.off("styledata", bind);+ map.off("click", hide);+ unbind();+ hide();+ // The pointer is put back by hand, since this can be torn down while it sits on+ // something and the `mouseleave` that would have cleared it is no longer listened for.+ setCursor("");+ };+ }, [ parentMap, disabled ]);+}++/** The name as it is shown: the mark the thing wears, where it wears one, and what it is called. */+function nameLabel({ icon, text }: HoverName) {+ const label = document.createElement("span");+ label.className = "geo-hover-name-label";++ if (icon) {+ const mark = document.createElement("i");+ mark.className = icon;+ label.appendChild(mark);+ }++ const name = document.createElement("span");+ // A place is named by whatever OpenStreetMap holds and a shape by its note's title, neither of+ // which is ours to read as markup.+ name.textContent = text;+ label.appendChild(name);++ return label;+}diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsxindex 64adbf9b89..4dc671e0dc 100644--- a/apps/client/src/widgets/collections/geomap/index.tsx+++ b/apps/client/src/widgets/collections/geomap/index.tsx@@ -34,7 +34,7 @@ import Pois from "./Pois";import ResultNavigator from "./ResultNavigator";import { NOTE_ZOOM, type SearchResult } from "./results";import SearchBox from "./SearchBox";-import { ShapeLayer } from "./ShapeLayer";+import { ShapeLayer, ShapeNames } from "./ShapeLayer";import { GeoShape, parseGeoShape, SHAPE_ATTRIBUTE } from "./shapes";import Tooltips from "./Tooltips";@@ -479,6 +479,8 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM<Markers notes={notes} hideLabels={hideLabels} isDarkTheme={layerData.isDarkTheme ?? false} clustered={clustered} placing={!!placement} opensNotes={false} selectedNoteId={selection?.noteId ?? null} />{notes.map(note => <NoteGpxTrackWrapper key={note.noteId} note={note} hideLabels={hideLabels} isDarkTheme={layerData.isDarkTheme ?? false} />)}{notes.map(note => <NoteShapeWrapper key={note.noteId} note={note} />)}+ {/* One binding for every shape's layers, rather than one per shape (see ShapeNames). */}+ <ShapeNames /><FitToNotes notes={notes} enabled={!viewConfig?.view} /></Map>}</div>