Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): say how far off each search result stands

Elian Doran7c5918f39d46
diff --git a/apps/client/src/utils/formatters.ts b/apps/client/src/utils/formatters.ts
index 2bf3ecde78..56faca2091 100644
--- a/apps/client/src/utils/formatters.ts
+++ b/apps/client/src/utils/formatters.ts
@@ -1,4 +1,5 @@
import { getLocaleById, t } from "../services/i18n";
+import type { MeasurementSystem } from "./units";
import options from "../services/options";
type DateTimeStyle = "full" | "long" | "medium" | "short" | "none" | undefined;
@@ -221,7 +222,7 @@ export function isContentRightToLeft(noteLanguage: string | null | undefined): b
* carrying no region is maximized first, which is what makes Trilium's plain `en` -- listed as
* "English (United States)" -- resolve to `US`; `en-GB` is a separate entry and resolves to `GB`.
*/
-export function getMeasurementSystem(): "metric" | "imperial" {
+export function getMeasurementSystem(): MeasurementSystem {
// An explicitly chosen formatting locale wins. Failing that the browser's locale is preferred
// over what getFormattingLocale() would settle on (the UI language), because the UI language
// says nothing about where the user is -- an English UI is common well outside the US.
diff --git a/apps/client/src/utils/units.ts b/apps/client/src/utils/units.ts
new file mode 100644
index 0000000000..d6b5bc83c9
--- /dev/null
+++ b/apps/client/src/utils/units.ts
@@ -0,0 +1,44 @@
+import { t } from "../services/i18n";
+
+/** Whether distances are stated in miles or in kilometres (see `getMeasurementSystem`). */
+export type MeasurementSystem = "metric" | "imperial";
+
+const METERS_PER_MILE = 1609.344;
+const FEET_PER_METER = 3.28084;
+
+/**
+ * A distance as it is read: metres up close and kilometres beyond, or miles throughout where that is
+ * how distances are stated.
+ *
+ * The unit strings are keyed under `gpx_preview`, which is where they were first written. They name
+ * nothing in particular — "{{value}} km" — and a renamed key drops what 38 locales have made of it.
+ */
+export function formatDistance(meters: number, system: MeasurementSystem): string {
+ if (system === "imperial") {
+ return t("gpx_preview.unit_mi", { value: round(meters / METERS_PER_MILE) });
+ }
+ if (meters < 1000) {
+ return t("gpx_preview.unit_m", { value: Math.round(meters).toLocaleString() });
+ }
+ return t("gpx_preview.unit_km", { value: round(meters / 1000) });
+}
+
+export function formatElevation(meters: number, system: MeasurementSystem): string {
+ if (system === "imperial") {
+ return t("gpx_preview.unit_ft", { value: Math.round(meters * FEET_PER_METER).toLocaleString() });
+ }
+ return t("gpx_preview.unit_m", { value: Math.round(meters).toLocaleString() });
+}
+
+export function formatSpeed(kmh: number, system: MeasurementSystem): string {
+ if (system === "imperial") {
+ return t("gpx_preview.unit_mph", { value: round(kmh * 1000 / METERS_PER_MILE) });
+ }
+ return t("gpx_preview.unit_kmh", { value: round(kmh) });
+}
+
+/** Fewer decimals the larger the number, so a measurement reads at the precision it is worth. */
+function round(value: number): string {
+ const decimals = value >= 100 ? 0 : value >= 10 ? 1 : 2;
+ return value.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: decimals });
+}
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.css b/apps/client/src/widgets/collections/geomap/SearchBox.css
index bbc2f0caa8..c00990a6bf 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.css
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.css
@@ -67,6 +67,19 @@ 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;
+ padding-inline-start: 8px;
+ font-size: 0.85em;
+ font-variant-numeric: tabular-nums;
+ opacity: 0.6;
}
.form-autocomplete-dropdown .geo-search-entry-address {
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
index 68554d17a4..6b922a1c2f 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
@@ -21,6 +21,11 @@ vi.mock("./PlaceMarker", () => ({
<div className="place-marker" data-center={center.join(",")} data-name={name} data-outline={outline?.type} />
}));
+vi.mock("../../../utils/formatters", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../utils/formatters")>()),
+ getMeasurementSystem: () => "metric"
+}));
+
// i18next is not initialized under test, so t() returns "". The key stands in for the text, with any
// interpolated values after it, which is enough to tell the rows apart.
vi.mock("../../../services/i18n", () => ({
@@ -44,11 +49,15 @@ function mockGeocoder(results: GeoSearchResult[]) {
/** Where a fake map is looking, which is what a search is told to prefer. */
const VIEWPORT = { west: 19.8, south: 39.5, east: 20.1, north: 39.8 };
+/** The middle of that view, which is what a row's distance is measured from. */
+const CENTRE = { lng: 19.95, lat: 39.65 };
+
/** A map that can be flown somewhere or framed on something, and that says what it is showing. */
function fakeMap() {
return {
flyTo: vi.fn(),
fitBounds: vi.fn(),
+ getCenter: () => ({ toArray: () => [ CENTRE.lng, CENTRE.lat ] as [number, number] }),
getBounds: () => ({
getWest: () => VIEWPORT.west,
getSouth: () => VIEWPORT.south,
@@ -112,7 +121,9 @@ function entries() {
/** What each row is called: the first line of a place, and the whole of any other row. */
function labels() {
return entries().map((entry) =>
- entry.querySelector(".geo-search-entry-name")?.textContent ?? entry.textContent);
+ entry.querySelector(".geo-search-entry-name")?.textContent
+ ?? entry.querySelector(".geo-search-entry-lines")?.textContent
+ ?? entry.textContent);
}
/** Picks a row and lets whatever it started settle. */
@@ -321,6 +332,28 @@ describe("geo map SearchBox", () => {
]);
});
+ it("says how far off each place stands, and says nothing of the rows that are nowhere", async () => {
+ mockGeocoder([ TOKYO ]);
+ const container = renderSearchBox(fakeMap(), mapNotes());
+
+ await type(container, "tokyo");
+
+ const distances = () => entries().map((entry) =>
+ entry.querySelector(".geo-search-entry-distance")?.textContent ?? null);
+
+ // The note is on the other side of the world from the view, which is in Corfu.
+ const [ tokyoTrip, geocoderRow ] = distances();
+ expect(tokyoTrip).toMatch(/^gpx_preview\.unit_km/);
+ expect(Number(tokyoTrip?.replace(/\D/g, ""))).toBeGreaterThan(9000);
+ // The row that runs the geocoder names no place, so it stands nowhere.
+ expect(geocoderRow).toBeNull();
+
+ await pick(1);
+
+ // The place the geocoder found is measured the same way.
+ expect(distances()[1]).toMatch(/^gpx_preview\.unit_km/);
+ });
+
it("takes the pin off the map once the field is emptied", async () => {
mockGeocoder([ TOKYO ]);
const container = renderSearchBox(fakeMap(), []);
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.tsx
index 8e872bdb21..d05a5335a9 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.tsx
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.tsx
@@ -7,6 +7,8 @@ import type { Map as MapLibreGLMap } from "maplibre-gl";
import type FNote from "../../../entities/fnote";
import { t } from "../../../services/i18n";
import { logError } from "../../../services/ws";
+import { getMeasurementSystem } from "../../../utils/formatters";
+import { formatDistance } from "../../../utils/units";
import FormAutocomplete from "../../react/FormAutocomplete";
import Icon from "../../react/Icon";
import OverlayToolbar from "../../react/OverlayToolbar";
@@ -33,6 +35,9 @@ const PLACE_PADDING = 60;
/** The zoom level a marker is shown at, closer in since a note marks a spot rather than an area. */
const MARKER_ZOOM = 15;
+/** The mean radius of the Earth, which is what a great-circle distance is measured on. */
+const EARTH_RADIUS_M = 6_371_008.8;
+
/**
* How wide the result list is drawn. The field is a corner of the map, while what it offers is whole
* addresses, which at the field's own width is mostly an ellipsis.
@@ -62,6 +67,8 @@ type SearchEntry = {
label: string;
/** A boxicons class, as `FNote.getIcon()` gives it. */
icon: string;
+ /** How far the place is from the middle of the map, in metres. */
+ distance?: number;
} & (
| { kind: "marker"; center: [number, number] }
/**
@@ -133,10 +140,14 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {
return [];
}
- const entries = [ ...matchMarkers(notes, trimmed), ...geocodeEntries(geocodeRun, trimmed) ];
+ // Measured from the middle of what the map is showing, at the moment the list is built: two
+ // places of the same name are told apart by which of them is at hand.
+ const origin = map ? map.getCenter().toArray() : null;
+ const entries = [ ...matchMarkers(notes, trimmed), ...geocodeEntries(geocodeRun, trimmed) ]
+ .map((entry) => withDistance(entry, origin));
entriesByKey.current = new Map(entries.map((entry) => [ entry.key, entry ]));
return entries.map((entry) => entry.key);
- }, [ notes, geocodeRun, dismissed ]);
+ }, [ notes, geocodeRun, dismissed, map ]);
const changeQuery = useCallback((newQuery: string) => {
setDismissed(false);
@@ -210,12 +221,18 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {
return (
<span className={`geo-search-entry geo-search-entry-${entry.kind}`}>
<Icon icon={entry.icon} />
- {entry.kind === "place"
- ? <span className="geo-search-entry-lines">
- <span className="geo-search-entry-name">{entry.name}</span>
- {address && <span className="geo-search-entry-address">{address}</span>}
- </span>
- : entry.label}
+ <span className="geo-search-entry-lines">
+ {entry.kind === "place"
+ ? <>
+ <span className="geo-search-entry-name">{entry.name}</span>
+ {address && <span className="geo-search-entry-address">{address}</span>}
+ </>
+ : entry.label}
+ </span>
+ {entry.distance !== undefined &&
+ <span className="geo-search-entry-distance">
+ {formatDistance(entry.distance, getMeasurementSystem())}
+ </span>}
</span>
);
}, []);
@@ -248,6 +265,29 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {
);
}
+/**
+ * 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.
+ */
+function withDistance(entry: SearchEntry, origin: [number, number] | null): SearchEntry {
+ if (!origin || !("center" in entry)) {
+ return entry;
+ }
+
+ return { ...entry, distance: metresBetween(origin, entry.center) };
+}
+
+/** The great-circle metres between two `[lng, lat]` points. */
+function metresBetween([ lngA, latA ]: [number, number], [ lngB, latB ]: [number, number]) {
+ const toRadians = Math.PI / 180;
+ const deltaLat = (latB - latA) * toRadians;
+ const deltaLng = (lngB - lngA) * toRadians;
+ const h = Math.sin(deltaLat / 2) ** 2
+ + Math.cos(latA * toRadians) * Math.cos(latB * toRadians) * Math.sin(deltaLng / 2) ** 2;
+
+ return 2 * EARTH_RADIUS_M * Math.asin(Math.sqrt(h));
+}
+
/** What the map is showing, as a geocoder reads a preferred area. */
function viewportOf(map: MapLibreGLMap): GeoBounds {
const bounds = map.getBounds();
diff --git a/apps/client/src/widgets/type_widgets/file/GpxPreview.tsx b/apps/client/src/widgets/type_widgets/file/GpxPreview.tsx
index 02d920b4cf..ebdeab2690 100644
--- a/apps/client/src/widgets/type_widgets/file/GpxPreview.tsx
+++ b/apps/client/src/widgets/type_widgets/file/GpxPreview.tsx
@@ -8,10 +8,10 @@ import { GpxElevationSample, GpxJourney, GpxStats, parseGpxStats } from "../../.
import { t } from "../../../services/i18n";
import server from "../../../services/server";
import { formatDateTime, getMeasurementSystem } from "../../../utils/formatters";
+import { formatDistance, formatElevation, formatSpeed, type MeasurementSystem } from "../../../utils/units";
import Alert from "../../react/Alert";
import Collapsible from "../../react/Collapsible";
-type MeasurementSystem = ReturnType<typeof getMeasurementSystem>;
interface GpxPreviewProps {
note: FNote;
@@ -296,33 +296,6 @@ function nearestSample(profile: GpxElevationSample[], distance: number): GpxElev
return distance - profile[lo].distance <= profile[hi].distance - distance ? profile[lo] : profile[hi];
}
-const METERS_PER_MILE = 1609.344;
-const FEET_PER_METER = 3.28084;
-
-function formatDistance(meters: number, system: MeasurementSystem): string {
- if (system === "imperial") {
- return t("gpx_preview.unit_mi", { value: round(meters / METERS_PER_MILE) });
- }
- if (meters < 1000) {
- return t("gpx_preview.unit_m", { value: Math.round(meters).toLocaleString() });
- }
- return t("gpx_preview.unit_km", { value: round(meters / 1000) });
-}
-
-function formatElevation(meters: number, system: MeasurementSystem): string {
- if (system === "imperial") {
- return t("gpx_preview.unit_ft", { value: Math.round(meters * FEET_PER_METER).toLocaleString() });
- }
- return t("gpx_preview.unit_m", { value: Math.round(meters).toLocaleString() });
-}
-
-function formatSpeed(kmh: number, system: MeasurementSystem): string {
- if (system === "imperial") {
- return t("gpx_preview.unit_mph", { value: round(kmh * 1000 / METERS_PER_MILE) });
- }
- return t("gpx_preview.unit_kmh", { value: round(kmh) });
-}
-
function formatTravelDuration(milliseconds: number): string {
const totalMinutes = Math.round(milliseconds / 60_000);
const hours = Math.floor(totalMinutes / 60);
@@ -332,9 +305,3 @@ function formatTravelDuration(milliseconds: number): string {
}
return t("gpx_preview.duration_hours_minutes", { hours, minutes });
}
-
-/** A magnitude-appropriate rounding: two decimals close up, none once they would say nothing. */
-function round(value: number): string {
- const decimals = value >= 100 ? 0 : value >= 10 ? 1 : 2;
- return value.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: decimals });
-}