Skip to content

Build your personal knowledge base with Trilium Notes

refactor(geomap): move the Nominatim geocoder into its own module

Elian Doran0b6b6d9b8817
diff --git a/apps/client/src/widgets/collections/geomap/geocoding.ts b/apps/client/src/widgets/collections/geomap/geocoding.ts
index 46e839f325..04314b892c 100644
--- a/apps/client/src/widgets/collections/geomap/geocoding.ts
+++ b/apps/client/src/widgets/collections/geomap/geocoding.ts
@@ -1,4 +1,4 @@
-import { getCurrentLanguage } from "../../../services/i18n";
+import { nominatim } from "./nominatim";
/** A single place returned by a geocoder. */
export interface GeoSearchResult {
@@ -26,99 +26,7 @@ export interface GeocodingProvider {
* Same shape as `MAP_LAYERS` in map_layer.ts, so both are read the same way.
*/
export const GEOCODING_PROVIDERS: Record<string, GeocodingProvider> = {
- "nominatim": {
- name: "Nominatim (OpenStreetMap)",
- search: searchNominatim
- }
+ "nominatim": nominatim
};
export const DEFAULT_GEOCODING_PROVIDER_NAME: keyof typeof GEOCODING_PROVIDERS = "nominatim";
-
-const NOMINATIM_URL = "https://nominatim.openstreetmap.org/search";
-
-/** Caps how many results one search returns. */
-const MAX_RESULTS = 8;
-
-/**
- * Nominatim's usage policy allows at most one request per second, and blocks clients that exceed it.
- * See https://operations.osmfoundation.org/policies/nominatim/.
- */
-const MIN_REQUEST_INTERVAL = 1000;
-
-/** When the next request is allowed to go out, moved forward by every request that is queued. */
-let nextRequestAt = 0;
-
-/**
- * Looks a query up through Nominatim, the geocoder run by the OpenStreetMap Foundation.
- *
- * No API key, and it answers with `Access-Control-Allow-Origin: *`, so the browser can ask it
- * directly — which matters on desktop, where the page is served from `trilium-app://`. Its policy
- * also asks that clients identify themselves, which a browser can only do through the `Referer` it
- * sends of its own accord.
- *
- * The same policy rules out searching as the user types, which is why a search runs only when the
- * user asks for one (see SearchBox).
- */
-async function searchNominatim(query: string): Promise<GeoSearchResult[]> {
- const params = new URLSearchParams({
- q: query,
- format: "jsonv2",
- limit: String(MAX_RESULTS)
- });
-
- // Place names in the language the app runs in, where Nominatim holds one. Trilium writes some
- // locale ids with an underscore (`pt_br`), which is not what a language tag looks like.
- const language = getCurrentLanguage();
- if (language) {
- params.set("accept-language", language.replace("_", "-"));
- }
-
- await waitForRequestSlot();
- const response = await fetch(`${NOMINATIM_URL}?${params}`);
- if (!response.ok) {
- throw new Error(`Nominatim answered ${response.status} ${response.statusText}`);
- }
-
- const places: NominatimPlace[] = await response.json();
- return places.map(toSearchResult).filter((result) => result !== null);
-}
-
-/** One entry of a Nominatim `jsonv2` response, narrowed to the fields a result is built from. */
-interface NominatimPlace {
- place_id?: number;
- display_name?: string;
- lat?: string;
- lon?: string;
-}
-
-/** A place as the app holds one, or `null` where the entry carries no readable position. */
-function toSearchResult(place: NominatimPlace): GeoSearchResult | null {
- const lat = Number(place.lat);
- const lng = Number(place.lon);
- if (!place.display_name || !Number.isFinite(lat) || !Number.isFinite(lng)) {
- return null;
- }
-
- return {
- id: String(place.place_id ?? `${lat},${lng}`),
- label: place.display_name,
- lat,
- lng
- };
-}
-
-/**
- * Holds a request back until the interval the policy asks for has passed since the last one.
- *
- * The slot is claimed before the wait rather than after it, so two searches started at once queue
- * behind each other instead of both finding the same slot free.
- */
-async function waitForRequestSlot() {
- const now = Date.now();
- const slot = Math.max(now, nextRequestAt);
- nextRequestAt = slot + MIN_REQUEST_INTERVAL;
-
- if (slot > now) {
- await new Promise((resolve) => setTimeout(resolve, slot - now));
- }
-}
diff --git a/apps/client/src/widgets/collections/geomap/geocoding.spec.ts b/apps/client/src/widgets/collections/geomap/nominatim.spec.ts
similarity index 95%
rename from apps/client/src/widgets/collections/geomap/geocoding.spec.ts
rename to apps/client/src/widgets/collections/geomap/nominatim.spec.ts
index 7edd0d22cd..b13ed07ee8 100644
--- a/apps/client/src/widgets/collections/geomap/geocoding.spec.ts
+++ b/apps/client/src/widgets/collections/geomap/nominatim.spec.ts
@@ -4,12 +4,10 @@
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { DEFAULT_GEOCODING_PROVIDER_NAME, GEOCODING_PROVIDERS } from "./geocoding";
+import { nominatim as provider } from "./nominatim";
vi.mock("../../../services/i18n", () => ({ getCurrentLanguage: () => "pt_br" }));
-const provider = GEOCODING_PROVIDERS[DEFAULT_GEOCODING_PROVIDER_NAME];
-
/** One entry as Nominatim's `jsonv2` answer carries it. */
function place(overrides: Record<string, unknown> = {}) {
return {
diff --git a/apps/client/src/widgets/collections/geomap/nominatim.ts b/apps/client/src/widgets/collections/geomap/nominatim.ts
new file mode 100644
index 0000000000..12aedc3548
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/nominatim.ts
@@ -0,0 +1,96 @@
+import { getCurrentLanguage } from "../../../services/i18n";
+import type { GeocodingProvider, GeoSearchResult } from "./geocoding";
+
+const NOMINATIM_URL = "https://nominatim.openstreetmap.org/search";
+
+/** Caps how many results one search returns. */
+const MAX_RESULTS = 8;
+
+/**
+ * Nominatim's usage policy allows at most one request per second, and blocks clients that exceed it.
+ * See https://operations.osmfoundation.org/policies/nominatim/.
+ */
+const MIN_REQUEST_INTERVAL = 1000;
+
+/** When the next request is allowed to go out, moved forward by every request that is queued. */
+let nextRequestAt = 0;
+
+/**
+ * Nominatim, the geocoder run by the OpenStreetMap Foundation.
+ *
+ * No API key, and it answers with `Access-Control-Allow-Origin: *`, so the browser can ask it
+ * directly — which matters on desktop, where the page is served from `trilium-app://`. Its policy
+ * also asks that clients identify themselves, which a browser can only do through the `Referer` it
+ * sends of its own accord.
+ *
+ * The same policy rules out searching as the user types, which is why a search runs only when the
+ * user asks for one (see SearchBox).
+ */
+export const nominatim: GeocodingProvider = {
+ name: "Nominatim (OpenStreetMap)",
+ search: searchNominatim
+};
+
+async function searchNominatim(query: string): Promise<GeoSearchResult[]> {
+ const params = new URLSearchParams({
+ q: query,
+ format: "jsonv2",
+ limit: String(MAX_RESULTS)
+ });
+
+ // Place names in the language the app runs in, where Nominatim holds one. Trilium writes some
+ // locale ids with an underscore (`pt_br`), which is not what a language tag looks like.
+ const language = getCurrentLanguage();
+ if (language) {
+ params.set("accept-language", language.replace("_", "-"));
+ }
+
+ await waitForRequestSlot();
+ const response = await fetch(`${NOMINATIM_URL}?${params}`);
+ if (!response.ok) {
+ throw new Error(`Nominatim answered ${response.status} ${response.statusText}`);
+ }
+
+ const places: NominatimPlace[] = await response.json();
+ return places.map(toSearchResult).filter((result) => result !== null);
+}
+
+/** One entry of a Nominatim `jsonv2` response, narrowed to the fields a result is built from. */
+interface NominatimPlace {
+ place_id?: number;
+ display_name?: string;
+ lat?: string;
+ lon?: string;
+}
+
+/** A place as the app holds one, or `null` where the entry carries no readable position. */
+function toSearchResult(place: NominatimPlace): GeoSearchResult | null {
+ const lat = Number(place.lat);
+ const lng = Number(place.lon);
+ if (!place.display_name || !Number.isFinite(lat) || !Number.isFinite(lng)) {
+ return null;
+ }
+
+ return {
+ id: String(place.place_id ?? `${lat},${lng}`),
+ label: place.display_name,
+ lat,
+ lng
+ };
+}
+
+/**
+ * Holds a request back until the interval the policy asks for has passed since the last one.
+ *
+ * The slot is claimed before the wait rather than after it, so two searches started at once queue
+ * behind each other instead of both finding the same slot free.
+ */
+async function waitForRequestSlot() {
+ const now = Date.now();
+ const slot = Math.max(now, nextRequestAt);
+ nextRequestAt = slot + MIN_REQUEST_INTERVAL;
+
+ if (slot > now) {
+ await new Promise((resolve) => setTimeout(resolve, slot - now));
+ }
+}