Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): show a note, not just its name, when a marker is hovered

Elian Doranfbc2ac88e393
diff --git a/apps/client/src/widgets/collections/geomap/Tooltips.spec.tsx b/apps/client/src/widgets/collections/geomap/Tooltips.spec.tsx
new file mode 100644
index 0000000000..5959b6f77d
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/Tooltips.spec.tsx
@@ -0,0 +1,265 @@
+/**
+ * The marker preview, which is the app's own note tooltip drawn into a MapLibre popup.
+ *
+ * The notes are drawn into one symbol layer rather than an element apiece, so none of the tooltip
+ * service's element-hovering applies: what has to be got right here is reading the note behind the
+ * pixel under the pointer, and keeping the preview up long enough to be reached and read.
+ */
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import type FNote from "../../../entities/fnote";
+import { buildNote } from "../../../test/easy-froca";
+import { ParentMap } from "./map";
+import { MARKER_LAYER } from "./Markers";
+import Tooltips from "./Tooltips";
+
+/** What a note's preview renders to, standing in for the shared tooltip renderer. */
+const renderTooltip = vi.fn(async (note: FNote | null) =>
+ note ? `<h5 class="note-tooltip-title">${note.title}</h5><p>Body of ${note.title}</p>` : undefined);
+
+vi.mock("../../../services/note_tooltip", () => ({ renderTooltip: (note: FNote | null) => renderTooltip(note) }));
+
+/**
+ * The popup MapLibre would draw, recording what it was shown and whether it is up. Hoisted because
+ * the module mock below it is, and the mock is what hands the class to the component.
+ */
+const { FakePopup } = vi.hoisted(() => {
+ class FakePopup {
+ static open: FakePopup[] = [];
+
+ html = "";
+ lngLat: unknown;
+ element: HTMLElement | null = null;
+
+ setLngLat(lngLat: unknown) { this.lngLat = lngLat; return this; }
+
+ setHTML(html: string) {
+ this.html = html;
+ if (this.element) this.element.innerHTML = html;
+ return this;
+ }
+
+ addTo() {
+ // Rebuilt on every opening, as MapLibre rebuilds it — which is why the listeners that
+ // keep the preview open have to be bound per opening.
+ this.element = document.createElement("div");
+ this.element.innerHTML = this.html;
+ document.body.appendChild(this.element);
+ FakePopup.open.push(this);
+ return this;
+ }
+
+ getElement() { return this.element; }
+
+ remove() {
+ this.element?.remove();
+ this.element = null;
+ FakePopup.open = FakePopup.open.filter((popup) => popup !== this);
+ return this;
+ }
+ }
+
+ return { FakePopup };
+});
+
+vi.mock("maplibre-gl", () => ({ Popup: FakePopup }));
+
+/** A map that only delegates layer events, which is all this component asks of one. */
+function fakeMap() {
+ const listeners = new Map<string, Set<(e: unknown) => void>>();
+ const key = (event: string, layer: string) => `${event}:${layer}`;
+
+ return {
+ on(event: string, layer: string, fn: (e: unknown) => void) {
+ const listenersForKey = listeners.get(key(event, layer)) ?? new Set();
+ listeners.set(key(event, layer), listenersForKey.add(fn));
+ },
+ off(event: string, layer: string, fn: (e: unknown) => void) {
+ listeners.get(key(event, layer))?.delete(fn);
+ },
+ /** The pointer coming to rest on a marker, as MapLibre reports it. */
+ hover(note: FNote) {
+ const feature = {
+ geometry: { type: "Point", coordinates: [ 1, 2 ] },
+ properties: { id: note.noteId, name: note.title }
+ };
+ for (const fn of listeners.get(key("mousemove", MARKER_LAYER)) ?? []) fn({ features: [ feature ] });
+ },
+ /** The pointer leaving every marker. */
+ leave() {
+ for (const fn of listeners.get(key("mouseleave", MARKER_LAYER)) ?? []) fn({});
+ },
+ get listenerCount() {
+ return [ ...listeners.values() ].reduce((total, set) => total + set.size, 0);
+ }
+ };
+}
+
+/** Drains the promise chain in `show` (note read → preview rendered) without moving the clock. */
+async function flush() {
+ await act(async () => {
+ for (let i = 0; i < 10; i++) await Promise.resolve();
+ });
+}
+
+/** Moves the clock on and lets whatever that started finish. */
+async function advance(ms: number) {
+ await act(async () => { vi.advanceTimersByTime(ms); });
+ await flush();
+}
+
+/** The preview currently on screen, or `undefined` where there is none. */
+function shownPreview() {
+ return FakePopup.open[0]?.element?.textContent ?? undefined;
+}
+
+describe("Tooltips", () => {
+ let container: HTMLElement | undefined;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ FakePopup.open = [];
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ });
+
+ afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ vi.useRealTimers();
+ renderTooltip.mockClear();
+ });
+
+ function mount(map: ReturnType<typeof fakeMap>) {
+ return act(async () => {
+ render(
+ <ParentMap.Provider value={map as never}>
+ <Tooltips />
+ </ParentMap.Provider>,
+ container as HTMLElement
+ );
+ });
+ }
+
+ it("shows the note's preview once the pointer has rested on its marker", async () => {
+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });
+ const map = fakeMap();
+ await mount(map);
+
+ map.hover(note);
+ // A marker merely passed over is not a note worth reading.
+ await advance(200);
+ expect(shownPreview()).toBeUndefined();
+ expect(renderTooltip).not.toHaveBeenCalled();
+
+ await advance(400);
+ expect(shownPreview()).toContain("Body of Somewhere");
+ // Drawn in the shape the app's tooltip styles are written against.
+ expect(FakePopup.open[0]?.html).toContain(`class="tooltip note-tooltip show"`);
+ expect(FakePopup.open[0]?.html).toContain(`class="note-tooltip-content"`);
+ });
+
+ /**
+ * `mouseenter` fires on entering the layer, not on entering a marker, so a pointer dragged from
+ * one pin straight onto the next never leaves it — the first note's preview used to stay up over
+ * the second, which is why the move is what is watched.
+ */
+ it("swaps the preview when the pointer moves straight from one marker to another", async () => {
+ const first = buildNote({ title: "Here", "#geolocation": "1,2" });
+ const second = buildNote({ title: "There", "#geolocation": "3,4" });
+ const map = fakeMap();
+ await mount(map);
+
+ map.hover(first);
+ await advance(500);
+ expect(shownPreview()).toContain("Body of Here");
+
+ // The pointer crosses onto the second marker without ever leaving the layer.
+ map.hover(second);
+ // The first note's preview goes at once rather than standing there wrong for as long as the
+ // second takes to read.
+ await flush();
+ expect(shownPreview()).toBeUndefined();
+
+ await advance(500);
+ expect(shownPreview()).toContain("Body of There");
+ expect(FakePopup.open).toHaveLength(1);
+ });
+
+ it("stays up while the pointer is on it, and closes once the pointer leaves it", async () => {
+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });
+ const map = fakeMap();
+ await mount(map);
+
+ map.hover(note);
+ await advance(500);
+ const element = FakePopup.open[0]?.element;
+
+ // The preview sits a little away from the pin, so reaching it means leaving the marker.
+ map.leave();
+ await act(async () => { element?.dispatchEvent(new Event("mouseenter")); });
+ await advance(2000);
+ expect(shownPreview()).toContain("Body of Somewhere");
+
+ await act(async () => { element?.dispatchEvent(new Event("mouseleave")); });
+ await advance(500);
+ expect(shownPreview()).toBeUndefined();
+ });
+
+ it("closes the preview when the pointer leaves the marker without reaching it", async () => {
+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });
+ const map = fakeMap();
+ await mount(map);
+
+ map.hover(note);
+ await advance(500);
+ expect(shownPreview()).toContain("Body of Somewhere");
+
+ map.leave();
+ await advance(500);
+ expect(shownPreview()).toBeUndefined();
+ });
+
+ /** Reading a note is asynchronous, so a marker skimmed past is usually left before it lands. */
+ it("drops a preview whose marker was left before it finished rendering", async () => {
+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });
+ const map = fakeMap();
+ await mount(map);
+
+ let release: (() => void) | undefined;
+ renderTooltip.mockImplementationOnce(async () => {
+ await new Promise<void>((resolve) => { release = resolve; });
+ return "<p>Body of Somewhere</p>";
+ });
+
+ map.hover(note);
+ await advance(500);
+ expect(renderTooltip).toHaveBeenCalled();
+
+ map.leave();
+ await act(async () => { release?.(); });
+ await flush();
+
+ expect(shownPreview()).toBeUndefined();
+ });
+
+ it("takes its listeners and any open preview with it when it goes away", async () => {
+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });
+ const map = fakeMap();
+ await mount(map);
+
+ map.hover(note);
+ await advance(500);
+ expect(shownPreview()).toContain("Body of Somewhere");
+
+ await act(async () => { render(null, container as HTMLElement); });
+
+ expect(FakePopup.open).toHaveLength(0);
+ expect(map.listenerCount).toBe(0);
+ });
+});
diff --git a/apps/client/src/widgets/collections/geomap/Tooltips.tsx b/apps/client/src/widgets/collections/geomap/Tooltips.tsx
index 2b28c70238..a0e35e25b3 100644
--- a/apps/client/src/widgets/collections/geomap/Tooltips.tsx
+++ b/apps/client/src/widgets/collections/geomap/Tooltips.tsx
@@ -1,10 +1,40 @@
-import { type MapGeoJSONFeature, MapMouseEvent, Popup } from "maplibre-gl";
+import { type MapGeoJSONFeature, type MapMouseEvent, Popup } from "maplibre-gl";
import { useContext, useEffect } from "preact/hooks";
-import { escapeHtml } from "../../../services/utils";
+import froca from "../../../services/froca";
+import { renderTooltip } from "../../../services/note_tooltip";
+import { sanitizeNoteContentHtml } from "../../../services/sanitize_content";
+import { isHtmlEmpty } from "../../../services/utils";
import { ParentMap } from "./map";
import { MARKER_LAYER } from "./Markers";
+/**
+ * How long the pointer has to rest on a marker before its note is read.
+ *
+ * The same wait the tooltips everywhere else in the app make, and for the same reason: a preview is
+ * a note's content, so dragging the pointer across a crowded map would otherwise read every note it
+ * happens to brush past.
+ */
+const HOVER_DELAY = 500;
+
+/**
+ * How long the preview is left standing after the pointer leaves the marker.
+ *
+ * It is not closed at once because it is meant to be reached: the preview scrolls, carries the
+ * note's links and a quick-edit button, and sits a little away from the pin — so getting to it
+ * means crossing a gap where neither it nor the marker is under the pointer.
+ */
+const DISMISS_DELAY = 400;
+
+/**
+ * The preview shown while the pointer rests on a marker.
+ *
+ * The same preview a note link shows anywhere else in the app — title and path, attributes, the
+ * note's content and a quick-edit button — put together by the shared renderer. It is drawn into a
+ * MapLibre popup rather than by the app's tooltip service because a marker is no longer an element:
+ * the notes are drawn into one symbol layer (see {@link Markers}), and the service works by hovering
+ * elements. What the layer gives us instead is the note behind the pixel under the pointer.
+ */
export default function Tooltips() {
const map = useContext(ParentMap);
@@ -15,31 +45,132 @@ export default function Tooltips() {
closeButton: false,
closeOnClick: false,
offset: 12,
+ // The preview brings its own width — `.tooltip-inner` caps it at 500px — and MapLibre's
+ // 240px default would squeeze a note's content into a column half that wide.
+ maxWidth: "none",
+ // Otherwise MapLibre puts the caret on the first link in the preview the moment it
+ // opens, so merely passing the pointer over a marker takes the focus out of whatever
+ // the user was actually typing in.
+ focusAfterOpen: false,
className: "marker-tooltip"
});
- function onMouseEnter(e: MapMouseEvent & { features?: MapGeoJSONFeature[]; }) {
- const feature = e.features?.[0];
- if (!feature || !map || feature.geometry.type !== "Point") return;
+ // The note under the pointer, which is not necessarily the one the preview shows: reading a
+ // note and rendering it is asynchronous, and a marker only skimmed past has usually been
+ // left again by the time its preview is ready.
+ let hovered: string | null = null;
+ let shown: string | null = null;
+ // Whether the pointer is on the preview itself, which is what keeps it open.
+ let onTooltip = false;
+ let showTimer: ReturnType<typeof setTimeout> | undefined;
+ let dismissTimer: ReturnType<typeof setTimeout> | undefined;
+ async function show(noteId: string, coordinates: [ number, number ]) {
+ const note = await froca.getNote(noteId);
+ const content = await renderTooltip(note);
+ // A note with no content and no path renders to nothing, and the pointer may well have
+ // moved on to another marker while this one was being read.
+ if (!map || hovered !== noteId || !content || isHtmlEmpty(content)) return;
+
+ shown = noteId;
tooltip
- .setLngLat(feature.geometry.coordinates as [ number, number ])
- .setHTML(`<strong>${escapeHtml(feature.properties.name)}</strong>`)
+ .setLngLat(coordinates)
+ .setHTML(buildTooltipHtml(content))
.addTo(map);
+
+ // The popup builds its element afresh every time it is added to a map, so what keeps it
+ // open while the pointer is on it has to be bound per opening rather than once.
+ const element = tooltip.getElement();
+ element?.addEventListener("mouseenter", onTooltipEnter);
+ element?.addEventListener("mouseleave", onTooltipLeave);
}
- function onMouseLeave() {
+ function hide() {
+ clearTimeout(showTimer);
+ shown = null;
+ onTooltip = false;
tooltip.remove();
}
- map.on("mouseenter", MARKER_LAYER, onMouseEnter);
+ /**
+ * Closes the preview unless the pointer has landed on it — or on another marker — by the
+ * time this runs.
+ */
+ function scheduleDismiss() {
+ clearTimeout(dismissTimer);
+ dismissTimer = setTimeout(() => {
+ if (!hovered && !onTooltip) hide();
+ }, DISMISS_DELAY);
+ }
+
+ function onMouseMove(e: MapMouseEvent & { features?: MapGeoJSONFeature[]; }) {
+ const feature = e.features?.[0];
+ if (!feature || feature.geometry.type !== "Point") return;
+
+ const noteId = String(feature.properties.id);
+ // Watched by the move rather than by `mouseenter`, which fires on entering the layer and
+ // not on entering a marker: dragging the pointer from one pin straight onto the next
+ // never leaves the layer, so the first note's preview would stay up over the second.
+ if (noteId === hovered) return;
+
+ hovered = noteId;
+ clearTimeout(showTimer);
+ // Whatever is up belongs to the marker just left, so it goes now rather than standing
+ // there wrong for as long as the new one takes to read.
+ if (shown && shown !== noteId) hide();
+
+ const coordinates = feature.geometry.coordinates as [ number, number ];
+ showTimer = setTimeout(() => show(noteId, coordinates), HOVER_DELAY);
+ }
+
+ function onMouseLeave() {
+ hovered = null;
+ clearTimeout(showTimer);
+ scheduleDismiss();
+ }
+
+ function onTooltipEnter() {
+ onTooltip = true;
+ clearTimeout(dismissTimer);
+ }
+
+ function onTooltipLeave() {
+ onTooltip = false;
+ scheduleDismiss();
+ }
+
+ map.on("mousemove", MARKER_LAYER, onMouseMove);
map.on("mouseleave", MARKER_LAYER, onMouseLeave);
return () => {
- map.off("mouseenter", MARKER_LAYER, onMouseEnter);
+ clearTimeout(showTimer);
+ clearTimeout(dismissTimer);
+ map.off("mousemove", MARKER_LAYER, onMouseMove);
map.off("mouseleave", MARKER_LAYER, onMouseLeave);
+ tooltip.remove();
};
}, [ map ]);
return null;
}
+
+/**
+ * The rendered preview, in the shape the app's tooltip styles are written against.
+ *
+ * Those styles reach all the way down from `.tooltip.note-tooltip > .tooltip-inner`, so a preview
+ * drawn outside Bootstrap has to put that shape on by hand or it inherits none of them — including
+ * everything the theme says about the title, the attribute line and the quick-edit button. `show`
+ * stands in for the class Bootstrap adds when it reveals a tooltip, without which the preview would
+ * be rendered at zero opacity.
+ *
+ * The content is sanitized because a note's HTML reaches the client through paths CKEditor never
+ * saw — the internal API, ETAPI and sync — exactly as the tooltip service sanitizes it.
+ */
+function buildTooltipHtml(content: string) {
+ return `\
+<div class="tooltip note-tooltip show" role="tooltip">
+ <div class="tooltip-inner">
+ <div class="note-tooltip-content">${sanitizeNoteContentHtml(content)}</div>
+ </div>
+</div>`;
+}
diff --git a/apps/client/src/widgets/collections/geomap/index.css b/apps/client/src/widgets/collections/geomap/index.css
index 6fe1c6197e..cbe037b87c 100644
--- a/apps/client/src/widgets/collections/geomap/index.css
+++ b/apps/client/src/widgets/collections/geomap/index.css
@@ -23,6 +23,29 @@
cursor: crosshair;
}
+/* The marker preview is the app's own note tooltip (see Tooltips), so the popup around it is taken
+ back to nothing — otherwise the tooltip, chrome and all, would sit inside a second box of
+ MapLibre's own, white on every theme and with its own padding, corners and shadow. */
+.marker-tooltip .maplibregl-popup-content {
+ padding: 0;
+ background: none;
+ border-radius: 0;
+ box-shadow: none;
+}
+
+/* Drawn in a hard white by MapLibre, and the tooltip it would point at hides its own arrow anyway. */
+.marker-tooltip .maplibregl-popup-tip {
+ display: none;
+}
+
+/* Bootstrap positions a tooltip absolutely, which here would take the preview out of the popup's
+ flow and collapse the box the popup is sized and placed by — MapLibre already places it. Still
+ positioned, though, so that the quick-edit button, which is pinned to the corner of the tooltip,
+ still has that tooltip to be pinned to. */
+.marker-tooltip .tooltip {
+ position: relative;
+}
+
/* No `position` here: MapLibre positions markers itself with `.maplibregl-marker`'s
`position: absolute` + a transform, and this more specific selector would override it back to
`relative`, dropping every marker into the canvas container's normal flow — each one then sits