Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): pin a searched place where it stands

Elian Dorandeec069298ed
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.css b/apps/client/src/widgets/collections/geomap/SearchBox.css
index 2a566bed77..759dced7d7 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.css
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.css
@@ -66,3 +66,33 @@ body.mobile .geo-map-container .geo-search-toolbar {
background: none;
color: inherit;
}
+
+/*
+ * The pin standing on a place taken from the geocoder. MapLibre places the element and writes its
+ * transform, so the drop is animated on the image inside it.
+ */
+.geo-map-container .geo-place-marker {
+ /* A click at the place belongs to the map, which is what arms placement and opens the context
+ menu (see index.tsx). */
+ pointer-events: none;
+}
+
+.geo-map-container .geo-place-marker 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;
+ animation: geo-place-marker-drop 200ms ease-out;
+}
+
+@keyframes geo-place-marker-drop {
+ from {
+ transform: translateY(-10px);
+ opacity: 0;
+ }
+ to {
+ transform: none;
+ opacity: 1;
+ }
+}
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
index bc0258e634..13f672f874 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
@@ -14,6 +14,42 @@ import { DEFAULT_GEOCODING_PROVIDER_NAME, GEOCODING_PROVIDERS, type GeoSearchRes
import { ParentMap } from "./map";
import SearchBox from "./SearchBox";
+// Hoisted, because map.tsx imports maplibre-gl as this file is loaded — a class declared below would
+// still be in its temporal dead zone when the factory runs.
+const { FakeMarker } = vi.hoisted(() => {
+ /** Stands in for MapLibre's own marker, which wants a real map to attach itself to. */
+ class FakeMarker {
+ static standing: FakeMarker[] = [];
+ lngLat?: [number, number];
+
+ constructor(readonly options: { element: HTMLElement; anchor?: string; offset?: [number, number] }) {}
+
+ setLngLat(lngLat: [number, number]) {
+ this.lngLat = lngLat;
+ return this;
+ }
+
+ addTo(_map: unknown) {
+ FakeMarker.standing.push(this);
+ return this;
+ }
+
+ remove() {
+ FakeMarker.standing = FakeMarker.standing.filter((marker) => marker !== this);
+ return this;
+ }
+ }
+
+ return { FakeMarker };
+});
+
+vi.mock("maplibre-gl", () => ({ Marker: FakeMarker }));
+
+// The pin's image is drawn from an icon the glyph service resolves against the real stylesheet.
+vi.mock("../../../services/icon_glyphs", () => ({
+ renderIconImage: vi.fn(async () => "data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=")
+}));
+
// i18next is not initialized under test, so t() returns "". The key stands in for the text, with any
// interpolated values after it, which is enough to tell the rows apart.
vi.mock("../../../services/i18n", () => ({
@@ -94,7 +130,10 @@ async function pick(index: number) {
await settle();
}
-beforeEach(() => vi.useFakeTimers());
+beforeEach(() => {
+ vi.useFakeTimers();
+ FakeMarker.standing = [];
+});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
@@ -196,6 +235,39 @@ describe("geo map SearchBox", () => {
expect(labels()).toEqual([ "geo-map.search-online(berlin de)" ]);
});
+ it("pins a searched place where it stands, since the map has nothing there of its own", async () => {
+ mockGeocoder([ TOKYO ]);
+ const container = renderSearchBox(fakeMap(), mapNotes());
+
+ await type(container, "tokyo");
+ await pick(1);
+ await pick(1);
+
+ expect(FakeMarker.standing).toHaveLength(1);
+ expect(FakeMarker.standing[0].lngLat).toEqual([ TOKYO.lng, TOKYO.lat ]);
+ // The tip of the pin stands on the place rather than the bottom edge of its image.
+ expect(FakeMarker.standing[0].options.anchor).toBe("bottom");
+
+ // A note of the map's own is already pinned, so taking one takes the searched pin away.
+ await type(container, "tokyo trip");
+ await pick(0);
+ expect(FakeMarker.standing).toHaveLength(0);
+ });
+
+ it("takes the pin off the map once the field is emptied", async () => {
+ mockGeocoder([ TOKYO ]);
+ const container = renderSearchBox(fakeMap(), []);
+
+ await type(container, "tokyo");
+ await pick(0);
+ await pick(0);
+ expect(FakeMarker.standing).toHaveLength(1);
+
+ await type(container, "");
+
+ expect(FakeMarker.standing).toHaveLength(0);
+ });
+
it("renders nothing when the map failed to initialize", () => {
expect(renderSearchBox(null).querySelector(".geo-search-toolbar")).toBeNull();
});
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.tsx
index adf0ae8a19..81bcb754c4 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.tsx
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.tsx
@@ -1,6 +1,7 @@
import "./SearchBox.css";
-import { useCallback, useContext, useRef, useState } from "preact/hooks";
+import { Marker } from "maplibre-gl";
+import { useCallback, useContext, useEffect, useRef, useState } from "preact/hooks";
import type FNote from "../../../entities/fnote";
import { t } from "../../../services/i18n";
@@ -10,7 +11,7 @@ import Icon from "../../react/Icon";
import OverlayToolbar from "../../react/OverlayToolbar";
import { DEFAULT_GEOCODING_PROVIDER_NAME, GEOCODING_PROVIDERS, type GeoSearchResult } from "./geocoding";
import { ParentMap } from "./map";
-import { LOCATION_ATTRIBUTE, parseLocation } from "./Markers";
+import { drawMarkerImage, LOCATION_ATTRIBUTE, MARKER_SHADOW_PADDING, parseLocation } from "./Markers";
/** Shorter queries are not searched. */
const MIN_QUERY_LENGTH = 2;
@@ -27,6 +28,12 @@ const MAX_MARKER_RESULTS = 8;
/** The key of the row reporting on a geocoder run, which only ever appears once. */
const STATUS_KEY = "geocode-status";
+/** The colour the pin for a searched place is drawn in, so it is not read as one of the map's notes. */
+const PLACE_MARKER_COLOR = "#E8833A";
+
+/** The icon that pin wears, naming where it came from. */
+const PLACE_MARKER_ICON = "bx bx-search";
+
interface SearchBoxProps {
/** The notes on the map, searched by title. */
notes: FNote[];
@@ -63,6 +70,10 @@ interface GeocodeRun {
* to a third party, and providers rate-limit and discourage per-keystroke lookups, so it sits at the
* bottom of the list as a row that runs it when picked.
*
+ * A place taken from the geocoder is pinned where it stands, since flying to a spot the map has
+ * nothing at otherwise leaves the user to work out which patch of ground was meant. The pin stands
+ * until another is taken or the field is emptied.
+ *
* `FormAutocomplete` handles the debounce, the stale-response guard, keyboard navigation and a
* dropdown portalled out of the map's scrolling container. `keepOpenOnPick` keeps the list up so the
* geocoder row can replace itself with results, so closing it after a marker or place is taken is
@@ -75,6 +86,8 @@ export default function SearchBox({ notes }: SearchBoxProps) {
// Empties the list once a marker or place has been taken, which is what closes the dropdown under
// `keepOpenOnPick`. Typing again clears it.
const [ dismissed, setDismissed ] = useState(false);
+ // Where the geocoder's last answer is pinned, and nothing while the map shows only its own notes.
+ const [ pickedPlace, setPickedPlace ] = useState<[number, number]>();
const entriesByKey = useRef(new Map<string, SearchEntry>());
// Discards a run superseded by a later one, since each reports through the same state.
const latestRun = useRef(0);
@@ -95,6 +108,10 @@ export default function SearchBox({ notes }: SearchBoxProps) {
const changeQuery = useCallback((newQuery: string) => {
setDismissed(false);
setQuery(newQuery);
+ // Emptying the field is how the pin is taken back off the map.
+ if (!newQuery.trim()) {
+ setPickedPlace(undefined);
+ }
}, []);
const runGeocoder = useCallback(async (searchQuery: string) => {
@@ -121,6 +138,8 @@ export default function SearchBox({ notes }: SearchBoxProps) {
} else if (entry.kind === "marker" || entry.kind === "place") {
setQuery(entry.label);
setDismissed(true);
+ // A note already has a marker of its own to fly to; only a place needs one put down.
+ setPickedPlace(entry.kind === "place" ? entry.center : undefined);
map.flyTo({ center: entry.center, zoom: entry.kind === "marker" ? MARKER_ZOOM : PLACE_ZOOM });
}
}, [ map, runGeocoder ]);
@@ -141,23 +160,68 @@ export default function SearchBox({ notes }: SearchBoxProps) {
if (!map) return null;
return (
- <OverlayToolbar className="geo-search-toolbar" titlePosition="bottom">
- <Icon icon="bx bx-search" className="geo-search-icon" />
- <FormAutocomplete
- className="geo-search-input"
- currentValue={query}
- onChange={changeQuery}
- onPick={pickEntry}
- source={source}
- renderItem={renderEntry}
- keepOpenOnPick
- placeholder={t("geo-map.search-placeholder")}
- aria-label={t("geo-map.search")}
- />
- </OverlayToolbar>
+ <>
+ {pickedPlace && <PlaceMarker center={pickedPlace} />}
+ <OverlayToolbar className="geo-search-toolbar" titlePosition="bottom">
+ <Icon icon="bx bx-search" className="geo-search-icon" />
+ <FormAutocomplete
+ className="geo-search-input"
+ currentValue={query}
+ onChange={changeQuery}
+ onPick={pickEntry}
+ source={source}
+ renderItem={renderEntry}
+ keepOpenOnPick
+ placeholder={t("geo-map.search-placeholder")}
+ aria-label={t("geo-map.search")}
+ />
+ </OverlayToolbar>
+ </>
);
}
+/**
+ * The pin standing on a place taken from the geocoder, for as long as that place is the one searched
+ * for.
+ *
+ * A MapLibre `Marker` rather than a feature in the notes' symbol layer: that layer is built from the
+ * notes and reloaded with them, and this pin belongs to neither. It wears the image the symbol layer
+ * stamps (see `drawMarkerImage`), in a colour and an icon no note marker uses.
+ */
+function PlaceMarker({ center }: { center: [number, number] }) {
+ const map = useContext(ParentMap);
+
+ useEffect(() => {
+ if (!map) return;
+
+ const element = document.createElement("div");
+ element.className = "geo-place-marker";
+ // The pin names nothing the search field does not already say, and a click at the place has
+ // the map to reach (see the armed click in index.tsx).
+ element.ariaHidden = "true";
+
+ // `icon-offset` on the symbol layer, as a marker offset: the tip of the pin sits a shadow's
+ // padding above the bottom edge of the image it is drawn in.
+ const marker = new Marker({ element, anchor: "bottom", offset: [ 0, MARKER_SHADOW_PADDING ] })
+ .setLngLat(center)
+ .addTo(map);
+
+ let cancelled = false;
+ drawMarkerImage(PLACE_MARKER_COLOR, PLACE_MARKER_ICON).then((image) => {
+ if (!cancelled && image) {
+ element.replaceChildren(image);
+ }
+ });
+
+ return () => {
+ cancelled = true;
+ marker.remove();
+ };
+ }, [ map, center ]);
+
+ return null;
+}
+
/** The notes on the map whose title contains the query and that are drawn somewhere. */
function matchMarkers(notes: FNote[], query: string): SearchEntry[] {
const needle = query.toLowerCase();