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 drawn shape's context menu on a right click
Elian Dorana97aa556c472
diff --git a/apps/client/src/widgets/collections/geomap/ContextMenus.spec.tsx b/apps/client/src/widgets/collections/geomap/ContextMenus.spec.tsxindex c5bef6601a..651be039a4 100644--- a/apps/client/src/widgets/collections/geomap/ContextMenus.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/ContextMenus.spec.tsx@@ -34,16 +34,24 @@ vi.mock("../../../menus/link_context_menu", () => ({vi.mock("../../../menus/custom-items/NoteColorPicker", () => ({ default: () => null }));/** A map that reports what is under a click and delegates its own, which is all this component asks. */-function fakeMap(markerUnderPointer?: FNote, trackUnderPointer?: FNote) {+function fakeMap(markerUnderPointer?: FNote, trackUnderPointer?: FNote, shapeUnderPointer?: FNote) {const listeners = new Set<(e: unknown) => void>();- // The layer a GPX track offers to be pointed at by, named after its note (see `trackHitLayers`).+ // The layers a track and a shape offer to be pointed at by, each named after its note (see+ // `trackHitLayers` and `shapeHitLayers`).const trackLayer = trackUnderPointer && `gpx-hit-${trackUnderPointer.noteId}`;+ const shapeLayer = shapeUnderPointer && `shape-hit-${shapeUnderPointer.noteId}`;return {on(event: string, fn: (e: unknown) => void) { if (event === "contextmenu") listeners.add(fn); },off(event: string, fn: (e: unknown) => void) { if (event === "contextmenu") listeners.delete(fn); },- getLayersOrder: () => (trackLayer ? [ trackLayer ] : []),+ getLayersOrder: () => [ trackLayer, shapeLayer ].filter((id) => id !== undefined),+ // Answered in the map's drawing order rather than in the order of `layers`, which is how+ // MapLibre answers: the shapes go on last and so are drawn above the pins standing on them.+ // A single query naming both would therefore hand back the shape.queryRenderedFeatures: (_point: unknown, options: { layers: string[] }) => [+ ...(shapeUnderPointer && shapeLayer && options.layers.includes(shapeLayer)+ ? [ { properties: { id: shapeUnderPointer.noteId } } ]+ : []),...(markerUnderPointer && options.layers.includes(MARKER_LAYER)? [ { properties: { id: markerUnderPointer.noteId } } ]: []),@@ -86,6 +94,9 @@ async function openMenu(map: ReturnType<typeof fakeMap>, { isReadOnly = false, oreturn { items, onRelocate, onCreateNote };}+/** A triangular lot, in the label format a shape note carries (see shapes.ts). */+const LOT_SHAPE = "polygon:45.79,24.13 45.81,24.16 45.89,24.08";+/** The item offering to move a marker, where one was offered. */function moveItem(items: MenuItem<string>[]) {return items.find((item): item is MenuCommandItem<string> =>@@ -180,4 +191,41 @@ describe("ContextMenus", () => {move?.handler?.(move, undefined as never);expect(onRelocate).toHaveBeenCalledWith(marker.noteId);});++ /**+ * A drawn shape is one of the map's notes like any other, so right-clicking it opens that note's+ * menu rather than the bare map's. Taking it off the map clears its geometry and leaves the note+ * behind, which is the plain removal a marker is offered and not a track's deletion.+ */+ it("opens the note of a drawn shape that was right-clicked", async () => {+ const shape = buildNote({ title: "The lot", "#geoShape": LOT_SHAPE });+ const { items } = await openMenu(fakeMap(undefined, undefined, shape));++ expect(items).not.toContainEqual(expect.objectContaining({ title: "geo-map-context.add-note" }));+ expect(items).toContainEqual(expect.objectContaining({ title: "geo-map-context.remove-from-map" }));+ expect(items).not.toContainEqual(expect.objectContaining({ title: "geo-map-context.delete-note" }));+ });++ /** A shape has no marker to put somewhere else either: moving one means drawing it again. */+ it("does not offer to move a drawn shape", async () => {+ const shape = buildNote({ title: "The lot", "#geoShape": LOT_SHAPE });+ const { items } = await openMenu(fakeMap(undefined, undefined, shape));++ expect(moveItem(items)).toBeUndefined();+ });++ /**+ * An area's fill covers its whole inside and is drawn above the pins standing on it, so asking+ * for both at once would hand back the polygon for every point within it. The shapes are asked+ * about only where the markers and the tracks were missed.+ */+ it("prefers a marker standing inside a shape to the shape", async () => {+ const marker = buildNote({ title: "The well", "#geolocation": "1,2" });+ const shape = buildNote({ title: "The lot", "#geoShape": LOT_SHAPE });+ const { items, onRelocate } = await openMenu(fakeMap(marker, undefined, shape));++ const move = moveItem(items);+ move?.handler?.(move, undefined as never);+ expect(onRelocate).toHaveBeenCalledWith(marker.noteId);+ });});diff --git a/apps/client/src/widgets/collections/geomap/ContextMenus.ts b/apps/client/src/widgets/collections/geomap/ContextMenus.tsindex 2ea7b66a55..4ba41ec9bb 100644--- a/apps/client/src/widgets/collections/geomap/ContextMenus.ts+++ b/apps/client/src/widgets/collections/geomap/ContextMenus.ts@@ -11,9 +11,11 @@ import froca from "../../../services/froca.js";import { t } from "../../../services/i18n.js";import link from "../../../services/link.js";import { removeFromMap } from "./api.js";-import { GPX_MIME, trackHitLayers } from "./GpxTrack.js";+import { GPX_MIME } from "./GpxTrack.js";import { type GeoMouseEvent, ParentMap, toGeoMouseEvent } from "./map.js";-import { formatLocation, MARKER_LAYER } from "./Markers.js";+import { formatLocation } from "./Markers.js";+import { featureAt } from "./ShapeLayer.js";+import { isShapeNote } from "./shapes.js";interface ContextMenusProps {/** The map's own note, which is how the tree is told what the map holds a note by. */@@ -39,16 +41,13 @@ export default function ContextMenus({ parentNote, isReadOnly, onRelocate, onCreconst onContextMenu = useCallback((e: GeoMouseEvent) => {if (!map) return;- // The markers first and the tracks after, so that a pin standing on its own track opens the- // pin's menu rather than the line's — they are the same note either way, but a marker is the- // smaller target and is what the user was aiming at when they hit both.- const features = map.queryRenderedFeatures(e.point, {- layers: [ MARKER_LAYER, ...trackHitLayers(map) ]- });-- if (features.length > 0) {- // Marker or track context menu.- openContextMenu(features[0].properties.id, e, { isEditable: !isReadOnly, onRelocate, parentNote });+ // Whichever of the map's notes the pointer landed on — a marker, a track or a drawn shape,+ // the order between them being the hit test's own business (see featureAt).+ const feature = featureAt(map, e.point);++ if (feature) {+ // A note's context menu.+ openContextMenu(feature.properties.id, e, { isEditable: !isReadOnly, onRelocate, parentNote });} else {// Empty area context menu.openMapContextMenu(e, !isReadOnly, onCreateNote);@@ -150,13 +149,15 @@ export function openMapContextMenu(e: GeoMouseEvent, isEditable: boolean, onCrea* The marker is moved by being placed again rather than dragged: the notes are drawn into one symbol* layer, not an element apiece, so there is nothing on the map to take hold of.*- * A GPX track is offered nothing, which is why this is a list and not an item. A track is on the map- * by being drawn across it — its place is the line its file holds, which no click can pick up. What- * the offer did was write a location onto the note, planting a stray pin somewhere else while the- * line stayed exactly where it was. The detail pane leaves the button out for the same reason.+ * Neither a GPX track nor a drawn shape is offered anything, which is why this is a list and not an+ * item. Each is on the map by the figure it draws across it, which no click can pick up, and what+ * the offer did was write a location onto the note — planting a stray pin somewhere else while the+ * line or the shape stayed exactly where it was. The detail pane leaves the button out for the same+ * reason.*/function buildRelocateItem(noteId: string, onRelocate: (noteId: string) => void): MenuItem<keyof CommandMappings>[] {- if (froca.getNoteFromCache(noteId)?.mime === GPX_MIME) {+ const note = froca.getNoteFromCache(noteId);+ if (!note || note.mime === GPX_MIME || isShapeNote(note)) {return [];}diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.tsxindex 4f343543d0..f2a55239dd 100644--- a/apps/client/src/widgets/collections/geomap/DetailPane.tsx+++ b/apps/client/src/widgets/collections/geomap/DetailPane.tsx@@ -19,11 +19,11 @@ import Modal from "../../react/Modal";import OverlayPanel, { OverlayPanelBody } from "../../react/OverlayPanel";import { removeFromMap } from "./api";import { type Bounds, boundsOf } from "./coordinates";-import { GPX_MIME, trackHitLayers, trackSourceId } from "./GpxTrack";+import { GPX_MIME, trackSourceId } from "./GpxTrack";import { ParentMap } from "./map";-import { formatLocation, LOCATION_ATTRIBUTE, MARKER_LAYER, parseLocation } from "./Markers";-import { shapeHitLayers } from "./ShapeLayer";-import { geoShapeBounds, parseGeoShape, SHAPE_ATTRIBUTE } from "./shapes";+import { formatLocation, LOCATION_ATTRIBUTE, parseLocation } from "./Markers";+import { featureAt } from "./ShapeLayer";+import { geoShapeBounds, isShapeNote, parseGeoShape, SHAPE_ATTRIBUTE } from "./shapes";/*** Which marker the pane stands for, and why it came to be selected.@@ -152,19 +152,12 @@ export default function DetailPane({ notes, parentNote, placing, isReadOnly, sel// A marker, a GPX track or a drawn shape selects, anywhere else clears. Read off the rendered// layers rather than bound to them (`map.on("click", MARKER_LAYER, ...)`) so one handler answers- // all.- //- // The shapes are queried separately, and only where the markers and tracks were missed:- // queryRenderedFeatures() answers in the map's drawing order rather than in the order of the- // `layers` argument, and an area's fill covers its whole inside and is drawn above the markers.- // One combined query would therefore return the polygon for every click inside it.+ // all, the order between the three being the hit test's own business (see featureAt).useEffect(() => {if (!map || placing) return;const onClick = (e: MapMouseEvent) => {- const shapeLayers = shapeHitLayers(map);- const feature = map.queryRenderedFeatures(e.point, { layers: [ MARKER_LAYER, ...trackHitLayers(map) ] })[0]- ?? (shapeLayers.length > 0 ? map.queryRenderedFeatures(e.point, { layers: shapeLayers })[0] : undefined);+ const feature = featureAt(map, e.point);if (!feature) {void closePane();return;@@ -356,7 +349,7 @@ const FIT_MAX_ZOOM = 16;function standsOnMap(note: FNote) {return note.mime === GPX_MIME|| !!parseLocation(note.getLabelValue(LOCATION_ATTRIBUTE))- || !!parseGeoShape(note.getLabelValue(SHAPE_ATTRIBUTE) ?? "");+ || isShapeNote(note);}/**@@ -577,9 +570,10 @@ const PANE_NTX_ID = "_geo-detail-pane";*/function MarkerActions({ note, parentNote, isReadOnly, onRelocate }: { note: FNote; parentNote: FNote; isReadOnly: boolean; onRelocate(): void }) {const [ location ] = useNoteLabel(note, LOCATION_ATTRIBUTE);- const [ shapeValue ] = useNoteLabel(note, SHAPE_ATTRIBUTE);+ // Read so the row is rebuilt when the geometry is edited away, the note ceasing to be a shape.+ useNoteLabel(note, SHAPE_ATTRIBUTE);const latLng = parseLocation(location);- const isShape = !!parseGeoShape(shapeValue ?? "");+ const isShape = isShapeNote(note);return (<EmbeddedNoteActions>diff --git a/apps/client/src/widgets/collections/geomap/ShapeLayer.tsx b/apps/client/src/widgets/collections/geomap/ShapeLayer.tsxindex e2ccc3020c..04541fdaa5 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 { Map as MapLibreGLMap } from "maplibre-gl";+import type { MapGeoJSONFeature, Map as MapLibreGLMap, Point } from "maplibre-gl";import { useContext, useEffect } from "preact/hooks";+import { trackHitLayers } from "./GpxTrack";import { MapStyleLoaded, ParentMap } from "./map";+import { MARKER_LAYER } from "./Markers";import { circleRing, closeRing, type GeoShape, serializeGeoShape } from "./shapes";/**@@ -178,3 +180,16 @@ export function shapeSourceId(noteId: string) {export function shapeHitLayers(map: MapLibreGLMap) {return map.getLayersOrder().filter((id) => id.startsWith(HIT_LAYER_PREFIX) || id.startsWith(FILL_LAYER_PREFIX));}++/**+ * The feature of one of the map's notes under a point, or `undefined` where none is hit.+ *+ * The shapes are queried separately because `queryRenderedFeatures()` returns features in drawing+ * order, not in `layers` order: an area's fill covers its interior and draws above the markers, so+ * one query would answer a click on a pin inside a polygon with the polygon. An empty `layers` list+ * matches nothing, so a map without shapes needs no guard.+ */+export function featureAt(map: MapLibreGLMap, point: Point): MapGeoJSONFeature | undefined {+ return map.queryRenderedFeatures(point, { layers: [ MARKER_LAYER, ...trackHitLayers(map) ] })[0]+ ?? map.queryRenderedFeatures(point, { layers: shapeHitLayers(map) })[0];+}diff --git a/apps/client/src/widgets/collections/geomap/shapes.ts b/apps/client/src/widgets/collections/geomap/shapes.tsindex 5fc3203989..9d819a766b 100644--- a/apps/client/src/widgets/collections/geomap/shapes.ts+++ b/apps/client/src/widgets/collections/geomap/shapes.ts@@ -15,6 +15,8 @@* track keeps its own file-note form; see GpxTrack).*/+import { GEO_SHAPE_ATTRIBUTE } from "@triliumnext/commons";+import { type Bounds, boundsOf } from "./coordinates";/** The label a shape note carries its geometry in. Named in commons because `getNoteIcon` reads it@@ -97,6 +99,15 @@ export function parseGeoShape(value: string): GeoShape | null {return { type, coordinates };}+/**+ * Whether the note is drawn on the map as a shape, which is what carrying a readable geometry label+ * means. Asked wherever a shape is offered something different from a marker — it has no pin to put+ * somewhere else, for one (see the detail pane and the context menu).+ */+export function isShapeNote(note: { getLabelValue(name: string): string | null }): boolean {+ return !!parseGeoShape(note.getLabelValue(GEO_SHAPE_ATTRIBUTE) ?? "");+}+function parseCircle(rest: string): GeoShapeCircle | null {const parts = rest.trim().split(/\s+/);if (parts.length !== 2) return null;