Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): add a search bar over the map

Elian Doranaa82bf43c8f6
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index b3f5b82408..90c8e3e9dd 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2953,7 +2953,9 @@
"exit-3d": "Lay the map flat again",
"close-details": "Close",
"marker-color": "Marker color",
- "copy-coordinates": "Copy coordinates"
+ "copy-coordinates": "Copy coordinates",
+ "search": "Search",
+ "search-placeholder": "Search for a place"
},
"embedded_note": {
"open-note": "Open note",
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.css b/apps/client/src/widgets/collections/geomap/SearchBox.css
new file mode 100644
index 0000000000..4ea7a7b699
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.css
@@ -0,0 +1,40 @@
+/* Top leading corner of the map, using the insets and z-index every overlay here uses (see
+ index.css). */
+.geo-map-container .geo-search-toolbar {
+ top: var(--geo-map-inset-top);
+ inset-inline-start: var(--geo-map-inset-start);
+ z-index: 3;
+ gap: 6px;
+ padding-inline: 8px;
+
+ /* The surface the control groups use, rather than the menu background OverlayToolbar defaults
+ to, which stays light over a dark map. */
+ background: var(--geo-map-panel-background);
+ color: var(--geo-map-panel-text-color);
+ border-color: var(--geo-map-panel-border-color);
+}
+
+/* On mobile the attribution takes the top leading corner (see map.tsx), so start below it. */
+body.mobile .geo-map-container .geo-search-toolbar {
+ top: calc(var(--geo-map-inset-top) * 2 + var(--geo-map-toolbar-height));
+}
+
+.geo-map-container .geo-search-toolbar .geo-search-icon {
+ opacity: 0.7;
+}
+
+/* The toolbar already frames the field, so drop the input's own border. */
+.geo-map-container .geo-search-toolbar .geo-search-input {
+ width: 15rem;
+ max-width: 40vw;
+ padding: 0;
+ color: inherit;
+ background: transparent;
+ border: none;
+ box-shadow: none;
+}
+
+.geo-map-container .geo-search-toolbar .geo-search-input::placeholder {
+ color: inherit;
+ opacity: 0.6;
+}
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
new file mode 100644
index 0000000000..08d37027e8
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
@@ -0,0 +1,90 @@
+/**
+ * The geo map search bar: which results a query produces, and what picking one does to the map.
+ * Results come from the dummy provider, so these cover the bar rather than any one geocoder.
+ */
+import type { Map as MapLibreGLMap } from "maplibre-gl";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { renderInto } from "../../../test/render";
+import { ParentMap } from "./map";
+import SearchBox from "./SearchBox";
+
+/** A map that can be flown somewhere, which is all the bar uses. */
+function fakeMap() {
+ return { flyTo: vi.fn() };
+}
+
+function renderSearchBox(map: ReturnType<typeof fakeMap> | null) {
+ let container: HTMLElement | undefined;
+ act(() => {
+ container = renderInto(
+ <ParentMap.Provider value={map as unknown as MapLibreGLMap}>
+ <SearchBox />
+ </ParentMap.Provider>
+ );
+ });
+ if (!container) throw new Error("the search bar was not rendered");
+ return container;
+}
+
+function field(container: HTMLElement) {
+ const input = container.querySelector<HTMLInputElement>("input.geo-search-input");
+ if (!input) throw new Error("the search bar has no field");
+ return input;
+}
+
+/** Types into the field and runs out the debounced lookup. */
+async function type(container: HTMLElement, text: string) {
+ const input = field(container);
+ // Two acts: the field has to re-render as open before the effect that schedules the lookup runs,
+ // so advancing the timers in the same act would find nothing scheduled.
+ await act(async () => {
+ input.value = text;
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ await act(async () => { await vi.advanceTimersByTimeAsync(300); });
+}
+
+/** The dropdown is portalled to the body, so look for it there rather than in the container. */
+function entries() {
+ return [ ...document.querySelectorAll<HTMLElement>(".form-autocomplete-dropdown .form-autocomplete-item") ];
+}
+
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => vi.useRealTimers());
+
+describe("geo map SearchBox", () => {
+ it("lists the places a query matches, and nothing for a query below the minimum length", async () => {
+ const container = renderSearchBox(fakeMap());
+
+ await type(container, "l");
+ expect(entries()).toHaveLength(0);
+
+ await type(container, "london");
+ // Two places of the same name, distinguished by the rest of the label.
+ expect(entries().map((entry) => entry.textContent)).toEqual([
+ "London, England, United Kingdom",
+ "London, Ontario, Canada"
+ ]);
+
+ await type(container, "nowhere at all");
+ expect(entries()).toHaveLength(0);
+ });
+
+ it("flies the map to the place picked and puts its name in the field", async () => {
+ const map = fakeMap();
+ const container = renderSearchBox(map);
+
+ await type(container, "tokyo");
+ await act(async () => { entries()[0].click(); });
+
+ expect(map.flyTo).toHaveBeenCalledWith({ center: [ 139.6503, 35.6762 ], zoom: expect.any(Number) });
+ expect(field(container).value).toBe("Tokyo, Japan");
+ expect(entries()).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
new file mode 100644
index 0000000000..bf23b7a0d7
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.tsx
@@ -0,0 +1,71 @@
+import "./SearchBox.css";
+
+import { useCallback, useContext, useRef, useState } from "preact/hooks";
+
+import { t } from "../../../services/i18n";
+import FormAutocomplete from "../../react/FormAutocomplete";
+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";
+
+/** Shorter queries are not looked up. */
+const MIN_QUERY_LENGTH = 2;
+
+/** The zoom level a picked result is shown at. */
+const RESULT_ZOOM = 12;
+
+/**
+ * A search bar over a geo map that flies the map to the place picked from it.
+ *
+ * Results come from a `GeocodingProvider`, currently the dummy one.
+ *
+ * `FormAutocomplete` handles the debounce, the stale-response guard, keyboard navigation and a
+ * dropdown portalled out of the map's scrolling container. Its items are strings, so `resultsByLabel`
+ * holds the matching `GeoSearchResult` to look up on pick. Results with the same label collapse to
+ * one, since they read identically in the list.
+ */
+export default function SearchBox() {
+ const map = useContext(ParentMap);
+ const [ query, setQuery ] = useState("");
+ const resultsByLabel = useRef(new Map<string, GeoSearchResult>());
+ const provider = GEOCODING_PROVIDERS[DEFAULT_GEOCODING_PROVIDER_NAME];
+
+ const source = useCallback(async (currentQuery: string) => {
+ const trimmed = currentQuery.trim();
+ if (trimmed.length < MIN_QUERY_LENGTH) {
+ resultsByLabel.current = new Map();
+ return [];
+ }
+
+ const results = await provider.search(trimmed);
+ resultsByLabel.current = new Map(results.map((result) => [ result.label, result ]));
+ return [ ...resultsByLabel.current.keys() ];
+ }, [ provider ]);
+
+ const flyToResult = useCallback((label: string) => {
+ const result = resultsByLabel.current.get(label);
+ if (!result || !map) return;
+
+ setQuery(label);
+ map.flyTo({ center: [ result.lng, result.lat ], zoom: RESULT_ZOOM });
+ }, [ map ]);
+
+ // The map failed to initialize, e.g. WebGL is unavailable (see map.tsx).
+ 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={setQuery}
+ onPick={flyToResult}
+ source={source}
+ placeholder={t("geo-map.search-placeholder")}
+ aria-label={t("geo-map.search")}
+ />
+ </OverlayToolbar>
+ );
+}
diff --git a/apps/client/src/widgets/collections/geomap/geocoding.ts b/apps/client/src/widgets/collections/geomap/geocoding.ts
new file mode 100644
index 0000000000..16ad20d8a4
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/geocoding.ts
@@ -0,0 +1,65 @@
+/** A single place returned by a geocoder. */
+export interface GeoSearchResult {
+ /** Unique within one result set. */
+ id: string;
+ /** Display text, with enough context to tell two places of the same name apart. */
+ label: string;
+ lat: number;
+ lng: number;
+}
+
+export interface GeocodingProvider {
+ /** Display name, shown where the user picks a provider. */
+ name: string;
+ /** Returns matches, best first, or an empty array when nothing matches. */
+ search(query: string): Promise<GeoSearchResult[]>;
+}
+
+/**
+ * The geocoders a map can search, keyed by the name a note selects one by.
+ *
+ * Same shape as `MAP_LAYERS` in map_layer.ts, so both are read the same way. Only the dummy provider
+ * exists so far; a real one is a new entry here.
+ */
+export const GEOCODING_PROVIDERS: Record<string, GeocodingProvider> = {
+ "dummy": {
+ name: "Dummy",
+ search: searchDummyPlaces
+ }
+};
+
+export const DEFAULT_GEOCODING_PROVIDER_NAME: keyof typeof GEOCODING_PROVIDERS = "dummy";
+
+/** The places `searchDummyPlaces()` matches against. */
+const DUMMY_PLACES: GeoSearchResult[] = [
+ { id: "dummy-amsterdam", label: "Amsterdam, Netherlands", lat: 52.3676, lng: 4.9041 },
+ { id: "dummy-berlin", label: "Berlin, Germany", lat: 52.52, lng: 13.405 },
+ { id: "dummy-bucharest", label: "Bucharest, Romania", lat: 44.4268, lng: 26.1025 },
+ { id: "dummy-cluj", label: "Cluj-Napoca, Cluj, Romania", lat: 46.7712, lng: 23.6236 },
+ { id: "dummy-lisbon", label: "Lisbon, Portugal", lat: 38.7223, lng: -9.1393 },
+ { id: "dummy-london", label: "London, England, United Kingdom", lat: 51.5072, lng: -0.1276 },
+ { id: "dummy-london-on", label: "London, Ontario, Canada", lat: 42.9849, lng: -81.2453 },
+ { id: "dummy-new-york", label: "New York, New York, United States", lat: 40.7128, lng: -74.006 },
+ { id: "dummy-paris", label: "Paris, Île-de-France, France", lat: 48.8566, lng: 2.3522 },
+ { id: "dummy-reykjavik", label: "Reykjavík, Iceland", lat: 64.1466, lng: -21.9426 },
+ { id: "dummy-sydney", label: "Sydney, New South Wales, Australia", lat: -33.8688, lng: 151.2093 },
+ { id: "dummy-tokyo", label: "Tokyo, Japan", lat: 35.6762, lng: 139.6503 }
+];
+
+/** Caps how many results one search returns. */
+const MAX_RESULTS = 8;
+
+/**
+ * Matches `DUMMY_PLACES` by substring, so the search bar works before a real geocoder is wired up.
+ * Async like a real provider, so callers cannot depend on results arriving in the same tick.
+ */
+async function searchDummyPlaces(query: string): Promise<GeoSearchResult[]> {
+ const needle = query.trim().toLowerCase();
+ if (!needle) {
+ return [];
+ }
+
+ return DUMMY_PLACES
+ .filter((place) => place.label.toLowerCase().includes(needle))
+ .slice(0, MAX_RESULTS);
+}
diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsx
index 10df3e4295..13822f5637 100644
--- a/apps/client/src/widgets/collections/geomap/index.tsx
+++ b/apps/client/src/widgets/collections/geomap/index.tsx
@@ -23,6 +23,7 @@ import Map, { DEFAULT_ZOOM, GeoMouseEvent } from "./map";
import { DEFAULT_MAP_LAYER_NAME, MAP_LAYERS, MapLayer } from "./map_layer";
import MapToolbar from "./MapToolbar";
import Markers, { DEFAULT_MARKER_COLOR, LOCATION_ATTRIBUTE } from "./Markers";
+import SearchBox from "./SearchBox";
import Tooltips from "./Tooltips";
const DEFAULT_COORDINATES: [number, number] = [3.878638227135724, 446.6630455551659];
@@ -243,6 +244,7 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
onClick={onClick}
scale={hasScale}
>
+ <SearchBox />
<MapToolbar />
<EditToolbar
isReadOnly={isReadOnly}