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): open the detail pane on a clicked shape
Elian Doranf715d75a03f6
diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsxindex e42e74442d..50dcf22891 100644--- a/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx@@ -93,6 +93,8 @@ function fakeMap({ width = MAP_WIDTH, features = [] as unknown[] } = {}) {const fitted: unknown[] = [];const sources = new Map<string, unknown>();let under: unknown[] = features;+ let underShapes: { properties: { id: string } }[] = [];+ let shapeLayers: string[] = [];return {/** Every camera move the pane has asked for, which is how it holds a marker clear of itself. */@@ -108,6 +110,15 @@ function fakeMap({ width = MAP_WIDTH, features = [] as unknown[] } = {}) {},/** What the next click will land on: a marker's feature, or nothing at all. */setUnderPointer(hit: unknown[]) { under = hit; },+ /**+ * What the next click lands on among the drawn shapes, which the pane queries separately.+ * Putting a shape under the pointer also adds its hit layer to the style, which is how+ * `shapeHitLayers()` finds the shapes to query.+ */+ setShapesUnderPointer(hit: { properties: { id: string } }[]) {+ underShapes = hit;+ shapeLayers = hit.map((feature) => `shape-hit-${feature.properties.id}`);+ },/** A click on the map, wherever `setUnderPointer` says it landed. */click() {for (const fn of listeners.get("click") ?? []) fn({ point: { x: 0, y: 0 } });@@ -121,14 +132,21 @@ function fakeMap({ width = MAP_WIDTH, features = [] as unknown[] } = {}) {off(event: string, fnOrLayer: unknown, fn?: () => void) {listeners.get(fn ? `${event}:${fnOrLayer}` : event)?.delete((fn ?? fnOrLayer) as Listener);},+ /**+ * What was hit, in the map's drawing order rather than the order of `layers`, which is how+ * MapLibre answers and the reason the pane queries twice. The shapes go on last and so draw+ * above the markers, meaning a query naming both returns the shape first.+ */queryRenderedFeatures(_point: unknown, { layers }: { layers: string[] }) {- return layers.includes(MARKER_LAYER) ? under : [];+ const shapes = shapeLayers.some((id) => layers.includes(id)) ? underShapes : [];+ return [ ...shapes, ...(layers.includes(MARKER_LAYER) ? under : []) ];},easeTo(options: unknown) { eased.push(options); },fitBounds(bounds: unknown, options: unknown) { fitted.push({ bounds, options }); },getContainer: () => ({ clientWidth: width, clientHeight: 800 }),- // Asked for by `trackHitLayers`, which reads the current GPX hit layers off the style.- getLayersOrder: () => [] as string[]+ // Read by `trackHitLayers()` and `shapeHitLayers()` to find the layers the tracks and the+ // shapes currently have in the style.+ getLayersOrder: () => shapeLayers};}@@ -143,6 +161,18 @@ function trackFeature(note: FNote, track?: number) {return { geometry: { type: "MultiLineString", coordinates: [] }, properties: { id: note.noteId, ...(track !== undefined ? { track } : {}) } };}+/**+ * A drawn shape's boundary or fill, as MapLibre reports one that was hit (see ShapeLayer). The+ * geometry is empty because nothing reads it: a shape's extent comes off its own label, not off the+ * feature, which is clipped to the tile it was hit in.+ */+function shapeFeature(note: FNote) {+ return { geometry: { type: "Polygon", coordinates: [] }, properties: { id: note.noteId } };+}++/** A triangular lot, in the label format a shape note carries (see shapes.ts). */+const LOT_SHAPE = "polygon:45.79,24.13 45.81,24.16 45.89,24.08";+describe("DetailPane", () => {let container: HTMLElement | undefined;@@ -273,6 +303,75 @@ describe("DetailPane", () => {expect(pane()?.querySelector(".geo-detail-pane-location")).toBeNull();});+ /**+ * A drawn shape opens the pane as a marker does, which is the point of a shape being a note.+ * Its extent comes off its own label rather than off the map: the label holds every point at+ * once, so there is no source to wait for as a track's file needs.+ */+ it("stands for a drawn shape that was clicked, and frames it as it frames a track", async () => {+ // Hung under the root so there is a path to point the note context at.+ buildNote({ id: "root", title: "root", children: [ { id: "thelot", title: "The lot", "#geoShape": LOT_SHAPE } ] });+ const note = froca.notes["thelot"];+ const map = fakeMap();+ await mount([ note ], map);++ map.setShapesUnderPointer([ shapeFeature(note) ]);+ await act(async () => map.click());+ await settle();++ expect(pane()?.querySelector<HTMLInputElement>(".title-row input")?.value).toBe("The lot");+ // Fitted rather than centred, and never eased: a shape is an extent, not a point.+ expect(map.eased).toEqual([]);+ expect(map.fitted).toEqual([ {+ bounds: [ [ 24.08, 45.79 ], [ 24.16, 45.89 ] ],+ options: { padding: { top: 60, bottom: 60, left: 60, right: 460 }, maxZoom: 16 }+ } ]);+ // No location line, a shape carrying geometry rather than a point.+ expect(pane()?.querySelector(".geo-detail-pane-location")).toBeNull();+ });++ /**+ * An area's fill covers its whole inside and draws above the markers, so one combined query,+ * answered in drawing order, would return the polygon for every click inside it. The shapes are+ * therefore queried only where the markers and tracks were missed.+ */+ it("gives a marker standing inside a shape the click, not the shape", async () => {+ buildNote({ id: "root", title: "root", children: [+ { id: "thewell", title: "The well", "#geolocation": "45.85,24.11" },+ { id: "surroundinglot", title: "The lot", "#geoShape": LOT_SHAPE }+ ] });+ const marker = froca.notes["thewell"];+ const lot = froca.notes["surroundinglot"];+ const map = fakeMap();+ await mount([ marker, lot ], map);++ map.setUnderPointer([ markerFeature(marker) ]);+ map.setShapesUnderPointer([ shapeFeature(lot) ]);+ await act(async () => map.click());+ await settle();++ expect(pane()?.querySelector<HTMLInputElement>(".title-row input")?.value).toBe("The well");+ });++ /**+ * Taking a shape off the map only clears its geometry, which leaves a note the map cannot draw.+ * The pane closes with it, as it does for a cleared location.+ */+ it("goes away when its shape is taken off the map", async () => {+ const note = buildNote({ title: "The lot", "#geoShape": LOT_SHAPE });+ const map = fakeMap();+ await mount([ note ], map);++ map.setShapesUnderPointer([ shapeFeature(note) ]);+ await act(async () => map.click());+ expect(pane()).toBeTruthy();++ const shapeless = vi.spyOn(note, "getLabelValue").mockReturnValue(null);+ await mount([ note ], map);+ expect(pane()).toBeNull();+ shapeless.mockRestore();+ });+/*** A track is not a point but a shape, so opening one does not centre a coordinate: the camera* is solved for the track's corners — pan and zoom both — held clear of the pane on its side@@ -993,6 +1092,20 @@ describe("DetailPane", () => {expect(container?.querySelector(".tn-embedded-note-actions button.bx-log-in")).toBeTruthy();expect(moveButton()).toBeNull();});++ /** A drawn shape has no marker to move either: moving one means drawing it again. */+ it("is not offered for a drawn shape, which is where it was drawn", async () => {+ const note = buildNote({ title: "The lot", "#geoShape": LOT_SHAPE });+ const map = fakeMap();++ await mount([ note ], map);+ map.setShapesUnderPointer([ shapeFeature(note) ]);+ await act(async () => map.click());+ await settle();++ expect(pane()).toBeTruthy();+ expect(moveButton()).toBeNull();+ });});describe("taking the marker off the map", () => {@@ -1085,6 +1198,31 @@ describe("DetailPane", () => {expect.objectContaining({ mustDeleteNote: true }));});++ /**+ * A shape reaches the map through its geometry rather than a location, so that is the label+ * cleared, and the note keeps its content. Clearing the location would leave the shape drawn.+ */+ it("clears a drawn shape's geometry rather than a location it never had", async () => {+ const note = buildNote({ title: "The lot", "#geoShape": LOT_SHAPE });+ const map = fakeMap();+ const setLabel = vi.spyOn(attributes, "setLabel").mockResolvedValue(undefined);+ confirmDelete.mockResolvedValue({ confirmed: true, isDeleteNoteChecked: false });++ try {+ await mount([ note ], map);+ map.setShapesUnderPointer([ shapeFeature(note) ]);+ await act(async () => map.click());+ await settle();++ await act(async () => { removeButton()?.click(); });++ expect(setLabel).toHaveBeenCalledWith(note.noteId, "geoShape", "");+ expect(setLabel).not.toHaveBeenCalledWith(note.noteId, "geolocation", "");+ } finally {+ setLabel.mockRestore();+ }+ });});it("keeps clicks and key presses from reaching the map underneath", async () => {diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.tsxindex 6af7c7ee1a..ac74c6be4b 100644--- a/apps/client/src/widgets/collections/geomap/DetailPane.tsx+++ b/apps/client/src/widgets/collections/geomap/DetailPane.tsx@@ -19,6 +19,8 @@ import { removeFromMap } from "./api";import { GPX_MIME, trackHitLayers, trackSourceId } from "./GpxTrack";import { ParentMap } from "./map";import { formatLocation, LOCATION_ATTRIBUTE, MARKER_LAYER, parseLocation } from "./Markers";+import { shapeHitLayers } from "./ShapeLayer";+import { boundsOfPoints, type GeoBounds, geoShapeBounds, parseGeoShape, SHAPE_ATTRIBUTE } from "./shapes";/*** Which marker the pane stands for, and why it came to be selected.@@ -72,6 +74,10 @@ export default function DetailPane({ notes, parentNote, placing, isReadOnly, selconst map = useContext(ParentMap);const note = notes.find((note) => note.noteId === selection?.noteId);const [ location ] = useNoteLabel(note, LOCATION_ATTRIBUTE);+ // Read as a label rather than from the click, so the camera effect below follows an edit to the+ // geometry the way it follows a marker that moves.+ const [ shapeValue ] = useNoteLabel(note, SHAPE_ATTRIBUTE);+ const shape = shapeValue ? parseGeoShape(shapeValue) : null;const { noteContext, component: paneComponent } = useEmbeddedNoteContext(note, PANE_NTX_ID);/**@@ -106,30 +112,35 @@ export default function DetailPane({ notes, parentNote, placing, isReadOnly, sel*/const followLink = useCallback((noteId: string) => {const target = notes.find((n) => n.noteId === noteId);- if (!target || !parseLocation(target.getLabelValue(LOCATION_ATTRIBUTE))) return false;+ if (!target || !standsOnMap(target)) return false;onSelect({ noteId });return true;}, [ notes, onSelect ]);- // A note no longer on the map takes the pane with it. Its location may merely have been cleared- // — which is all "remove from map" does — so the note being gone is not the only case. A GPX- // track is on the map by being one: its place is its line, not a location label.+ // The pane closes once its note is no longer on the map. "Remove from map" only clears the+ // label that put it there, so a note that is gone is not the only case. See standsOnMap().useEffect(() => {- if (selection && (!note || (note.mime !== GPX_MIME && !parseLocation(location)))) {+ if (selection && !(note && standsOnMap(note))) {void closePane();}- }, [ selection, note, location, closePane ]);+ }, [ selection, note, location, shapeValue, closePane ]);- // A marker or a GPX track selects, anywhere else clears. Read off the rendered layers rather- // than bound to them (`map.on("click", MARKER_LAYER, ...)`) so one handler answers all, with no- // ordering to rely on. The markers come ahead of the tracks for the reason the context menu- // puts them there: a pin standing on its own line is the smaller target, and the one aimed at.+ // A marker, a GPX track or a drawn shape selects, anywhere else clears. Read off the rendered+ // layers rather than bound to them (`map.on("click", MARKER_LAYER, ...)`) so one handler answers+ // all.+ //+ // The shapes are queried separately, and only where the markers and tracks were missed:+ // queryRenderedFeatures() answers in the map's drawing order rather than in the order of the+ // `layers` argument, and an area's fill covers its whole inside and is drawn above the markers.+ // One combined query would therefore return the polygon for every click inside it.useEffect(() => {if (!map || placing) return;const onClick = (e: MapMouseEvent) => {- const feature = map.queryRenderedFeatures(e.point, { layers: [ MARKER_LAYER, ...trackHitLayers(map) ] })[0];+ const shapeLayers = shapeHitLayers(map);+ const feature = map.queryRenderedFeatures(e.point, { layers: [ MARKER_LAYER, ...trackHitLayers(map) ] })[0]+ ?? (shapeLayers.length > 0 ? map.queryRenderedFeatures(e.point, { layers: shapeLayers })[0] : undefined);if (!feature) {void closePane();return;@@ -147,12 +158,22 @@ export default function DetailPane({ notes, parentNote, placing, isReadOnly, sel// created — is held clear of the pane the same way as one that was clicked; and off the// location too, so a marker that has just been put somewhere else is followed there.//- // A GPX track is not a point but a shape, so it is fitted rather than centred: panned and- // zoomed until it stands in the part of the map the pane leaves uncovered — the whole file,- // or only what the click named where it named more (see PaneFocus).+ // A GPX track and a drawn shape are not points but extents, so they are fitted rather than+ // centred: panned and zoomed until they stand in the part of the map the pane leaves uncovered+ // — the whole file, or only what the click named where it named more (see PaneFocus).useEffect(() => {if (!map || !note) return;+ // A shape is measured off its own label, which holds every point the map draws from and+ // holds them at once, so there is no source to wait for as a track's file needs.+ if (shape) {+ const bounds = geoShapeBounds(shape);+ if (bounds) {+ map.fitBounds(bounds, { padding: fitPadding(map), maxZoom: FIT_MAX_ZOOM });+ }+ return;+ }+if (note.mime === GPX_MIME) {const focus = selection?.focus;@@ -175,7 +196,7 @@ export default function DetailPane({ notes, parentNote, placing, isReadOnly, selif (done || !bounds) return;done = true;map.off("sourcedata", onSourceData);- map.fitBounds(bounds, { padding: trackFitPadding(map), maxZoom: TRACK_FIT_MAX_ZOOM });+ map.fitBounds(bounds, { padding: fitPadding(map), maxZoom: FIT_MAX_ZOOM });};// A track selected the moment it was brought onto the map has no line yet: its content@@ -201,7 +222,7 @@ export default function DetailPane({ notes, parentNote, placing, isReadOnly, selmap.easeTo({ center: coordinates, offset: paneOffset(map) });// The focus is depended on by identity, which a click renews even on the same note: every// click is a fresh ask, and re-clicking what is already open brings it back into view.- }, [ map, note?.noteId, location, selection?.focus ]);+ }, [ map, note?.noteId, location, shapeValue, selection?.focus ]);// Bound only while something is selected, so the map's other Escape — giving up on placing a// marker (see index.tsx) — stands alone when nothing is.@@ -265,12 +286,25 @@ function paneOffset(map: MapLibreGLMap): [number, number] {return [ glob.isRtl ? shift : -shift, 0 ];}-/** Air kept around a fitted track, so its ends stand clear of the pane and the map's own edges. */-const TRACK_FIT_AIR = 60;+/** Air kept around a fitted extent, so its edges stand clear of the pane and the map's own edges. */+const FIT_AIR = 60;-/** How close fitting a track may zoom: a stroll around the block is still shown as a map of the+/** How close fitting an extent may zoom: a stroll around the block is still shown as a map of the* neighbourhood, not of somebody's garden. */-const TRACK_FIT_MAX_ZOOM = 16;+const FIT_MAX_ZOOM = 16;++/**+ * Whether the note is on this map, which is what keeps the pane open.+ *+ * Three kinds of note reach the map three ways: a marker through `LOCATION_ATTRIBUTE`, a drawn+ * shape through `SHAPE_ATTRIBUTE` (see shapes.ts), and a GPX track through its mime, its line+ * coming from the note's own file rather than from anything written on it.+ */+function standsOnMap(note: FNote) {+ return note.mime === GPX_MIME+ || !!parseLocation(note.getLabelValue(LOCATION_ATTRIBUTE))+ || !!parseGeoShape(note.getLabelValue(SHAPE_ATTRIBUTE) ?? "");+}/*** What of its note a clicked feature names, beyond the note itself: its own place, for a point (a@@ -298,64 +332,41 @@ function featureFocus(feature: MapGeoJSONFeature): PaneFocus | undefined {* its flags stand on its line, and another journey's ground — or a waypoint hung off in a third* place — is exactly what focusing one track is meant to leave out of frame.*- * Longitude is read in two frames at once, because it is a circle wearing a seam: a track across- * the antimeridian holds points either side of ±180° that are a stroll apart on the ground, and- * their raw minimum and maximum span nearly the whole world. The same longitudes are therefore- * also read with the seam moved to 0° — each western value pushed a turn east — and whichever- * frame drew the narrower box is the one answered. A crossing of one seam is whole in the other- * frame; only a track truly girdling half the earth stays wide in both, and then wide is the- * truth. The shifted answer may name longitudes past 180°, which `fitBounds` takes in stride.+ * {@link boundsOfPoints} measures the corners, as it does for a drawn shape, so a track crossing+ * the antimeridian frames the crossing rather than the world.*/-async function trackBounds(map: MapLibreGLMap, noteId: string, track?: number): Promise<[[number, number], [number, number]] | null> {+async function trackBounds(map: MapLibreGLMap, noteId: string, track?: number): Promise<GeoBounds | null> {const data = await map.getSource<GeoJSONSource>(trackSourceId(noteId))?.getData();if (!data || data.type !== "FeatureCollection") return null;- let west = Infinity, south = Infinity, east = -Infinity, north = -Infinity;- let westShifted = Infinity, eastShifted = -Infinity;- const extend = ([ lng, lat ]: number[]) => {- west = Math.min(west, lng);- south = Math.min(south, lat);- east = Math.max(east, lng);- north = Math.max(north, lat);-- const shifted = lng < 0 ? lng + 360 : lng;- westShifted = Math.min(westShifted, shifted);- eastShifted = Math.max(eastShifted, shifted);- };-+ const points: number[][] = [];for (const { geometry, properties } of data.features) {if (track !== undefined && properties?.track !== track) continue;if (geometry.type === "Point") {- extend(geometry.coordinates);+ points.push(geometry.coordinates);} else if (geometry.type === "MultiLineString") {for (const line of geometry.coordinates) {- for (const point of line) {- extend(point);- }+ points.push(...line);}}}- if (!Number.isFinite(west)) return null;-- return eastShifted - westShifted < east - west- ? [ [ westShifted, south ], [ eastShifted, north ] ]- : [ [ west, south ], [ east, north ] ];+ return boundsOfPoints(points);}/**- * What a fitted track has to keep clear of: the pane on its side of the map, and a rim of air all- * round, so the line reads as standing in the viewport rather than pinned to its corners.+ * What a fitted track or shape has to keep clear of: the pane on its side of the map, and a rim of+ * air all round, so the line reads as standing in the viewport rather than pinned to its corners.** The air gives way on a map too small to spare it, and the pane's reach is only counted where* there is room left over — the same bargain {@link paneOffset} strikes — since padding wider than* the map does not clip the fit but forfeits it: MapLibre cannot solve the camera and leaves it* where it stands.*/-function trackFitPadding(map: MapLibreGLMap) {+function fitPadding(map: MapLibreGLMap) {const { clientWidth, clientHeight } = map.getContainer();- const air = Math.max(0, Math.min(TRACK_FIT_AIR, Math.floor(Math.min(clientWidth, clientHeight) / 4)));+ const air = Math.max(0, Math.min(FIT_AIR, Math.floor(Math.min(clientWidth, clientHeight) / 4)));const padding = { top: air, bottom: air, left: air, right: air };if (clientWidth > PANE_REACH + 2 * air) {@@ -412,10 +423,10 @@ function MarkerDetails({ note, parentNote, isReadOnly, onClose, onRelocate, onFoeditor puts them — a marker is often a note whose type says less about it thanits 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 ]} />+ Neither the location nor the geometry is among them: promoted, each is a field of+ raw digits beside a map that already draws it, and a marker is moved rather than+ retyped. */}+ <PromotedAttributes omit={[ LOCATION_ATTRIBUTE, SHAPE_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.@@ -436,7 +447,9 @@ const PANE_NTX_ID = "_geo-detail-pane";*/function MarkerActions({ note, parentNote, isReadOnly, onRelocate }: { note: FNote; parentNote: FNote; isReadOnly: boolean; onRelocate(): void }) {const [ location ] = useNoteLabel(note, LOCATION_ATTRIBUTE);+ const [ shapeValue ] = useNoteLabel(note, SHAPE_ATTRIBUTE);const latLng = parseLocation(location);+ const isShape = !!parseGeoShape(shapeValue ?? "");return (<EmbeddedNoteActions>@@ -457,10 +470,10 @@ function MarkerActions({ note, parentNote, isReadOnly, onRelocate }: { note: FNoshows (see NoteColorPicker). */}<NoteColorAction note={note} title={t("geo-map.marker-color")} />- {/* A track is offered nothing here: it is on the map by being drawn across it, and- its place is the line its file holds rather than a location that could be- written somewhere else. The right-click menu leaves it out for the same reason. */}- {note.mime !== GPX_MIME && <ActionButton+ {/* Not offered for a track or a drawn shape: neither has a location label to+ rewrite, and moving one means drawing it again. The right-click menu leaves it+ out for a track for the same reason. */}+ {note.mime !== GPX_MIME && !isShape && <ActionButtonclassName="geo-detail-pane-move"icon="bx bx-move"text={t("geo-map-context.move-marker")}diff --git a/apps/client/src/widgets/collections/geomap/ShapeLayer.spec.tsx b/apps/client/src/widgets/collections/geomap/ShapeLayer.spec.tsxindex aae17db515..7d7b9ab0d6 100644--- a/apps/client/src/widgets/collections/geomap/ShapeLayer.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/ShapeLayer.spec.tsx@@ -8,7 +8,7 @@ import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it } from "vitest";import type { GeoShape } from "./shapes";-import { ShapeLayer, shapeSourceId } from "./ShapeLayer";+import { shapeHitLayers, ShapeLayer, shapeSourceId } from "./ShapeLayer";import { MapStyleLoaded, ParentMap } from "./map";/**@@ -51,6 +51,10 @@ function fakeMap() {removeLayer(id: string) {layers.delete(id);},+ /** The style's layers in the order they were added, which is how the hit layers are found. */+ getLayersOrder() {+ return [ ...layers.keys() ];+ },/** The style finishing, which is what `style.load` announces. */loadStyle() {@@ -157,6 +161,31 @@ describe("ShapeLayer", () => {expect(map.layers.has(`shape-stroke-${NOTE_ID}`)).toBe(true);});+ /**+ * The boundary is drawn 3px wide, too thin to click reliably, so a transparent line far wider+ * than that takes the pointer hits, as a GPX track's does. An area is clickable across its+ * inside as well as along its edge.+ */+ it("stands a widened transparent line in for the boundary, an area offering its wash as well", () => {+ map.loadStyle();+ renderShape(LINE);++ const hit = map.layers.get(`shape-hit-${NOTE_ID}`) as { paint: Record<string, unknown> };+ // Drawn at zero opacity rather than hidden: MapLibre drops a layer from a query for+ // `visibility: none` but not for being invisible.+ expect(hit.paint["line-opacity"]).toBe(0);+ expect(hit.paint["line-width"]).toBe(20);+ expect(shapeHitLayers(map as never)).toEqual([ `shape-hit-${NOTE_ID}` ]);++ act(() => render(null, container));+ // The hit line goes with the rest: a query naming a layer the style has lost returns+ // nothing at all, for every shape.+ expect(map.layers.size).toBe(0);++ renderShape(POLYGON);+ expect(shapeHitLayers(map as never)).toEqual([ `shape-fill-${NOTE_ID}`, `shape-hit-${NOTE_ID}` ]);+ });+it("waits for the style, and is put back when a style switch wipes the map", () => {// Mounted before the style has loaded — as a shape whose note arrives early always is —// nothing can go on yet.diff --git a/apps/client/src/widgets/collections/geomap/ShapeLayer.tsx b/apps/client/src/widgets/collections/geomap/ShapeLayer.tsxindex 20a8810248..e2ccc3020c 100644--- a/apps/client/src/widgets/collections/geomap/ShapeLayer.tsx+++ b/apps/client/src/widgets/collections/geomap/ShapeLayer.tsx@@ -1,8 +1,20 @@+import type { Map as MapLibreGLMap } from "maplibre-gl";import { useContext, useEffect } from "preact/hooks";import { MapStyleLoaded, ParentMap } from "./map";import { circleRing, closeRing, type GeoShape, serializeGeoShape } from "./shapes";+/**+ * The prefixes a shape's layer ids start with. Every shape adds layers of its own, so+ * {@link shapeHitLayers} matches these against the style's layer order instead of naming layers.+ */+const STROKE_LAYER_PREFIX = "shape-stroke-";+const FILL_LAYER_PREFIX = "shape-fill-";+const HIT_LAYER_PREFIX = "shape-hit-";++/** Width in pixels of the transparent line that takes pointer hits on a shape's boundary. */+const HIT_WIDTH = 20;+interface ShapeLayerProps {/** The note the shape belongs to, which is what its source and layers are named after. */noteId: string;@@ -18,9 +30,9 @@ interface ShapeLayerProps {* The GPX track's little sibling: the same source-and-layers arrangement, the same put-it-back-on-* every-style-load dance, without the file, the flags or the name written along it. A line is its* stroke alone; an area wears a wash of its colour under the same stroke, which is its boundary- * drawn the way the line is. What a track has that this does not yet: the label layer, the widened- * hit line the context menu needs, and the marks. Each is a straight lift from {@link GpxTrack}- * when its turn comes.+ * drawn the way the line is. A transparent wide line over the boundary takes the pointer hits that+ * select the shape (see {@link shapeHitLayers}). What a track has that this does not yet: the label+ * layer and the marks. Each is a straight lift from {@link GpxTrack} when its turn comes.*/export function ShapeLayer({ noteId, shape, color }: ShapeLayerProps) {const parentMap = useContext(ParentMap);@@ -36,8 +48,9 @@ export function ShapeLayer({ noteId, shape, color }: ShapeLayerProps) {const map = parentMap;const sourceId = shapeSourceId(noteId);- const strokeLayerId = `shape-stroke-${noteId}`;- const fillLayerId = `shape-fill-${noteId}`;+ const strokeLayerId = `${STROKE_LAYER_PREFIX}${noteId}`;+ const fillLayerId = `${FILL_LAYER_PREFIX}${noteId}`;+ const hitLayerId = `${HIT_LAYER_PREFIX}${noteId}`;const hasArea = shape.type !== "line";// The shape lives in the map style, which setStyle() wipes for a URL-named vector style@@ -96,6 +109,22 @@ export function ShapeLayer({ noteId, shape, color }: ShapeLayerProps) {}});}++ // Takes the pointer hits on the boundary, the 3px stroke being too thin to click+ // reliably. Drawn at zero opacity rather than hidden: MapLibre drops a layer from+ // queryRenderedFeatures() for `visibility: none` but not for being invisible.+ if (!map.getLayer(hitLayerId)) {+ map.addLayer({+ id: hitLayerId,+ type: "line",+ source: sourceId,+ paint: {+ "line-color": color,+ "line-opacity": 0,+ "line-width": HIT_WIDTH+ }+ });+ }} catch (e) {// Only worth a word if the style was ready and it still would not take the shape.if (styleLoaded) {@@ -113,7 +142,7 @@ export function ShapeLayer({ noteId, shape, color }: ShapeLayerProps) {map.off("style.load", addShapeLayers);try {// Every layer before the source they draw from: one still in use cannot be removed.- for (const layer of [ strokeLayerId, fillLayerId ]) {+ for (const layer of [ hitLayerId, strokeLayerId, fillLayerId ]) {if (map.getLayer(layer)) {map.removeLayer(layer);}@@ -137,3 +166,15 @@ export function ShapeLayer({ noteId, shape, color }: ShapeLayerProps) {export function shapeSourceId(noteId: string) {return `shape-source-${noteId}`;}++/**+ * The layers that take pointer hits for the shapes on the map: each shape's widened boundary, plus+ * the fill of an area so that a click inside a polygon selects it. Each feature carries its note id.+ *+ * Read off the style on every call rather than cached, as `trackHitLayers()` is: a shape's layers+ * come and go with its note, and `queryRenderedFeatures()` returns nothing at all if a single named+ * layer is missing.+ */+export function shapeHitLayers(map: MapLibreGLMap) {+ return map.getLayersOrder().filter((id) => id.startsWith(HIT_LAYER_PREFIX) || id.startsWith(FILL_LAYER_PREFIX));+}diff --git a/apps/client/src/widgets/collections/geomap/api.ts b/apps/client/src/widgets/collections/geomap/api.tsindex 37058fe4fb..9f179b21ce 100644--- a/apps/client/src/widgets/collections/geomap/api.ts+++ b/apps/client/src/widgets/collections/geomap/api.ts@@ -59,6 +59,10 @@ export async function removeFromMap(note: FNote, mapNote: FNote) {if (result.isDeleteNoteChecked) {await deleteNoteOrBranch(note.noteId, branchId);+ } else if (note.hasLabel(SHAPE_ATTRIBUTE)) {+ // A shape is on the map through its geometry rather than a location, so clearing+ // SHAPE_ATTRIBUTE is what takes it off. The note and its content stay.+ await attributes.setLabel(note.noteId, SHAPE_ATTRIBUTE, "");} else {await moveMarker(note.noteId, null);}diff --git a/apps/client/src/widgets/collections/geomap/shapes.spec.ts b/apps/client/src/widgets/collections/geomap/shapes.spec.tsindex 4de593f785..f638b22c70 100644--- a/apps/client/src/widgets/collections/geomap/shapes.spec.ts+++ b/apps/client/src/widgets/collections/geomap/shapes.spec.ts@@ -1,6 +1,9 @@import { describe, expect, it } from "vitest";-import { circleRing, closeRing, type GeoShape, parseGeoShape, polygonFromRing, ringCenter, serializeGeoShape } from "./shapes";+import {+ boundsOfPoints, circleRing, closeRing, type GeoShape, geoShapeBounds, parseGeoShape,+ polygonFromRing, ringCenter, serializeGeoShape+} from "./shapes";describe("serializeGeoShape", () => {it("writes lat,lng pairs behind the kind's prefix, rounded but not padded", () => {@@ -123,6 +126,47 @@ describe("rings", () => {});});+describe("bounds", () => {+ it("boxes a line and a polygon by their own points, and answers nothing for none", () => {+ expect(geoShapeBounds({+ type: "line",+ coordinates: [ [ 24.13, 45.79 ], [ 24.16, 45.96 ], [ 24.08, 45.89 ] ]+ })).toEqual([ [ 24.08, 45.79 ], [ 24.16, 45.96 ] ]);++ expect(boundsOfPoints([])).toBeNull();+ });++ /** A circle is stored as a centre and a radius, so the box has to cover the radius. */+ it("boxes a circle across the ring its radius walks out", () => {+ const circle: GeoShape = { type: "circle", center: [ 2.29, 48.85 ], radiusMeters: 1000 };+ const bounds = geoShapeBounds(circle);+ const [ [ west, south ], [ east, north ] ] = bounds ?? [ [ NaN, NaN ], [ NaN, NaN ] ];++ // A kilometre spans about 0.018° of latitude, and more of longitude at this latitude. The+ // centre sits in the middle of both.+ expect((south + north) / 2).toBeCloseTo(48.85, 4);+ expect((west + east) / 2).toBeCloseTo(2.29, 4);+ expect(north - south).toBeCloseTo(0.018, 3);+ expect(east - west).toBeGreaterThan(north - south);+ });++ /**+ * Longitude wraps. Points either side of ±180° sit metres apart on the ground but span nearly+ * the world when measured raw, so the same longitudes are measured again with the seam at 0°+ * and the narrower box wins.+ */+ it("frames a shape crossing the antimeridian rather than the world", () => {+ expect(geoShapeBounds({+ type: "polygon",+ coordinates: [ [ 179.9, -16.5 ], [ -179.9, -16.5 ], [ -179.95, -16.6 ] ]+ })).toEqual([ [ 179.9, -16.6 ], [ 180.1, -16.5 ] ]);++ // A shape that really spans half the earth stays wide in both frames.+ expect(boundsOfPoints([ [ -120, 10 ], [ 0, 20 ], [ 120, 30 ] ]))+ .toEqual([ [ -120, 10 ], [ 120, 30 ] ]);+ });+});+/** The distance between two points the way the ring generator must honour it: over the sphere. */function haversineMeters([ lng1, lat1 ]: [number, number], [ lng2, lat2 ]: [number, number]): number {const toRad = (d: number) => (d * Math.PI) / 180;diff --git a/apps/client/src/widgets/collections/geomap/shapes.ts b/apps/client/src/widgets/collections/geomap/shapes.tsindex 38f6311766..b85ae7a26e 100644--- a/apps/client/src/widgets/collections/geomap/shapes.ts+++ b/apps/client/src/widgets/collections/geomap/shapes.ts@@ -174,6 +174,50 @@ export function ringCenter(ring: [number, number][]): [number, number] | null {return [ lngSum / ring.length, latSum / ring.length ];}+/** `[[west, south], [east, north]]`, the form `fitBounds` takes. */+export type GeoBounds = [[number, number], [number, number]];++/**+ * The corners of a shape, which `DetailPane` frames the shape it opens on by. A circle is measured+ * across {@link circleRing} rather than at its centre, so the box covers the whole radius.+ */+export function geoShapeBounds(shape: GeoShape): GeoBounds | null {+ return boundsOfPoints(shape.type === "circle"+ ? circleRing(shape.center, shape.radiusMeters)+ : shape.coordinates);+}++/**+ * The box a set of points fits in, or `null` for no points at all.+ *+ * Longitude is measured twice because it wraps. Points either side of ±180° sit metres apart on the+ * ground, but their raw minimum and maximum span nearly the world, so the same longitudes are+ * measured again with the seam at 0° — each western value moved a turn east — and the narrower of+ * the two boxes wins. Only a shape that really spans half the earth stays wide in both. The shifted+ * box can name longitudes past 180°, which `fitBounds` accepts.+ */+export function boundsOfPoints(points: Iterable<number[]>): GeoBounds | null {+ let west = Infinity, south = Infinity, east = -Infinity, north = -Infinity;+ let westShifted = Infinity, eastShifted = -Infinity;++ for (const [ lng, lat ] of points) {+ west = Math.min(west, lng);+ south = Math.min(south, lat);+ east = Math.max(east, lng);+ north = Math.max(north, lat);++ const shifted = lng < 0 ? lng + 360 : lng;+ westShifted = Math.min(westShifted, shifted);+ eastShifted = Math.max(eastShifted, shifted);+ }++ if (!Number.isFinite(west)) return null;++ return eastShifted - westShifted < east - west+ ? [ [ westShifted, south ], [ eastShifted, north ] ]+ : [ [ west, south ], [ east, north ] ];+}+function toRadians(degrees: number): number {return (degrees * Math.PI) / 180;}