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): preview the pin under the pointer while a place is being pointed out
Elian Doran10da4f17917d
diff --git a/apps/client/src/widgets/collections/geomap/GhostPin.css b/apps/client/src/widgets/collections/geomap/GhostPin.cssnew file mode 100644index 0000000000..0432f8d91a--- /dev/null+++ b/apps/client/src/widgets/collections/geomap/GhostPin.css@@ -0,0 +1,36 @@+/*+ * The translucent pin that follows the pointer while the map is waiting to be told a place (see+ * GhostPin.tsx). It stands at the container's origin and is carried to the pointer by a transform+ * the component writes, so nothing here says where it is — only what it looks like.+ */+.geo-map-container .geo-ghost-pin {+ position: absolute;+ top: 0;+ /* `left` whatever the writing direction: the transform carries pixel offsets measured from the+ left edge, which is where MapLibre measures a point from. */+ left: 0;+ /* Over the map and its control corners (2), under the toolbar and the detail pane (3): the+ ghost is part of the map's picture, not of the furniture standing over it. */+ z-index: 2;+ /* The click this pin previews has to fall through it onto the canvas — which is also what keeps+ the crosshair up, the cursor being the canvas container's to say (see index.css). */+ pointer-events: none;+ opacity: 0;+ transition: opacity 120ms ease;+}++.geo-map-container .geo-ghost-pin.visible {+ /* Present enough to be read, translucent enough to read as an offer rather than a marker. */+ opacity: 0.6;+}++.geo-map-container .geo-ghost-pin img {+ display: block;+ /* The canvas drawMarkerImage draws, in CSS pixels: the pin plus the room left around it for its+ shadow. Must agree with MARKER_WIDTH, MARKER_HEIGHT and MARKER_SHADOW_PADDING (Markers.tsx). */+ width: 37px;+ height: 53px;+ /* The tip of the pin is what stands on the pointer, and it sits a shadow-padding's height above+ the image's bottom edge — the same correction the symbol layer applies (see `icon-offset`). */+ transform: translate(-50%, calc(-100% + 6px));+}diff --git a/apps/client/src/widgets/collections/geomap/GhostPin.spec.tsx b/apps/client/src/widgets/collections/geomap/GhostPin.spec.tsxnew file mode 100644index 0000000000..aced8ccaec--- /dev/null+++ b/apps/client/src/widgets/collections/geomap/GhostPin.spec.tsx@@ -0,0 +1,160 @@+/**+ * The ghost pin that follows the pointer while the map is armed for placement (see GhostPin.tsx):+ * a translucent copy of the very pin the click will produce, so the map shows what it is offering+ * before it is taken up on it.+ */+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 GhostPin from "./GhostPin";+import { ParentMap } from "./map";+import { DEFAULT_MARKER_COLOR } from "./Markers";++vi.mock("../../../services/icon_glyphs", () => ({+ renderIconImage: vi.fn(async () => "data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=")+}));++/** A map that hands out pointer events, which is all the ghost asks of one. */+function fakeMap() {+ const listeners = new Map<string, Set<(e?: unknown) => void>>();+ return {+ on(event: string, fn: (e?: unknown) => void) {+ if (!listeners.has(event)) listeners.set(event, new Set());+ listeners.get(event)?.add(fn);+ },+ off(event: string, fn: (e?: unknown) => void) {+ listeners.get(event)?.delete(fn);+ },+ listenerCount(event: string) {+ return listeners.get(event)?.size ?? 0;+ },+ /** The pointer moving across the map, as MapLibre reports it. */+ moveTo(x: number, y: number) {+ for (const fn of listeners.get("mousemove") ?? []) fn({ point: { x, y } });+ },+ /** The pointer leaving the canvas — for the edge of the map or anything standing over it. */+ leave() {+ for (const fn of listeners.get("mouseout") ?? []) fn();+ }+ };+}++describe("GhostPin", () => {+ let container: HTMLElement | undefined;+ /** What the pin was last drawn from, captured on its way to becoming an image. */+ let lastSvgBlob: Blob | undefined;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ lastSvgBlob = undefined;++ // The pin is drawn by handing an SVG blob to an <img> and waiting for it to load, which no+ // DOM stand-in actually does — but here the image also has to be a real element, since the+ // ghost puts it in the document.+ vi.stubGlobal("Image", function ImageStub() {+ const image = document.createElement("img");+ Object.defineProperty(image, "src", {+ set: () => { setTimeout(() => image.onload?.(new Event("load"))); }+ });+ return image;+ });+ vi.stubGlobal("URL", {+ ...URL,+ createObjectURL: (blob: Blob) => {+ lastSvgBlob = blob;+ return "blob:pin";+ },+ revokeObjectURL: () => {}+ });+ });++ afterEach(() => {+ if (container) {+ render(null, container);+ container.remove();+ container = undefined;+ }+ vi.unstubAllGlobals();+ });++ function mount(map: ReturnType<typeof fakeMap>, note?: FNote) {+ return act(async () => {+ render(+ <ParentMap.Provider value={map as never}>+ <GhostPin note={note} />+ </ParentMap.Provider>,+ container as HTMLElement+ );+ });+ }++ /** Drains the awaits in drawMarkerImage (icon render → svg decode). */+ async function settle() {+ for (let i = 0; i < 20; i++) await new Promise((resolve) => setTimeout(resolve));+ }++ it("waits for the pointer, rides under it, and goes when it leaves the map", async () => {+ const map = fakeMap();+ await mount(map);++ // Hidden at first: the map does not say where the pointer is until it moves.+ const ghost = container?.querySelector<HTMLElement>(".geo-ghost-pin");+ expect(ghost).toBeTruthy();+ expect(ghost?.classList.contains("visible")).toBe(false);++ map.moveTo(40, 60);+ expect(ghost?.classList.contains("visible")).toBe(true);+ expect(ghost?.style.transform).toBe("translate(40px, 60px)");++ map.moveTo(41, 61);+ expect(ghost?.style.transform).toBe("translate(41px, 61px)");++ map.leave();+ expect(ghost?.classList.contains("visible")).toBe(false);+ });++ it("wears the pin a new note will be given", async () => {+ const { renderIconImage } = await import("../../../services/icon_glyphs");+ const map = fakeMap();++ await mount(map);+ await act(async () => { await settle(); });++ // The image the symbol layer would stamp, in the colour and icon a created note gets.+ expect(container?.querySelector(".geo-ghost-pin img")).toBeTruthy();+ expect(renderIconImage).toHaveBeenCalledWith("bx bx-pin", expect.anything());+ expect(await lastSvgBlob?.text()).toContain(`fill="${DEFAULT_MARKER_COLOR}"`);+ });++ it("wears the moved note's own colour and icon", async () => {+ const { renderIconImage } = await import("../../../services/icon_glyphs");+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2", "#color": "red", "#iconClass": "bx bx-star" });+ const map = fakeMap();++ await mount(map, note);+ await act(async () => { await settle(); });++ expect(container?.querySelector(".geo-ghost-pin img")).toBeTruthy();+ // The class comes through whole, as getIcon gives it — family and all (see drawMarkerImage).+ expect(renderIconImage).toHaveBeenCalledWith("tn-icon bx bx-star", expect.anything());+ expect(await lastSvgBlob?.text()).toContain(`fill="red"`);+ });++ it("lets go of the map when it is disarmed", async () => {+ const map = fakeMap();+ await mount(map);+ expect(map.listenerCount("mousemove")).toBe(1);+ expect(map.listenerCount("mouseout")).toBe(1);++ await act(async () => {+ render(null, container as HTMLElement);+ });++ expect(map.listenerCount("mousemove")).toBe(0);+ expect(map.listenerCount("mouseout")).toBe(0);+ });+});diff --git a/apps/client/src/widgets/collections/geomap/GhostPin.tsx b/apps/client/src/widgets/collections/geomap/GhostPin.tsxnew file mode 100644index 0000000000..123d47f1bd--- /dev/null+++ b/apps/client/src/widgets/collections/geomap/GhostPin.tsx@@ -0,0 +1,74 @@+import "./GhostPin.css";++import type { MapMouseEvent } from "maplibre-gl";+import { useContext, useEffect, useRef } from "preact/hooks";++import FNote from "../../../entities/fnote";+import { CHILD_NOTE_ICON } from "./api";+import { ParentMap } from "./map";+import { DEFAULT_MARKER_COLOR, drawMarkerImage } from "./Markers";++/**+ * The pin that rides under the pointer while the map is armed for placement, so the click is+ * preceded by a picture of what it will do: the crosshair says a place is wanted, and this says+ * what will stand on it.+ *+ * Drawn with the very image the symbol layer would stamp there (see {@link drawMarkerImage}) — the+ * note's own colour and icon for a marker being moved, the pin a new note is given for one being+ * created — and translucent, so it reads as an offer rather than as a marker already standing.+ *+ * Positioned by hand off the map's `mousemove` rather than as a MapLibre marker: the ghost follows+ * the pointer, not a coordinate, so there is no lngLat for a marker to be held at.+ */+export default function GhostPin({ note }: {+ /** The note being moved, whose pin the ghost wears — or none, for a note yet to be created. */+ note?: FNote;+}) {+ const map = useContext(ParentMap);+ const elementRef = useRef<HTMLDivElement>(null);++ const color = note?.getLabelValue("color") ?? DEFAULT_MARKER_COLOR;+ const iconClass = note?.getIcon() ?? CHILD_NOTE_ICON;++ // The pin image, drawn fresh rather than through the layer's cache: the cache keeps one <img>+ // element per look, and an element can only stand in one place — two maps split side by side,+ // both armed at once, would steal it from each other's ghost.+ useEffect(() => {+ const element = elementRef.current;+ if (!element) return;++ let cancelled = false;+ drawMarkerImage(color, iconClass).then((image) => {+ if (!cancelled && image) {+ element.replaceChildren(image);+ }+ });+ return () => { cancelled = true; };+ }, [ color, iconClass ]);++ // Following the pointer. Written straight onto the element rather than through state, so a+ // pointer being waved across the map is a style write per event and not a render per event.+ useEffect(() => {+ const element = elementRef.current;+ if (!map || !element) return;++ // Hidden until the pointer says where it is: the map does not remember where it last was,+ // so until the first move there is nowhere honest to draw the ghost.+ const follow = (e: MapMouseEvent) => {+ element.style.transform = `translate(${e.point.x}px, ${e.point.y}px)`;+ element.classList.add("visible");+ };+ // Gone with the pointer — which also covers it resting on the toolbar, since reaching+ // anything standing over the canvas is leaving the canvas.+ const hide = () => element.classList.remove("visible");++ map.on("mousemove", follow);+ map.on("mouseout", hide);+ return () => {+ map.off("mousemove", follow);+ map.off("mouseout", hide);+ };+ }, [ map ]);++ return <div ref={elementRef} className="geo-ghost-pin" aria-hidden="true" />;+}diff --git a/apps/client/src/widgets/collections/geomap/Markers.tsx b/apps/client/src/widgets/collections/geomap/Markers.tsxindex 81dcae93ca..951468a2c7 100644--- a/apps/client/src/widgets/collections/geomap/Markers.tsx+++ b/apps/client/src/widgets/collections/geomap/Markers.tsx@@ -12,7 +12,7 @@ import { ParentMap } from "./map";export const LOCATION_ATTRIBUTE = "geolocation";export const MARKER_LAYER = "points-layer";export const MARKER_SOURCE = "points";-const DEFAULT_MARKER_COLOR = "#2A81CB";+export const DEFAULT_MARKER_COLOR = "#2A81CB";/*** The pin, in the coordinates its SVG is drawn in.@@ -458,7 +458,7 @@ function buildMarkerImage(color: string, iconClass: string) {* built-in pack's font competing with the pack the icon actually belongs to, and whichever won would* decide the font the glyph is drawn in.*/-async function drawMarkerImage(color: string, iconClass: string) {+export async function drawMarkerImage(color: string, iconClass: string) {const scale = window.devicePixelRatio || 1;const icon = await renderIconImage(iconClass, {size: MARKER_ICON_SIZE,diff --git a/apps/client/src/widgets/collections/geomap/api.ts b/apps/client/src/widgets/collections/geomap/api.tsindex 9b98a5e5d7..ef13c91f32 100644--- a/apps/client/src/widgets/collections/geomap/api.ts+++ b/apps/client/src/widgets/collections/geomap/api.ts@@ -6,7 +6,8 @@ import note_create from "../../../services/note_create";import type { GeoMouseEvent } from "./map";import { LOCATION_ATTRIBUTE } from "./Markers";-const CHILD_NOTE_ICON = "bx bx-pin";+/** The icon a note created on the map is given, and so what the ghost pin previews for one. */+export const CHILD_NOTE_ICON = "bx bx-pin";export async function moveMarker(noteId: string, latLng: { lat: number; lng: number } | null) {const value = latLng ? [latLng.lat, latLng.lng].join(",") : "";diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsxindex c3521580fa..a7b44cf4b9 100644--- a/apps/client/src/widgets/collections/geomap/index.tsx+++ b/apps/client/src/widgets/collections/geomap/index.tsx@@ -20,6 +20,7 @@ import { ViewModeProps } from "../interface";import { createNewNote, moveMarker } from "./api";import ContextMenus from "./ContextMenus";import DetailPane from "./DetailPane";+import GhostPin from "./GhostPin";import { GpxTrack } from "./GpxTrack";import Map, { GeoMouseEvent } from "./map";import { DEFAULT_MAP_LAYER_NAME, MAP_LAYERS, MapLayer } from "./map_layer";@@ -208,6 +209,10 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM><MapToolbar /><Tooltips />+ {/* The preview under the pointer while a click is armed to mean a place — the note+ being moved wearing its own pin, a note to be created wearing the pin it will be+ given (see api.ts). */}+ {placement && <GhostPin note={placement.mode === "move" ? notes.find((n) => n.noteId === placement.noteId) : undefined} />}<DetailPane notes={notes} placing={!!placement} isReadOnly={isReadOnly} onRelocate={startMarkerRelocation} /><ContextMenus note={note} isReadOnly={isReadOnly} onRelocate={startMarkerRelocation} />{/* The pane above is what a click on a marker opens now, so the markers no longer