Skip to content

Build your personal knowledge base with Trilium Notes

fix(geomap): draw the searched place as a marker of the map, and name it

Elian Dorane355c5840d87
diff --git a/apps/client/src/widgets/collections/geomap/PlaceMarker.spec.tsx b/apps/client/src/widgets/collections/geomap/PlaceMarker.spec.tsx
new file mode 100644
index 0000000000..c47f553419
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/PlaceMarker.spec.tsx
@@ -0,0 +1,142 @@
+/**
+ * The pin standing on a place taken from the search: that it is drawn as a marker of the map rather
+ * than as something laid over it, labelled with the place's name and following the style from light
+ * to dark, and that it leaves nothing behind when it goes.
+ */
+import type { Map as MapLibreGLMap } from "maplibre-gl";
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { MapStyleLoaded, ParentMap } from "./map";
+import { LABEL_PAINT, MARKER_SHADOW_PADDING, markerImageId } from "./Markers";
+import PlaceMarker, { PLACE_LAYER, PLACE_MARKER_COLOR, PLACE_MARKER_ICON, PLACE_SOURCE } from "./PlaceMarker";
+
+// The pin is rasterized by loading an SVG into an Image, and happy-dom never fires that load — so
+// the layer, which waits for the pin, would never be added. Only the rasterizing is stood in for;
+// the layout and paint the assertions read are the real ones.
+vi.mock("./Markers", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("./Markers")>()),
+ buildMarkerImage: vi.fn(async () => new Image())
+}));
+
+const TOKYO: [number, number] = [ 139.6503, 35.6762 ];
+
+interface FakeLayer {
+ id: string;
+ source?: string;
+ layout?: Record<string, unknown>;
+ paint?: Record<string, unknown>;
+}
+
+/** A map that records what the component adds to it and takes away again. */
+function fakeMap() {
+ const layers = new Map<string, FakeLayer>();
+ const sources = new Map<string, unknown>();
+ const images = new Set<string>();
+ const removals: string[] = [];
+
+ return {
+ removals,
+ layer: (id: string) => layers.get(id),
+ source: (id: string) => sources.get(id),
+ hasImage: (id: string) => images.has(id),
+ addImage: (id: string) => { images.add(id); },
+ addSource: (id: string, source: unknown) => { sources.set(id, source); },
+ addLayer: (layer: FakeLayer) => { layers.set(layer.id, layer); },
+ getSource: (id: string) => sources.get(id),
+ getLayer: (id: string) => layers.get(id),
+ removeSource: (id: string) => { removals.push(`source:${id}`); sources.delete(id); },
+ removeLayer: (id: string) => { removals.push(`layer:${id}`); layers.delete(id); },
+ on: () => {},
+ off: () => {}
+ };
+}
+
+const containers: HTMLElement[] = [];
+
+/** Puts the pin on a map whose style is ready, and settles the pin image the layer waits for. */
+async function renderMarker(map: ReturnType<typeof fakeMap>, { name = "Tokyo", isDarkTheme = false } = {}) {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ containers.push(container);
+
+ await act(async () => {
+ render(
+ <ParentMap.Provider value={map as unknown as MapLibreGLMap}>
+ <MapStyleLoaded.Provider value={true}>
+ <PlaceMarker center={TOKYO} name={name} isDarkTheme={isDarkTheme} />
+ </MapStyleLoaded.Provider>
+ </ParentMap.Provider>,
+ container
+ );
+ });
+ await settle();
+
+ return { unmount: async () => { await act(async () => { render(null, container); }); } };
+}
+
+/** Lets the awaited pin image arrive, which is what the layer is held back for. */
+async function settle() {
+ await act(async () => { await Promise.resolve(); });
+}
+
+afterEach(() => {
+ for (const container of containers) {
+ render(null, container);
+ container.remove();
+ }
+ containers.length = 0;
+});
+
+describe("geo map PlaceMarker", () => {
+ it("stands the place on its own layer, pinned and named where the geocoder put it", async () => {
+ const map = fakeMap();
+
+ await renderMarker(map);
+
+ expect(map.source(PLACE_SOURCE)).toMatchObject({
+ type: "geojson",
+ data: {
+ geometry: { type: "Point", coordinates: TOKYO },
+ properties: { name: "Tokyo" }
+ }
+ });
+
+ const layer = map.layer(PLACE_LAYER);
+ expect(layer?.source).toBe(PLACE_SOURCE);
+ expect(layer?.layout).toMatchObject({
+ "icon-image": markerImageId(PLACE_MARKER_COLOR, PLACE_MARKER_ICON),
+ // The tip stands on the coordinate rather than the bottom edge of the image, as the note
+ // pins do.
+ "icon-anchor": "bottom",
+ "icon-offset": [ 0, MARKER_SHADOW_PADDING ],
+ // The one thing on the map the user has just asked to see does not give way to a label
+ // that was already there.
+ "icon-allow-overlap": true,
+ "text-allow-overlap": true,
+ "text-field": [ "get", "name" ]
+ });
+ });
+
+ it("labels the place the way the map labels its own markers, on a light style and a dark one", async () => {
+ const light = fakeMap();
+ await renderMarker(light);
+ expect(light.layer(PLACE_LAYER)?.paint).toMatchObject(LABEL_PAINT.light);
+
+ const dark = fakeMap();
+ await renderMarker(dark, { isDarkTheme: true });
+ expect(dark.layer(PLACE_LAYER)?.paint).toMatchObject(LABEL_PAINT.dark);
+ });
+
+ it("takes the layer and its source away with it, the layer first", async () => {
+ const map = fakeMap();
+ const { unmount } = await renderMarker(map);
+ expect(map.layer(PLACE_LAYER)).toBeTruthy();
+
+ await unmount();
+
+ // A source still drawn from cannot be removed, so the layer goes first.
+ expect(map.removals).toEqual([ `layer:${PLACE_LAYER}`, `source:${PLACE_SOURCE}` ]);
+ });
+});
diff --git a/apps/client/src/widgets/collections/geomap/PlaceMarker.tsx b/apps/client/src/widgets/collections/geomap/PlaceMarker.tsx
new file mode 100644
index 0000000000..fff1459d9b
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/PlaceMarker.tsx
@@ -0,0 +1,128 @@
+import { useContext, useEffect } from "preact/hooks";
+
+import { MapStyleLoaded, ParentMap } from "./map";
+import { buildMarkerImage, LABEL_LAYOUT, LABEL_PAINT, MARKER_SHADOW_PADDING, markerImageId } from "./Markers";
+
+/** The colour the pin is drawn in, so a searched place is not read as one of the map's own notes. */
+export const PLACE_MARKER_COLOR = "#E8833A";
+
+/** The icon that pin wears, naming where it came from. */
+export const PLACE_MARKER_ICON = "bx bx-search";
+
+export const PLACE_SOURCE = "searched-place";
+export const PLACE_LAYER = "searched-place-layer";
+
+interface PlaceMarkerProps {
+ /** Where the place stands, as `[lng, lat]`. */
+ center: [number, number];
+ /** What the pin is labelled with: the place's own name rather than its full address. */
+ name: string;
+ /** Whether the map's style is a dark one, which decides how the label is drawn (see Markers). */
+ isDarkTheme: boolean;
+}
+
+/**
+ * The pin standing on a place taken from the geocoder.
+ *
+ * A symbol layer of its own rather than a feature among the notes': that layer is built from the
+ * notes and reloaded with them, and a searched place is neither. It goes through the same pin
+ * rasterizer and the same label layout and paint the note markers use (see Markers), so it is drawn
+ * as a marker of the map rather than as something laid over it — the name included, which follows
+ * the style from light to dark as every other label on the map does.
+ */
+export default function PlaceMarker({ center, name, isDarkTheme }: PlaceMarkerProps) {
+ const parentMap = useContext(ParentMap);
+ const styleLoaded = useContext(MapStyleLoaded);
+
+ useEffect(() => {
+ if (!parentMap) return;
+ // Aliased so the narrowing above carries into the nested function below.
+ const map = parentMap;
+ const imageId = markerImageId(PLACE_MARKER_COLOR, PLACE_MARKER_ICON);
+ let cancelled = false;
+ let image: HTMLImageElement | null = null;
+
+ function addLayer() {
+ const pin = image;
+ if (cancelled || !pin) return;
+
+ try {
+ if (map.getLayer(PLACE_LAYER)) return;
+
+ if (!map.hasImage(imageId)) {
+ map.addImage(imageId, pin, { pixelRatio: window.devicePixelRatio || 1 });
+ }
+
+ map.addSource(PLACE_SOURCE, {
+ type: "geojson",
+ data: {
+ type: "Feature",
+ geometry: { type: "Point", coordinates: center },
+ properties: { name }
+ }
+ });
+
+ map.addLayer({
+ id: PLACE_LAYER,
+ type: "symbol",
+ source: PLACE_SOURCE,
+ layout: {
+ "icon-image": imageId,
+ "icon-size": 1,
+ "icon-anchor": "bottom",
+ // The image carries padding for its shadow, pushed back down by exactly that
+ // much so the tip stands on the coordinate — as the note pins are.
+ "icon-offset": [ 0, MARKER_SHADOW_PADDING ],
+ ...LABEL_LAYOUT,
+ // Neither the pin nor its name gives way to a crowded map: this is the one
+ // thing on it the user has just asked to be shown, and it stands only until
+ // they have done with it.
+ "icon-allow-overlap": true,
+ "text-allow-overlap": true
+ },
+ paint: {
+ ...LABEL_PAINT[isDarkTheme ? "dark" : "light"],
+ "text-halo-width": 2,
+ "text-halo-blur": 1
+ }
+ });
+ } catch (e) {
+ // Only worth a word if the style was ready and it still would not take the pin.
+ if (styleLoaded) {
+ console.warn("Geo map: could not pin the searched place —", e);
+ }
+ }
+ }
+
+ buildMarkerImage(PLACE_MARKER_COLOR, PLACE_MARKER_ICON).then((built) => {
+ if (cancelled) return;
+ image = built;
+ if (styleLoaded) {
+ addLayer();
+ }
+ });
+
+ if (styleLoaded) {
+ addLayer();
+ }
+ map.on("style.load", addLayer);
+
+ return () => {
+ cancelled = true;
+ map.off("style.load", addLayer);
+ try {
+ // The layer before the source it draws from: one still in use cannot be removed.
+ if (map.getLayer(PLACE_LAYER)) {
+ map.removeLayer(PLACE_LAYER);
+ }
+ if (map.getSource(PLACE_SOURCE)) {
+ map.removeSource(PLACE_SOURCE);
+ }
+ } catch {
+ // The map may already have been removed.
+ }
+ };
+ }, [ parentMap, styleLoaded, center, name, isDarkTheme ]);
+
+ return null;
+}
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.css b/apps/client/src/widgets/collections/geomap/SearchBox.css
index 759dced7d7..2a566bed77 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.css
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.css
@@ -66,33 +66,3 @@ 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 13f672f874..0486240e90 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
@@ -14,40 +14,11 @@ 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=")
+/** The pin is drawn on the map by its own component, which has a spec of its own; here it only has to
+ * stand in the right place, so it is rendered as something the DOM can be asked about. */
+vi.mock("./PlaceMarker", () => ({
+ default: ({ center, name }: { center: [number, number]; name: string }) =>
+ <div className="place-marker" data-center={center.join(",")} data-name={name} />
}));
// i18next is not initialized under test, so t() returns "". The key stands in for the text, with any
@@ -56,7 +27,7 @@ vi.mock("../../../services/i18n", () => ({
t: (key: string, vars?: Record<string, unknown>) => (vars ? `${key}(${Object.values(vars).join(",")})` : key)
}));
-const TOKYO: GeoSearchResult = { id: "1", label: "Tokyo, Japan", lat: 35.6762, lng: 139.6503 };
+const TOKYO: GeoSearchResult = { id: "1", label: "Tokyo, Japan", name: "Tokyo", lat: 35.6762, lng: 139.6503 };
/** Stands in for the geocoder, which would otherwise reach for the network. */
function mockGeocoder(results: GeoSearchResult[]) {
@@ -84,7 +55,7 @@ function renderSearchBox(map: ReturnType<typeof fakeMap> | null, notes: FNote[]
act(() => {
container = renderInto(
<ParentMap.Provider value={map as unknown as MapLibreGLMap}>
- <SearchBox notes={notes} />
+ <SearchBox notes={notes} isDarkTheme={false} />
</ParentMap.Provider>
);
});
@@ -130,10 +101,7 @@ async function pick(index: number) {
await settle();
}
-beforeEach(() => {
- vi.useFakeTimers();
- FakeMarker.standing = [];
-});
+beforeEach(() => vi.useFakeTimers());
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
@@ -224,7 +192,7 @@ describe("geo map SearchBox", () => {
});
it("offers the geocoder again once the query moves on from what it answered", async () => {
- mockGeocoder([ { id: "2", label: "Berlin, Germany", lat: 52.52, lng: 13.405 } ]);
+ mockGeocoder([ { id: "2", label: "Berlin, Germany", name: "Berlin", lat: 52.52, lng: 13.405 } ]);
const container = renderSearchBox(fakeMap(), []);
await type(container, "berlin");
@@ -235,7 +203,7 @@ 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 () => {
+ it("pins a searched place where it stands, named as the geocoder names it", async () => {
mockGeocoder([ TOKYO ]);
const container = renderSearchBox(fakeMap(), mapNotes());
@@ -243,15 +211,15 @@ describe("geo map SearchBox", () => {
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");
+ const pin = () => container.querySelector<HTMLElement>(".place-marker");
+ expect(pin()?.dataset.center).toBe(`${TOKYO.lng},${TOKYO.lat}`);
+ // The place's own name rather than the full label the list reads.
+ expect(pin()?.dataset.name).toBe("Tokyo");
// 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);
+ expect(pin()).toBeNull();
});
it("takes the pin off the map once the field is emptied", async () => {
@@ -261,11 +229,11 @@ describe("geo map SearchBox", () => {
await type(container, "tokyo");
await pick(0);
await pick(0);
- expect(FakeMarker.standing).toHaveLength(1);
+ expect(container.querySelector(".place-marker")).not.toBeNull();
await type(container, "");
- expect(FakeMarker.standing).toHaveLength(0);
+ expect(container.querySelector(".place-marker")).toBeNull();
});
it("renders nothing when the map failed to initialize", () => {
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.tsx
index 81bcb754c4..84c92e984e 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.tsx
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.tsx
@@ -1,7 +1,6 @@
import "./SearchBox.css";
-import { Marker } from "maplibre-gl";
-import { useCallback, useContext, useEffect, useRef, useState } from "preact/hooks";
+import { useCallback, useContext, useRef, useState } from "preact/hooks";
import type FNote from "../../../entities/fnote";
import { t } from "../../../services/i18n";
@@ -11,7 +10,8 @@ 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 { drawMarkerImage, LOCATION_ATTRIBUTE, MARKER_SHADOW_PADDING, parseLocation } from "./Markers";
+import { LOCATION_ATTRIBUTE, parseLocation } from "./Markers";
+import PlaceMarker from "./PlaceMarker";
/** Shorter queries are not searched. */
const MIN_QUERY_LENGTH = 2;
@@ -28,15 +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[];
+ /** Whether the map's style is a dark one, which a pinned place is labelled against. */
+ isDarkTheme: boolean;
}
/**
@@ -49,7 +46,9 @@ type SearchEntry = {
/** A boxicons class, as `FNote.getIcon()` gives it. */
icon: string;
} & (
- | { kind: "marker" | "place"; center: [number, number] }
+ | { kind: "marker"; center: [number, number] }
+ /** A place from the geocoder, `name` being what its pin is labelled with. */
+ | { kind: "place"; center: [number, number]; name: string }
/** Runs the geocoder for `query`. */
| { kind: "geocode"; query: string }
/** Reports on a geocoder run; picking it does nothing. */
@@ -79,15 +78,15 @@ interface GeocodeRun {
* geocoder row can replace itself with results, so closing it after a marker or place is taken is
* this component's job — see `dismissed`.
*/
-export default function SearchBox({ notes }: SearchBoxProps) {
+export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {
const map = useContext(ParentMap);
const [ query, setQuery ] = useState("");
const [ geocodeRun, setGeocodeRun ] = useState<GeocodeRun>();
// 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]>();
+ // The geocoder's last answer, pinned where it stands; nothing while the map shows only its notes.
+ const [ pickedPlace, setPickedPlace ] = useState<{ center: [number, number]; name: string }>();
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);
@@ -139,7 +138,7 @@ export default function SearchBox({ notes }: SearchBoxProps) {
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);
+ setPickedPlace(entry.kind === "place" ? { center: entry.center, name: entry.name } : undefined);
map.flyTo({ center: entry.center, zoom: entry.kind === "marker" ? MARKER_ZOOM : PLACE_ZOOM });
}
}, [ map, runGeocoder ]);
@@ -161,7 +160,7 @@ export default function SearchBox({ notes }: SearchBoxProps) {
return (
<>
- {pickedPlace && <PlaceMarker center={pickedPlace} />}
+ {pickedPlace && <PlaceMarker center={pickedPlace.center} name={pickedPlace.name} isDarkTheme={isDarkTheme} />}
<OverlayToolbar className="geo-search-toolbar" titlePosition="bottom">
<Icon icon="bx bx-search" className="geo-search-icon" />
<FormAutocomplete
@@ -180,48 +179,6 @@ export default function SearchBox({ notes }: SearchBoxProps) {
);
}
-/**
- * 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();
@@ -281,6 +238,7 @@ function placeEntry(result: GeoSearchResult): SearchEntry {
kind: "place",
key: `place:${result.id}`,
label: result.label,
+ name: result.name,
icon: "bx bx-map-pin",
center: [ result.lng, result.lat ]
};
diff --git a/apps/client/src/widgets/collections/geomap/geocoding.ts b/apps/client/src/widgets/collections/geomap/geocoding.ts
index 04314b892c..ee3cf55380 100644
--- a/apps/client/src/widgets/collections/geomap/geocoding.ts
+++ b/apps/client/src/widgets/collections/geomap/geocoding.ts
@@ -6,6 +6,8 @@ export interface GeoSearchResult {
id: string;
/** Display text, with enough context to tell two places of the same name apart. */
label: string;
+ /** The place's own name, for labelling it on the map where the full label would be a paragraph. */
+ name: string;
lat: number;
lng: number;
}
diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsx
index e081455017..e50f65672b 100644
--- a/apps/client/src/widgets/collections/geomap/index.tsx
+++ b/apps/client/src/widgets/collections/geomap/index.tsx
@@ -244,7 +244,7 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
onClick={onClick}
scale={hasScale}
>
- <SearchBox notes={notes} />
+ <SearchBox notes={notes} isDarkTheme={layerData.isDarkTheme ?? false} />
<MapToolbar />
<EditToolbar
isReadOnly={isReadOnly}
diff --git a/apps/client/src/widgets/collections/geomap/nominatim.spec.ts b/apps/client/src/widgets/collections/geomap/nominatim.spec.ts
index b13ed07ee8..8adf77610d 100644
--- a/apps/client/src/widgets/collections/geomap/nominatim.spec.ts
+++ b/apps/client/src/widgets/collections/geomap/nominatim.spec.ts
@@ -12,6 +12,7 @@ vi.mock("../../../services/i18n", () => ({ getCurrentLanguage: () => "pt_br" }))
function place(overrides: Record<string, unknown> = {}) {
return {
place_id: 240109189,
+ name: "Berlin",
display_name: "Berlin, Germany",
lat: "52.5170365",
lon: "13.3888599",
@@ -67,12 +68,13 @@ describe("Nominatim geocoding", () => {
place(),
place({ place_id: 2, display_name: "Nowhere", lat: "not a number" }),
place({ place_id: 3, display_name: undefined }),
- place({ place_id: 4, display_name: "Paris, France", lat: "48.8566", lon: "2.3522" })
+ place({ place_id: 4, name: undefined, display_name: "Paris, France", lat: "48.8566", lon: "2.3522" })
]);
expect(await search("anywhere")).toEqual([
- { id: "240109189", label: "Berlin, Germany", lat: 52.5170365, lng: 13.3888599 },
- { id: "4", label: "Paris, France", lat: 48.8566, lng: 2.3522 }
+ { id: "240109189", label: "Berlin, Germany", name: "Berlin", lat: 52.5170365, lng: 13.3888599 },
+ // Named by the leading part of its label, Nominatim having named it nothing itself.
+ { id: "4", label: "Paris, France", name: "Paris", lat: 48.8566, lng: 2.3522 }
]);
});
diff --git a/apps/client/src/widgets/collections/geomap/nominatim.ts b/apps/client/src/widgets/collections/geomap/nominatim.ts
index 12aedc3548..0d8cb0928d 100644
--- a/apps/client/src/widgets/collections/geomap/nominatim.ts
+++ b/apps/client/src/widgets/collections/geomap/nominatim.ts
@@ -59,6 +59,7 @@ async function searchNominatim(query: string): Promise<GeoSearchResult[]> {
interface NominatimPlace {
place_id?: number;
display_name?: string;
+ name?: string;
lat?: string;
lon?: string;
}
@@ -74,6 +75,9 @@ function toSearchResult(place: NominatimPlace): GeoSearchResult | null {
return {
id: String(place.place_id ?? `${lat},${lng}`),
label: place.display_name,
+ // Nominatim leaves `name` empty for a result that is an address rather than a named place,
+ // where the leading part of the label is what names it.
+ name: place.name || place.display_name.split(",")[0].trim(),
lat,
lng
};