Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): keep a searched place as a marker of the map

Elian Doran492aacf6cae2
diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.css b/apps/client/src/widgets/collections/geomap/DetailPane.css
index d39a73b79b..f725b5bd49 100644
--- a/apps/client/src/widgets/collections/geomap/DetailPane.css
+++ b/apps/client/src/widgets/collections/geomap/DetailPane.css
@@ -81,6 +81,7 @@
* own until it is aimed at.
*/
.geo-map-container .geo-detail-pane .geo-detail-pane-location,
+.geo-map-container .geo-place-panel .geo-detail-pane-location,
.modal.geo-detail-sheet .geo-detail-pane-location {
display: flex;
align-items: center;
diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.tsx
index a0a3692397..3a325be5d1 100644
--- a/apps/client/src/widgets/collections/geomap/DetailPane.tsx
+++ b/apps/client/src/widgets/collections/geomap/DetailPane.tsx
@@ -632,7 +632,7 @@ function MarkerLocation({ note }: { note: FNote }) {
* pane does: the hook binds on mount and does not look again, and there is a render before the
* location has been read in which there is no button to bind to.
*/
-function LocationButton({ coordinates }: { coordinates: [number, number] }) {
+export function LocationButton({ coordinates }: { coordinates: [number, number] }) {
const buttonRef = useRef<HTMLButtonElement>(null);
// The app's own tooltip rather than the browser's, as the buttons under it wear (see
diff --git a/apps/client/src/widgets/collections/geomap/PlaceMarker.tsx b/apps/client/src/widgets/collections/geomap/PlaceMarker.tsx
index ba3850e05d..2570a5ed82 100644
--- a/apps/client/src/widgets/collections/geomap/PlaceMarker.tsx
+++ b/apps/client/src/widgets/collections/geomap/PlaceMarker.tsx
@@ -6,7 +6,7 @@ import { buildMarkerImage, LABEL_LAYOUT, LABEL_PAINT, MARKER_SHADOW_PADDING, mar
/** 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. */
+/** The icon inside that pin, naming where it came from. */
export const PLACE_MARKER_ICON = "bx bx-search";
export const PLACE_SOURCE = "searched-place";
diff --git a/apps/client/src/widgets/collections/geomap/PlacePanel.css b/apps/client/src/widgets/collections/geomap/PlacePanel.css
new file mode 100644
index 0000000000..a9c47a97c9
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/PlacePanel.css
@@ -0,0 +1,28 @@
+/* The corner the detail pane stands in, and the width it is given, the two never standing at once.
+ Sized to what it holds, though: it is a card rather than a pane the height of the map. */
+.geo-map-container .geo-place-panel {
+ position: absolute;
+ top: var(--geo-map-inset-top);
+ inset-inline-end: var(--geo-map-inset-end);
+ width: var(--geo-detail-pane-width);
+ max-width: calc(100% - var(--geo-map-inset-start) - var(--geo-map-inset-end));
+ /* Clear of MapLibre's own control corners, which sit at 2 (see MapToolbar.css). */
+ z-index: 3;
+}
+
+.geo-map-container .geo-place-panel .geo-place-panel-body {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 8px;
+ padding: 10px 12px 12px;
+}
+
+.geo-map-container .geo-place-panel .geo-place-panel-address {
+ font-size: 0.9em;
+ opacity: 0.8;
+}
+
+.geo-map-container .geo-place-panel .geo-place-panel-add {
+ align-self: stretch;
+}
diff --git a/apps/client/src/widgets/collections/geomap/PlacePanel.spec.tsx b/apps/client/src/widgets/collections/geomap/PlacePanel.spec.tsx
new file mode 100644
index 0000000000..9341d4e5dd
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/PlacePanel.spec.tsx
@@ -0,0 +1,70 @@
+/**
+ * The panel standing over a place taken from the search: what it says about the place, and the two
+ * things that can be done with one — kept as a marker of the map, or sent away.
+ */
+import { act } from "preact/test-utils";
+import { describe, expect, it, vi } from "vitest";
+
+import { renderInto } from "../../../test/render";
+import type { GeoSearchResult } from "./geocoding";
+import PlacePanel from "./PlacePanel";
+
+// The real module besides `t`, which is left to stand for the text it would return: something in the
+// tree below awaits `translationsInitializedPromise`, and a mock without it fails after the test has
+// passed.
+vi.mock("../../../services/i18n", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../services/i18n")>()),
+ t: (key: string) => key
+}));
+
+const JUMBO: GeoSearchResult = {
+ id: "N5",
+ name: "Jumbo",
+ label: "Jumbo, Str. Șos. Alba Iulia 70, Sibiu, Romania",
+ lat: 45.796,
+ lng: 24.147
+};
+
+function renderPanel({ isReadOnly = false } = {}) {
+ const onAddMarker = vi.fn();
+ const onClose = vi.fn();
+ let container: HTMLElement | undefined;
+
+ act(() => {
+ container = renderInto(
+ <PlacePanel place={JUMBO} isReadOnly={isReadOnly} onAddMarker={onAddMarker} onClose={onClose} />
+ );
+ });
+ if (!container) throw new Error("the panel was not rendered");
+
+ return { container, onAddMarker, onClose };
+}
+
+describe("geo map PlacePanel", () => {
+ it("names the place and gives the address under it, with the coordinates to copy", () => {
+ const { container } = renderPanel();
+
+ expect(container.querySelector(".tn-overlay-panel-title-text")?.textContent).toBe("Jumbo");
+ // The whole of it, the heading carrying only the name.
+ expect(container.querySelector(".geo-place-panel-address")?.textContent)
+ .toBe("Jumbo, Str. Șos. Alba Iulia 70, Sibiu, Romania");
+ expect(container.querySelector(".geo-detail-pane-location")?.textContent).toContain("45.796");
+ });
+
+ it("keeps the place as a marker when asked, and sends itself away when told", () => {
+ const { container, onAddMarker, onClose } = renderPanel();
+
+ act(() => { container.querySelector<HTMLButtonElement>(".geo-place-panel-add")?.click(); });
+ expect(onAddMarker).toHaveBeenCalledOnce();
+
+ act(() => { container.querySelector<HTMLButtonElement>(".tn-overlay-panel-close")?.click(); });
+ expect(onClose).toHaveBeenCalledOnce();
+ });
+
+ it("offers no marker on a map that may not be edited, the place still being worth reading", () => {
+ const { container } = renderPanel({ isReadOnly: true });
+
+ expect(container.querySelector(".geo-place-panel-add")).toBeNull();
+ expect(container.querySelector(".geo-place-panel-address")).not.toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/collections/geomap/PlacePanel.tsx b/apps/client/src/widgets/collections/geomap/PlacePanel.tsx
new file mode 100644
index 0000000000..2e21f43029
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/PlacePanel.tsx
@@ -0,0 +1,56 @@
+import "./PlacePanel.css";
+
+import { t } from "../../../services/i18n";
+import Button from "../../react/Button";
+import OverlayPanel, { OverlayPanelBody, OverlayPanelTitle } from "../../react/OverlayPanel";
+import { LocationButton } from "./DetailPane";
+import type { GeoSearchResult } from "./geocoding";
+import { PLACE_MARKER_ICON } from "./PlaceMarker";
+
+interface PlacePanelProps {
+ place: GeoSearchResult;
+ /** The map may not be edited, so the place can be looked at but not kept. */
+ isReadOnly: boolean;
+ /** Makes a note of the place, which is what turns the temporary pin into a marker of the map. */
+ onAddMarker(): void;
+ /** Sends the panel away, and the pin with it. */
+ onClose(): void;
+}
+
+/**
+ * What can be done with a place taken from the search: kept as a marker of the map, or read and
+ * dismissed.
+ *
+ * It stands where the detail pane stands, and the two are one selection between them — picking a
+ * place closes the pane and selecting a note closes this (see index.tsx). A panel rather than a popup
+ * over the pin: a popup would crowd the address that tells two places of the same name apart, and
+ * MapLibre's popups already belong to the markers' previews (see Tooltips).
+ */
+export default function PlacePanel({ place, isReadOnly, onAddMarker, onClose }: PlacePanelProps) {
+ return (
+ <OverlayPanel
+ className="geo-place-panel"
+ header={<OverlayPanelTitle icon={PLACE_MARKER_ICON} text={place.name} />}
+ close={{ text: t("geo-map.close-details"), onClick: onClose }}
+ >
+ <OverlayPanelBody className="geo-place-panel-body">
+ {/* The whole of what the geocoder calls the place, the heading above carrying only
+ its name. */}
+ <div className="geo-place-panel-address">{place.label}</div>
+
+ {/* The pane's own, so a place and a marker offer their coordinates alike. */}
+ <LocationButton coordinates={[ place.lng, place.lat ]} />
+
+ {!isReadOnly && (
+ <Button
+ className="geo-place-panel-add"
+ kind="primary"
+ icon="bx bx-pin"
+ text={t("geo-map.add-place-as-marker")}
+ onClick={onAddMarker}
+ />
+ )}
+ </OverlayPanelBody>
+ </OverlayPanel>
+ );
+}
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.css b/apps/client/src/widgets/collections/geomap/SearchBox.css
index ee188e3375..7cdeb74655 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.css
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.css
@@ -50,11 +50,10 @@ body.mobile .geo-map-container .geo-search-toolbar {
opacity: 0.6;
}
-/* Every row reads as icon + what it says, whether it offers a marker, a place, the geocoder or a
- report on it. Scoped to the portalled dropdown, which is a body child rather than part of the map. */
+/* The dropdown is portalled to the body, so these are not scoped under .geo-map-container. */
.form-autocomplete-dropdown .geo-search-entry {
display: flex;
- /* The mark sits on the first line rather than in the middle of a row that runs to two. */
+ /* The icon sits on the first line of a row that runs to two. */
align-items: flex-start;
gap: 6px;
overflow: hidden;
@@ -63,12 +62,10 @@ body.mobile .geo-map-container .geo-search-toolbar {
.form-autocomplete-dropdown .geo-search-entry .tn-icon {
flex-shrink: 0;
opacity: 0.7;
- /* Set against the line beside it, the mark being drawn taller than the text it stands with. */
line-height: 1.4;
}
-/* A place says what it is called and then where it is, so the row is given the height of both and
- the address wraps instead of ending in an ellipsis a word in. */
+/* Overrides the single-line ellipsis in FormAutocomplete.css, so an address can wrap. */
.form-autocomplete-dropdown .form-autocomplete-item:has(.geo-search-entry) {
white-space: normal;
padding-block: 6px;
@@ -78,12 +75,9 @@ body.mobile .geo-map-container .geo-search-toolbar {
display: flex;
flex-direction: column;
min-width: 0;
- /* Takes the room the mark and the distance leave, so the distance keeps the trailing edge. */
flex: 1;
}
-/* How far off the place is, against the trailing edge where a row's rightmost column belongs — read
- after what the row offers rather than before it. */
.form-autocomplete-dropdown .geo-search-entry-distance {
flex-shrink: 0;
align-self: center;
@@ -96,8 +90,7 @@ body.mobile .geo-map-container .geo-search-toolbar {
.form-autocomplete-dropdown .geo-search-entry-address {
font-size: 0.85em;
opacity: 0.7;
- /* Two lines of address and no more: past that the list is a page, and what is cut is the part of
- an address that names a postcode or a country. */
+ /* Two lines at most: a Nominatim address can run to five. */
display: -webkit-box;
-webkit-line-clamp: 2;
line-clamp: 2;
@@ -112,12 +105,6 @@ body.mobile .geo-map-container .geo-search-toolbar {
opacity: 0.85;
}
-/* A heading names the rows under it and reads as the dropdown's own furniture rather than as one of
- the entries, so it keeps none of the room a row's mark and distance are given. */
-.form-autocomplete-dropdown .geo-search-heading {
- display: block;
-}
-
/* A report is not a choice, so it neither highlights nor takes a pointer. */
.form-autocomplete-dropdown .form-autocomplete-item:has(.geo-search-entry-info) {
cursor: default;
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
index 7941f3e01e..44d67894d5 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
@@ -77,12 +77,16 @@ 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)[] = [];
+
function renderSearchBox(map: ReturnType<typeof fakeMap> | null, notes: FNote[] = []) {
+ picked = [];
let container: HTMLElement | undefined;
act(() => {
container = renderInto(
<ParentMap.Provider value={map as unknown as MapLibreGLMap}>
- <SearchBox notes={notes} isDarkTheme={false} />
+ <SearchBox notes={notes} onPickPlace={(place) => picked.push(place)} />
</ParentMap.Provider>
);
});
@@ -218,7 +222,8 @@ describe("geo map SearchBox", () => {
await pick(0);
expect(map.flyTo).toHaveBeenCalledWith({ center: [ 139.7, 35.6 ], zoom: expect.any(Number) });
- expect(field(container).value).toBe("Tokyo trip");
+ // The field keeps what was typed, so the next search starts from it.
+ expect(field(container).value).toBe("tokyo trip");
expect(entries()).toHaveLength(0);
});
@@ -237,7 +242,8 @@ describe("geo map SearchBox", () => {
maxZoom: expect.any(Number)
});
expect(map.flyTo).not.toHaveBeenCalled();
- expect(field(container).value).toBe("Tokyo, Japan");
+ // Not the place's whole label, which is an address the field has no room for.
+ expect(field(container).value).toBe("tokyo");
});
it("falls back to a zoom for a place the geocoder gave no extent for", async () => {
@@ -287,7 +293,7 @@ describe("geo map SearchBox", () => {
expect(labels()).toEqual([ "geo-map.search-online(berlin de)" ]);
});
- it("pins a searched place where it stands, named as the geocoder names it", async () => {
+ it("reports the place picked, whole, and reports moving on from it", async () => {
mockGeocoder([ TOKYO ]);
const container = renderSearchBox(fakeMap(), mapNotes());
@@ -295,49 +301,13 @@ describe("geo map SearchBox", () => {
await pickNamed("geo-map.search-online(tokyo)");
await pickNamed("Tokyo");
- 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");
+ // Once, and whole — so what stands it on the map has its boundary and its bounds to hand.
+ expect(picked).toEqual([ TOKYO ]);
- // A note of the map's own is already pinned, so taking one takes the searched pin away.
+ // A note of the map's own has a marker already, so taking one moves on from the place.
await type(container, "tokyo trip");
await pick(0);
- expect(pin()).toBeNull();
- });
-
- it("asks for a place's boundary only once that place has been picked", async () => {
- const outline = vi.fn(async () => ({ type: "Polygon", coordinates: [] } as GeoJSON.Geometry));
- mockGeocoder([ { ...TOKYO, outline } ]);
- const container = renderSearchBox(fakeMap(), []);
-
- await type(container, "tokyo");
- // The row that runs the geocoder, which offers the place but does not settle on it.
- await pick(0);
- expect(outline).not.toHaveBeenCalled();
-
- await pick(0);
-
- expect(outline).toHaveBeenCalledOnce();
- expect(container.querySelector<HTMLElement>(".place-marker")?.dataset.outline).toBe("Polygon");
- });
-
- it("drops a boundary that arrives after the place it belongs to has been replaced", async () => {
- let deliver: ((outline: GeoJSON.Geometry) => void) | undefined;
- const outline = vi.fn(() => new Promise<GeoJSON.Geometry>((resolve) => { deliver = resolve; }));
- mockGeocoder([ { ...TOKYO, outline } ]);
- const container = renderSearchBox(fakeMap(), mapNotes());
-
- await type(container, "tokyo");
- await pick(1);
- await pick(1);
-
- // A note of the map's own is settled on while the boundary is still being fetched.
- await type(container, "tokyo trip");
- await pick(0);
- await act(async () => { deliver?.({ type: "Polygon", coordinates: [] }); });
-
- expect(container.querySelector(".place-marker")).toBeNull();
+ expect(picked).toEqual([ TOKYO, null ]);
});
it("gives a place two lines: what it is called, and the address that places it", async () => {
@@ -395,7 +365,7 @@ describe("geo map SearchBox", () => {
await press(container, "Enter");
expect(map.flyTo).toHaveBeenCalledWith({ center: [ 139.7, 35.6 ], zoom: expect.any(Number) });
- expect(field(container).value).toBe("Tokyo trip");
+ expect(field(container).value).toBe("tokyo");
});
it("runs the geocoder on Enter where the map has nothing of its own, and takes the first place on the next", async () => {
@@ -411,7 +381,7 @@ describe("geo map SearchBox", () => {
await press(container, "Enter");
expect(map.fitBounds).toHaveBeenCalledWith(TOKYO.bounds, expect.anything());
- expect(field(container).value).toBe("Tokyo, Japan");
+ expect(field(container).value).toBe("tokyo");
});
it("puts what is at hand under one heading and what is far off under another, nearest first", async () => {
@@ -451,18 +421,18 @@ describe("geo map SearchBox", () => {
expect(labels()).toEqual([ "Tokyo" ]);
});
- it("takes the pin off the map once the field is emptied", async () => {
+ it("reports moving on from a place once the field is emptied", async () => {
mockGeocoder([ TOKYO ]);
const container = renderSearchBox(fakeMap(), []);
await type(container, "tokyo");
- await pick(0);
- await pick(0);
- expect(container.querySelector(".place-marker")).not.toBeNull();
+ await pickNamed("geo-map.search-online(tokyo)");
+ await pickNamed("Tokyo");
+ expect(picked).toEqual([ TOKYO ]);
await type(container, "");
- expect(container.querySelector(".place-marker")).toBeNull();
+ expect(picked).toEqual([ TOKYO, null ]);
});
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 996cdec452..2787939a0a 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.tsx
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.tsx
@@ -15,7 +15,6 @@ import OverlayToolbar from "../../react/OverlayToolbar";
import { DEFAULT_GEOCODING_PROVIDER_NAME, type GeoBounds, GEOCODING_PROVIDERS, type GeoSearchResult, SEARCH_RADIUS_M } from "./geocoding";
import { ParentMap } from "./map";
import { LOCATION_ATTRIBUTE, parseLocation } from "./Markers";
-import PlaceMarker from "./PlaceMarker";
/** Shorter queries are not searched. */
const MIN_QUERY_LENGTH = 2;
@@ -54,8 +53,12 @@ const STATUS_KEY = "geocode-status";
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;
+ /**
+ * 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).
+ */
+ onPickPlace(place: GeoSearchResult | null): void;
}
/**
@@ -71,17 +74,8 @@ type SearchEntry = {
distance?: number;
} & (
| { kind: "marker"; center: [number, number] }
- /**
- * A place from the geocoder: `name` is what its pin is labelled with, and `bounds` how much
- * ground it covers, where the geocoder says.
- */
- | {
- kind: "place";
- center: [number, number];
- name: string;
- bounds?: GeoSearchResult["bounds"];
- outline?: GeoSearchResult["outline"];
- }
+ /** 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). */
| { kind: "heading" }
/** Runs the geocoder for `query`. */
@@ -118,22 +112,13 @@ 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, isDarkTheme }: SearchBoxProps) {
+export default function SearchBox({ notes, onPickPlace }: 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);
- // 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;
- outline?: GeoJSON.Geometry;
- }>();
- // Which pick the map currently stands on, so a boundary arriving after a later pick is dropped
- // rather than drawn around the place that replaced it.
- const latestPick = useRef(0);
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);
@@ -162,10 +147,9 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {
setQuery(newQuery);
// Emptying the field is how the pin is taken back off the map.
if (!newQuery.trim()) {
- latestPick.current++;
- setPickedPlace(undefined);
+ onPickPlace(null);
}
- }, []);
+ }, [ onPickPlace ]);
const runGeocoder = useCallback(async (searchQuery: string) => {
const runId = ++latestRun.current;
@@ -191,32 +175,21 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {
if (entry.kind === "geocode") {
runGeocoder(entry.query);
} else if (entry.kind === "marker" || entry.kind === "place") {
- const pickId = ++latestPick.current;
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" ? { center: entry.center, name: entry.name } : undefined);
-
- // The ground a country or a county covers, fetched only now that one of the places the
- // search offered has been settled on. A place that is a point has none, and one whose
- // boundary cannot be fetched keeps its pin.
- if (entry.kind === "place" && entry.outline) {
- entry.outline()
- .then((outline) => {
- if (!outline || latestPick.current !== pickId) return;
- setPickedPlace((current) => current && { ...current, outline });
- })
- .catch((e) => logError(`Fetching the boundary of "${entry.label}" failed: ${e}`));
- }
- if (entry.kind === "place" && entry.bounds) {
+ // 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(entry.bounds, { padding: PLACE_PADDING, maxZoom: PLACE_MAX_ZOOM });
+ map.fitBounds(bounds, { padding: PLACE_PADDING, maxZoom: PLACE_MAX_ZOOM });
} else {
map.flyTo({ center: entry.center, zoom: entry.kind === "marker" ? MARKER_ZOOM : PLACE_ZOOM });
}
}
- }, [ map, runGeocoder ]);
+ }, [ map, runGeocoder, onPickPlace ]);
const isHeading = useCallback(
(key: string) => entriesByKey.current.get(key)?.kind === "heading", []);
@@ -231,7 +204,7 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {
// A place reads over two lines: what it is called, and the address that places it. Every
// other row is one thing said once.
- const address = entry.kind === "place" ? addressOf(entry.label, entry.name) : null;
+ const address = entry.kind === "place" ? addressOf(entry.label, entry.result.name) : null;
return (
<span className={`geo-search-entry geo-search-entry-${entry.kind}`}>
@@ -239,7 +212,7 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {
<span className="geo-search-entry-lines">
{entry.kind === "place"
? <>
- <span className="geo-search-entry-name">{entry.name}</span>
+ <span className="geo-search-entry-name">{entry.result.name}</span>
{address && <span className="geo-search-entry-address">{address}</span>}
</>
: entry.label}
@@ -256,12 +229,7 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {
if (!map) return null;
return (
- <>
- {pickedPlace && <PlaceMarker
- center={pickedPlace.center} name={pickedPlace.name}
- outline={pickedPlace.outline} isDarkTheme={isDarkTheme}
- />}
- <OverlayToolbar className="geo-search-toolbar" titlePosition="bottom">
+ <OverlayToolbar className="geo-search-toolbar" titlePosition="bottom">
<Icon icon="bx bx-search" className="geo-search-icon" />
<FormAutocomplete
className="geo-search-input"
@@ -276,9 +244,8 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {
keepOpenOnPick
placeholder={t("geo-map.search-placeholder")}
aria-label={t("geo-map.search")}
- />
- </OverlayToolbar>
- </>
+ />
+ </OverlayToolbar>
);
}
@@ -418,11 +385,9 @@ 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 ],
- bounds: result.bounds,
- outline: result.outline
+ result
};
}
diff --git a/apps/client/src/widgets/collections/geomap/api.ts b/apps/client/src/widgets/collections/geomap/api.ts
index 107b4409bc..997247589c 100644
--- a/apps/client/src/widgets/collections/geomap/api.ts
+++ b/apps/client/src/widgets/collections/geomap/api.ts
@@ -56,14 +56,6 @@ export async function removeFromMap(note: FNote, mapNote: FNote) {
}
}
-/**
- * Creates a note where the click landed, and hands it back for the pane to open on.
- *
- * No title is asked for first. A modal between the click and the note was the wrong way round: it
- * blocked the map to ask for the one thing the detail pane is made for editing. The note is created
- * under the stock name instead, and the caller opens the pane on it with that name selected — naming
- * the place is typing over it (see index.tsx).
- */
/**
* Brings a GPX file onto the map as a child note, and hands the note back.
*
@@ -93,15 +85,38 @@ export async function importGpxTrack(parentNote: FNote, file: File) {
return note;
}
+/**
+ * Creates a note where the click landed, and hands it back for the pane to open on.
+ *
+ * No title is asked for first. A modal between the click and the note was the wrong way round: it
+ * blocked the map to ask for the one thing the detail pane is made for editing. The note is created
+ * under the stock name instead, and the caller opens the pane on it with that name selected — naming
+ * the place is typing over it (see index.tsx).
+ */
export async function createNewNote(parentNote: FNote, e: GeoMouseEvent) {
+ return createNoteAt(parentNote, [ e.latlng.lat, e.latlng.lng ], t("relation_map.default_new_note_title"));
+}
+
+/**
+ * Turns a place found by searching into a note of the map's own, named as the geocoder names it.
+ *
+ * Unlike a note dropped by clicking the map, this one arrives with a name worth keeping, so the
+ * detail pane opens on it as it stands rather than with the title picked out to be typed over (see
+ * `isNew` in DetailPane).
+ */
+export async function createNoteForPlace(parentNote: FNote, place: { name: string; lat: number; lng: number }) {
+ return createNoteAt(parentNote, [ place.lat, place.lng ], place.name);
+}
+
+async function createNoteAt(parentNote: FNote, [ lat, lng ]: [number, number], title: string) {
const { note } = await note_create.createNote(parentNote.noteId, {
- title: t("relation_map.default_new_note_title"),
+ title,
content: "",
type: "text",
activate: false,
isProtected: parentNote.isProtected,
attributes: [
- { type: "label", name: LOCATION_ATTRIBUTE, value: [e.latlng.lat, e.latlng.lng].join(",") },
+ { type: "label", name: LOCATION_ATTRIBUTE, value: [ lat, lng ].join(",") },
{ type: "label", name: "iconClass", value: CHILD_NOTE_ICON }
]
});
diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsx
index e50f65672b..03bb0f6426 100644
--- a/apps/client/src/widgets/collections/geomap/index.tsx
+++ b/apps/client/src/widgets/collections/geomap/index.tsx
@@ -8,11 +8,12 @@ import branches from "../../../services/branches";
import froca from "../../../services/froca";
import { t } from "../../../services/i18n";
import server from "../../../services/server";
+import { logError } from "../../../services/ws";
import toast from "../../../services/toast";
import CollectionProperties from "../../note_bars/CollectionProperties";
import { useCollectionTreeDrag, useEffectiveReadOnly, useNoteBlob, useNoteContext, useNoteLabel, useNoteLabelBoolean, useNoteProperty, useSpacedUpdate } from "../../react/hooks";
import { ViewModeProps } from "../interface";
-import { createNewNote, importGpxTrack, moveMarker } from "./api";
+import { createNewNote, createNoteForPlace, importGpxTrack, moveMarker } from "./api";
import Buildings from "./Buildings";
import ContextMenus from "./ContextMenus";
import DetailPane, { PaneSelection } from "./DetailPane";
@@ -22,7 +23,10 @@ import { GPX_MIME, GpxTrack } from "./GpxTrack";
import Map, { DEFAULT_ZOOM, GeoMouseEvent } from "./map";
import { DEFAULT_MAP_LAYER_NAME, MAP_LAYERS, MapLayer } from "./map_layer";
import MapToolbar from "./MapToolbar";
+import type { GeoSearchResult } from "./geocoding";
import Markers, { DEFAULT_MARKER_COLOR, LOCATION_ATTRIBUTE } from "./Markers";
+import PlaceMarker from "./PlaceMarker";
+import PlacePanel from "./PlacePanel";
import SearchBox from "./SearchBox";
import Tooltips from "./Tooltips";
@@ -62,6 +66,18 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
// Which marker the detail pane stands for. Held here rather than in the pane so that creating a
// note can open the pane on it (see createNoteAt below).
const [ selection, setSelection ] = useState<PaneSelection | null>(null);
+ // The place taken from the search, standing on the map under a pin of its own until it is kept as
+ // a note or dismissed. It and the selection above are one state between them: both are what the
+ // map is currently standing on, and both are shown in the same corner.
+ const [ pickedPlace, setPickedPlace ] = useState<GeoSearchResult>();
+ const [ placeOutline, setPlaceOutline ] = useState<GeoJSON.Geometry>();
+ // 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);
+ // Held still between renders: the pin's layer is rebuilt whenever it is handed a different one,
+ // and an array literal is different every time (see PlaceMarker).
+ const placeCenter = useMemo<[number, number] | null>(
+ () => pickedPlace ? [ pickedPlace.lng, pickedPlace.lat ] : null, [ pickedPlace ]);
// Whether that pane has been grown over the map. Held here for the reason the selection is: what
// the map places around the pane has to know of it too (see the maximized pane in DetailPane).
const [ paneMaximized, setPaneMaximized ] = useState(false);
@@ -98,6 +114,48 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
// pressing it again is the visible way out of it — the counterpart of the toast's Escape. It
// also takes over a map armed to move a marker, a press on + saying what the next click is for
// more plainly than whatever was armed before.
+ /** Opens the pane on a note, which sends away the searched place the panel would otherwise share
+ * a corner with. */
+ const selectNote = useCallback((next: PaneSelection | null) => {
+ setSelection(next);
+ if (next) {
+ latestPlacePick.current++;
+ setPickedPlace(undefined);
+ setPlaceOutline(undefined);
+ }
+ }, []);
+
+ /** Stands the map on a place found by searching, and fetches the ground it covers where it covers
+ * any (see PlaceMarker). */
+ const pickPlace = useCallback((place: GeoSearchResult | null) => {
+ const pickId = ++latestPlacePick.current;
+ setPickedPlace(place ?? undefined);
+ setPlaceOutline(undefined);
+ if (place) {
+ setSelection(null);
+ }
+
+ place?.outline?.()
+ .then((outline) => {
+ if (outline && latestPlacePick.current === pickId) {
+ setPlaceOutline(outline);
+ }
+ })
+ .catch((e) => logError(`Fetching the boundary of "${place.label}" failed: ${e}`));
+ }, []);
+
+ /** 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 () => {
+ if (!pickedPlace) return;
+
+ const created = await createNoteForPlace(note, pickedPlace);
+ if (!created) return;
+
+ setNotes((current) => current.some((n) => n.noteId === created.noteId) ? current : [ ...current, created ]);
+ selectNote({ noteId: created.noteId });
+ }, [ note, pickedPlace, selectNote ]);
+
const toggleNotePlacement = useCallback(() => {
setPlacement((current) => current?.mode === "new" ? undefined : { mode: "new" });
}, []);
@@ -118,7 +176,7 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
if (!created) return;
setNotes((current) => current.some((n) => n.noteId === created.noteId) ? current : [ ...current, created ]);
- setSelection({ noteId: created.noteId, isNew: true });
+ selectNote({ noteId: created.noteId, isNew: true });
}, [ note ]);
/**
@@ -139,7 +197,7 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
if (!created) return;
setNotes((current) => current.some((n) => n.noteId === created.noteId) ? current : [ ...current, created ]);
- setSelection({ noteId: created.noteId });
+ selectNote({ noteId: created.noteId });
}, [ note ]);
// Placement mode is armed by the button or by the context menu. Tying the instruction toast and
@@ -244,7 +302,17 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
onClick={onClick}
scale={hasScale}
>
- <SearchBox notes={notes} isDarkTheme={layerData.isDarkTheme ?? false} />
+ <SearchBox notes={notes} onPickPlace={pickPlace} />
+ {pickedPlace && placeCenter && <>
+ <PlaceMarker
+ center={placeCenter} name={pickedPlace.name}
+ outline={placeOutline} isDarkTheme={layerData.isDarkTheme ?? false}
+ />
+ <PlacePanel
+ place={pickedPlace} isReadOnly={isReadOnly}
+ onAddMarker={keepPlaceAsMarker} onClose={() => pickPlace(null)}
+ />
+ </>}
<MapToolbar />
<EditToolbar
isReadOnly={isReadOnly}
@@ -259,7 +327,7 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
{placement && <GhostPin note={placement.mode === "move" ? notes.find((n) => n.noteId === placement.noteId) : undefined} />}
<DetailPane
notes={notes} parentNote={note} placing={!!placement} isReadOnly={isReadOnly}
- selection={selection} onSelect={setSelection} onRelocate={startMarkerRelocation}
+ selection={selection} onSelect={selectNote} onRelocate={startMarkerRelocation}
maximized={paneMaximized} onMaximizedChange={setPaneMaximized}
/>
<ContextMenus parentNote={note} isReadOnly={isReadOnly} onRelocate={startMarkerRelocation} onCreateNote={createNoteAt} />