Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(geomap): let a marker say where it stands, in its own words
Elian Doranf2bf120f0d0a
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 66338d2fbf..7eb7f67451 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2751,7 +2751,8 @@"fullscreen": "Fullscreen","exit-fullscreen": "Exit fullscreen","close-details": "Close",- "open-note": "Open note"+ "open-note": "Open note",+ "copy-coordinates": "Copy coordinates"},"geo-map-context": {"open-location": "Open location",diff --git a/apps/client/src/widgets/PromotedAttributes.spec.tsx b/apps/client/src/widgets/PromotedAttributes.spec.tsxindex 01e91d9891..36fcc4ec89 100644--- a/apps/client/src/widgets/PromotedAttributes.spec.tsx+++ b/apps/client/src/widgets/PromotedAttributes.spec.tsx@@ -280,7 +280,7 @@ describe("PromotedAttributes", () => {container.remove();});- function mount(note: FNote) {+ function mount(note: FNote, omit?: readonly string[]) {shownNote.current = note;const parent = {componentId: "cid",@@ -289,7 +289,7 @@ describe("PromotedAttributes", () => {} as unknown as Component;act(() => render(<ParentComponent.Provider value={parent}>- <PromotedAttributes />+ <PromotedAttributes omit={omit} /></ParentComponent.Provider>,container));@@ -314,6 +314,22 @@ describe("PromotedAttributes", () => {expect(multiInput.current?.values).toEqual([ "alpha", "beta" ]);});+ /** A host showing a value better than a field would says so by name — see the geo map's pane. */+ it("leaves out the definitions the host names, and keeps the rest", () => {+ const note = buildNote({+ title: "Place",+ "#label:geolocation": "promoted,single,text",+ "#geolocation": "1,2",+ "#label:visited": "promoted,single,text",+ "#visited": "yes"+ });+ mount(note, [ "geolocation" ]);++ const names = [ ...container.querySelectorAll(".promoted-attribute-cell > label") ]+ .map((label) => label.textContent);+ expect(names).toEqual([ "visited" ]);+ });+it("keeps the grid empty for a table view, whose cells already edit the same fields", () => {const note = buildNote({title: "Grid", "#viewType": "table",diff --git a/apps/client/src/widgets/PromotedAttributes.tsx b/apps/client/src/widgets/PromotedAttributes.tsxindex a161e3987e..6ea05c3ef3 100644--- a/apps/client/src/widgets/PromotedAttributes.tsx+++ b/apps/client/src/widgets/PromotedAttributes.tsx@@ -47,10 +47,20 @@ interface CellProps {type OnChangeEventData = TargetedEvent<HTMLInputElement | HTMLTextAreaElement, Event> | InputEvent | JQuery.TriggeredEvent<HTMLInputElement, undefined, HTMLInputElement, HTMLInputElement>;type OnChangeListener = (e: OnChangeEventData) => void | Promise<void>;-export default function PromotedAttributes() {+export default function PromotedAttributes({ omit }: {+ /**+ * Names of definitions to leave out, for a host that shows what they hold better than a field+ * would — the geo map's marker pane leaves out the location it is already standing on.+ *+ * Left out of the grid only: the note keeps the attribute and every other view of it still+ * offers the field, this being about where a value is best edited rather than whether it counts.+ */+ omit?: readonly string[];+} = {}) {const { note, componentId, noteContext } = useNoteContext();const [ cells, setCells ] = usePromotedAttributeData(note, componentId, noteContext);- return <PromotedAttributesContent note={note} componentId={componentId} cells={cells} setCells={setCells} />;+ const shown = omit?.length ? cells?.filter((cell) => !omit.includes(cell.valueName)) : cells;+ return <PromotedAttributesContent note={note} componentId={componentId} cells={shown} setCells={setCells} />;}export function PromotedAttributesContent({ note, componentId, cells, setCells }: {diff --git a/apps/client/src/widgets/collections/geomap/ContextMenus.ts b/apps/client/src/widgets/collections/geomap/ContextMenus.tsindex 407328a6c8..b342c1d48e 100644--- a/apps/client/src/widgets/collections/geomap/ContextMenus.ts+++ b/apps/client/src/widgets/collections/geomap/ContextMenus.ts@@ -12,7 +12,7 @@ import link from "../../../services/link.js";import { createNewNote } from "./api.js";import { trackHitLayers } from "./GpxTrack.js";import { type GeoMouseEvent, ParentMap, toGeoMouseEvent } from "./map.js";-import { MARKER_LAYER } from "./Markers.js";+import { formatLocation, MARKER_LAYER } from "./Markers.js";interface ContextMenusProps {note: FNote;@@ -129,15 +129,13 @@ export function openMapContextMenu(note: FNote, e: GeoMouseEvent, isEditable: bo}function buildGeoLocationItem(e: GeoMouseEvent) {- function formatGeoLocation(latlng: { lat: number; lng: number }, precision: number = 6) {- return `${latlng.lat.toFixed(precision)}, ${latlng.lng.toFixed(precision)}`;- }+ const coordinates: [number, number] = [ e.latlng.lng, e.latlng.lat ];return [{- title: formatGeoLocation(e.latlng),+ title: formatLocation(coordinates),uiIcon: "bx bx-current-location",- handler: () => copyTextWithToast(formatGeoLocation(e.latlng, 15))+ handler: () => copyTextWithToast(formatLocation(coordinates, 15))},{title: t("geo-map-context.open-location"),diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.css b/apps/client/src/widgets/collections/geomap/DetailPane.cssindex 8ee353b6b2..9e7279daa2 100644--- a/apps/client/src/widgets/collections/geomap/DetailPane.css+++ b/apps/client/src/widgets/collections/geomap/DetailPane.css@@ -83,6 +83,32 @@min-height: 120px;}+/*+ * Where the marker stands, reading as a subtitle to the name above it rather than as one more thing+ * to press: it is a line of text that happens to answer to a click, so it stands on no plate of its+ * own until it is aimed at.+ */+.geo-map-container .geo-detail-pane .geo-detail-pane-location {+ display: flex;+ align-items: center;+ gap: 6px;+ align-self: flex-start;+ /* Room to be pressed, taken back at the leading edge so the text still lines up with the button+ row under it. */+ margin-inline-start: -6px;+ padding: 2px 6px;+ border: none;+ border-radius: 6px;+ background: none;+ color: var(--muted-text-color);+ font-size: 0.85em;++ &:hover {+ background: var(--hover-item-background-color);+ color: var(--main-text-color);+ }+}+/** The note's promoted fields, laid out for a third of the width they are written for.*diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsxindex 7d7e145594..4d0aa92919 100644--- a/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx@@ -48,6 +48,13 @@ vi.mock("../../NoteDetail", () => ({}}));+/** What the pane puts on the clipboard, the writing of it being the browser's business. */+const copied = vi.fn();+vi.mock("../../../services/clipboard_ext", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ copyTextWithToast: (...args: unknown[]) => copied(...args)+}));+// A promoted text field suggests what other notes hold under its name, asked for through the Algolia// jQuery plugin and answered by the server. Neither is loaded here.type PluggedIn = { autocomplete(...args: unknown[]): PluggedIn };@@ -463,6 +470,43 @@ describe("DetailPane", () => {});});+ /**+ * The place has a line of its own under the name, and is kept out of the grid of fields: the+ * collection promotes `geolocation` so that a marker can be placed from the tree, but in the+ * pane that field is a box of raw digits standing beside a map of the very place it names.+ */+ it("names the place under the title rather than among the fields", async () => {+ // An id of its own: the froca raised for a test keeps the attributes of every note built+ // under a given id, so reusing one would read back whatever an earlier test placed there.+ buildNote({ id: "root", title: "root", children: [ {+ id: "placeDesVosges",+ title: "Somewhere",+ // What the map writes when a marker is placed, which is a float's worth of decimals.+ "#geolocation": "48.855653506551015,2.36549253686366",+ // As the geo map template promotes it (see hidden_subtree_templates.ts).+ "#label:geolocation": "promoted,single,text"+ } ] });+ const map = fakeMap();+ await mount([ froca.notes["placeDesVosges"] ], map);++ map.setUnderPointer([ markerFeature(froca.notes["placeDesVosges"], [ 2.365, 48.855 ]) ]);+ await act(async () => map.click());+ await settle();++ // Rounded to a stride, which is as finely as anywhere is pointed out on a map.+ const location = pane()?.querySelector<HTMLButtonElement>(".geo-detail-pane-location");+ expect(location?.textContent).toBe("48.855654, 2.365493");+ expect(pane()?.querySelector(".promoted-attribute-cell")).toBeNull();++ // Carried at every digit the note holds, so what is pasted elsewhere is the place itself.+ await act(async () => { location?.click(); });+ expect(copied).toHaveBeenCalledWith("48.855653506551015, 2.365492536863660");++ // Named by the app's own tooltip, as the buttons beneath it are, rather than by the one the+ // browser draws from a `title` — which is what carrying no such attribute leaves.+ expect(location?.getAttribute("title")).toBeNull();+ });+/*** A marker is very often a note whose fields say more about the place than its content does — the* grid of them is the quick editor's, standing where the quick editor puts it.diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.tsxindex a69d5e6a5b..31bb377d16 100644--- a/apps/client/src/widgets/collections/geomap/DetailPane.tsx+++ b/apps/client/src/widgets/collections/geomap/DetailPane.tsx@@ -2,24 +2,25 @@ import "./DetailPane.css";import clsx from "clsx";import type { Map as MapLibreGLMap, MapMouseEvent } from "maplibre-gl";-import { useCallback, useContext, useEffect, useRef, useState } from "preact/hooks";+import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "preact/hooks";import appContext from "../../../components/app_context";import Component from "../../../components/component";import NoteContext, { openInCurrentNoteContext } from "../../../components/note_context";import FNote from "../../../entities/fnote";+import { copyTextWithToast } from "../../../services/clipboard_ext";import { t } from "../../../services/i18n";import link from "../../../services/link";import TitleRow from "../../layout/TitleRow";import NoteDetail from "../../NoteDetail";-import ActionButton from "../../react/ActionButton";-import { useLegacyComponentElement, useNoteColorClass, useNoteLabel } from "../../react/hooks";import PromotedAttributes from "../../PromotedAttributes";+import ActionButton from "../../react/ActionButton";+import { useLegacyComponentElement, useNoteColorClass, useNoteLabel, useStaticTooltip } from "../../react/hooks";import OverlayPanel, { OverlayPanelBody } from "../../react/OverlayPanel";import { NoteContextContext, ParentComponent } from "../../react/react_utils";import { moveMarker } from "./api";import { ParentMap } from "./map";-import { LOCATION_ATTRIBUTE, MARKER_LAYER, parseLocation } from "./Markers";+import { formatLocation, LOCATION_ATTRIBUTE, MARKER_LAYER, parseLocation } from "./Markers";/*** The pane standing against the trailing edge of the map for as long as a marker is selected.@@ -189,12 +190,18 @@ function MarkerDetails({ note, isReadOnly, onClose, onRelocate }: { note: FNote;close={{ text: t("geo-map.close-details"), onClick: onClose }}><OverlayPanelBody className="geo-detail-pane-body">+ <MarkerLocation note={note} />+<MarkerActions note={note} isReadOnly={isReadOnly} onRelocate={onRelocate} />{/* Whatever fields the note's own definitions ask for, ahead of the note as the quickeditor puts them — a marker is often a note whose type says less about it than- its fields do. Nothing at all is shown for a note that promotes none. */}- <PromotedAttributes />+ its fields do. Nothing at all is shown for a note that promotes none.++ The location is not among them, the line above naming it better: promoted, it is+ a box of raw digits standing beside a map of the very place it names, and the way+ to put a marker somewhere else here is to move it. */}+ <PromotedAttributes omit={[ LOCATION_ATTRIBUTE ]} />{/* The note itself, drawn by whichever widget its type calls for — the same one thequick editor mounts, so a marker is written in exactly as it is anywhere else.@@ -340,3 +347,55 @@ function MarkerActions({ note, isReadOnly, onRelocate }: { note: FNote; isReadOn</div>);}++/**+ * Where the marker stands, written out under the note's name.+ *+ * The map says it too, but only as exactly as the eye can read a map, and it is the written pair+ * that gets carried into a message or a search box. Pressing it copies — every digit the note holds+ * rather than the six shown, so what lands in the clipboard is the place and not the rounding, which+ * is the bargain the map's own menu strikes for the point under the pointer.+ */+function MarkerLocation({ note }: { note: FNote }) {+ const [ location ] = useNoteLabel(note, LOCATION_ATTRIBUTE);+ const coordinates = parseLocation(location);++ // The label is read in an effect, so a marker just opened has nothing to say yet.+ if (!coordinates) {+ return null;+ }++ return <LocationButton coordinates={coordinates} />;+}++/**+ * A component of its own so that the tooltip is built when the button appears rather than when the+ * 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] }) {+ const buttonRef = useRef<HTMLButtonElement>(null);++ // The app's own tooltip rather than the browser's, as the buttons under it wear (see+ // ActionButton). Held still between renders because the hook builds the tooltip afresh whenever+ // it is handed different options, and an object literal is different every time.+ useStaticTooltip(buttonRef, useMemo(() => ({+ title: t("geo-map.copy-coordinates"),+ placement: "bottom" as const,+ animation: false+ }), []));++ return (+ <button+ ref={buttonRef}+ className="geo-detail-pane-location"+ onClick={() => copyTextWithToast(formatLocation(coordinates, FULL_PRECISION))}+ >+ <span className="bx bx-current-location" />+ {formatLocation(coordinates)}+ </button>+ );+}++/** Enough decimals to give back whatever was stored, the map writing a float's worth of them. */+const FULL_PRECISION = 15;diff --git a/apps/client/src/widgets/collections/geomap/Markers.spec.tsx b/apps/client/src/widgets/collections/geomap/Markers.spec.tsxindex 9372bffcae..0ea128c71e 100644--- a/apps/client/src/widgets/collections/geomap/Markers.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/Markers.spec.tsx@@ -23,7 +23,7 @@ import { buildNote } from "../../../test/easy-froca";import { ParentComponent } from "../../react/react_utils";import { CLUSTER_COUNT_LAYER, CLUSTER_LAYER } from "./clusters";import { ParentMap } from "./map";-import Markers, { MARKER_LAYER, MARKER_SOURCE } from "./Markers";+import Markers, { formatLocation, MARKER_LAYER, MARKER_SOURCE, parseLocation } from "./Markers";vi.mock("../../../services/icon_glyphs", () => ({renderIconImage: vi.fn(async () => "data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=")@@ -546,3 +546,26 @@ describe("Markers", () => {});});});++/**+ * The label writes latitude first, as coordinates are written; GeoJSON wants the other order. The+ * two functions are the crossing point, so the order is pinned here rather than trusted at each of+ * the half-dozen places that use them.+ */+describe("reading and writing a place", () => {+ it("keeps latitude first on the way out, whichever way round it is held", () => {+ const coordinates = parseLocation("48.855654, 2.365493");++ // Stored latitude first, carried longitude first.+ expect(coordinates).toEqual([ 2.365493, 48.855654 ]);+ expect(coordinates && formatLocation(coordinates)).toBe("48.855654, 2.365493");+ });++ it("rounds to a stride by default and gives back every digit when asked", () => {+ // What the map writes when a marker is placed, which is a float's worth of decimals.+ const coordinates = parseLocation("48.855653506551015,2.36549253686366");++ expect(coordinates && formatLocation(coordinates)).toBe("48.855654, 2.365493");+ expect(coordinates && formatLocation(coordinates, 15)).toBe("48.855653506551015, 2.365492536863660");+ });+});diff --git a/apps/client/src/widgets/collections/geomap/Markers.tsx b/apps/client/src/widgets/collections/geomap/Markers.tsxindex 0ad9688904..81dcae93ca 100644--- a/apps/client/src/widgets/collections/geomap/Markers.tsx+++ b/apps/client/src/widgets/collections/geomap/Markers.tsx@@ -414,6 +414,18 @@ export function parseLocation(location: string | null | undefined): [number, numreturn [ lng, lat ];}+/**+ * A place as it is written and as the label stores it — latitude first — from the `[lng, lat]`+ * {@link parseLocation} yields and MapLibre reports.+ *+ * Six decimals name a spot to within a stride, which is as fine as anything is pointed out on a map.+ * The full stored value is worth having when it is being carried somewhere else, so what is copied+ * asks for every digit rather than what was read.+ */+export function formatLocation([ lng, lat ]: [number, number], precision = 6) {+ return `${lat.toFixed(precision)}, ${lng.toFixed(precision)}`;+}+function markerImageId(color: string, iconClass: string) {return `marker|${color}|${iconClass}`;}