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): hold the marker preview above its pin, wherever the pin stands
Elian Dorane96e635c411f
diff --git a/apps/client/src/widgets/collections/geomap/Tooltips.spec.tsx b/apps/client/src/widgets/collections/geomap/Tooltips.spec.tsxindex eb2186c812..722e926f49 100644--- a/apps/client/src/widgets/collections/geomap/Tooltips.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/Tooltips.spec.tsx@@ -12,7 +12,7 @@ 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_HEIGHT, MARKER_LAYER, MARKER_WIDTH } from "./Markers";+import { MARKER_HEIGHT, MARKER_LAYER } from "./Markers";import Tooltips from "./Tooltips";/** What a note's preview renders to, standing in for the shared tooltip renderer. */@@ -23,18 +23,24 @@ vi.mock("../../../services/note_tooltip", () => ({ renderTooltip: (note: FNote |/*** 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.+ * the module mock below it is, and the mock is what hands the class to the component — and the+ * preview's pretended size lives with it, because the hoisted block cannot reach anything outside+ * itself.*/-const { FakePopup } = vi.hoisted(() => {+const { FakePopup, PREVIEW_WIDTH } = vi.hoisted(() => {+ /** A preview about the size the app renders one at, for the placement arithmetic below. */+ const PREVIEW_WIDTH = 500;+ const PREVIEW_HEIGHT = 120;+class FakePopup {static open: FakePopup[] = [];html = "";lngLat: unknown;element: HTMLElement | null = null;- options: { offset?: Record<string, [ number, number ]> };+ options: { anchor?: string; offset?: [ number, number ] };- constructor(options: { offset?: Record<string, [ number, number ]> }) {+ constructor(options: object) {this.options = options;}@@ -46,11 +52,20 @@ const { FakePopup } = vi.hoisted(() => {return this;}+ setOffset(offset: [ number, number ]) {+ this.options.offset = offset;+ 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;+ // The size the placement is measured against, which happy-dom's layoutless elements+ // would otherwise report as nothing at all.+ Object.defineProperty(this.element, "offsetWidth", { value: PREVIEW_WIDTH, configurable: true });+ Object.defineProperty(this.element, "offsetHeight", { value: PREVIEW_HEIGHT, configurable: true });document.body.appendChild(this.element);FakePopup.open.push(this);return this;@@ -66,13 +81,17 @@ const { FakePopup } = vi.hoisted(() => {}}- return { FakePopup };+ return { FakePopup, PREVIEW_WIDTH, PREVIEW_HEIGHT };});vi.mock("maplibre-gl", () => ({ Popup: FakePopup }));-/** A map that only delegates events — per layer or map-wide — which is all this component asks of one. */-function fakeMap() {+/**+ * A map that delegates events — per layer or map-wide — and answers the questions the placement+ * asks: where a coordinate projects to, and how big the map is. Both are settable per test, since+ * the placement is chosen from exactly those two answers and the preview's size.+ */+function fakeMap({ width = 800, height = 800, point = { x: 400, y: 300 } } = {}) {const listeners = new Map<string, Set<(e: unknown) => void>>();const key = (event: string, layer: string) => `${event}:${layer}`;// The two shapes MapLibre's `on`/`off` take: with a layer between event and listener, and without.@@ -95,6 +114,8 @@ function fakeMap() {click() {for (const fn of listeners.get(key("click", "")) ?? []) fn({});},+ project: () => ({ ...point }),+ getContainer: () => ({ clientWidth: width, clientHeight: height }),/** The pointer coming to rest on a marker, as MapLibre reports it. */hover(note: FNote) {const feature = {@@ -113,34 +134,6 @@ function fakeMap() {};}-/** A preview about the size the app renders one at, for the placement arithmetic below. */-const PREVIEW_WIDTH = 500;-const PREVIEW_HEIGHT = 120;--/** The pin, in pixels around the coordinate it stands on. */-const PIN = {- left: -MARKER_WIDTH / 2,- right: MARKER_WIDTH / 2,- top: -MARKER_HEIGHT,- bottom: 0-};--/**- * Where each of MapLibre's placements puts the preview's top-left corner before the offset is- * applied — its `anchorTranslate` table, worked out for a preview of the size above. `center` is- * left out: MapLibre's own placement logic never arrives at it.- */-const PLACEMENTS: Record<string, [ number, number ]> = {- "top": [ -PREVIEW_WIDTH / 2, 0 ],- "bottom": [ -PREVIEW_WIDTH / 2, -PREVIEW_HEIGHT ],- "left": [ 0, -PREVIEW_HEIGHT / 2 ],- "right": [ -PREVIEW_WIDTH, -PREVIEW_HEIGHT / 2 ],- "top-left": [ 0, 0 ],- "top-right": [ -PREVIEW_WIDTH, 0 ],- "bottom-left": [ 0, -PREVIEW_HEIGHT ],- "bottom-right": [ -PREVIEW_WIDTH, -PREVIEW_HEIGHT ]-};-/** Drains the promise chain in `show` (note read → preview rendered) without moving the clock. */async function flush() {await act(async () => {@@ -267,31 +260,84 @@ describe("Tooltips", () => {expect(shownPreview()).toBeUndefined();});- /**- * A pin stands on its coordinate, so every placement MapLibre can choose opens onto some part of- * it. Checked as the geometry it is rather than as a rule per axis: the first attempt cleared the- * pin's height, which reads as right until a corner placement — which spreads sideways from the- * point, not upwards — lies across half the pin anyway.+ /*+ * Placement is taken over from MapLibre (see placePreview in Tooltips): left to itself it+ * swings the preview beside a pin standing near the map's edge, vertically centred on it —+ * lying across the pin's title and reading as attached to nothing. The preview stays above+ * the pin instead and slides sideways; only a pin too near the top has it open downwards.*/- it("keeps clear of the pin wherever the map decides to put it", async () => {++ it("stands above the pin, centred on it, where there is room", async () => {const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });const map = fakeMap();await mount(map);map.hover(note);await advance(500);- const offset = FakePopup.open[0]?.options.offset;- for (const [ placement, corner ] of Object.entries(PLACEMENTS)) {- const [ offsetX, offsetY ] = offset?.[placement] ?? [ 0, 0 ];- const left = corner[0] + offsetX;- const top = corner[1] + offsetY;- const clear = left >= PIN.right || left + PREVIEW_WIDTH <= PIN.left- || top >= PIN.bottom || top + PREVIEW_HEIGHT <= PIN.top;+ const popup = FakePopup.open[0];+ expect(popup?.options.anchor).toBe("bottom");+ // Straight up, past the whole pin standing on its coordinate.+ expect(popup?.options.offset).toEqual([ 0, -(MARKER_HEIGHT + 8) ]);+ });- // Named in the assertion so a failure says which placement covers the pin.- expect(`${placement} is ${clear ? "clear of" : "over"} the pin`).toBe(`${placement} is clear of the pin`);- }+ it("slides sideways at the map's edge instead of swinging beside the pin", async () => {+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });+ // A pin forty pixels from the left edge, where MapLibre's own placement would go beside it.+ const map = fakeMap({ point: { x: 40, y: 300 } });+ await mount(map);++ map.hover(note);+ await advance(500);++ const popup = FakePopup.open[0];+ expect(popup?.options.anchor).toBe("bottom");+ // Slid right exactly far enough for the preview's left edge to stand its air off the map's:+ // half its width past the pin, less the forty pixels the pin already stands in.+ expect(popup?.options.offset).toEqual([ 8 + PREVIEW_WIDTH / 2 - 40, -(MARKER_HEIGHT + 8) ]);+ });++ it("opens below a pin standing too near the top, past its title", async () => {+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });+ const map = fakeMap({ point: { x: 400, y: 60 } });+ await mount(map);++ map.hover(note);+ await advance(500);++ const popup = FakePopup.open[0];+ expect(popup?.options.anchor).toBe("top");+ // Below the point, and below the title hanging under it too.+ expect(popup?.options.offset).toEqual([ 0, 18 + 8 ]);+ });++ it("slides out from under the detail pane while one is up", async () => {+ const selected = buildNote({ title: "Open in the pane", "#geolocation": "5,6" });+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });+ // A pin standing in the map's trailing 400 pixels, which the pane covers while it is up+ // (see PANE_REACH); a preview left there would be shown to nobody.+ const map = fakeMap({ width: 1200, point: { x: 1000, y: 300 } });+ await mount(map, selected.noteId);++ map.hover(note);+ await advance(500);++ const popup = FakePopup.open[0];+ expect(popup?.options.anchor).toBe("bottom");+ // Slid left until its right edge stands its air short of the pane, not merely of the map.+ expect(popup?.options.offset).toEqual([ (1200 - 8 - 400) - PREVIEW_WIDTH / 2 - 1000, -(MARKER_HEIGHT + 8) ]);+ });++ it("centres on the pin where the map is too narrow to slide within", async () => {+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });+ const map = fakeMap({ width: 400, point: { x: 200, y: 300 } });+ await mount(map);++ map.hover(note);+ await advance(500);++ // Overflowing both edges evenly is the best a map narrower than the preview can do.+ expect(FakePopup.open[0]?.options.offset).toEqual([ 0, -(MARKER_HEIGHT + 8) ]);});/**diff --git a/apps/client/src/widgets/collections/geomap/Tooltips.tsx b/apps/client/src/widgets/collections/geomap/Tooltips.tsxindex 0ff172020f..53ac7f7370 100644--- a/apps/client/src/widgets/collections/geomap/Tooltips.tsx+++ b/apps/client/src/widgets/collections/geomap/Tooltips.tsx@@ -1,12 +1,13 @@-import { type MapGeoJSONFeature, type MapMouseEvent, type Offset, Popup } from "maplibre-gl";+import { type Map as MapLibreGLMap, type MapGeoJSONFeature, type MapMouseEvent, Popup } from "maplibre-gl";import { useContext, useEffect } from "preact/hooks";import froca from "../../../services/froca";import { renderTooltip } from "../../../services/note_tooltip";import { sanitizeNoteContentHtml } from "../../../services/sanitize_content";import { isHtmlEmpty } from "../../../services/utils";+import { PANE_REACH } from "./DetailPane";import { ParentMap } from "./map";-import { MARKER_HEIGHT, MARKER_LAYER, MARKER_WIDTH } from "./Markers";+import { MARKER_HEIGHT, MARKER_LAYER } from "./Markers";/*** How long the pointer has to rest on a marker before its note is read.@@ -38,47 +39,23 @@ const HOVER_DELAY = 500;*/const DISMISS_DELAY = 400;-/** How much air is left between the pin and the preview, whichever side it lands on. */+/** How much air is left between the marker and the preview, whichever side it lands on. */const MARKER_GAP = 8;-/** What it takes to get past the pin sideways, and to get above it. */-const CLEAR_SIDEWAYS = MARKER_WIDTH / 2 + MARKER_GAP;-const CLEAR_ABOVE = MARKER_HEIGHT + MARKER_GAP;-/**- * Where the preview sits, for each placement MapLibre might choose.+ * What it takes to clear the marker from above and from below.*- * A pin stands on its coordinate rather than over it: everything it draws is *above* that point, and- * within half its width either side. A preview pushed away from the point by one flat distance- * therefore covers the very marker it belongs to, so each placement has to clear whichever part of- * the pin it opens onto — which is not the same part each time, and is why MapLibre asks for the- * offset per placement at all (see the `popupOffsets` example in its `Popup` documentation).- *- * What opens onto what is easy to get wrong. Placed straight above the point the preview meets the- * pin's full height, and straight below it meets nothing. But a preview placed from a *corner* has- * that corner on the point and spreads sideways from it, so what stands in its way there is the- * pin's width, not its height — clearing only the height leaves the corner placements lying across- * whichever half of the pin they open towards.+ * A pin stands on its coordinate rather than over it: the whole of it is drawn *above* that point,+ * and its title hangs *below* it (see the top-anchored text in {@link Markers}'s label layout). So+ * a preview opening upwards has the pin's height to get past, and one opening downwards has the+ * title's — a line of twelve-pixel text, cleared with a little to spare, since its exact reach is+ * the renderer's business rather than ours.*/-const PREVIEW_OFFSET: Offset = {- // Straight below the point, where the pin draws nothing.- "top": [ 0, MARKER_GAP ],- // Straight above it, with the whole pin standing in between.- "bottom": [ 0, -CLEAR_ABOVE ],- // Beside it: past the pin's width, and lifted to the middle of its height rather than left- // hanging off the tip.- "left": [ CLEAR_SIDEWAYS, -MARKER_HEIGHT / 2 ],- "right": [ -CLEAR_SIDEWAYS, -MARKER_HEIGHT / 2 ],- // From a corner, spreading sideways: past the pin's width in whichever direction it opens, and- // clear of the point itself vertically. Getting past the width is what does the work here, so- // there is no need to rise the pin's whole height as well and leave the preview stranded up in- // the air away from the marker it belongs to.- "top-left": [ CLEAR_SIDEWAYS, MARKER_GAP ],- "top-right": [ -CLEAR_SIDEWAYS, MARKER_GAP ],- "bottom-left": [ CLEAR_SIDEWAYS, -MARKER_GAP ],- "bottom-right": [ -CLEAR_SIDEWAYS, -MARKER_GAP ],- "center": [ 0, 0 ]-};+const CLEAR_ABOVE = MARKER_HEIGHT + MARKER_GAP;+const CLEAR_BELOW = 18 + MARKER_GAP;++/** Air kept between the preview and the map's edges when it is slid back inside them. */+const EDGE_PADDING = 8;/*** The preview shown while the pointer rests on a marker.@@ -109,7 +86,6 @@ export default function Tooltips({ selectedNoteId }: {const tooltip = new Popup({closeButton: false,closeOnClick: false,- offset: PREVIEW_OFFSET,// 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",@@ -151,6 +127,7 @@ export default function Tooltips({ selectedNoteId }: {.setLngLat(coordinates).setHTML(buildTooltipHtml(content)).addTo(map);+ placePreview(map, tooltip, coordinates, selectedNoteId !== null);// 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.@@ -253,6 +230,63 @@ export default function Tooltips({ selectedNoteId }: {return null;}+/**+ * Puts the preview where it covers neither the pin nor its title, taken over from MapLibre.+ *+ * Left to itself, MapLibre swings a popup *beside* its point whenever the point stands within half+ * the popup's width of the map's edge — and a preview beside a pin lies across the very marker it+ * belongs to: the pin's title hangs at the point, and the popup arrives vertically centred on it.+ * What a map application does instead is what is done here: the preview stays above the marker and+ * is *slid sideways* as far as it takes to stay on the map — and out from under the detail pane,+ * while one is up — the pin keeping its place under it.+ * Only a marker too near the top for the preview to fit above it has the preview open downwards,+ * past the title (see {@link CLEAR_BELOW}) — and a marker so hemmed in that neither fits gets the+ * upward one anyway, there being no placement left to prefer.+ *+ * Called after the popup is added, because the sliding is measured against the preview's rendered+ * size, which only mounting it can say. The correction lands in the same synchronous turn as the+ * mounting, so nothing is painted in between; and the offset it sets is read back by MapLibre on+ * every later reposition, so the preview follows its marker through any map movement.+ */+function placePreview(map: MapLibreGLMap, tooltip: Popup, coordinates: [ number, number ], paneUp: boolean) {+ const element = tooltip.getElement();+ if (!element) return;++ const { offsetWidth: width, offsetHeight: height } = element;+ const point = map.project(coordinates);+ const { clientWidth: mapWidth, clientHeight: mapHeight } = map.getContainer();++ const fitsAbove = point.y - CLEAR_ABOVE - height >= EDGE_PADDING;+ const fitsBelow = point.y + CLEAR_BELOW + height <= mapHeight - EDGE_PADDING;+ const anchor = fitsAbove || !fitsBelow ? "bottom" : "top";++ // Where the preview may stand: inside the map's edges with their due air — and short of the+ // detail pane, which covers the map's trailing side for as long as a marker is selected. A+ // preview slid under the pane would be shown to nobody. The trailing side is the left one in+ // a right-to-left app, as the pane's own arithmetic has it (see paneOffset in DetailPane).+ let nearEdge = EDGE_PADDING;+ let farEdge = mapWidth - EDGE_PADDING;+ if (paneUp) {+ if (glob.isRtl) nearEdge += PANE_REACH;+ else farEdge -= PANE_REACH;+ }++ // How far sideways the preview has to give: enough to bring whichever edge stands outside+ // that room back into it — and nothing at all where the room is too narrow to ever manage,+ // centring on the pin being the best that can then be done.+ let slide = 0;+ if (farEdge - nearEdge >= width) {+ slide = Math.max(slide, nearEdge + width / 2 - point.x);+ slide = Math.min(slide, farEdge - width / 2 - point.x);+ }++ // The anchor is an option rather than a setter, but one MapLibre reads afresh on every+ // reposition — setting it here is what its own auto-anchoring would otherwise do in the same+ // place (see `_update` in its Popup).+ tooltip.options.anchor = anchor;+ tooltip.setOffset([ slide, anchor === "bottom" ? -CLEAR_ABOVE : CLEAR_BELOW ]);+}+/*** The rendered preview, in the shape the app's tooltip styles are written against.*