Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): put the locate button on the map's own toolbar

Elian Doran14d939c9db18
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index ed956caa6a..95fbe3755b 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3000,7 +3000,15 @@
"next-result": "Next result",
"result-position": "Result {{index}} of {{total}}, click to return to it",
"results-on-map": "On this map",
- "go-to-coordinates": "Go to {{- coordinates}}"
+ "go-to-coordinates": "Go to {{- coordinates}}",
+ "locate": "Show your location",
+ "locate-waiting": "Finding your location…",
+ "locate-following": "Stop following your location",
+ "locate-return": "Return to your location",
+ "locate-error": "Couldn't find your location. Press again to stop looking.",
+ "locate-unavailable": "Your location isn't available",
+ "location-denied": "Location access was denied. Allow it for Trilium in your browser or system settings to show your location on the map.",
+ "location-unavailable": "Your location couldn't be determined right now."
},
"embedded_note": {
"open-note": "Open note",
diff --git a/apps/client/src/widgets/collections/geomap/MapToolbar.css b/apps/client/src/widgets/collections/geomap/MapToolbar.css
index 3242570b1e..230560fb99 100644
--- a/apps/client/src/widgets/collections/geomap/MapToolbar.css
+++ b/apps/client/src/widgets/collections/geomap/MapToolbar.css
@@ -5,11 +5,19 @@
width: 32px;
}
-/* MapLibre's locate button is added to the corner this group stands in (see useGeolocateControl in
- MapToolbar.tsx), so it is lifted to stand above the group: the foot is the room kept from the
- edge, the group's height and as much air again. Named by four classes to outweigh the corner
- margins index.css gives every control. */
-.geo-map-container .maplibregl-ctrl-bottom-right .maplibregl-ctrl.maplibregl-ctrl-group {
- margin-bottom: var(--geo-map-foot);
+/* The glyph breathes while the device is being asked where it is: the one state of the button that
+ is a wait rather than a choice. Boxicons draws the glyph in the button's ::before. */
+.geo-map-container .geo-map-toolbar .geo-map-locate-button.locating::before {
+ animation: geo-map-locating 1.2s ease-in-out infinite alternate;
+}
+
+@keyframes geo-map-locating {
+ to { opacity: 0.3; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .geo-map-container .geo-map-toolbar .geo-map-locate-button.locating::before {
+ animation: none;
+ }
}
diff --git a/apps/client/src/widgets/collections/geomap/MapToolbar.spec.tsx b/apps/client/src/widgets/collections/geomap/MapToolbar.spec.tsx
index 1356743033..9428f1f066 100644
--- a/apps/client/src/widgets/collections/geomap/MapToolbar.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/MapToolbar.spec.tsx
@@ -8,18 +8,25 @@
import { GeolocateControl, type Map as MapLibreGLMap } from "maplibre-gl";
import { render } from "preact";
import { act } from "preact/test-utils";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { renderInto } from "../../../test/render";
import { ParentMap } from "./map";
import MapToolbar from "./MapToolbar";
+const { showError } = vi.hoisted(() => ({ showError: vi.fn() }));
+vi.mock("../../../services/toast", () => ({ default: { showError } }));
+// t() returns the key, so the assertions below are on which title the button wears rather than on
+// its English wording.
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
/** The order the group lays its buttons out in — the image viewer's, with the tilt leading and the
* screen at the end. */
const TILT = 0;
const ZOOM_OUT = 1;
const ZOOM_IN = 2;
-const FULLSCREEN = 3;
+const LOCATE = 3;
+const FULLSCREEN = 4;
/** A map that zooms and tilts, says so, and stands somewhere — all these controls ask of one. */
function fakeMap({ zoom = 5, minZoom = 2, maxZoom = 22, pitch = 0 } = {}) {
@@ -43,7 +50,7 @@ function fakeMap({ zoom = 5, minZoom = 2, maxZoom = 22, pitch = 0 } = {}) {
const controls = new Set<unknown>();
return {
- addControl: vi.fn((control: unknown, _position?: string) => { controls.add(control); }),
+ addControl: vi.fn((control: unknown) => { controls.add(control); }),
removeControl: vi.fn((control: unknown) => { controls.delete(control); }),
hasControl: (control: unknown) => controls.has(control),
/** The map being torn down, as `map.remove()` does before any cleanup around it runs. */
@@ -83,6 +90,17 @@ function setFullscreenElement(element: Element | null) {
beforeEach(() => {
Object.defineProperty(document, "fullscreenElement", { value: null, configurable: true });
document.exitFullscreen = vi.fn(async () => {});
+ // What a browser offers on a secure origin, which is the only place the locate button is
+ // offered: happy-dom leaves the first undefined and the second null.
+ Object.defineProperty(window, "isSecureContext", { value: true, configurable: true });
+ Object.defineProperty(navigator, "geolocation", { value: {}, configurable: true });
+ // The control's own press, which would otherwise reach for the browser's geolocation.
+ vi.spyOn(GeolocateControl.prototype, "trigger").mockReturnValue(true);
+ showError.mockClear();
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
});
/** Builds the controls over a map and settles them, so they are listening before being spoken to. */
@@ -107,6 +125,13 @@ function press(container: HTMLElement, index: number) {
act(() => buttons(container)[index].click());
}
+/** The locate control the toolbar stood on the map, which the tests speak for as the browser would. */
+function controlOn(map: ReturnType<typeof fakeMap>) {
+ const control: unknown = map.addControl.mock.calls[0]?.[0];
+ if (!(control instanceof GeolocateControl)) throw new Error("no locate control was added");
+ return control;
+}
+
describe("geo map MapToolbar", () => {
it("offers what the map's own controls did, laid out as the image viewer's group", () => {
const container = renderToolbar(fakeMap());
@@ -115,6 +140,7 @@ describe("geo map MapToolbar", () => {
expect.stringContaining("geo-map-tilt-button"),
expect.stringContaining("bx-minus-circle"),
expect.stringContaining("bx-plus-circle"),
+ expect.stringContaining("bx-current-location"),
expect.stringContaining("bx-fullscreen")
]);
});
@@ -153,9 +179,11 @@ describe("geo map MapToolbar", () => {
try {
const container = renderToolbar(fakeMap());
- // Only the tilt and the screen remain — see the mobile note in MapToolbar.tsx.
+ // The tilt, the device's position and the screen remain — see the mobile note in
+ // MapToolbar.tsx.
expect(buttons(container).map((button) => button.className)).toEqual([
expect.stringContaining("geo-map-tilt-button"),
+ expect.stringContaining("bx-current-location"),
expect.stringContaining("bx-fullscreen")
]);
} finally {
@@ -169,19 +197,22 @@ describe("geo map MapToolbar", () => {
expect(buttons(container)).toHaveLength(0);
});
- it("stands MapLibre's locate button on the map, set to follow the device, and takes it off again", () => {
+ it("stands MapLibre's locate control on the map with its own button hidden, and takes it off again", () => {
const map = fakeMap();
const container = renderToolbar(map);
expect(map.addControl).toHaveBeenCalledTimes(1);
- const [ control, position ] = map.addControl.mock.calls[0];
- expect(control).toBeInstanceOf(GeolocateControl);
+ const control = controlOn(map);
// A toggle that follows the device rather than a button that flies there once.
- expect((control as GeolocateControl).options.trackUserLocation).toBe(true);
+ expect(control.options.trackUserLocation).toBe(true);
// GPS where the device has it; MapLibre's default settles for a coarse fix.
- expect((control as GeolocateControl).options.positionOptions?.enableHighAccuracy).toBe(true);
- // The corner this group stands in, lifted above it (see MapToolbar.css).
- expect(position).toBe("bottom-right");
+ expect(control.options.positionOptions?.enableHighAccuracy).toBe(true);
+
+ // MapLibre builds the control's white box; the toolbar wears the button instead.
+ const box = document.createElement("div");
+ vi.spyOn(GeolocateControl.prototype, "onAdd").mockReturnValue(box);
+ expect(control.onAdd(map as unknown as MapLibreGLMap)).toBe(box);
+ expect(box.hidden).toBe(true);
act(() => { render(null, container); });
expect(map.removeControl).toHaveBeenCalledWith(control);
@@ -195,6 +226,89 @@ describe("geo map MapToolbar", () => {
expect(torn.removeControl).not.toHaveBeenCalled();
});
+ it("presses the control's own button, and wears what the control is doing", () => {
+ const map = fakeMap();
+ const container = renderToolbar(map);
+ const control = controlOn(map);
+ const button = () => buttons(container)[LOCATE];
+
+ expect(button().getAttribute("aria-label")).toBe("geo-map.locate");
+ expect(button().classList.contains("active")).toBe(false);
+
+ press(container, LOCATE);
+ expect(control.trigger).toHaveBeenCalledTimes(1);
+
+ // The press as the control reports it: waiting on the browser, then following the fix.
+ act(() => { control.fire("trackuserlocationstart"); });
+ expect(button().getAttribute("aria-label")).toBe("geo-map.locate-waiting");
+ expect(button().classList.contains("active")).toBe(true);
+ expect(button().classList.contains("locating")).toBe(true);
+
+ act(() => { control.fire("geolocate", { coords: {}, timestamp: 0 }); });
+ expect(button().getAttribute("aria-label")).toBe("geo-map.locate-following");
+ expect(button().classList.contains("active")).toBe(true);
+ expect(button().classList.contains("locating")).toBe(false);
+
+ // A drag frees the camera. The control says the tracking ended and, in the same breath,
+ // that the dot merely lost the camera; the second word is the one that counts.
+ act(() => {
+ control.fire("trackuserlocationend");
+ control.fire("userlocationlostfocus");
+ });
+ expect(button().getAttribute("aria-label")).toBe("geo-map.locate-return");
+ expect(button().classList.contains("active")).toBe(false);
+
+ // Pressed again, the camera returns to the dot.
+ act(() => {
+ control.fire("trackuserlocationstart");
+ control.fire("userlocationfocus");
+ });
+ expect(button().getAttribute("aria-label")).toBe("geo-map.locate-following");
+ expect(button().classList.contains("active")).toBe(true);
+
+ // Pressed while following, the watch stops: the drag's first word with no second one.
+ act(() => { control.fire("trackuserlocationend"); });
+ expect(button().getAttribute("aria-label")).toBe("geo-map.locate");
+ expect(button().classList.contains("active")).toBe(false);
+ });
+
+ it("says once when the position cannot be found, and stands down when access is denied", () => {
+ const map = fakeMap();
+ const container = renderToolbar(map);
+ const control = controlOn(map);
+ const button = () => buttons(container)[LOCATE];
+
+ act(() => { control.fire("trackuserlocationstart"); });
+ act(() => { control.fire("error", { code: 2, message: "unavailable" }); });
+ expect(button().getAttribute("aria-label")).toBe("geo-map.locate-error");
+ expect(showError).toHaveBeenCalledTimes(1);
+ expect(showError).toHaveBeenLastCalledWith("geo-map.location-unavailable");
+
+ // The watch goes on reporting the same failure; the reader was told the first time.
+ act(() => { control.fire("error", { code: 2, message: "unavailable" }); });
+ expect(showError).toHaveBeenCalledTimes(1);
+
+ // A fix arriving after all takes the word back.
+ act(() => { control.fire("geolocate", { coords: {}, timestamp: 0 }); });
+ expect(button().getAttribute("aria-label")).toBe("geo-map.locate-following");
+
+ // Denied is the end of it: the control clears its watch, and the button stands down.
+ act(() => { control.fire("error", { code: 1, message: "denied" }); });
+ expect(button().disabled).toBe(true);
+ expect(button().getAttribute("aria-label")).toBe("geo-map.locate-unavailable");
+ expect(showError).toHaveBeenLastCalledWith("geo-map.location-denied");
+ });
+
+ it("keeps the locate button off a map that cannot ask where the device is", () => {
+ // What a browser says of a page served over plain HTTP, where the Geolocation API refuses.
+ Object.defineProperty(window, "isSecureContext", { value: false, configurable: true });
+ const map = fakeMap();
+ const container = renderToolbar(map);
+
+ expect(buttons(container).some((button) => button.classList.contains("bx-current-location"))).toBe(false);
+ expect(map.addControl).not.toHaveBeenCalled();
+ });
+
it("zooms the map in either direction", () => {
const map = fakeMap();
const container = renderToolbar(map);
diff --git a/apps/client/src/widgets/collections/geomap/MapToolbar.tsx b/apps/client/src/widgets/collections/geomap/MapToolbar.tsx
index 9837559ac9..14f2ed6e06 100644
--- a/apps/client/src/widgets/collections/geomap/MapToolbar.tsx
+++ b/apps/client/src/widgets/collections/geomap/MapToolbar.tsx
@@ -1,9 +1,11 @@
import "./MapToolbar.css";
+import clsx from "clsx";
import { GeolocateControl, type Map as MapLibreGLMap } from "maplibre-gl";
-import { useContext, useEffect, useState } from "preact/hooks";
+import { useCallback, useContext, useEffect, useRef, useState } from "preact/hooks";
import { t } from "../../../services/i18n";
+import toast from "../../../services/toast";
import { isMobile } from "../../../services/utils";
import { useFullscreen } from "../../react/hooks";
import OverlayControlGroup, { OverlayControlButton, OverlayFullscreenButton } from "../../react/OverlayControlGroup";
@@ -31,6 +33,10 @@ import { ParentMap, useMapPitch } from "./map";
* remembered from the last press — MapLibre tilts for Ctrl and a drag as well, and a button that
* only watched itself would go on offering a 3D the reader is already in.
*
+ * Between the steps and the screen stands the locate button. It asks the device where it is, frames
+ * the map there and follows the position until the map is dragged or the button pressed again. The
+ * work is MapLibre's own GeolocateControl with its button hidden (see useGeolocate).
+ *
* On mobile the two steps stay home, as the image viewer's do: the fingers already zoom, and the
* foot of a narrow map is spoken for. The tilt is kept — the two-finger drag that leans the view
* is told to nobody, so the button is the one visible way into 3D — and so is the screen, which a
@@ -49,7 +55,7 @@ export default function MapToolbar() {
// The map itself rather than the whole view: what is around it is the note's own chrome, and
// everything the bar above the map offers is on the map's right-click menu as well.
const [ isFullscreen, toggleFullscreen ] = useFullscreen(map?.getContainer());
- useGeolocateControl(map);
+ const locate = useGeolocate(map);
if (!map) return null;
@@ -81,6 +87,15 @@ export default function MapToolbar() {
onClick={() => map.zoomIn()}
/>
</>}
+ {locate && <OverlayControlButton
+ title={locateTitle(locate)}
+ icon="bx-current-location"
+ className={clsx("geo-map-locate-button", locate.state === "waiting" && "locating")}
+ // Held down while the camera is the device's: waiting for the first fix, or following.
+ active={locate.state === "waiting" || locate.state === "following"}
+ disabled={locate.state === "denied"}
+ onClick={locate.toggle}
+ />}
{/* Nothing is measured across the change: the map keeps the middle of its view through
a resize of its own accord, and it is told of the new size by the view itself (see
`useElementSize` in map.tsx). */}
@@ -115,33 +130,135 @@ function useMapZoom(map: MapLibreGLMap | null) {
return zoom;
}
+/** What the locate button is doing, read off the control's events (see {@link useGeolocate}). */
+type LocateState = "off" | "waiting" | "following" | "background" | "denied";
+
+interface Locate {
+ state: LocateState;
+ /** Whether the last position update failed while the watch stays on. */
+ hasError: boolean;
+ /** Presses the control's own button: on, back to the position, or off, depending on the state. */
+ toggle: () => void;
+}
+
+/** The Geolocation API's code for a permission the user or the browser refused. */
+const PERMISSION_DENIED = 1;
+
+/**
+ * MapLibre's GeolocateControl with its button hidden. The map keeps the control's behaviour and the
+ * toolbar wears the button (see {@link useGeolocate}).
+ */
+class HiddenGeolocateControl extends GeolocateControl {
+ onAdd(map: MapLibreGLMap) {
+ const container = super.onAdd(map);
+ container.hidden = true;
+ return container;
+ }
+}
+
/**
- * Stands MapLibre's own locate button on the map, in the corner above this group (see
- * MapToolbar.css for the lift).
+ * Drives MapLibre's locate control from the toolbar's own button.
+ *
+ * The control keeps its behaviour: the first press starts a watch on the device's position, frames
+ * the first fix to its accuracy and follows the later ones; dragging the map keeps the dot and frees
+ * the camera; a press while following stops the watch and removes the dot, and a press while the
+ * camera is free returns it to the dot. The dot and its accuracy circle are DOM markers, so they need
+ * no carrying across a style switch (see `keepAdditions` in map.tsx). What the control's hidden button
+ * would show is read off its events instead.
+ *
+ * `trackuserlocationend` fires both when the watch stops and when a drag frees the camera; only the
+ * drag follows it, synchronously, with `userlocationlostfocus`, so the state is set to off and then
+ * corrected. A denied permission is terminal: the control clears its watch and disables its button,
+ * and so does this.
*
- * With `trackUserLocation` the button is a toggle: the first press asks the browser for the device's
- * position, frames it and follows it as it changes; dragging the map keeps the dot but frees the
- * camera; a second press turns the watch off and takes the dot away. The control draws the dot and
- * its accuracy circle itself, as DOM markers over the canvas, so nothing here survives a style
- * switch only by being carried across (see `keepAdditions` in map.tsx).
+ * Returns `null` where the button cannot work: no Geolocation API, or an insecure origin, where
+ * browsers refuse the call outright.
*/
-function useGeolocateControl(map: MapLibreGLMap | null) {
+function useGeolocate(map: MapLibreGLMap | null): Locate | null {
+ const available = canLocate();
+ const control = useRef<GeolocateControl | null>(null);
+ const [ state, setState ] = useState<LocateState>("off");
+ const [ hasError, setHasError ] = useState(false);
+ // Whether the reader has been told of the failure the watch is in; a watch reports the same
+ // failure over and over, and one toast is enough for it.
+ const toldOfError = useRef(false);
+
useEffect(() => {
- if (!map) return;
+ if (!map || !available) return;
- const control = new GeolocateControl({
+ const geolocate = new HiddenGeolocateControl({
trackUserLocation: true,
// GPS where the device has it, rather than the cell or Wi-Fi fix the default settles for.
positionOptions: { enableHighAccuracy: true }
});
- map.addControl(control, "bottom-right");
+ control.current = geolocate;
+ map.addControl(geolocate);
+
+ // A press from off waits on the browser; a press with the camera free returns to the dot,
+ // which userlocationfocus says as well.
+ geolocate.on("trackuserlocationstart", () => {
+ setState((current) => current === "background" ? "following" : "waiting");
+ });
+ geolocate.on("userlocationfocus", () => setState("following"));
+ geolocate.on("trackuserlocationend", () => {
+ setState("off");
+ setHasError(false);
+ toldOfError.current = false;
+ });
+ geolocate.on("userlocationlostfocus", () => setState("background"));
+ geolocate.on("geolocate", () => {
+ setHasError(false);
+ toldOfError.current = false;
+ setState((current) => current === "waiting" ? "following" : current);
+ });
+ geolocate.on("error", ({ code }) => {
+ if (code === PERMISSION_DENIED) {
+ setState("denied");
+ toast.showError(t("geo-map.location-denied"));
+ return;
+ }
+ setHasError(true);
+ if (!toldOfError.current) {
+ toldOfError.current = true;
+ toast.showError(t("geo-map.location-unavailable"));
+ }
+ });
return () => {
+ control.current = null;
+ setState("off");
+ setHasError(false);
+ toldOfError.current = false;
// A map being removed lets go of its controls first, and MapLibre's `removeControl`
// throws for one the map no longer holds (see the scale control in map.tsx).
- if (map.hasControl(control)) {
- map.removeControl(control);
+ if (map.hasControl(geolocate)) {
+ map.removeControl(geolocate);
}
};
- }, [ map ]);
+ }, [ map, available ]);
+
+ const toggle = useCallback(() => { control.current?.trigger(); }, []);
+
+ if (!available) return null;
+
+ return { state, hasError, toggle };
+}
+
+/** Whether the Geolocation API can be asked at all: browsers refuse it on an insecure origin. */
+function canLocate() {
+ return window.isSecureContext === true && !!navigator.geolocation;
+}
+
+function locateTitle({ state, hasError }: Locate) {
+ switch (state) {
+ case "denied": return t("geo-map.locate-unavailable");
+ case "off": return t("geo-map.locate");
+ default: break;
+ }
+ if (hasError) return t("geo-map.locate-error");
+ switch (state) {
+ case "waiting": return t("geo-map.locate-waiting");
+ case "following": return t("geo-map.locate-following");
+ case "background": return t("geo-map.locate-return");
+ }
}
diff --git a/apps/desktop/src/services/web_contents_security.ts b/apps/desktop/src/services/web_contents_security.ts
index 13322094c3..2b22146e5f 100644
--- a/apps/desktop/src/services/web_contents_security.ts
+++ b/apps/desktop/src/services/web_contents_security.ts
@@ -159,7 +159,7 @@ export function hardenWebviewPreferences(webPreferences: Electron.WebPreferences
* *check* handler rather than the request handler, so granting it here is
* what keeps the picker from falling back to the stock list.
* `geolocation` lets the geo map's locate button ask where this device is
- * (see `useGeolocateControl` in the client). Chromium prompts for nothing
+ * (see `useGeolocate` in the client). Chromium prompts for nothing
* of its own in Electron, so this grant is the only gate; the origin check
* below keeps it from remote embeds, and MapLibre probes the *check*
* handler before it enables the button at all.