Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): step through what a search turned up

Elian Doran85dd19aab3a6
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 0f90076536..32c763dc2b 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2962,7 +2962,10 @@
"search-failed": "Couldn't search for places",
"results-nearby": "Nearby",
"results-far": "Far away",
- "add-place-as-marker": "Add as marker"
+ "add-place-as-marker": "Add as marker",
+ "previous-result": "Previous result",
+ "next-result": "Next result",
+ "result-position": "Result {{index}} of {{total}}, click to return to it"
},
"embedded_note": {
"open-note": "Open note",
diff --git a/apps/client/src/widgets/collections/geomap/ResultNavigator.css b/apps/client/src/widgets/collections/geomap/ResultNavigator.css
new file mode 100644
index 0000000000..00dd6c344f
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/ResultNavigator.css
@@ -0,0 +1,14 @@
+/* Under the search bar, in the same corner: the room the bar keeps from the top, the bar's own
+ height, and as much air again. */
+.geo-map-container .geo-result-navigator {
+ --overlay-group-inset-top: calc(
+ var(--geo-map-inset-top) + var(--geo-map-toolbar-height) + var(--geo-map-inset));
+}
+
+/* The count is read rather than pressed for its own sake, so it keeps a readout's room rather than
+ an icon button's width. */
+.geo-map-container .geo-result-navigator .geo-result-position {
+ min-width: 0;
+ padding-inline: 10px;
+ font-variant-numeric: tabular-nums;
+}
diff --git a/apps/client/src/widgets/collections/geomap/ResultNavigator.spec.tsx b/apps/client/src/widgets/collections/geomap/ResultNavigator.spec.tsx
new file mode 100644
index 0000000000..ce0cc577ee
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/ResultNavigator.spec.tsx
@@ -0,0 +1,91 @@
+/**
+ * Stepping through what a search turned up: which of them the map is pointed at, how the ends are
+ * held, and where a step leaves the reader.
+ */
+import type { Map as MapLibreGLMap } from "maplibre-gl";
+import { act } from "preact/test-utils";
+import { describe, expect, it, vi } from "vitest";
+
+import { renderInto } from "../../../test/render";
+import { ParentMap } from "./map";
+import type { SearchResult } from "./results";
+import ResultNavigator from "./ResultNavigator";
+
+vi.mock("../../../services/i18n", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../services/i18n")>()),
+ t: (key: string) => key
+}));
+
+const RESULTS: SearchResult[] = [
+ { kind: "note", noteId: "note1", center: [ 24.15, 45.79 ] },
+ { kind: "place", place: { id: "N5", name: "Jumbo", label: "Jumbo, Sibiu", lat: 45.8, lng: 24.2, bounds: [ [ 24.1, 45.7 ], [ 24.3, 45.9 ] ] } },
+ { kind: "place", place: { id: "N6", name: "Jumbo", label: "Jumbo, Ohio", lat: 40.4, lng: -82.9 } }
+];
+
+function fakeMap() {
+ return { flyTo: vi.fn(), fitBounds: vi.fn() };
+}
+
+function renderNavigator(index: number, results = RESULTS) {
+ const map = fakeMap();
+ const onStep = vi.fn();
+ let container: HTMLElement | undefined;
+
+ act(() => {
+ container = renderInto(
+ <ParentMap.Provider value={map as unknown as MapLibreGLMap}>
+ <ResultNavigator results={results} index={index} onStep={onStep} />
+ </ParentMap.Provider>
+ );
+ });
+ if (!container) throw new Error("the navigator was not rendered");
+
+ const buttons = [ ...container.querySelectorAll<HTMLButtonElement>("button") ];
+ return { map, onStep, buttons, container };
+}
+
+describe("geo map ResultNavigator", () => {
+ it("says where the reader stands among the results, counting from one", () => {
+ const { buttons } = renderNavigator(1);
+
+ expect(buttons[1].textContent).toBe("2 / 3");
+ });
+
+ it("steps to the next result and points the map at it", () => {
+ const { buttons, onStep, map } = renderNavigator(0);
+
+ act(() => { buttons[2].click(); });
+
+ expect(onStep).toHaveBeenCalledWith(1);
+ // The place covers ground the geocoder reported, so it is framed rather than flown to.
+ expect(map.fitBounds).toHaveBeenCalledOnce();
+ });
+
+ it("steps back to a note, which marks a spot and is flown to", () => {
+ const { buttons, onStep, map } = renderNavigator(1);
+
+ act(() => { buttons[0].click(); });
+
+ expect(onStep).toHaveBeenCalledWith(0);
+ expect(map.flyTo).toHaveBeenCalledWith({ center: [ 24.15, 45.79 ], zoom: expect.any(Number) });
+ });
+
+ it("holds the ends rather than wrapping round them", () => {
+ expect(renderNavigator(0).buttons[0].disabled).toBe(true);
+ expect(renderNavigator(2).buttons[2].disabled).toBe(true);
+ expect(renderNavigator(1).buttons.some((button) => button.disabled)).toBe(false);
+ });
+
+ it("points the map back at where it stands when the count itself is pressed", () => {
+ const { buttons, onStep, map } = renderNavigator(2);
+
+ act(() => { buttons[1].click(); });
+
+ expect(onStep).toHaveBeenCalledWith(2);
+ expect(map.flyTo).toHaveBeenCalledWith({ center: [ -82.9, 40.4 ], zoom: expect.any(Number) });
+ });
+
+ it("stands aside where there is nothing to step between", () => {
+ expect(renderNavigator(0, RESULTS.slice(0, 1)).container.querySelector("button")).toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/collections/geomap/ResultNavigator.tsx b/apps/client/src/widgets/collections/geomap/ResultNavigator.tsx
new file mode 100644
index 0000000000..b640d255c5
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/ResultNavigator.tsx
@@ -0,0 +1,65 @@
+import "./ResultNavigator.css";
+
+import { useContext } from "preact/hooks";
+
+import { t } from "../../../services/i18n";
+import OverlayControlGroup, { OverlayControlButton } from "../../react/OverlayControlGroup";
+import { ParentMap } from "./map";
+import { frameResult, type SearchResult } from "./results";
+
+interface ResultNavigatorProps {
+ /** What the search turned up, in the order the list offered it. */
+ results: SearchResult[];
+ /** Which of them the map is standing on. */
+ index: number;
+ /** Stands the map on another of them; the map is pointed at it here. */
+ onStep(index: number): void;
+}
+
+/**
+ * Steps through what a search turned up, one result at a time.
+ *
+ * Taking a result closes the list, so comparing several of them meant asking for the list again for
+ * each — this walks them in the order they were offered, nearest first.
+ *
+ * A group of its own under the search bar rather than buttons in it: the bar has no room for three
+ * more, and one of the results may be a note of the map's own, which opens the detail pane instead of
+ * the place panel — buttons living on either panel would go as soon as the other was reached.
+ */
+export default function ResultNavigator({ results, index, onStep }: ResultNavigatorProps) {
+ const map = useContext(ParentMap);
+
+ // Nothing to step between, and nothing worth saying about where one stands among one.
+ if (!map || results.length < 2) return null;
+
+ const step = (to: number) => {
+ onStep(to);
+ frameResult(map, results[to]);
+ };
+
+ return (
+ <OverlayControlGroup className="geo-result-navigator" placement="top-start" overCanvas>
+ <OverlayControlButton
+ title={t("geo-map.previous-result")}
+ icon="bx-chevron-left"
+ disabled={index <= 0}
+ onClick={() => step(index - 1)}
+ />
+ {/* The count is a readout rather than a choice, so pressing it does the one thing that
+ needs no choosing: points the map back at what it is standing on, after the reader
+ has panned away from it. */}
+ <OverlayControlButton
+ text={`${index + 1} / ${results.length}`}
+ className="geo-result-position"
+ aria-label={t("geo-map.result-position", { index: index + 1, total: results.length })}
+ onClick={() => step(index)}
+ />
+ <OverlayControlButton
+ title={t("geo-map.next-result")}
+ icon="bx-chevron-right"
+ disabled={index >= results.length - 1}
+ onClick={() => step(index + 1)}
+ />
+ </OverlayControlGroup>
+ );
+}
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
index 90c0b561ce..902e6eeac8 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
@@ -12,6 +12,7 @@ import { buildNote } from "../../../test/easy-froca";
import { renderInto } from "../../../test/render";
import { DEFAULT_GEOCODING_PROVIDER_NAME, GEOCODING_PROVIDERS, type GeoSearchResult } from "./geocoding";
import { ParentMap } from "./map";
+import type { SearchResult } from "./results";
import SearchBox from "./SearchBox";
/** The pin is drawn on the map by its own component, which has a spec of its own; here it only has to
@@ -77,8 +78,15 @@ function mapNotes(): FNote[] {
];
}
-/** What the bar has reported picking, the map being what stands a place on itself (see index.tsx). */
-let picked: (GeoSearchResult | null)[] = [];
+/** What the bar has reported picking, the map being what stands a result on itself (see index.tsx). */
+let picked: ({ results: SearchResult[]; index: number } | null)[] = [];
+
+/** The place of the last result reported, or none where the bar reported moving on from the search. */
+function pickedPlace() {
+ const last = picked.at(-1);
+ const result = last && last.results[last.index];
+ return result?.kind === "place" ? result.place : null;
+}
function renderSearchBox(map: ReturnType<typeof fakeMap> | null, notes: FNote[] = []) {
picked = [];
@@ -86,7 +94,7 @@ function renderSearchBox(map: ReturnType<typeof fakeMap> | null, notes: FNote[]
act(() => {
container = renderInto(
<ParentMap.Provider value={map as unknown as MapLibreGLMap}>
- <SearchBox notes={notes} onPickPlace={(place) => picked.push(place)} />
+ <SearchBox notes={notes} onPickResult={(result) => picked.push(result)} />
</ParentMap.Provider>
);
});
@@ -301,13 +309,16 @@ describe("geo map SearchBox", () => {
await pickNamed("geo-map.search-online(tokyo)");
await pickNamed("Tokyo");
- // Once, and whole — so what stands it on the map has its boundary and its bounds to hand.
- expect(picked).toEqual([ TOKYO ]);
+ // Whole, so what stands it on the map has its boundary and its bounds to hand.
+ expect(pickedPlace()).toBe(TOKYO);
+ // And with everything the list offered, so the rest can be stepped through after it.
+ expect(picked.at(-1)?.results).toHaveLength(2);
- // A note of the map's own has a marker already, so taking one moves on from the place.
+ // A note of the map's own is one of the results too, and taking it stands the map there.
await type(container, "tokyo trip");
await pick(0);
- expect(picked).toEqual([ TOKYO, null ]);
+ expect(picked.at(-1)?.results[picked.at(-1)?.index ?? -1])
+ .toEqual({ kind: "note", noteId: expect.any(String), center: [ 139.7, 35.6 ] });
});
it("gives a place two lines: what it is called, and the address that places it", async () => {
@@ -489,15 +500,15 @@ describe("geo map SearchBox", () => {
await pickNamed("geo-map.search-online(tokyo)");
await pickNamed("Tokyo");
- expect(picked).toEqual([ TOKYO ]);
+ expect(pickedPlace()).toBe(TOKYO);
await act(async () => { clearButton()?.click(); });
await settle();
expect(field(container).value).toBe("");
expect(isShown()).toBe(false);
- // Clearing the field is what takes the place off the map, panel and pin alike.
- expect(picked).toEqual([ TOKYO, null ]);
+ // Clearing the field is what takes the search off the map, panel and pin alike.
+ expect(picked.at(-1)).toBeNull();
// Rarely the end of searching, so the field is where the reader was left.
expect(document.activeElement).toBe(field(container));
});
@@ -509,11 +520,11 @@ describe("geo map SearchBox", () => {
await type(container, "tokyo");
await pickNamed("geo-map.search-online(tokyo)");
await pickNamed("Tokyo");
- expect(picked).toEqual([ TOKYO ]);
+ expect(pickedPlace()).toBe(TOKYO);
await type(container, "");
- expect(picked).toEqual([ TOKYO, null ]);
+ expect(picked.at(-1)).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 cb1c57c899..5a20b8587f 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.tsx
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.tsx
@@ -18,6 +18,7 @@ import { DEFAULT_GEOCODING_PROVIDER_NAME, DEFAULT_PLACE_ICON, type GeoBounds, GE
import { ParentMap } from "./map";
import { describePlace } from "./place_address";
import { LOCATION_ATTRIBUTE, parseLocation } from "./Markers";
+import { frameResult, type SearchResult } from "./results";
/** Shorter queries are not searched. */
const MIN_QUERY_LENGTH = 2;
@@ -57,11 +58,11 @@ interface SearchBoxProps {
/** The notes on the map, searched by title. */
notes: FNote[];
/**
- * Reports the place picked from the list, or none where the reader has moved on from it — a note
- * of the map's own taken instead, or the field emptied. What is done with it is the map's (see
- * `pickPlace` in index.tsx).
+ * Reports what the list offered and which of it was taken, so the map can stand on that one and
+ * step through the rest (see `showResult` in index.tsx). None where the reader has moved on from
+ * the search altogether, the field having been emptied.
*/
- onPickPlace(place: GeoSearchResult | null): void;
+ onPickResult(picked: { results: SearchResult[]; index: number } | null): void;
}
/**
@@ -76,7 +77,7 @@ type SearchEntry = {
/** How far the place is from the middle of the map, in metres. */
distance?: number;
} & (
- | { kind: "marker"; center: [number, number] }
+ | { kind: "marker"; center: [number, number]; noteId: string }
/** A place from the geocoder, carried whole for whoever the pick is reported to. */
| { kind: "place"; center: [number, number]; result: GeoSearchResult }
/** Names the run of rows below it; not a choice (see `isHeading` on FormAutocomplete). */
@@ -115,7 +116,7 @@ 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, onPickPlace }: SearchBoxProps) {
+export default function SearchBox({ notes, onPickResult }: SearchBoxProps) {
const map = useContext(ParentMap);
const [ query, setQuery ] = useState("");
const [ geocodeRun, setGeocodeRun ] = useState<GeocodeRun>();
@@ -149,11 +150,11 @@ export default function SearchBox({ notes, onPickPlace }: SearchBoxProps) {
const changeQuery = useCallback((newQuery: string) => {
setDismissed(false);
setQuery(newQuery);
- // Emptying the field is how the pin is taken back off the map.
+ // Emptying the field is how the search is taken back off the map, pin and all.
if (!newQuery.trim()) {
- onPickPlace(null);
+ onPickResult(null);
}
- }, [ onPickPlace ]);
+ }, [ onPickResult ]);
const runGeocoder = useCallback(async (searchQuery: string) => {
const runId = ++latestRun.current;
@@ -206,19 +207,15 @@ export default function SearchBox({ notes, onPickPlace }: SearchBoxProps) {
runGeocoder(entry.query);
} else if (entry.kind === "marker" || entry.kind === "place") {
setDismissed(true);
- // A note of the map's own has a marker already; only a place needs one put down for it.
- onPickPlace(entry.kind === "place" ? entry.result : null);
-
- const bounds = entry.kind === "place" ? entry.result.bounds : undefined;
- if (bounds) {
- // Framed by what the place covers rather than flown to at a level guessed for every
- // place alike: one zoom that suits a city shows a street as the city around it.
- map.fitBounds(bounds, { padding: PLACE_PADDING, maxZoom: PLACE_MAX_ZOOM });
- } else {
- map.flyTo({ center: entry.center, zoom: entry.kind === "marker" ? MARKER_ZOOM : PLACE_ZOOM });
- }
+
+ // The whole of what was offered, so the map can step through the rest of it once the
+ // list has stood down (see ResultNavigator).
+ const results = walkableResults(entriesByKey.current);
+ const index = results.findIndex((result) => keyOf(result) === entry.key);
+ onPickResult({ results, index });
+ frameResult(map, results[index]);
}
- }, [ map, runGeocoder, onPickPlace ]);
+ }, [ map, runGeocoder, onPickResult ]);
const isHeading = useCallback(
(key: string) => entriesByKey.current.get(key)?.kind === "heading", []);
@@ -292,6 +289,29 @@ export default function SearchBox({ notes, onPickPlace }: SearchBoxProps) {
);
}
+/**
+ * The rows that stand somewhere on the map, in the order they were offered — the headings and the
+ * geocoder's own rows being neither results nor anywhere.
+ */
+function walkableResults(entries: Map<string, SearchEntry>): SearchResult[] {
+ const results: SearchResult[] = [];
+
+ for (const entry of entries.values()) {
+ if (entry.kind === "marker") {
+ results.push({ kind: "note", noteId: entry.noteId, center: entry.center });
+ } else if (entry.kind === "place") {
+ results.push({ kind: "place", place: entry.result });
+ }
+ }
+
+ return results;
+}
+
+/** The key the row a result came from was listed under (see `placeEntry` and `matchMarkers`). */
+function keyOf(result: SearchResult) {
+ return result.kind === "note" ? `marker:${result.noteId}` : `place:${result.place.id}`;
+}
+
/**
* How far a row's place stands from where the map is looking, for the rows that stand anywhere: the
* geocoder's row and its reports name no place, and a map that could not be drawn is looking nowhere.
@@ -338,6 +358,7 @@ function matchMarkers(notes: FNote[], query: string): SearchEntry[] {
matches.push({
kind: "marker",
key: `marker:${note.noteId}`,
+ noteId: note.noteId,
label: note.title,
icon: note.getIcon(),
center
diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsx
index fac63bf6cf..bbedc089f4 100644
--- a/apps/client/src/widgets/collections/geomap/index.tsx
+++ b/apps/client/src/widgets/collections/geomap/index.tsx
@@ -27,6 +27,8 @@ import type { GeoSearchResult } from "./geocoding";
import Markers, { DEFAULT_MARKER_COLOR, LOCATION_ATTRIBUTE } from "./Markers";
import PlaceMarker from "./PlaceMarker";
import PlacePanel from "./PlacePanel";
+import ResultNavigator from "./ResultNavigator";
+import type { SearchResult } from "./results";
import SearchBox from "./SearchBox";
import Tooltips from "./Tooltips";
@@ -71,6 +73,9 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
// map is currently standing on, and both are shown in the same corner.
const [ pickedPlace, setPickedPlace ] = useState<GeoSearchResult>();
const [ placeOutline, setPlaceOutline ] = useState<GeoJSON.Geometry>();
+ // What the last search offered and which of it the map stands on, so the rest can be stepped
+ // through once the list has stood down (see ResultNavigator).
+ const [ walk, setWalk ] = useState<{ results: SearchResult[]; index: number }>();
// Which pick the map stands on, so a boundary arriving after a later one is dropped rather than
// drawn around whatever took its place.
const latestPlacePick = useRef(0);
@@ -144,6 +149,30 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
.catch((e) => logError(`Fetching the boundary of "${place.label}" failed: ${e}`));
}, []);
+ /**
+ * Stands the map on one of a search's results: a place under a pin of its own, or a note of the
+ * map's own in the detail pane. Where the map is pointed is the caller's, which is the one thing
+ * that differs between taking a result from the list and stepping onto it.
+ */
+ const showResult = useCallback((results: SearchResult[], index: number) => {
+ setWalk({ results, index });
+
+ const result = results[index];
+ if (result.kind === "place") {
+ pickPlace(result.place);
+ } else {
+ selectNote({ noteId: result.noteId });
+ }
+ }, [ pickPlace, selectNote ]);
+
+ /** Takes the search off the map altogether: what it was standing on, and the rest it offered. */
+ const clearSearch = useCallback(() => {
+ latestPlacePick.current++;
+ setWalk(undefined);
+ setPickedPlace(undefined);
+ setPlaceOutline(undefined);
+ }, []);
+
/** Keeps the place the map stands on as a note of its own, which is what turns its pin into a
* marker; the pane then opens on the note as any other newly created one. */
const keepPlaceAsMarker = useCallback(async () => {
@@ -302,7 +331,14 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
onClick={onClick}
scale={hasScale}
>
- <SearchBox notes={notes} onPickPlace={pickPlace} />
+ <SearchBox
+ notes={notes}
+ onPickResult={(picked) => picked ? showResult(picked.results, picked.index) : clearSearch()}
+ />
+ {walk && <ResultNavigator
+ results={walk.results} index={walk.index}
+ onStep={(index) => showResult(walk.results, index)}
+ />}
{pickedPlace && placeCenter && <>
<PlaceMarker
center={placeCenter} name={pickedPlace.name} icon={pickedPlace.icon}
diff --git a/apps/client/src/widgets/collections/geomap/results.ts b/apps/client/src/widgets/collections/geomap/results.ts
new file mode 100644
index 0000000000..1582b99393
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/results.ts
@@ -0,0 +1,43 @@
+import type { Map as MapLibreGLMap } from "maplibre-gl";
+
+import type { GeoSearchResult } from "./geocoding";
+
+/** One of the things a search turned up: a note of the map's own, or a place from the geocoder. */
+export type SearchResult =
+ | { kind: "note"; noteId: string; center: [number, number] }
+ | { kind: "place"; place: GeoSearchResult };
+
+/** The zoom level a place is shown at where the geocoder does not say how much ground it covers. */
+const PLACE_ZOOM = 12;
+
+/** The zoom level a note is shown at, closer in since it marks a spot rather than an area. */
+const NOTE_ZOOM = 15;
+
+/**
+ * How close a place is framed at most. A house's extent is a few metres across, which on its own
+ * would fill the screen with the roof.
+ */
+const PLACE_MAX_ZOOM = 17;
+
+/** The room kept around a framed place, so its pin and name do not sit against the map's edge. */
+const PLACE_PADDING = 60;
+
+/**
+ * Points the map at one of a search's results.
+ *
+ * A place is framed on the ground it covers, where the geocoder says how much that is: one zoom
+ * level suited to a city shows a street as the city around it. A note marks a spot and has no extent
+ * to frame, and neither has a place the geocoder gave no bounding box for.
+ */
+export function frameResult(map: MapLibreGLMap, result: SearchResult) {
+ if (result.kind === "place" && result.place.bounds) {
+ map.fitBounds(result.place.bounds, { padding: PLACE_PADDING, maxZoom: PLACE_MAX_ZOOM });
+ return;
+ }
+
+ const center: [number, number] = result.kind === "place"
+ ? [ result.place.lng, result.place.lat ]
+ : result.center;
+
+ map.flyTo({ center, zoom: result.kind === "place" ? PLACE_ZOOM : NOTE_ZOOM });
+}