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): open a marker into a pane of its own
Elian Doranc14bf91ca5ed
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex ea72b8e197..151f0d5241 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2749,7 +2749,8 @@"zoom-in": "Zoom in","zoom-out": "Zoom out","fullscreen": "Fullscreen",- "exit-fullscreen": "Exit fullscreen"+ "exit-fullscreen": "Exit fullscreen",+ "close-details": "Close"},"geo-map-context": {"open-location": "Open location",diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.css b/apps/client/src/widgets/collections/geomap/DetailPane.cssnew file mode 100644index 0000000000..147347c228--- /dev/null+++ b/apps/client/src/widgets/collections/geomap/DetailPane.css@@ -0,0 +1,51 @@+/*+ * The pane stands against the trailing edge of the map, the full height of it.+ *+ * Flush rather than inset, and square rather than rounded: a card floating in the corner is what the+ * mind map's panel is (see NodePanel.css), and it is the right shape there, where what it holds is a+ * handful of controls for whatever is selected. This one holds a note, stands as tall as the map and+ * is meant to be read from, so it reads as a wall of the map rather than as a sheet laid over it.+ *+ * The width has to agree with `PANE_WIDTH` in DetailPane.tsx, which is what the map is told to hold+ * a selected marker clear of.+ */+.geo-map-container {+ --geo-detail-pane-width: 380px;+}++.geo-map-container .geo-detail-pane {+ --overlay-panel-radius: 0;++ position: absolute;+ top: 0;+ bottom: 0;+ inset-inline-end: 0;+ width: var(--geo-detail-pane-width);+ /* An embedded map may be narrower than the pane would like to be. */+ max-width: 100%;+ /* Above the canvas and clear of MapLibre's own control corners, which sit at 2 — the same+ reckoning the bar of buttons makes (see MapToolbar.css). */+ z-index: 3;+ /* Only the inner edge is an edge at all; the other three are the map's own. */+ border-block: none;+ border-inline-end: none;+}++/*+ * What the bar of buttons in the corner steps aside by, which is the whole of the pane while one is+ * open and nothing at all otherwise (see MapToolbar.css, which reads it).+ *+ * Written against the pane being there rather than set as the pane opens, so that the map's own+ * furniture answers to what is on it without the pane having to reach outside itself to say so.+ */+.geo-map-container:has(.geo-detail-pane) {+ --geo-pane-width: var(--geo-detail-pane-width);+}++/*+ * The pane is dressed in the app's own colors rather than the map's, which is what the bar beside it+ * does (see MapToolbar.css): what stands here is a note, and a note belongs to the app — the same+ * reasoning that leaves a marker's preview dressed as the app's tooltip. Nothing to write for it,+ * the shared panel reading the app's menu colors already; said here so that the difference between+ * the two is a decision on the record rather than an omission.+ */diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsxnew file mode 100644index 0000000000..45631bbc1b--- /dev/null+++ b/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx@@ -0,0 +1,219 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import Component from "../../../components/component";+import type FNote from "../../../entities/fnote";+import { buildNote } from "../../../test/easy-froca";+import { ParentComponent } from "../../react/react_utils";+import DetailPane from "./DetailPane";+import { ParentMap } from "./map";+import { MARKER_LAYER } from "./Markers";++/** What a marker click hands the handler, and what the pane reads the note out of. */+type Listener = (e?: unknown) => void;++/** How wide the map is in these tests, which is room enough for the pane and then some. */+const MAP_WIDTH = 1200;++/**+ * A map that records what the pane asks of it, standing in for MapLibre.+ *+ * What it has to answer is the hit test: the pane is bound to the map at large rather than to the+ * marker layer, and asks what is under the point that was clicked (see DetailPane).+ */+function fakeMap({ width = MAP_WIDTH, features = [] as unknown[] } = {}) {+ const listeners = new Map<string, Set<Listener>>();+ const eased: unknown[] = [];+ let under: unknown[] = features;++ return {+ /** Every camera move the pane has asked for, which is how it holds a marker clear of itself. */+ get eased() { return eased; },+ /** What the next click will land on: a marker's feature, or nothing at all. */+ setUnderPointer(hit: unknown[]) { under = hit; },+ /** A click on the map, wherever `setUnderPointer` says it landed. */+ click() {+ for (const fn of listeners.get("click") ?? []) fn({ point: { x: 0, y: 0 } });+ },+ on(event: string, fnOrLayer: unknown, fn?: () => void) {+ const key = fn ? `${event}:${fnOrLayer}` : event;+ const handler = (fn ?? fnOrLayer) as Listener;+ if (!listeners.has(key)) listeners.set(key, new Set());+ listeners.get(key)?.add(handler);+ },+ off(event: string, fnOrLayer: unknown, fn?: () => void) {+ listeners.get(fn ? `${event}:${fnOrLayer}` : event)?.delete((fn ?? fnOrLayer) as Listener);+ },+ queryRenderedFeatures(_point: unknown, { layers }: { layers: string[] }) {+ return layers.includes(MARKER_LAYER) ? under : [];+ },+ easeTo(options: unknown) { eased.push(options); },+ getContainer: () => ({ clientWidth: width })+ };+}++/** A marker of the layer, as MapLibre reports one that was hit. */+function markerFeature(note: FNote, coordinates: [number, number] = [ 2, 1 ]) {+ return { geometry: { type: "Point", coordinates }, properties: { id: note.noteId } };+}++describe("DetailPane", () => {+ let container: HTMLElement | undefined;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ if (container) {+ render(null, container);+ container.remove();+ container = undefined;+ }+ });++ /** Renders into the same container, so calling it again is a re-render with fresh props. */+ function mount(notes: FNote[], map: ReturnType<typeof fakeMap>, placing = false) {+ return act(async () => {+ render(+ <ParentComponent.Provider value={new Component()}>+ <ParentMap.Provider value={map as never}>+ <DetailPane notes={notes} placing={placing} />+ </ParentMap.Provider>+ </ParentComponent.Provider>,+ container as HTMLElement+ );+ });+ }++ function pane() {+ return container?.querySelector(".geo-detail-pane") ?? null;+ }++ it("stands for the marker that was clicked, naming its note", async () => {+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });+ const map = fakeMap();+ await mount([ note ], map);++ // Nothing is selected to begin with, so there is no pane over the map at all.+ expect(pane()).toBeNull();++ map.setUnderPointer([ markerFeature(note) ]);+ await act(async () => map.click());++ expect(pane()?.querySelector(".tn-overlay-panel-title-text")?.textContent).toBe("Somewhere");+ });++ /**+ * The pane covers the trailing edge of the map, so the marker it stands for is brought to the+ * middle of what is left uncovered rather than to the middle of the map — where the pane itself+ * would be sitting on top of it.+ */+ it("holds the marker it opens for clear of itself", async () => {+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });+ const map = fakeMap();+ await mount([ note ], map);++ map.setUnderPointer([ markerFeature(note, [ 2, 1 ]) ]);+ await act(async () => map.click());++ expect(map.eased).toEqual([ { center: [ 2, 1 ], offset: [ -190, 0 ] } ]);+ });++ /** An embedded map may be narrower than the pane wants to be, and then there is nowhere to move to. */+ it("leaves the marker where it is on a map the pane covers whole", async () => {+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });+ const map = fakeMap({ width: 300 });+ await mount([ note ], map);++ map.setUnderPointer([ markerFeature(note) ]);+ await act(async () => map.click());++ expect(map.eased).toEqual([ { center: [ 2, 1 ], offset: [ 0, 0 ] } ]);+ });++ it("clears on a click that misses every marker, and on Escape", async () => {+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });+ const map = fakeMap();+ await mount([ note ], map);++ map.setUnderPointer([ markerFeature(note) ]);+ await act(async () => map.click());+ expect(pane()).toBeTruthy();++ map.setUnderPointer([]);+ await act(async () => map.click());+ expect(pane()).toBeNull();++ map.setUnderPointer([ markerFeature(note) ]);+ await act(async () => map.click());+ expect(pane()).toBeTruthy();++ await act(async () => { window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); });+ expect(pane()).toBeNull();+ });++ it("leaves the click alone while the map is armed to place something", async () => {+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });+ const map = fakeMap();+ await mount([ note ], map, true);++ // The click belongs to the placement, which is handled where that state lives.+ map.setUnderPointer([ markerFeature(note) ]);+ await act(async () => map.click());++ expect(pane()).toBeNull();+ expect(map.eased).toEqual([]);+ });++ /**+ * Taking a marker off the map clears the note's location and leaves the note itself exactly where+ * it was, so the pane cannot wait to be told the note has gone — there is no pin left for it to+ * stand for either way.+ */+ it("goes away when its marker leaves the map, whether the note does or not", async () => {+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });+ const map = fakeMap();+ await mount([ note ], map);++ map.setUnderPointer([ markerFeature(note) ]);+ await act(async () => map.click());+ expect(pane()).toBeTruthy();++ // The note has had its location cleared, which is all that taking a marker off the map does.+ const located = vi.spyOn(note, "getLabelValue").mockReturnValue(null);+ await mount([ note ], map);+ expect(pane()).toBeNull();++ located.mockRestore();+ map.setUnderPointer([ markerFeature(note) ]);+ await act(async () => map.click());+ expect(pane()).toBeTruthy();++ // And the note gone from the collection altogether.+ await mount([], map);+ expect(pane()).toBeNull();+ });++ it("keeps clicks and key presses from reaching the map underneath", async () => {+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });+ const map = fakeMap();+ await mount([ note ], map);++ map.setUnderPointer([ markerFeature(note) ]);+ await act(async () => map.click());++ const onMouseDown = vi.fn();+ const onKeyDown = vi.fn();+ container?.addEventListener("mousedown", onMouseDown);+ container?.addEventListener("keydown", onKeyDown);++ pane()?.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));+ pane()?.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "a" }));++ expect(onMouseDown).not.toHaveBeenCalled();+ expect(onKeyDown).not.toHaveBeenCalled();+ });+});diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.tsxnew file mode 100644index 0000000000..a52d36a6f4--- /dev/null+++ b/apps/client/src/widgets/collections/geomap/DetailPane.tsx@@ -0,0 +1,137 @@+import "./DetailPane.css";++import type { Map as MapLibreGLMap, MapMouseEvent } from "maplibre-gl";+import { useContext, useEffect, useState } from "preact/hooks";++import FNote from "../../../entities/fnote";+import { t } from "../../../services/i18n";+import { useNoteIcon, useNoteLabel, useNoteProperty } from "../../react/hooks";+import OverlayPanel, { OverlayPanelBody, OverlayPanelTitle } from "../../react/OverlayPanel";+import { ParentMap } from "./map";+import { LOCATION_ATTRIBUTE, MARKER_LAYER, parseLocation } from "./Markers";++/**+ * What is known about the marker that has been clicked, standing against the trailing edge of the+ * map for as long as one is selected.+ *+ * The pane is drawn over the map rather than beside it — the map is what goes fullscreen (see+ * MapToolbar), so a pane standing outside it would leave the screen the moment it was filled, and an+ * embedded map may be narrower than the pane is wide. What makes it read as a dock instead of a card+ * laid over the map is that the map keeps out of its way: the marker is brought to the middle of+ * what is left uncovered rather than to the middle of the map (see {@link paneOffset}), and the bar+ * of buttons in the corner steps aside for it (see DetailPane.css).+ */+export default function DetailPane({ notes, placing }: {+ notes: FNote[];+ /** A marker is being placed, which is what the next click on the map is for. */+ placing: boolean;+}) {+ const map = useContext(ParentMap);+ const [ selectedNoteId, setSelectedNoteId ] = useState<string | null>(null);+ const note = notes.find((note) => note.noteId === selectedNoteId);+ const [ location ] = useNoteLabel(note, LOCATION_ATTRIBUTE);++ // A note that is no longer on the map takes the pane with it, rather than leaving it standing+ // for a marker that is not there any more: the note may have left the collection, or been+ // deleted, or merely had its location cleared — which is what "remove from map" does, and which+ // leaves the note itself exactly where it was.+ useEffect(() => {+ if (selectedNoteId && (!note || !parseLocation(location))) {+ setSelectedNoteId(null);+ }+ }, [ selectedNoteId, note, location ]);++ // What is under the pointer decides: a marker is selected, and a click anywhere else clears the+ // selection, the way clicking off a place closes its card. Read off the rendered layer rather+ // than bound to it (`map.on("click", MARKER_LAYER, ...)`), so that one handler answers both+ // cases and there is no order between two of them to rely on.+ useEffect(() => {+ if (!map || placing) return;++ const onClick = (e: MapMouseEvent) => {+ const feature = map.queryRenderedFeatures(e.point, { layers: [ MARKER_LAYER ] })[0];+ if (!feature || feature.geometry.type !== "Point") {+ setSelectedNoteId(null);+ return;+ }++ setSelectedNoteId(String(feature.properties.id));+ map.easeTo({+ center: feature.geometry.coordinates as [ number, number ],+ offset: paneOffset(map)+ });+ };++ map.on("click", onClick);+ return () => { map.off("click", onClick); };+ }, [ map, placing ]);++ // The way out that every transient surface in the app answers to. Bound only while there is a+ // selection, so that the map's other Escape — the one that gives up placing a marker (see+ // index.tsx) — is the only listener standing when there is nothing selected.+ useEffect(() => {+ if (!selectedNoteId) return;++ const onKeyDown = (e: KeyboardEvent) => {+ if (e.key === "Escape") {+ setSelectedNoteId(null);+ }+ };+ window.addEventListener("keydown", onKeyDown);+ return () => window.removeEventListener("keydown", onKeyDown);+ }, [ selectedNoteId ]);++ if (!note) {+ return null;+ }++ return <MarkerDetails note={note} onClose={() => setSelectedNoteId(null)} />;+}++/**+ * How wide the pane stands.+ *+ * Has to agree with `--geo-detail-pane-width` in DetailPane.css: the map is told how much of itself+ * the pane covers so that it can hold the selected marker clear of it, and a number is the only form+ * that side of the pair can take.+ */+const PANE_WIDTH = 380;++/**+ * How far off its own centre the map has to hold a marker for the pane not to cover it.+ *+ * Handed over as `offset` rather than as camera `padding`, though padding is what it is for: padding+ * becomes part of the transform and stays there, so `getCenter()` — which is what the view is saved+ * from (see map.tsx) — would report the middle of the uncovered half from then on, and the saved+ * viewport would walk sideways every time the pane was opened. An offset applies to the one+ * animation and leaves nothing behind.+ */+function paneOffset(map: MapLibreGLMap): [number, number] {+ // A pane with the whole map under it — an embedded one narrower than the pane — leaves nowhere+ // to hold the marker clear of, so it is left where it is.+ if (map.getContainer().clientWidth <= PANE_WIDTH) {+ return [ 0, 0 ];+ }++ // The pane stands at the trailing edge, which is the left one where the app reads right to left.+ const shift = PANE_WIDTH / 2;+ return [ glob.isRtl ? shift : -shift, 0 ];+}++/** The pane itself, for a marker there is one to draw. */+function MarkerDetails({ note, onClose }: { note: FNote; onClose(): void }) {+ const icon = useNoteIcon(note);+ const title = useNoteProperty(note, "title");++ return (+ <OverlayPanel+ className="geo-detail-pane"+ header={<OverlayPanelTitle icon={icon ?? note.getIcon()} text={title ?? note.title} />}+ close={{ text: t("geo-map.close-details"), onClick: onClose }}+ >+ {/* Nothing is made of the note yet — what stands here is the wiring, and the pane is+ filled in a step of its own. */}+ <OverlayPanelBody>Hello world</OverlayPanelBody>+ </OverlayPanel>+ );+}diff --git a/apps/client/src/widgets/collections/geomap/MapToolbar.css b/apps/client/src/widgets/collections/geomap/MapToolbar.cssindex 6d3f439583..a0a1648ad2 100644--- a/apps/client/src/widgets/collections/geomap/MapToolbar.css+++ b/apps/client/src/widgets/collections/geomap/MapToolbar.css@@ -13,8 +13,12 @@*/.geo-map-container .geo-map-toolbar {bottom: var(--geo-map-inset);- inset-inline-end: var(--geo-map-inset);+ /* Past whatever stands against that edge, which today is the detail pane and by default nothing+ (see DetailPane.css, which is what sets it). The bar sliding clear as a pane opens is what+ makes the pane read as a wall of the map rather than as something laid on top of it. */+ inset-inline-end: calc(var(--geo-map-inset) + var(--geo-pane-width, 0px));z-index: 3;+ transition: inset-inline-end 150ms ease;}/*diff --git a/apps/client/src/widgets/collections/geomap/Markers.spec.tsx b/apps/client/src/widgets/collections/geomap/Markers.spec.tsxindex b963435da0..6389dc46b5 100644--- a/apps/client/src/widgets/collections/geomap/Markers.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/Markers.spec.tsx@@ -189,7 +189,7 @@ describe("Markers", () => {});/** Renders into the same container, so calling it again is a re-render with fresh props. */- function mount(notes: FNote[], map: ReturnType<typeof fakeMap>, parent: Component, look?: { hideLabels?: boolean, isDarkTheme?: boolean, clustered?: boolean, placing?: boolean }) {+ function mount(notes: FNote[], map: ReturnType<typeof fakeMap>, parent: Component, look?: { hideLabels?: boolean, isDarkTheme?: boolean, clustered?: boolean, placing?: boolean, opensNotes?: boolean }) {return act(async () => {render(<ParentComponent.Provider value={parent}>@@ -200,6 +200,10 @@ describe("Markers", () => {isDarkTheme={look?.isDarkTheme ?? false}clustered={look?.clustered ?? false}placing={look?.placing ?? false}+ // What these tests are about, so on unless a case says otherwise. The geo+ // map itself passes false, a marker being opened into the detail pane+ // there instead (see index.tsx).+ opensNotes={look?.opensNotes ?? true}/></ParentMap.Provider></ParentComponent.Provider>,@@ -464,6 +468,17 @@ describe("Markers", () => {expect(openInPopup).toHaveBeenCalledWith("openInPopup", { noteIdOrPath: note.noteId });});+ it("leaves the click alone where something else on the map has taken it over", async () => {+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });+ const map = fakeMap();+ await mount([ note ], map, new Component(), { opensNotes: false });++ // What the geo map itself passes: a marker is opened into the detail pane there, and+ // raising the quick editor as well would put it over the pane that had just opened.+ map.clickMarker(note);+ expect(openInPopup).not.toHaveBeenCalled();+ });+it("leaves the click alone while the map is armed to place something", async () => {const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });const map = fakeMap();diff --git a/apps/client/src/widgets/collections/geomap/Markers.tsx b/apps/client/src/widgets/collections/geomap/Markers.tsxindex b70bdc2454..729c92aa75 100644--- a/apps/client/src/widgets/collections/geomap/Markers.tsx+++ b/apps/client/src/widgets/collections/geomap/Markers.tsx@@ -98,9 +98,18 @@ interface MarkersProps {* on the map like any other for as long as the map is waiting to be told one.*/placing: boolean;+ /**+ * Whether opening the note is what a click on a marker means at all.+ *+ * False where something else on the map has taken that click over, which is what the detail pane+ * does: a marker is opened *into the pane* instead, and the note itself is reached from there+ * (see {@link DetailPane}). Left here rather than taken out, so that a map that carries no pane+ * — should one ever be wanted — still opens its notes the way it always did.+ */+ opensNotes: boolean;}-export default function Markers({ notes, hideLabels, isDarkTheme, clustered, placing }: MarkersProps) {+export default function Markers({ notes, hideLabels, isDarkTheme, clustered, placing, opensNotes }: MarkersProps) {const map = useContext(ParentMap);const version = useNoteChangeVersion(notes);// Whether the style has finished loading at least once. Held outside the effects because either@@ -287,7 +296,7 @@ export default function Markers({ notes, hideLabels, isDarkTheme, clustered, pla}, [ map, hideLabels, isDarkTheme ]);useClusterExpansion(map, MARKER_SOURCE, clustered);- useMarkerOpening(map, !placing);+ useMarkerOpening(map, opensNotes && !placing);return null;}diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsxindex f646d29e4a..e4f57e3dc4 100644--- a/apps/client/src/widgets/collections/geomap/index.tsx+++ b/apps/client/src/widgets/collections/geomap/index.tsx@@ -19,6 +19,7 @@ import { useCollectionTreeDrag, useNoteBlob, useNoteLabel, useNoteLabelBoolean,import { ViewModeProps } from "../interface";import { createNewNote, moveMarker } from "./api";import ContextMenus from "./ContextMenus";+import DetailPane from "./DetailPane";import { GpxTrack } from "./GpxTrack";import Map, { GeoMouseEvent } from "./map";import { DEFAULT_MAP_LAYER_NAME, MAP_LAYERS, MapLayer } from "./map_layer";@@ -207,8 +208,12 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM><MapToolbar /><Tooltips />+ <DetailPane notes={notes} placing={!!placement} /><ContextMenus note={note} isReadOnly={isReadOnly} onRelocate={startMarkerRelocation} />- <Markers notes={notes} hideLabels={hideLabels} isDarkTheme={layerData.isDarkTheme ?? false} clustered={clustered} placing={!!placement} />+ {/* The pane above is what a click on a marker opens now, so the markers no longer+ open the note themselves — the two would otherwise both answer the same click,+ raising the quick editor over the pane that had just opened behind it. */}+ <Markers notes={notes} hideLabels={hideLabels} isDarkTheme={layerData.isDarkTheme ?? false} clustered={clustered} placing={!!placement} opensNotes={false} />{notes.map(note => <NoteGpxTrackWrapper note={note} hideLabels={hideLabels} isDarkTheme={layerData.isDarkTheme ?? false} />)}</Map>}</div>