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): prefer what the map is showing when searching for a place
Elian Doran2ed24010ad73
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsxindex 272b9919f7..68554d17a4 100644--- a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx@@ -41,9 +41,21 @@ function mockGeocoder(results: GeoSearchResult[]) {.mockResolvedValue(results);}-/** A map that can be flown somewhere or framed on something, which is all the bar uses. */+/** Where a fake map is looking, which is what a search is told to prefer. */+const VIEWPORT = { west: 19.8, south: 39.5, east: 20.1, north: 39.8 };++/** A map that can be flown somewhere or framed on something, and that says what it is showing. */function fakeMap() {- return { flyTo: vi.fn(), fitBounds: vi.fn() };+ return {+ flyTo: vi.fn(),+ fitBounds: vi.fn(),+ getBounds: () => ({+ getWest: () => VIEWPORT.west,+ getSouth: () => VIEWPORT.south,+ getEast: () => VIEWPORT.east,+ getNorth: () => VIEWPORT.north+ })+ };}/** Two notes on the map and one that is only in its subtree, having no location to be drawn at. */@@ -148,7 +160,11 @@ describe("geo map SearchBox", () => {await pick(1);- expect(search).toHaveBeenCalledWith("tokyo");+ expect(search).toHaveBeenCalledWith("tokyo", {+ // The geocoder is told where the map is looking, so a name shared by two places is+ // answered with the one at hand.+ viewport: [ [ VIEWPORT.west, VIEWPORT.south ], [ VIEWPORT.east, VIEWPORT.north ] ]+ });// The row is replaced by what it found, the markers still standing above it.expect(labels()).toEqual([ "Tokyo trip", "Tokyo" ]);});diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.tsxindex f72e52a809..8e872bdb21 100644--- a/apps/client/src/widgets/collections/geomap/SearchBox.tsx+++ b/apps/client/src/widgets/collections/geomap/SearchBox.tsx@@ -2,13 +2,15 @@ import "./SearchBox.css";import { useCallback, useContext, useRef, useState } from "preact/hooks";+import type { Map as MapLibreGLMap } from "maplibre-gl";+import type FNote from "../../../entities/fnote";import { t } from "../../../services/i18n";import { logError } from "../../../services/ws";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 { DEFAULT_GEOCODING_PROVIDER_NAME, type GeoBounds, GEOCODING_PROVIDERS, type GeoSearchResult } from "./geocoding";import { ParentMap } from "./map";import { LOCATION_ATTRIBUTE, parseLocation } from "./Markers";import PlaceMarker from "./PlaceMarker";@@ -91,7 +93,8 @@ interface GeocodeRun {** The map's own notes are matched by title as the user types. The geocoder is not: it costs a request* 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.+ * bottom of the list as a row that runs it when picked. It is told what the map is showing, so that+ * what is nearby is preferred to what merely shares a name.** 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@@ -150,7 +153,9 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {setGeocodeRun({ query: searchQuery, status: "loading", results: [] });try {- const results = await provider.search(searchQuery);+ // Where the map is looking, so a shop searched for from Corfu is answered with the one in+ // Corfu rather than the one in Finland.+ const results = await provider.search(searchQuery, { viewport: map ? viewportOf(map) : undefined });if (latestRun.current !== runId) return;setGeocodeRun({ query: searchQuery, status: "done", results: results.map(placeEntry) });} catch (e) {@@ -158,7 +163,7 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {if (latestRun.current !== runId) return;setGeocodeRun({ query: searchQuery, status: "failed", results: [] });}- }, [ provider ]);+ }, [ provider, map ]);const pickEntry = useCallback((key: string) => {const entry = entriesByKey.current.get(key);@@ -243,6 +248,12 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {);}+/** What the map is showing, as a geocoder reads a preferred area. */+function viewportOf(map: MapLibreGLMap): GeoBounds {+ const bounds = map.getBounds();+ return [ [ bounds.getWest(), bounds.getSouth() ], [ bounds.getEast(), bounds.getNorth() ] ];+}+/*** What a label says beyond the place's own name, which is the address around it — "Ōta, Japan" of* "Tokyo, Ōta, Japan". A label that does not begin with the name is left whole, having nothing todiff --git a/apps/client/src/widgets/collections/geomap/geocoding.ts b/apps/client/src/widgets/collections/geomap/geocoding.tsindex 69d0864e8f..36c1b4df95 100644--- a/apps/client/src/widgets/collections/geomap/geocoding.ts+++ b/apps/client/src/widgets/collections/geomap/geocoding.ts@@ -1,5 +1,19 @@import { nominatim } from "./nominatim";+/** A rectangle of ground, as `[[west, south], [east, north]]`. */+export type GeoBounds = [[number, number], [number, number]];++export interface GeoSearchOptions {+ /**+ * What the map is showing. A place inside it is preferred to one of the same name elsewhere —+ * searching for a shop while looking at Corfu should not answer with the branch in Finland.+ *+ * A preference rather than a restriction: the only match for a query is worth offering wherever+ * it stands.+ */+ viewport?: GeoBounds;+}+/** A single place returned by a geocoder. */export interface GeoSearchResult {/** Unique within one result set. */@@ -11,11 +25,10 @@ export interface GeoSearchResult {lat: number;lng: number;/**- * What the place covers, as `[[west, south], [east, north]]`, where the geocoder says. A street- * and the city around it are told apart by their extent rather than by one zoom level guessed- * for both.+ * What the place covers, where the geocoder says. A street and the city around it are told apart+ * by their extent rather than by one zoom level guessed for both.*/- bounds?: [[number, number], [number, number]];+ bounds?: GeoBounds;/*** Fetches the boundary of the place — a country's coastline, a county's border — or `null` where* it has none worth drawing. Absent where the provider cannot supply one at all.@@ -33,7 +46,7 @@ export interface GeocodingProvider {* Returns matches, best first, or an empty array when nothing matches. Throws when the provider* cannot be reached or refuses the request.*/- search(query: string): Promise<GeoSearchResult[]>;+ search(query: string, options?: GeoSearchOptions): Promise<GeoSearchResult[]>;}/**diff --git a/apps/client/src/widgets/collections/geomap/nominatim.spec.ts b/apps/client/src/widgets/collections/geomap/nominatim.spec.tsindex 9d4d02a62d..df4667a345 100644--- a/apps/client/src/widgets/collections/geomap/nominatim.spec.ts+++ b/apps/client/src/widgets/collections/geomap/nominatim.spec.ts@@ -35,8 +35,8 @@ function respondWith(body: unknown, init: { ok?: boolean; status?: number } = {}}/** Runs a search, letting the rate limiter's wait elapse rather than sitting through it. */-async function search(query: string) {- const results = provider.search(query);+async function search(query: string, options?: Parameters<typeof provider.search>[1]) {+ const results = provider.search(query, options);await vi.runAllTimersAsync();return results;}@@ -102,6 +102,30 @@ describe("Nominatim geocoding", () => {await refused;});+ it("prefers what the map is showing, without refusing what lies outside it", async () => {+ const fetchMock = respondWith([]);++ await search("jumbo", { viewport: [ [ 19.8, 39.5 ], [ 20.1, 39.8 ] ] });++ // Two opposite corners, longitude first, as Nominatim reads a preferred area.+ expect(requestedUrl(fetchMock).searchParams.get("viewbox")).toBe("19.8,39.5,20.1,39.8");+ // A preference, not a restriction: `bounded` would answer nothing where the only match is+ // somewhere else entirely.+ expect(requestedUrl(fetchMock).searchParams.get("bounded")).toBeNull();+ });++ it("asks from nowhere in particular where the view says nothing usable", async () => {+ const fromNowhere = respondWith([]);+ await search("jumbo");+ expect(requestedUrl(fromNowhere).searchParams.get("viewbox")).toBeNull();++ // Panned across the antimeridian, where the view runs the other way round and no pair of+ // corners describes it.+ const wrapped = respondWith([]);+ await search("jumbo", { viewport: [ [ 170, 39.5 ], [ -170, 39.8 ] ] });+ expect(requestedUrl(wrapped).searchParams.get("viewbox")).toBeNull();+ });+it("fetches the boundary of a place on its own, simplified, only when it is asked for", async () => {const fetchMock = respondWith([ place() ]);const [ berlin ] = await search("berlin");diff --git a/apps/client/src/widgets/collections/geomap/nominatim.ts b/apps/client/src/widgets/collections/geomap/nominatim.tsindex 58ea3481c0..c583b74331 100644--- a/apps/client/src/widgets/collections/geomap/nominatim.ts+++ b/apps/client/src/widgets/collections/geomap/nominatim.ts@@ -1,5 +1,5 @@import { getCurrentLanguage } from "../../../services/i18n";-import type { GeocodingProvider, GeoSearchResult } from "./geocoding";+import type { GeoBounds, GeocodingProvider, GeoSearchOptions, GeoSearchResult } from "./geocoding";const NOMINATIM_URL = "https://nominatim.openstreetmap.org/search";const NOMINATIM_LOOKUP_URL = "https://nominatim.openstreetmap.org/lookup";@@ -44,7 +44,7 @@ export const nominatim: GeocodingProvider = {search: searchNominatim};-async function searchNominatim(query: string): Promise<GeoSearchResult[]> {+async function searchNominatim(query: string, { viewport }: GeoSearchOptions = {}): Promise<GeoSearchResult[]> {const params = new URLSearchParams({q: query,format: "jsonv2",@@ -58,6 +58,11 @@ async function searchNominatim(query: string): Promise<GeoSearchResult[]> {params.set("accept-language", language.replace("_", "-"));}+ const viewbox = toViewbox(viewport);+ if (viewbox) {+ params.set("viewbox", viewbox);+ }+await waitForRequestSlot();const response = await fetch(`${NOMINATIM_URL}?${params}`);if (!response.ok) {@@ -125,6 +130,27 @@ function toBounds(boundingbox: string[] | undefined): GeoSearchResult["bounds"]return [ [ west, south ], [ east, north ] ];}+/**+ * What the map is showing, as Nominatim reads a preferred area: two opposite corners, longitude+ * first. Sent without `bounded`, so a place is ranked up for being in view rather than a place out+ * of view being refused.+ *+ * A view running the other way round has been panned across the antimeridian, which no pair of+ * corners describes; nothing is sent for one, and the search is answered as if from nowhere.+ */+function toViewbox(viewport: GeoBounds | undefined) {+ if (!viewport) {+ return null;+ }++ const [ [ west, south ], [ east, north ] ] = viewport;+ if (!(west < east)) {+ return null;+ }++ return [ west, south, east, north ].join(",");+}+/*** The boundary of one OSM object, simplified, or `null` where it has none to draw.*