Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): move a marker by placing it again, and open a note by clicking it

Elian Doran28c402196841
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 5136fbdfcc..ea72b8e197 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2742,6 +2742,8 @@
"create-child-note-text": "Add marker",
"create-child-note-instruction": "Click on the map to create a new note at that location or press Escape to dismiss.",
"create-child-note-toast-title": "New note",
+ "move-marker-instruction": "Click on the map to move the marker to that location or press Escape to dismiss.",
+ "move-marker-toast-title": "Move marker",
"unable-to-load-map": "Unable to load map.",
"webgl-unavailable": "This map can't be drawn because WebGL isn't available. Check that hardware acceleration is enabled and that your graphics drivers are up to date.",
"zoom-in": "Zoom in",
@@ -2751,6 +2753,7 @@
},
"geo-map-context": {
"open-location": "Open location",
+ "move-marker": "Move to another location",
"remove-from-map": "Remove from map",
"add-note": "Add a marker at this location"
},
diff --git a/apps/client/src/widgets/collections/geomap/ContextMenus.spec.tsx b/apps/client/src/widgets/collections/geomap/ContextMenus.spec.tsx
new file mode 100644
index 0000000000..eb2b868c05
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/ContextMenus.spec.tsx
@@ -0,0 +1,112 @@
+/**
+ * The menus a geo map opens on a right click, and in particular the one way a marker can be put
+ * somewhere else.
+ *
+ * The notes are drawn into a single symbol layer rather than an element apiece, so there is no marker
+ * to take hold of and dragging one is gone: relocation is asking for it here and clicking where it
+ * should go. What is checked is that the offer is made only where the map may be edited, and that it
+ * names the note whose marker was clicked rather than the map or the last note read.
+ */
+import { act } from "preact/test-utils";
+import { describe, expect, it, vi } from "vitest";
+
+import type FNote from "../../../entities/fnote";
+import type { MenuCommandItem, MenuItem } from "../../../menus/context_menu";
+import { buildNote } from "../../../test/easy-froca";
+import { renderInto } from "../../../test/render";
+import ContextMenus from "./ContextMenus";
+import { ParentMap } from "./map";
+import { MARKER_LAYER } from "./Markers";
+
+// t() returns the key, so the assertions below are on which item is offered rather than on its
+// English wording.
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+const { show } = vi.hoisted(() => ({ show: vi.fn() }));
+vi.mock("../../../menus/context_menu", () => ({ default: { show } }));
+
+// The items a note's link brings with it are that menu's business, not this one's.
+vi.mock("../../../menus/link_context_menu", () => ({
+ default: { getItems: () => [], handleLinkContextMenuItem: vi.fn() }
+}));
+
+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) {
+ const listeners = new Set<(e: unknown) => void>();
+
+ 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); },
+ queryRenderedFeatures: (_point: unknown, options: { layers: string[] }) =>
+ markerUnderPointer && options.layers.includes(MARKER_LAYER)
+ ? [ { properties: { id: markerUnderPointer.noteId } } ]
+ : [],
+ /** The map being right-clicked, as MapLibre reports it. */
+ rightClick() {
+ for (const fn of listeners) {
+ fn({
+ lngLat: { lat: 1, lng: 2 },
+ point: { x: 10, y: 20 },
+ originalEvent: new MouseEvent("contextmenu"),
+ preventDefault: vi.fn()
+ });
+ }
+ }
+ };
+}
+
+/** Opens the menu over the given map and hands back the items it was shown with. */
+async function openMenu(map: ReturnType<typeof fakeMap>, { isReadOnly = false, onRelocate = vi.fn() } = {}) {
+ const note = buildNote({ title: "The map itself" });
+ // Settled before the map is clicked: the listener the menu opens from is bound in an effect, and
+ // effects do not run within the render itself.
+ await act(async () => {
+ renderInto(
+ <ParentMap.Provider value={map as never}>
+ <ContextMenus note={note} isReadOnly={isReadOnly} onRelocate={onRelocate} />
+ </ParentMap.Provider>
+ );
+ });
+
+ show.mockClear();
+ act(() => { map.rightClick(); });
+
+ const items: MenuItem<string>[] = show.mock.calls[0]?.[0]?.items ?? [];
+ return { items, onRelocate };
+}
+
+/** The item offering to move a marker, where one was offered. */
+function moveItem(items: MenuItem<string>[]) {
+ return items.find((item): item is MenuCommandItem<string> =>
+ "title" in item && item.title === "geo-map-context.move-marker");
+}
+
+describe("ContextMenus", () => {
+ it("offers to move the marker that was clicked, and says which note it belongs to", async () => {
+ const marker = buildNote({ title: "Somewhere", "#geolocation": "1,2" });
+ const { items, onRelocate } = await openMenu(fakeMap(marker));
+
+ const move = moveItem(items);
+ expect(move).toBeDefined();
+ move?.handler?.(move, undefined as never);
+ expect(onRelocate).toHaveBeenCalledWith(marker.noteId);
+ });
+
+ it("does not offer to move a marker on a map that may not be edited", async () => {
+ const marker = buildNote({ title: "Somewhere", "#geolocation": "1,2" });
+ const { items } = await openMenu(fakeMap(marker), { isReadOnly: true });
+
+ expect(moveItem(items)).toBeUndefined();
+ // Nor anything else that would change the map.
+ expect(items).not.toContainEqual(expect.objectContaining({ title: "geo-map-context.remove-from-map" }));
+ });
+
+ it("offers nothing to move where the click landed on no marker at all", async () => {
+ const { items } = await openMenu(fakeMap());
+
+ expect(moveItem(items)).toBeUndefined();
+ expect(items).toContainEqual(expect.objectContaining({ title: "geo-map-context.add-note" }));
+ });
+});
diff --git a/apps/client/src/widgets/collections/geomap/ContextMenus.ts b/apps/client/src/widgets/collections/geomap/ContextMenus.ts
index 3662ef6822..5b43ec2f07 100644
--- a/apps/client/src/widgets/collections/geomap/ContextMenus.ts
+++ b/apps/client/src/widgets/collections/geomap/ContextMenus.ts
@@ -13,7 +13,19 @@ import { createNewNote } from "./api.js";
import { type GeoMouseEvent, ParentMap, toGeoMouseEvent } from "./map.js";
import { MARKER_LAYER } from "./Markers.js";
-export default function ContextMenus({ note, isReadOnly }: { note: FNote, isReadOnly: boolean }) {
+interface ContextMenusProps {
+ note: FNote;
+ isReadOnly: boolean;
+ /**
+ * Arms this map for the marker of the given note to be put somewhere else, the next click on the
+ * map being where. Handed down rather than triggered as a command because a command is heard by
+ * every map at once: embedded maps share no note context, so a broadcast would arm all of them
+ * (see the same reasoning around note placement in `index.tsx`).
+ */
+ onRelocate: (noteId: string) => void;
+}
+
+export default function ContextMenus({ note, isReadOnly, onRelocate }: ContextMenusProps) {
const map = useContext(ParentMap);
const onContextMenu = useCallback((e: GeoMouseEvent) => {
@@ -24,12 +36,12 @@ export default function ContextMenus({ note, isReadOnly }: { note: FNote, isRead
if (features.length > 0) {
// Marker context menu.
- openContextMenu(features[0].properties.id, e, !isReadOnly);
+ openContextMenu(features[0].properties.id, e, !isReadOnly, onRelocate);
} else {
// Empty area context menu.
openMapContextMenu(note, e, !isReadOnly);
}
- }, [ map, note, isReadOnly ]);
+ }, [ map, note, isReadOnly, onRelocate ]);
useEffect(() => {
if (!onContextMenu || !map) return;
@@ -45,7 +57,7 @@ export default function ContextMenus({ note, isReadOnly }: { note: FNote, isRead
return null;
}
-export function openContextMenu(noteId: string, e: GeoMouseEvent, isEditable: boolean) {
+export function openContextMenu(noteId: string, e: GeoMouseEvent, isEditable: boolean, onRelocate: (noteId: string) => void) {
let items: MenuItem<keyof CommandMappings>[] = [
...buildGeoLocationItem(e),
{ kind: "separator" },
@@ -56,6 +68,10 @@ export function openContextMenu(noteId: string, e: GeoMouseEvent, isEditable: bo
items = [
...items,
{ kind: "separator" },
+ // The marker is put somewhere else 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.
+ { title: t("geo-map-context.move-marker"), handler: () => onRelocate(noteId), uiIcon: "bx bx-move" },
{ title: t("geo-map-context.remove-from-map"), command: "deleteFromMap", uiIcon: "bx bx-trash" },
{ kind: "separator"},
{
diff --git a/apps/client/src/widgets/collections/geomap/Markers.spec.tsx b/apps/client/src/widgets/collections/geomap/Markers.spec.tsx
index def00fbeb5..b963435da0 100644
--- a/apps/client/src/widgets/collections/geomap/Markers.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/Markers.spec.tsx
@@ -14,6 +14,7 @@ import { render } from "preact";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import appContext from "../../../components/app_context";
import Component from "../../../components/component";
import type FNote from "../../../entities/fnote";
import type { EntityChange } from "../../../server_types";
@@ -38,11 +39,14 @@ interface FakeLayer {
paint?: Record<string, unknown>;
}
+/** What the component hands the map, which for a layer-scoped event is given the event itself. */
+type Listener = (e?: unknown) => void;
+
/** A map that records what the component does to it, standing in for MapLibre. */
function fakeMap() {
const layers = new Map<string, FakeLayer>();
const sources = new Map<string, unknown>();
- const listeners = new Map<string, Set<() => void>>();
+ const listeners = new Map<string, Set<Listener>>();
const calls = { addLayer: 0, removeLayer: 0, addSource: 0, removeSource: 0, setData: 0 };
const properties = new Map<string, unknown>();
const canvas = { style: {} as Record<string, string> };
@@ -77,18 +81,34 @@ function fakeMap() {
for (const fn of listeners.get("remove") ?? []) fn();
},
/**
- * MapLibre lets a listener be scoped to a layer, which the cluster handlers use — the layer
- * comes between the event and the handler when it does. Keyed by event alone here, since
- * nothing in these tests fires a layer-scoped one.
+ * MapLibre lets a listener be scoped to a layer, which the cluster and marker handlers use —
+ * the layer comes between the event and the handler when it does, and is part of the key so
+ * that firing one of them does not reach a handler listening to the same event elsewhere.
*/
on(event: string, fnOrLayer: unknown, fn?: () => void) {
- const handler = (fn ?? fnOrLayer) as () => void;
- if (!listeners.has(event)) listeners.set(event, new Set());
- listeners.get(event)?.add(handler);
+ 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(event)?.delete((fn ?? fnOrLayer) as () => void);
+ listeners.get(fn ? `${event}:${fnOrLayer}` : event)?.delete((fn ?? fnOrLayer) as Listener);
+ },
+ /** A marker being clicked, as MapLibre reports a click that landed on the layer. */
+ clickMarker(note: FNote) {
+ for (const fn of listeners.get(`click:${MARKER_LAYER}`) ?? []) {
+ fn({ features: [ { properties: { id: note.noteId } } ] });
+ }
+ },
+ /** The pointer coming to rest on a marker, and leaving it again. */
+ enterMarker() {
+ for (const fn of listeners.get(`mouseenter:${MARKER_LAYER}`) ?? []) fn({});
},
+ leaveMarker() {
+ for (const fn of listeners.get(`mouseleave:${MARKER_LAYER}`) ?? []) fn({});
+ },
+ /** What the map is currently showing the pointer as. */
+ get cursor() { return canvas.style.cursor ?? ""; },
isStyleLoaded: () => false,
hasImage: () => false,
addImage: () => {},
@@ -169,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 }) {
+ function mount(notes: FNote[], map: ReturnType<typeof fakeMap>, parent: Component, look?: { hideLabels?: boolean, isDarkTheme?: boolean, clustered?: boolean, placing?: boolean }) {
return act(async () => {
render(
<ParentComponent.Provider value={parent}>
@@ -179,6 +199,7 @@ describe("Markers", () => {
hideLabels={look?.hideLabels ?? false}
isDarkTheme={look?.isDarkTheme ?? false}
clustered={look?.clustered ?? false}
+ placing={look?.placing ?? false}
/>
</ParentMap.Provider>
</ParentComponent.Provider>,
@@ -413,4 +434,64 @@ describe("Markers", () => {
expect(map.calls.removeLayer).toBe(0);
expect(map.calls.removeSource).toBe(0);
});
+
+ /**
+ * What a click on a marker is for.
+ *
+ * A note used to open only on a map that could not be edited, since on one that could the mouse
+ * belonged to dragging the marker. Nothing is dragged any more — a marker is moved by being
+ * placed again, from its own context menu — so a click means the same thing on every map.
+ */
+ describe("opening a note", () => {
+ let openInPopup: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ openInPopup = vi.spyOn(appContext, "triggerCommand").mockResolvedValue(undefined);
+ });
+
+ afterEach(() => openInPopup.mockRestore());
+
+ it("opens the note behind the marker that was clicked", async () => {
+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });
+ const map = fakeMap();
+ await mount([ note ], map, new Component());
+
+ map.enterMarker();
+ // A marker is a thing to be opened, and says so before it is.
+ expect(map.cursor).toBe("pointer");
+
+ map.clickMarker(note);
+ expect(openInPopup).toHaveBeenCalledWith("openInPopup", { noteIdOrPath: note.noteId });
+ });
+
+ 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, new Component(), { placing: true });
+
+ // The click belongs to the placement, which is handled where that state lives: opening
+ // the note as well would both put the marker down and open the note it landed on.
+ map.clickMarker(note);
+ expect(openInPopup).not.toHaveBeenCalled();
+ });
+
+ /**
+ * Relocation is armed from the marker's own context menu, so the pointer is almost always
+ * sitting on a marker at the moment the opening handlers are taken off — and the `mouseleave`
+ * that would have cleared the cursor is no longer being listened for. The map would be left
+ * offering to open a note while waiting to be told where to put one.
+ */
+ it("puts the cursor back when it is disarmed with the pointer on a marker", async () => {
+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });
+ const map = fakeMap();
+ const parent = new Component();
+ await mount([ note ], map, parent);
+
+ map.enterMarker();
+ expect(map.cursor).toBe("pointer");
+
+ await mount([ note ], map, parent, { placing: true });
+ expect(map.cursor).toBe("");
+ });
+ });
});
diff --git a/apps/client/src/widgets/collections/geomap/Markers.tsx b/apps/client/src/widgets/collections/geomap/Markers.tsx
index 83ba307ea8..1d6bdd3ead 100644
--- a/apps/client/src/widgets/collections/geomap/Markers.tsx
+++ b/apps/client/src/widgets/collections/geomap/Markers.tsx
@@ -1,6 +1,7 @@
-import { AddLayerObject, type GeoJSONSource } from "maplibre-gl";
+import { AddLayerObject, type GeoJSONSource, type MapGeoJSONFeature, type Map as MapLibreGLMap, type MapMouseEvent } from "maplibre-gl";
import { useCallback, useContext, useEffect, useRef, useState } from "preact/hooks";
+import appContext from "../../../components/app_context";
import FNote from "../../../entities/fnote";
import { getReadableTextColor } from "../../../services/css_class_manager";
import { renderIconImage } from "../../../services/icon_glyphs";
@@ -86,7 +87,20 @@ const HIDDEN_TEXT_FIELD = "";
* per note is what made that slow. The pin is rasterized once per colour and icon and handed to the
* map as an image, which the layer then stamps on the GPU.
*/
-export default function Markers({ notes, hideLabels, isDarkTheme, clustered }: { notes: FNote[], hideLabels: boolean, isDarkTheme: boolean, clustered: boolean }) {
+interface MarkersProps {
+ notes: FNote[];
+ hideLabels: boolean;
+ isDarkTheme: boolean;
+ clustered: boolean;
+ /**
+ * Whether the map is armed for a click that already means something — a note to be created where
+ * it lands, or a marker to be moved there. A marker is not opened by such a click: it is a place
+ * on the map like any other for as long as the map is waiting to be told one.
+ */
+ placing: boolean;
+}
+
+export default function Markers({ notes, hideLabels, isDarkTheme, clustered, placing }: MarkersProps) {
const map = useContext(ParentMap);
const version = useNoteChangeVersion(notes);
// Whether the style has finished loading at least once. Held outside the effects because either
@@ -273,10 +287,62 @@ export default function Markers({ notes, hideLabels, isDarkTheme, clustered }: {
}, [ map, hideLabels, isDarkTheme ]);
useClusterExpansion(map, MARKER_SOURCE, clustered);
+ useMarkerOpening(map, !placing);
return null;
}
+/**
+ * Opening a note by clicking its marker, which is what a marker is for.
+ *
+ * Bound to the layer rather than to the map, so MapLibre does the hit-testing and the handler hears
+ * only the clicks that landed on a pin — the same way a bubble is opened (see `useClusterExpansion`).
+ * A click that misses every marker is the map's own, and reaches the handler in `index.tsx`.
+ *
+ * Note that the note is opened whether or not the map may be edited. Clicking used to open a note on
+ * a read-only map alone, because on an editable one the mouse belonged to dragging the marker; there
+ * is no dragging any more — a marker is moved by being placed again, from its context menu — so
+ * nothing is left for a click to mean instead.
+ *
+ * @param enabled whether a click on a marker is this map's to act on at all. False while the map is
+ * armed for placement, whose click is handled where that state lives and would
+ * otherwise both put the marker down and open the note it was clicked through.
+ */
+function useMarkerOpening(map: MapLibreGLMap | null, enabled: boolean) {
+ useEffect(() => {
+ if (!map || !enabled) return;
+
+ function onClick(e: MapMouseEvent & { features?: MapGeoJSONFeature[] }) {
+ const noteId = e.features?.[0]?.properties.id;
+ if (noteId) {
+ appContext.triggerCommand("openInPopup", { noteIdOrPath: noteId });
+ }
+ }
+
+ // A marker is a thing to be opened, and says so before it is.
+ const setCursor = (cursor: string) => {
+ if (map) map.getCanvas().style.cursor = cursor;
+ };
+ const onEnter = () => setCursor("pointer");
+ const onLeave = () => setCursor("");
+
+ map.on("click", MARKER_LAYER, onClick);
+ map.on("mouseenter", MARKER_LAYER, onEnter);
+ map.on("mouseleave", MARKER_LAYER, onLeave);
+
+ return () => {
+ map.off("click", MARKER_LAYER, onClick);
+ map.off("mouseenter", MARKER_LAYER, onEnter);
+ map.off("mouseleave", MARKER_LAYER, onLeave);
+ // The pointer is put back by hand: relocation is armed from a marker's own context menu,
+ // so this is torn down with the pointer sitting on a marker more often than not, and the
+ // `mouseleave` that would have cleared it is no longer being listened for. The cursor
+ // would otherwise stay a pointer over a map that is waiting to be clicked somewhere.
+ onLeave();
+ };
+ }, [ map, enabled ]);
+}
+
/**
* A GeoJSON feature per located note, and the pin image each of them asks for.
*
diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsx
index d1fd1e9d5b..95a62f95ae 100644
--- a/apps/client/src/widgets/collections/geomap/index.tsx
+++ b/apps/client/src/widgets/collections/geomap/index.tsx
@@ -29,6 +29,13 @@ import Tooltips from "./Tooltips";
const DEFAULT_COORDINATES: [number, number] = [3.878638227135724, 446.6630455551659];
const DEFAULT_ZOOM = 2;
+/**
+ * The instruction toast that says what the map is waiting for. One id for both kinds of placement:
+ * only one of them can be armed at a time, and reusing the id means arming the other while one is up
+ * rewrites that toast rather than stacking a second one under it.
+ */
+const PLACEMENT_TOAST_ID = "geo-placement";
+
export { LOCATION_ATTRIBUTE };
interface MapData {
@@ -38,13 +45,20 @@ interface MapData {
};
}
-enum State {
- Normal,
- NewNote
-}
+/**
+ * What the next click on the map is for, where it is for anything at all: a new note is to be created
+ * there, or the marker of the note named here is to be moved there. `undefined` is a map that is only
+ * being looked at, which is every map most of the time.
+ *
+ * The two are one state rather than two because they are alternatives — a click cannot mean both — and
+ * because the note being moved has nowhere else to be kept where it could not go missing.
+ */
+type Placement =
+ | { mode: "new" }
+ | { mode: "move"; noteId: string };
export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewModeProps<MapData>) {
- const [ state, setState ] = useState(State.Normal);
+ const [ placement, setPlacement ] = useState<Placement>();
const [ coordinates, setCoordinates ] = useState(viewConfig?.view?.center);
const [ zoom, setZoom ] = useState(viewConfig?.view?.zoom);
const [ hasScale ] = useNoteLabelBoolean(note, "map:scale");
@@ -68,50 +82,67 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
setZoom(viewConfig?.view?.zoom ?? DEFAULT_ZOOM);
}, [ note, viewConfig ]);
- // Note creation. Scoped to this map instance via a local callback rather than the global
- // geoMapCreateChildNote command: embedded maps share no note context (no distinct ntxId), so a
- // broadcast command would arm placement mode on every map at once. The button is this command's
- // only trigger, so a direct handler keeps it isolated to the clicked map.
- const startNotePlacement = useCallback(() => setState(State.NewNote), []);
-
- // Placement mode (NewNote) is armed by the button. Tying the instruction toast and the global
- // Escape-to-cancel listener to the state (rather than the click handler) guarantees both are
- // torn down on cancel, on completion (map click) and on unmount — otherwise the listener leaks
- // and a fresh one accumulates on every placement cycle.
+ // Note creation and marker relocation. Both are scoped to this map instance via local callbacks
+ // rather than global commands: embedded maps share no note context (no distinct ntxId), so a
+ // broadcast command would arm placement mode on every map at once. The button and the marker's
+ // context menu are these callbacks' only triggers, so a direct handler keeps each isolated to the
+ // map that was clicked.
+ const startNotePlacement = useCallback(() => setPlacement({ mode: "new" }), []);
+ const startMarkerRelocation = useCallback((noteId: string) => setPlacement({ mode: "move", noteId }), []);
+
+ // Placement mode is armed by the button or by the context menu. Tying the instruction toast and
+ // the global Escape-to-cancel listener to the state (rather than the handler that armed it)
+ // guarantees both are torn down on cancel, on completion (map click) and on unmount — otherwise
+ // the listener leaks and a fresh one accumulates on every placement cycle.
useEffect(() => {
- if (state !== State.NewNote) return;
+ if (!placement) return;
toast.showPersistent({
- icon: "plus",
- id: "geo-new-note",
- title: t("geo-map.create-child-note-toast-title"),
- message: t("geo-map.create-child-note-instruction")
+ id: PLACEMENT_TOAST_ID,
+ ...(placement.mode === "new"
+ ? {
+ icon: "plus",
+ title: t("geo-map.create-child-note-toast-title"),
+ message: t("geo-map.create-child-note-instruction")
+ }
+ : {
+ icon: "move",
+ title: t("geo-map.move-marker-toast-title"),
+ message: t("geo-map.move-marker-instruction")
+ })
});
const globalKeyListener = (e: KeyboardEvent) => {
if (e.key === "Escape") {
- setState(State.Normal);
+ setPlacement(undefined);
}
};
window.addEventListener("keydown", globalKeyListener);
return () => {
window.removeEventListener("keydown", globalKeyListener);
- toast.closePersistent("geo-new-note");
+ toast.closePersistent(PLACEMENT_TOAST_ID);
};
- }, [ state ]);
+ }, [ placement ]);
useTriliumEvent("deleteFromMap", ({ noteId }) => {
moveMarker(noteId, null);
});
const onClick = useCallback(async (e: GeoMouseEvent) => {
- if (state === State.NewNote) {
- // Leaving NewNote closes the instruction toast via the placement-mode effect cleanup.
+ if (!placement) return;
+
+ // Leaving placement mode closes the instruction toast via the effect's cleanup. The state is
+ // cleared first either way, so a failure to write the location does not leave the map armed
+ // for a click the user has stopped expecting to mean anything.
+ setPlacement(undefined);
+
+ if (placement.mode === "new") {
await createNewNote(note, e);
- setState(State.Normal);
+ } else {
+ await moveMarker(placement.noteId, e.latlng);
}
- }, [ note, state ]);
+ }, [ note, placement ]);
// Dragging
const containerRef = useRef<HTMLDivElement>(null);
@@ -147,7 +178,7 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
});
return (
- <div className={`geo-view ${state === State.NewNote ? "placing-note" : ""}`}>
+ <div className={`geo-view ${placement ? "placing-note" : ""}`}>
<CollectionProperties
note={note}
rightChildren={<>
@@ -176,8 +207,8 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
>
<MapToolbar />
<Tooltips />
- <ContextMenus note={note} isReadOnly={isReadOnly} />
- <Markers notes={notes} hideLabels={hideLabels} isDarkTheme={layerData.isDarkTheme ?? false} clustered={clustered} />
+ <ContextMenus note={note} isReadOnly={isReadOnly} onRelocate={startMarkerRelocation} />
+ <Markers notes={notes} hideLabels={hideLabels} isDarkTheme={layerData.isDarkTheme ?? false} clustered={clustered} placing={!!placement} />
{notes.map(note => <NoteGpxTrackWrapper note={note} hideLabels={hideLabels} />)}
</Map>}
</div>