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): polygon drawing tool, and one shape pipeline for every tool
Claude0933d26614b7
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 83e00f172b..d10819070a 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2853,9 +2853,12 @@"create-child-note-toast-title": "New note","add-gpx-track": "Add a GPS track from a GPX file","draw-line": "Draw a path on the map",- "draw-line-cancel": "Cancel drawing",+ "draw-polygon": "Draw an area on the map",+ "draw-cancel": "Cancel drawing","draw-line-toast-title": "Draw a path","draw-line-instruction": "Click on the map to add points. Click the last point again or press Enter to finish, or press Escape to cancel.",+ "draw-polygon-toast-title": "Draw an area",+ "draw-polygon-instruction": "Click on the map to add corners. Click the first corner again or press Enter to finish, or press Escape to cancel.","move-marker-instruction": "Click on the map to move the marker to that location or press Escape to dismiss.","move-marker-toast-title": "Move marker","unable-to-load-map": "Unable to load map.",diff --git a/apps/client/src/widgets/collections/geomap/DrawLine.tsx b/apps/client/src/widgets/collections/geomap/DrawLine.tsxdeleted file mode 100644index 1abefde448..0000000000--- a/apps/client/src/widgets/collections/geomap/DrawLine.tsx+++ /dev/null@@ -1,63 +0,0 @@-import { useContext, useEffect, useRef } from "preact/hooks";-import { TerraDraw, TerraDrawLineStringMode } from "terra-draw";-import { TerraDrawMapLibreGLAdapter } from "terra-draw-maplibre-gl-adapter";--import { MapStyleLoaded, ParentMap } from "./map";--interface DrawLineProps {- /** Handed the finished line's `[lng, lat]` vertices. Standing the session down again is the- * caller's move — the component draws for as long as it is mounted, like GhostPin haunts. */- onFinish: (coordinates: [number, number][]) => void;-}--/**- * A line-drawing session: mounted while the map is armed to draw, gone when it is not.- *- * Terra Draw is the pencil here and nothing more. It owns the map only while this is mounted —- * click by click, the growing line and its vertex handles are its own ephemeral layers — and the- * moment a line is finished, the vertices are handed to the caller to become a note and the- * session's rendering is thrown away. What the reader sees from then on is {@link LineShape},- * drawing the note's label the way every persisted thing on this map is drawn. Keeping the- * library inside these brackets is the point: nothing persisted ever depends on it.- */-export default function DrawLine({ onFinish }: DrawLineProps) {- const parentMap = useContext(ParentMap);- const styleLoaded = useContext(MapStyleLoaded);-- // Read through a ref so a new callback identity does not tear down a half-drawn line.- const onFinishRef = useRef(onFinish);- onFinishRef.current = onFinish;-- useEffect(() => {- // The adapter puts its working layers on the style, so it must wait for one to be there —- // the same wait every layer-adding child of the map keeps (see MapStyleLoaded).- if (!parentMap || !styleLoaded) return;-- const draw = new TerraDraw({- adapter: new TerraDrawMapLibreGLAdapter({ map: parentMap }),- modes: [ new TerraDrawLineStringMode() ]- });-- draw.on("finish", (id, { action }) => {- if (action !== "draw") return;-- const feature = draw.getSnapshotFeature(id);- if (feature?.geometry.type !== "LineString") return;-- onFinishRef.current(feature.geometry.coordinates as [number, number][]);- });-- draw.start();- draw.setMode("linestring");-- return () => {- try {- draw.stop();- } catch {- // The map may already have been removed, taking the session's layers with it.- }- };- }, [ parentMap, styleLoaded ]);-- return <div />;-}diff --git a/apps/client/src/widgets/collections/geomap/DrawShape.spec.tsx b/apps/client/src/widgets/collections/geomap/DrawShape.spec.tsxnew file mode 100644index 0000000000..a1368b1149--- /dev/null+++ b/apps/client/src/widgets/collections/geomap/DrawShape.spec.tsx@@ -0,0 +1,151 @@+/**+ * The drawing session (see DrawShape.tsx): that mounting it arms Terra Draw with the tool's own+ * mode and unmounting stands it down, that a finished shape reaches the caller converted to what+ * its note will carry, and that anything else Terra Draw announces is left alone.+ */+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import DrawShape, { type DrawTool, shapeFromFeature } from "./DrawShape";+import { MapStyleLoaded, ParentMap } from "./map";++vi.mock("terra-draw", () => {+ /** Terra Draw as this component uses it: events, a snapshot, and a lifecycle. */+ class TerraDraw {+ static instances: TerraDraw[] = [];+ listeners = new Map<string, (id: string, context: { action: string }) => void>();+ features = new Map<string, unknown>();+ started = false;+ stopped = false;+ modeName: string | null = null;++ constructor(public config: { modes: { mode: string }[] }) {+ TerraDraw.instances.push(this);+ }+ on(event: string, listener: (id: string, context: { action: string }) => void) {+ this.listeners.set(event, listener);+ }+ start() { this.started = true; }+ stop() { this.stopped = true; }+ setMode(name: string) { this.modeName = name; }+ getSnapshotFeature(id: string) { return this.features.get(id); }++ /** A shape being finished, as the real library would announce it. */+ finish(id: string, action: string, feature: unknown) {+ this.features.set(id, feature);+ this.listeners.get("finish")?.(id, { action });+ }+ }++ return {+ TerraDraw,+ TerraDrawLineStringMode: class { mode = "linestring"; },+ TerraDrawPolygonMode: class { mode = "polygon"; }+ };+});++vi.mock("terra-draw-maplibre-gl-adapter", () => ({+ TerraDrawMapLibreGLAdapter: class { constructor(public config: unknown) {} }+}));++import { TerraDraw } from "terra-draw";++type FakeTerraDraw = InstanceType<typeof TerraDraw> & {+ finish(id: string, action: string, feature: unknown): void;+ started: boolean;+ stopped: boolean;+ modeName: string | null;+};++function instances(): FakeTerraDraw[] {+ return (TerraDraw as unknown as { instances: FakeTerraDraw[] }).instances;+}++const LINE_FEATURE = {+ geometry: { type: "LineString", coordinates: [ [ 1, 2 ], [ 3, 4 ] ] }+};+const RING_FEATURE = {+ geometry: { type: "Polygon", coordinates: [ [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 1, 2 ] ] ] }+};++describe("DrawShape", () => {+ let container: HTMLElement;+ let onFinish: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ instances().length = 0;+ onFinish = vi.fn();+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ });++ function renderSession(tool: DrawTool, { map = {} as never, styleLoaded = true } = {}) {+ act(() => {+ render(+ <ParentMap.Provider value={map}>+ <MapStyleLoaded.Provider value={styleLoaded}>+ <DrawShape tool={tool} onFinish={onFinish} />+ </MapStyleLoaded.Provider>+ </ParentMap.Provider>,+ container+ );+ });+ }++ it("arms Terra Draw with the tool's own mode, and stands it down on unmount", () => {+ renderSession("polygon");++ const [ session ] = instances();+ expect(session.started).toBe(true);+ expect(session.modeName).toBe("polygon");++ act(() => render(null, container));+ expect(session.stopped).toBe(true);+ });++ it("waits for a style to draw on, like every layer-adding child of the map", () => {+ renderSession("line", { styleLoaded: false });+ expect(instances()).toHaveLength(0);+ });++ it("hands a finished line over as the shape its note will carry", () => {+ renderSession("line");++ act(() => instances()[0].finish("f1", "draw", LINE_FEATURE));+ expect(onFinish).toHaveBeenCalledWith({ type: "line", coordinates: [ [ 1, 2 ], [ 3, 4 ] ] });+ });++ it("hands a finished ring over with its closing repeat left behind", () => {+ renderSession("polygon");++ act(() => instances()[0].finish("f1", "draw", RING_FEATURE));+ expect(onFinish).toHaveBeenCalledWith({ type: "polygon", coordinates: [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ] });+ });++ it("leaves alone what is not a drawing being finished", () => {+ renderSession("line");++ // Another action's finish (a drag in some future select mode), and a finish whose+ // feature is not what the tool draws.+ act(() => instances()[0].finish("f1", "dragFeature", LINE_FEATURE));+ act(() => instances()[0].finish("f2", "draw", RING_FEATURE));+ expect(onFinish).not.toHaveBeenCalled();+ });+});++describe("shapeFromFeature", () => {+ it("refuses a geometry that is not what the tool draws", () => {+ expect(shapeFromFeature("line", RING_FEATURE as never)).toBeNull();+ expect(shapeFromFeature("polygon", LINE_FEATURE as never)).toBeNull();+ });++ it("survives a polygon with no ring at all", () => {+ expect(shapeFromFeature("polygon", { geometry: { type: "Polygon", coordinates: [] } } as never)).toBeNull();+ });+});diff --git a/apps/client/src/widgets/collections/geomap/DrawShape.tsx b/apps/client/src/widgets/collections/geomap/DrawShape.tsxnew file mode 100644index 0000000000..e30b5d3231--- /dev/null+++ b/apps/client/src/widgets/collections/geomap/DrawShape.tsx@@ -0,0 +1,100 @@+import { useContext, useEffect, useRef } from "preact/hooks";+import { type GeoJSONStoreFeatures, TerraDraw, TerraDrawLineStringMode, TerraDrawPolygonMode } from "terra-draw";+import { TerraDrawMapLibreGLAdapter } from "terra-draw-maplibre-gl-adapter";++import { MapStyleLoaded, ParentMap } from "./map";+import { type GeoShape, polygonFromRing } from "./shapes";++/** The drawing tools on offer, each arming Terra Draw with a mode of its own. */+export type DrawTool = "line" | "polygon";++interface DrawShapeProps {+ tool: DrawTool;+ /** Handed the finished shape. Standing the session down again is the caller's move — the+ * component draws for as long as it is mounted, like GhostPin haunts. */+ onFinish: (shape: GeoShape) => void;+}++/**+ * A drawing session: mounted while the map is armed to draw, gone when it is not.+ *+ * Terra Draw is the pencil here and nothing more. It owns the map only while this is mounted —+ * click by click, the growing shape and its vertex handles are its own ephemeral layers — and the+ * moment a shape is finished, it is handed to the caller to become a note and the session's+ * rendering is thrown away. What the reader sees from then on is {@link ShapeLayer}, drawing the+ * note's label the way every persisted thing on this map is drawn. Keeping the library inside+ * these brackets is the point: nothing persisted ever depends on it.+ */+export default function DrawShape({ tool, onFinish }: DrawShapeProps) {+ const parentMap = useContext(ParentMap);+ const styleLoaded = useContext(MapStyleLoaded);++ // Read through a ref so a new callback identity does not tear down a half-drawn shape.+ const onFinishRef = useRef(onFinish);+ onFinishRef.current = onFinish;++ useEffect(() => {+ // The adapter puts its working layers on the style, so it must wait for one to be there —+ // the same wait every layer-adding child of the map keeps (see MapStyleLoaded).+ if (!parentMap || !styleLoaded) return;++ const mode = buildMode(tool);+ const draw = new TerraDraw({+ adapter: new TerraDrawMapLibreGLAdapter({ map: parentMap }),+ modes: [ mode ]+ });++ draw.on("finish", (id, { action }) => {+ if (action !== "draw") return;++ const feature = draw.getSnapshotFeature(id);+ const shape = feature && shapeFromFeature(tool, feature);+ if (shape) {+ onFinishRef.current(shape);+ }+ });++ draw.start();+ draw.setMode(mode.mode);++ return () => {+ try {+ draw.stop();+ } catch {+ // The map may already have been removed, taking the session's layers with it.+ }+ };+ }, [ parentMap, styleLoaded, tool ]);++ return <div />;+}++/** The Terra Draw mode a tool draws with — each knows its own name for `setMode`. */+function buildMode(tool: DrawTool) {+ switch (tool) {+ case "line":+ return new TerraDrawLineStringMode();+ case "polygon":+ return new TerraDrawPolygonMode();+ }+}++/**+ * The finished feature as the shape its note will carry, or null for one that is not the kind the+ * tool draws — nothing to make a note of then, and the session simply stays armed.+ *+ * Every area tool comes through the polygon branch: whatever hand movement made it, what was made+ * is a ring, and a ring is a polygon note (with its closing repeat left behind — the label does+ * not spell it; see shapes.ts).+ */+export function shapeFromFeature(tool: DrawTool, feature: GeoJSONStoreFeatures): GeoShape | null {+ if (tool === "line") {+ return feature.geometry.type === "LineString"+ ? { type: "line", coordinates: feature.geometry.coordinates as [number, number][] }+ : null;+ }++ if (feature.geometry.type !== "Polygon") return null;+ const ring = feature.geometry.coordinates[0] as [number, number][] | undefined;+ return ring ? polygonFromRing(ring) : null;+}diff --git a/apps/client/src/widgets/collections/geomap/EditToolbar.spec.tsx b/apps/client/src/widgets/collections/geomap/EditToolbar.spec.tsxindex c11f62e981..8bd0bf9a42 100644--- a/apps/client/src/widgets/collections/geomap/EditToolbar.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/EditToolbar.spec.tsx@@ -7,11 +7,12 @@ import { act } from "preact/test-utils";import { describe, expect, it, vi } from "vitest";import { renderInto } from "../../../test/render";+import type { DrawTool } from "./DrawShape";import EditToolbar from "./EditToolbar";import { ParentMap } from "./map";/** Builds the bar over a map, which it asks nothing more of than being there at all. */-function renderBar({ map = {} as never, isReadOnly = false, placing = false, drawing = false } = {}) {+function renderBar({ map = {} as never, isReadOnly = false, placing = false, drawingTool = null as DrawTool | null } = {}) {const onTogglePlacement = vi.fn();const onToggleDrawing = vi.fn();const onAddGpxTrack = vi.fn();@@ -19,7 +20,7 @@ function renderBar({ map = {} as never, isReadOnly = false, placing = false, draact(() => {container = renderInto(<ParentMap.Provider value={map}>- <EditToolbar isReadOnly={isReadOnly} placing={placing} onTogglePlacement={onTogglePlacement} drawing={drawing} onToggleDrawing={onToggleDrawing} onAddGpxTrack={onAddGpxTrack} />+ <EditToolbar isReadOnly={isReadOnly} placing={placing} onTogglePlacement={onTogglePlacement} drawingTool={drawingTool} onToggleDrawing={onToggleDrawing} onAddGpxTrack={onAddGpxTrack} /></ParentMap.Provider>);});@@ -33,11 +34,18 @@ function renderBar({ map = {} as never, isReadOnly = false, placing = false, drabuttons: all,/** The first button, which is the +. */button: () => all()[0] ?? null,- drawButton: () => all()[1] ?? null,- gpxButton: () => all()[2] ?? null+ /** The drawing tools, one button per tool, standing between the + and the GPX button. */+ drawButton: (icon: string) => all().find((b) => b.classList.contains(icon)) ?? null,+ gpxButton: () => all()[all().length - 1] ?? null};}+/** Every drawing tool on the bar, by the icon its button wears. */+const DRAW_TOOL_ICONS: { tool: DrawTool; icon: string }[] = [+ { tool: "line", icon: "bx-vector" },+ { tool: "polygon", icon: "bx-shape-polygon" }+];+describe("geo map EditToolbar", () => {it("offers to add a note, and hands the arming to the map view", () => {const { button, onTogglePlacement } = renderBar();@@ -60,17 +68,17 @@ describe("geo map EditToolbar", () => {expect(onTogglePlacement).toHaveBeenCalledTimes(1);});- it("offers to draw a line, wears an armed session as held down, and hands both to the map view", () => {- const { drawButton, onToggleDrawing } = renderBar();-- expect(drawButton()?.className).toContain("bx-vector");- expect(drawButton()?.classList.contains("active")).toBe(false);+ it("offers every drawing tool, wears the armed one as held down, and hands the arming to the map view", () => {+ for (const { tool, icon } of DRAW_TOOL_ICONS) {+ const { drawButton, onToggleDrawing } = renderBar();- act(() => drawButton()?.click());- expect(onToggleDrawing).toHaveBeenCalledTimes(1);+ expect(drawButton(icon)?.classList.contains("active")).toBe(false);+ act(() => drawButton(icon)?.click());+ expect(onToggleDrawing).toHaveBeenCalledWith(tool);- const armed = renderBar({ drawing: true });- expect(armed.drawButton()?.classList.contains("active")).toBe(true);+ const armed = renderBar({ drawingTool: tool });+ expect(armed.drawButton(icon)?.classList.contains("active")).toBe(true);+ }});it("offers to bring in a GPX track, and hands the asking to the map view", () => {@@ -85,6 +93,7 @@ describe("geo map EditToolbar", () => {it("refuses every button on a map that may not be edited", () => {const { buttons } = renderBar({ isReadOnly: true });+ expect(buttons().length).toBeGreaterThan(2);for (const button of buttons()) {expect(button.disabled).toBe(true);}diff --git a/apps/client/src/widgets/collections/geomap/EditToolbar.tsx b/apps/client/src/widgets/collections/geomap/EditToolbar.tsxindex 95b3286fb3..cc59030305 100644--- a/apps/client/src/widgets/collections/geomap/EditToolbar.tsx+++ b/apps/client/src/widgets/collections/geomap/EditToolbar.tsx@@ -4,6 +4,7 @@ import { useContext, useRef } from "preact/hooks";import { t } from "../../../services/i18n";import { useStaticTooltip } from "../../react/hooks";+import type { DrawTool } from "./DrawShape";import { ParentMap } from "./map";interface EditToolbarProps {@@ -15,19 +16,24 @@ interface EditToolbarProps {/** Arms the map for a note to be placed, or stands it down again — the visible counterpart of* the Escape the instruction toast offers (see index.tsx). */onTogglePlacement: () => void;- /** The map is armed for clicks to draw a line, worn held-down the way `placing` is. */- drawing: boolean;- /** Arms the map for a line to be drawn, or stands it down again (see index.tsx). */- onToggleDrawing: () => void;+ /** The tool the map is armed to draw with, if any — its button worn held-down like `placing`. */+ drawingTool: DrawTool | null;+ /** Arms the map to draw with the tool, or stands it down again (see index.tsx). */+ onToggleDrawing: (tool: DrawTool) => void;/** Asks for a GPX file and brings it onto the map (see `addGpxTrack` in index.tsx). */onAddGpxTrack: () => void;}+/** The drawing tools in the order they stand on the bar, each wearing the shape it draws. */+const DRAW_TOOLS: { tool: DrawTool; icon: string; title: () => string }[] = [+ { tool: "line", icon: "bx-vector", title: () => t("geo-map.draw-line") },+ { tool: "polygon", icon: "bx-shape-polygon", title: () => t("geo-map.draw-polygon") }+];+/*** The editing actions, standing in the middle of the map's foot on a control group of their own- * (`tn-overlay-control-group`, the surface every group over this map stands on): adding a marker and- * bringing in a GPX track today, with room along the row for whatever editing the map comes to offer- * next.+ * (`tn-overlay-control-group`, the surface every group over this map stands on): adding a marker,+ * the drawing tools, and bringing in a GPX track.** A group of its own rather than more buttons on {@link MapToolbar}: that one is the camera — how* close in the map is drawn, how much screen it gets — and what changes the map is another kind of@@ -40,10 +46,9 @@ interface EditToolbarProps {* is what goes fullscreen (see MapToolbar): the collection bar stays behind, and while the button* lived there, a fullscreen map could only be added to through its right-click menu.*/-export default function EditToolbar({ isReadOnly, placing, onTogglePlacement, drawing, onToggleDrawing, onAddGpxTrack }: EditToolbarProps) {+export default function EditToolbar({ isReadOnly, placing, onTogglePlacement, drawingTool, onToggleDrawing, onAddGpxTrack }: EditToolbarProps) {const map = useContext(ParentMap);const addMarkerRef = useRef<HTMLButtonElement>(null);- const drawLineRef = useRef<HTMLButtonElement>(null);const gpxRef = useRef<HTMLButtonElement>(null);// Standing at the foot of the map, the tooltips open away from that edge, where they would@@ -52,10 +57,6 @@ export default function EditToolbar({ isReadOnly, placing, onTogglePlacement, drtitle: placing ? t("geo-map.create-child-note-cancel") : t("geo-map.create-child-note-title"),placement: "top"});- useStaticTooltip(drawLineRef, {- title: drawing ? t("geo-map.draw-line-cancel") : t("geo-map.draw-line"),- placement: "top"- });useStaticTooltip(gpxRef, { title: t("geo-map.add-gpx-track"), placement: "top" });// No group over a map that could not be drawn (see the WebGL fallback in map.tsx).@@ -83,14 +84,16 @@ export default function EditToolbar({ isReadOnly, placing, onTogglePlacement, dr<span className="bx bx-pin" aria-hidden="true" />{placing ? t("geo-map.add-marker-cancel") : t("geo-map.add-marker")}</button>- <button- ref={drawLineRef}- type="button"- className={`tn-overlay-icon-button bx bx-vector ${drawing ? "active" : ""}`}- aria-label={drawing ? t("geo-map.draw-line-cancel") : t("geo-map.draw-line")}- disabled={isReadOnly}- onClick={onToggleDrawing}- />+ {DRAW_TOOLS.map(({ tool, icon, title }) => (+ <DrawToolButton+ key={tool}+ icon={icon}+ title={drawingTool === tool ? t("geo-map.draw-cancel") : title()}+ active={drawingTool === tool}+ disabled={isReadOnly}+ onClick={() => onToggleDrawing(tool)}+ />+ ))}<buttonref={gpxRef}type="button"@@ -102,3 +105,27 @@ export default function EditToolbar({ isReadOnly, placing, onTogglePlacement, dr</div>);}++/**+ * One drawing tool's button — a component apiece rather than markup in the loop above, because+ * each needs a tooltip of its own and a tooltip is a hook on a ref.+ */+function DrawToolButton({ icon, title, active, disabled, onClick }: {+ icon: string;+ title: string;+ active: boolean;+ disabled: boolean;+ onClick: () => void;+}) {+ const ref = useRef<HTMLButtonElement>(null);+ useStaticTooltip(ref, { title, placement: "top" });++ return <button+ ref={ref}+ type="button"+ className={`tn-overlay-icon-button bx ${icon} ${active ? "active" : ""}`}+ aria-label={title}+ disabled={disabled}+ onClick={onClick}+ />;+}diff --git a/apps/client/src/widgets/collections/geomap/LineShape.tsx b/apps/client/src/widgets/collections/geomap/LineShape.tsxdeleted file mode 100644index 1add66c29b..0000000000--- a/apps/client/src/widgets/collections/geomap/LineShape.tsx+++ /dev/null@@ -1,114 +0,0 @@-import { useContext, useEffect } from "preact/hooks";--import { MapStyleLoaded, ParentMap } from "./map";--interface LineShapeProps {- /** The note the line belongs to, which is what its source and layer are named after. */- noteId: string;- /** `[lng, lat]` pairs, as {@link parseGeoShape} hands them over. */- coordinates: [number, number][];- /** What the line is drawn in — the note's own colour, as a track's would be. */- color: string;-}--/**- * A line drawn onto the map by hand, read back off its note's `#geoShape` label (see shapes.ts).- *- * The GPX track's little sibling: the same source-and-line-layer shape, the same put-it-back-on-- * every-style-load dance, without the file, the flags or the name written along it — a spike's- * worth of track. 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.- */-export function LineShape({ noteId, coordinates, color }: LineShapeProps) {- const parentMap = useContext(ParentMap);- const styleLoaded = useContext(MapStyleLoaded);-- // The coordinates as a dependency the effect can compare: the array is rebuilt on every parse- // of the label, so handing it over as-is would tear the line down and put it back per render.- const coordinatesKey = coordinates.flat().join(",");-- useEffect(() => {- if (!parentMap) return;- const map = parentMap;-- const sourceId = lineShapeSourceId(noteId);- const layerId = `shape-line-${noteId}`;-- // The line lives in the map style, which setStyle() wipes for a URL-named vector style- // (keepAdditions cannot carry what it never saw; see map.tsx) — so it is put back on every- // style load, and each piece only if it is missing, exactly as a track is.- function addLineLayers() {- try {- if (!map.getSource(sourceId)) {- map.addSource(sourceId, {- type: "geojson",- data: {- type: "Feature",- // The note the line stands for, carried in the feature the way a- // track's is, for whatever comes to hit-test shapes.- properties: { id: noteId },- geometry: {- type: "LineString",- coordinates- }- }- });- }-- if (!map.getLayer(layerId)) {- map.addLayer({- id: layerId,- type: "line",- source: sourceId,- layout: {- // Otherwise a line doubling back meets its own corners as spikes,- // and ends in a flat stub.- "line-join": "round",- "line-cap": "round"- },- paint: {- "line-color": color,- "line-width": 3- }- });- }- } catch (e) {- // Only worth a word if the style was ready and it still would not take the line.- if (styleLoaded) {- console.warn("Geo map: could not draw a shape —", e);- }- }- }-- if (styleLoaded) {- addLineLayers();- }- map.on("style.load", addLineLayers);-- return () => {- map.off("style.load", addLineLayers);- try {- // The layer before the source it draws from: one still in use cannot be removed.- if (map.getLayer(layerId)) {- map.removeLayer(layerId);- }- if (map.getSource(sourceId)) {- map.removeSource(sourceId);- }- } catch {- // The map may already have been removed.- }- };- }, [ parentMap, styleLoaded, noteId, coordinatesKey, color ]);-- return <div />;-}--/**- * The one source a shape's layers draw from, named for whoever needs to read the shape back off- * the map — as a track's is (see `trackSourceId`).- */-export function lineShapeSourceId(noteId: string) {- return `shape-source-${noteId}`;-}diff --git a/apps/client/src/widgets/collections/geomap/LineShape.spec.tsx b/apps/client/src/widgets/collections/geomap/ShapeLayer.spec.tsxsimilarity index 53%rename from apps/client/src/widgets/collections/geomap/LineShape.spec.tsxrename to apps/client/src/widgets/collections/geomap/ShapeLayer.spec.tsxindex 89e1256a87..fc46770394 100644--- a/apps/client/src/widgets/collections/geomap/LineShape.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/ShapeLayer.spec.tsx@@ -1,12 +1,14 @@/**- * The hand-drawn line (see LineShape.tsx): that it goes onto a loaded style and not before, that it- * is put back after a style switch wipes the map, and that it leaves nothing behind when it goes.+ * The hand-drawn shape (see ShapeLayer.tsx): that it goes onto a loaded style and not before, that+ * a line is a stroke alone while an area wears a wash under the same stroke, that it is put back+ * after a style switch wipes the map, and that it leaves nothing behind when it goes.*/import { render } from "preact";import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it } from "vitest";-import { LineShape, lineShapeSourceId } from "./LineShape";+import type { GeoShape } from "./shapes";+import { ShapeLayer, shapeSourceId } from "./ShapeLayer";import { MapStyleLoaded, ParentMap } from "./map";/**@@ -57,7 +59,7 @@ function fakeMap() {listener();}},- /** A style switch as the line experiences one: everything wiped, then `style.load` again. */+ /** A style switch as the shape experiences one: everything wiped, then `style.load` again. */switchStyle() {sources.clear();layers.clear();@@ -67,9 +69,10 @@ function fakeMap() {}const NOTE_ID = "shapeNoteId1";-const COORDINATES: [number, number][] = [ [ 24.13, 45.79 ], [ 24.14, 45.81 ], [ 24.08, 45.89 ] ];+const LINE: GeoShape = { type: "line", coordinates: [ [ 24.13, 45.79 ], [ 24.14, 45.81 ], [ 24.08, 45.89 ] ] };+const POLYGON: GeoShape = { type: "polygon", coordinates: [ [ 24.13, 45.79 ], [ 24.14, 45.81 ], [ 24.08, 45.89 ] ] };-describe("LineShape", () => {+describe("ShapeLayer", () => {let container: HTMLElement;let map: ReturnType<typeof fakeMap>;@@ -84,12 +87,12 @@ describe("LineShape", () => {container.remove();});- function renderLine({ styleLoaded = true } = {}) {+ function renderShape(shape: GeoShape, { styleLoaded = true } = {}) {act(() => {render(<ParentMap.Provider value={map as never}><MapStyleLoaded.Provider value={styleLoaded}>- <LineShape noteId={NOTE_ID} coordinates={COORDINATES} color="purple" />+ <ShapeLayer noteId={NOTE_ID} shape={shape} color="purple" /></MapStyleLoaded.Provider></ParentMap.Provider>,container@@ -97,39 +100,61 @@ describe("LineShape", () => {});}- it("draws the line from the note's coordinates, and takes it down when unmounted", () => {+ it("draws a line as its stroke alone, and takes it down when unmounted", () => {map.loadStyle();- renderLine();+ renderShape(LINE);- const source = map.sources.get(lineShapeSourceId(NOTE_ID)) as {- data: { properties: { id: string }; geometry: { coordinates: unknown } };+ const source = map.sources.get(shapeSourceId(NOTE_ID)) as {+ data: { properties: { id: string }; geometry: { type: string; coordinates: unknown } };};- expect(source.data.geometry.coordinates).toEqual(COORDINATES);- // The note the line stands for rides in the feature, for whatever comes to hit-test it.+ expect(source.data.geometry.type).toBe("LineString");+ expect(source.data.geometry.coordinates).toEqual(LINE.coordinates);+ // The note the shape stands for rides in the feature, for whatever comes to hit-test it.expect(source.data.properties.id).toBe(NOTE_ID);- const layer = map.layers.get(`shape-line-${NOTE_ID}`) as { paint: Record<string, unknown> };- expect(layer.paint["line-color"]).toBe("purple");+ const stroke = map.layers.get(`shape-stroke-${NOTE_ID}`) as { paint: Record<string, unknown> };+ expect(stroke.paint["line-color"]).toBe("purple");+ // No wash under a line: it encloses nothing.+ expect(map.layers.has(`shape-fill-${NOTE_ID}`)).toBe(false);act(() => render(null, container));expect(map.sources.size).toBe(0);expect(map.layers.size).toBe(0);});+ it("draws an area as a wash under the stroke, its ring closed back up for GeoJSON", () => {+ map.loadStyle();+ renderShape(POLYGON);++ const source = map.sources.get(shapeSourceId(NOTE_ID)) as {+ data: { geometry: { type: string; coordinates: [number, number][][] } };+ };+ expect(source.data.geometry.type).toBe("Polygon");+ // The label leaves the closing point unwritten; GeoJSON wants the ring ended where it began.+ expect(source.data.geometry.coordinates[0]).toEqual([ ...POLYGON.coordinates, POLYGON.coordinates[0] ]);++ const fill = map.layers.get(`shape-fill-${NOTE_ID}`) as { paint: Record<string, unknown> };+ expect(fill.paint["fill-color"]).toBe("purple");+ expect(map.layers.has(`shape-stroke-${NOTE_ID}`)).toBe(true);++ act(() => render(null, container));+ expect(map.layers.size).toBe(0);+ });+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.- renderLine({ styleLoaded: false });+ renderShape(LINE, { styleLoaded: false });expect(map.sources.size).toBe(0);// MapStyleLoaded flipping true is a new render; the style itself also announces itself.act(() => map.loadStyle());- renderLine({ styleLoaded: true });- expect(map.sources.has(lineShapeSourceId(NOTE_ID))).toBe(true);+ renderShape(LINE, { styleLoaded: true });+ expect(map.sources.has(shapeSourceId(NOTE_ID))).toBe(true);// A style switch takes everything with it, and `style.load` is the cue to put it back.act(() => map.switchStyle());- expect(map.sources.has(lineShapeSourceId(NOTE_ID))).toBe(true);- expect(map.layers.has(`shape-line-${NOTE_ID}`)).toBe(true);+ expect(map.sources.has(shapeSourceId(NOTE_ID))).toBe(true);+ expect(map.layers.has(`shape-stroke-${NOTE_ID}`)).toBe(true);});});diff --git a/apps/client/src/widgets/collections/geomap/ShapeLayer.tsx b/apps/client/src/widgets/collections/geomap/ShapeLayer.tsxnew file mode 100644index 0000000000..3f501c2bbc--- /dev/null+++ b/apps/client/src/widgets/collections/geomap/ShapeLayer.tsx@@ -0,0 +1,132 @@+import { useContext, useEffect } from "preact/hooks";++import { MapStyleLoaded, ParentMap } from "./map";+import { closeRing, type GeoShape } from "./shapes";++interface ShapeLayerProps {+ /** The note the shape belongs to, which is what its source and layers are named after. */+ noteId: string;+ /** The shape off the note's label, as {@link parseGeoShape} hands it over. */+ shape: GeoShape;+ /** What the shape is drawn in — the note's own colour, as a track's would be. */+ color: string;+}++/**+ * A shape drawn onto the map by hand, read back off its note's `#geoShape` label (see shapes.ts).+ *+ * 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.+ */+export function ShapeLayer({ noteId, shape, color }: ShapeLayerProps) {+ const parentMap = useContext(ParentMap);+ const styleLoaded = useContext(MapStyleLoaded);++ // The shape as a dependency the effect can compare: the object is rebuilt on every parse of+ // the label, so handing it over as-is would tear the layers down and put them back per render.+ const shapeKey = `${shape.type}:${shape.coordinates.flat().join(",")}`;++ useEffect(() => {+ if (!parentMap) return;+ const map = parentMap;++ const sourceId = shapeSourceId(noteId);+ const strokeLayerId = `shape-stroke-${noteId}`;+ const fillLayerId = `shape-fill-${noteId}`;+ const hasArea = shape.type !== "line";++ // The shape lives in the map style, which setStyle() wipes for a URL-named vector style+ // (keepAdditions cannot carry what it never saw; see map.tsx) — so it is put back on every+ // style load, and each piece only if it is missing, exactly as a track is.+ function addShapeLayers() {+ try {+ if (!map.getSource(sourceId)) {+ map.addSource(sourceId, {+ type: "geojson",+ data: {+ type: "Feature",+ // The note the shape stands for, carried in the feature the way a+ // track's is, for whatever comes to hit-test shapes.+ properties: { id: noteId },+ geometry: shape.type === "line"+ ? { type: "LineString", coordinates: shape.coordinates }+ : { type: "Polygon", coordinates: [ closeRing(shape.coordinates) ] }+ }+ });+ }++ // The wash before the stroke, so the boundary is drawn over it rather than under.+ if (hasArea && !map.getLayer(fillLayerId)) {+ map.addLayer({+ id: fillLayerId,+ type: "fill",+ source: sourceId,+ paint: {+ "fill-color": color,+ "fill-opacity": 0.15+ }+ });+ }++ if (!map.getLayer(strokeLayerId)) {+ map.addLayer({+ id: strokeLayerId,+ type: "line",+ source: sourceId,+ layout: {+ // Otherwise a line doubling back meets its own corners as spikes,+ // and ends in a flat stub.+ "line-join": "round",+ "line-cap": "round"+ },+ paint: {+ "line-color": color,+ "line-width": 3+ }+ });+ }+ } catch (e) {+ // Only worth a word if the style was ready and it still would not take the shape.+ if (styleLoaded) {+ console.warn("Geo map: could not draw a shape —", e);+ }+ }+ }++ if (styleLoaded) {+ addShapeLayers();+ }+ map.on("style.load", addShapeLayers);++ return () => {+ 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 ]) {+ if (map.getLayer(layer)) {+ map.removeLayer(layer);+ }+ }+ if (map.getSource(sourceId)) {+ map.removeSource(sourceId);+ }+ } catch {+ // The map may already have been removed.+ }+ };+ }, [ parentMap, styleLoaded, noteId, shapeKey, color ]);++ return <div />;+}++/**+ * The one source a shape's layers draw from, named for whoever needs to read the shape back off+ * the map — as a track's is (see `trackSourceId`).+ */+export function shapeSourceId(noteId: string) {+ return `shape-source-${noteId}`;+}diff --git a/apps/client/src/widgets/collections/geomap/api.spec.ts b/apps/client/src/widgets/collections/geomap/api.spec.tsindex 820a0dea65..49d08ff13c 100644--- a/apps/client/src/widgets/collections/geomap/api.spec.ts+++ b/apps/client/src/widgets/collections/geomap/api.spec.ts@@ -7,7 +7,7 @@ import { describe, expect, it, vi } from "vitest";import note_create from "../../../services/note_create";import { buildNote } from "../../../test/easy-froca";-import { createNewNote, importGpxTrack } from "./api";+import { createNewNote, createShapeNote, importGpxTrack } from "./api";vi.mock("../../../services/note_create", () => ({default: { createNote: vi.fn(async () => ({ note: { noteId: "created" }, branch: null })) }@@ -38,6 +38,25 @@ describe("geo map api", () => {}));});+ it("creates a shape note under the stock name, its geometry in the label and its icon the tool's", async () => {+ const parent = buildNote({ title: "The map" });++ const created = await createShapeNote(parent, {+ type: "polygon",+ coordinates: [ [ 2.29, 48.85 ], [ 2.35, 48.86 ], [ 2.3, 48.9 ] ]+ });++ expect(created).toEqual({ noteId: "created" });+ expect(createNote).toHaveBeenCalledWith(parent.noteId, expect.objectContaining({+ type: "text",+ activate: false,+ attributes: expect.arrayContaining([+ { type: "label", name: "geoShape", value: "polygon:48.85,2.29 48.86,2.35 48.9,2.3" },+ { type: "label", name: "iconClass", value: "bx bx-shape-polygon" }+ ])+ }));+ });+it("brings a GPX file in as a file note the map draws tracks by", async () => {const parent = buildNote({ title: "The map" });const file = new File([ "<gpx><trk/></gpx>" ], "sunday-ride.gpx");diff --git a/apps/client/src/widgets/collections/geomap/api.ts b/apps/client/src/widgets/collections/geomap/api.tsindex d1cd7bc901..ae50eaec49 100644--- a/apps/client/src/widgets/collections/geomap/api.ts+++ b/apps/client/src/widgets/collections/geomap/api.ts@@ -7,13 +7,16 @@ import { deleteNoteOrBranch } from "../../../services/note_deletion";import { GPX_MIME } from "./GpxTrack";import type { GeoMouseEvent } from "./map";import { LOCATION_ATTRIBUTE } from "./Markers";-import { serializeLine, SHAPE_ATTRIBUTE } from "./shapes";+import { type GeoShape, serializeGeoShape, SHAPE_ATTRIBUTE } from "./shapes";/** The icon a note created on the map is given, and so what the ghost pin previews for one. */export const CHILD_NOTE_ICON = "bx bx-pin";-/** The icon a note drawn as a line is given — the shape of the tool that made it. */-export const LINE_NOTE_ICON = "bx bx-vector";+/** The icon a shape note wears, by the kind of shape its label spells. */+export const SHAPE_NOTE_ICONS = {+ line: "bx bx-vector",+ polygon: "bx bx-shape-polygon"+} as const satisfies Record<GeoShape["type"], string>;export async function moveMarker(noteId: string, latLng: { lat: number; lng: number } | null) {const value = latLng ? [latLng.lat, latLng.lng].join(",") : "";@@ -114,14 +117,14 @@ export async function createNewNote(parentNote: FNote, e: GeoMouseEvent) {}/**- * Makes a note of a line drawn on the map, and hands it back for the pane to open on.+ * Makes a note of a shape drawn on the map, and hands it back for the pane to open on.** A marker note in every way but the label: an ordinary text note, stock-named for the pane to* offer the title for typing over, whose place on the map is written in an attribute — the whole- * line in `#geoShape` where a marker keeps its point in `#geolocation` (see shapes.ts). The note+ * shape in `#geoShape` where a marker keeps its point in `#geolocation` (see shapes.ts). The note* is the shape the way a marker note is its pin; the content stays the user's to write.*/-export async function createLineNote(parentNote: FNote, coordinates: [number, number][]) {+export async function createShapeNote(parentNote: FNote, shape: GeoShape) {const { note } = await note_create.createNote(parentNote.noteId, {title: t("relation_map.default_new_note_title"),content: "",@@ -129,8 +132,8 @@ export async function createLineNote(parentNote: FNote, coordinates: [number, nuactivate: false,isProtected: parentNote.isProtected,attributes: [- { type: "label", name: SHAPE_ATTRIBUTE, value: serializeLine(coordinates) },- { type: "label", name: "iconClass", value: LINE_NOTE_ICON }+ { type: "label", name: SHAPE_ATTRIBUTE, value: serializeGeoShape(shape) },+ { type: "label", name: "iconClass", value: SHAPE_NOTE_ICONS[shape.type] }]});diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsxindex 60b45f085d..f845ab34d6 100644--- a/apps/client/src/widgets/collections/geomap/index.tsx+++ b/apps/client/src/widgets/collections/geomap/index.tsx@@ -13,20 +13,20 @@ import CollectionProperties from "../../note_bars/CollectionProperties";import ActionButton from "../../react/ActionButton";import { useCollectionTreeDrag, useNoteBlob, useNoteLabel, useNoteLabelBoolean, useNoteProperty, useSpacedUpdate } from "../../react/hooks";import { ViewModeProps } from "../interface";-import { createLineNote, createNewNote, importGpxTrack, moveMarker } from "./api";+import { createNewNote, createShapeNote, importGpxTrack, moveMarker } from "./api";import Buildings from "./Buildings";import ContextMenus from "./ContextMenus";import DetailPane, { PaneSelection } from "./DetailPane";-import DrawLine from "./DrawLine";+import DrawShape, { DrawTool } from "./DrawShape";import EditToolbar from "./EditToolbar";import GhostPin from "./GhostPin";import { GPX_MIME, GpxTrack } from "./GpxTrack";-import { LineShape } from "./LineShape";import Map, { DEFAULT_ZOOM, GeoMouseEvent } from "./map";import { DEFAULT_MAP_LAYER_NAME, MAP_LAYERS, MapLayer } from "./map_layer";import MapToolbar from "./MapToolbar";import Markers, { DEFAULT_MARKER_COLOR, LOCATION_ATTRIBUTE } from "./Markers";-import { parseGeoShape, SHAPE_ATTRIBUTE } from "./shapes";+import { GeoShape, parseGeoShape, SHAPE_ATTRIBUTE } from "./shapes";+import { ShapeLayer } from "./ShapeLayer";import Tooltips from "./Tooltips";const DEFAULT_COORDINATES: [number, number] = [3.878638227135724, 446.6630455551659];@@ -61,7 +61,7 @@ interface MapData {type Placement =| { mode: "new" }| { mode: "move"; noteId: string }- | { mode: "draw" };+ | { mode: "draw"; tool: DrawTool };export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewModeProps<MapData>) {const [ placement, setPlacement ] = useState<Placement>();@@ -105,19 +105,21 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewMsetPlacement((current) => current?.mode === "new" ? undefined : { mode: "new" });}, []);const startMarkerRelocation = useCallback((noteId: string) => setPlacement({ mode: "move", noteId }), []);- const toggleLineDrawing = useCallback(() => {- setPlacement((current) => current?.mode === "draw" ? undefined : { mode: "draw" });+ const toggleDrawing = useCallback((tool: DrawTool) => {+ // A press on the armed tool stands the map down; a press on another switches to it, the+ // way + takes over a map armed to move a marker.+ setPlacement((current) => current?.mode === "draw" && current.tool === tool ? undefined : { mode: "draw", tool });}, []);/**- * Makes a note of a finished line and opens the pane on it, title selected, exactly as a+ * Makes a note of a finished shape and opens the pane on it, title selected, exactly as a* placed marker is offered for naming (see createNoteAt). Disarming comes first so a failure- * to create the note does not leave the map drawing a line nobody is looking at any more.+ * to create the note does not leave the map drawing a shape nobody is looking at any more.*/- const finishLine = useCallback(async (coordinates: [number, number][]) => {+ const finishShape = useCallback(async (shape: GeoShape) => {setPlacement(undefined);- const created = await createLineNote(note, coordinates);+ const created = await createShapeNote(note, shape);if (!created) return;setNotes((current) => current.some((n) => n.noteId === created.noteId) ? current : [ ...current, created ]);@@ -184,11 +186,7 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewMtitle: t("geo-map.move-marker-toast-title"),message: t("geo-map.move-marker-instruction")}- : {- icon: "vector",- title: t("geo-map.draw-line-toast-title"),- message: t("geo-map.draw-line-instruction")- })+ : drawingToast(placement.tool))});const globalKeyListener = (e: KeyboardEvent) => {@@ -280,8 +278,8 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewMisReadOnly={isReadOnly}placing={placement?.mode === "new"}onTogglePlacement={toggleNotePlacement}- drawing={placement?.mode === "draw"}- onToggleDrawing={toggleLineDrawing}+ drawingTool={placement?.mode === "draw" ? placement.tool : null}+ onToggleDrawing={toggleDrawing}onAddGpxTrack={addGpxTrack}/><Tooltips selectedNoteId={selection?.noteId ?? null} />@@ -289,7 +287,7 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewMbeing moved wearing its own pin, a note to be created wearing the pin it will begiven (see api.ts). A drawing session previews itself, so no ghost then. */}{placement && placement.mode !== "draw" && <GhostPin note={placement.mode === "move" ? notes.find((n) => n.noteId === placement.noteId) : undefined} />}- {placement?.mode === "draw" && <DrawLine onFinish={finishLine} />}+ {placement?.mode === "draw" && <DrawShape tool={placement.tool} onFinish={finishShape} />}<DetailPane notes={notes} parentNote={note} placing={!!placement} isReadOnly={isReadOnly} selection={selection} onSelect={setSelection} onRelocate={startMarkerRelocation} /><ContextMenus parentNote={note} isReadOnly={isReadOnly} onRelocate={startMarkerRelocation} onCreateNote={createNoteAt} />{/* Stood up only while the view is leaned over, so the 3D button changes the map@@ -419,7 +417,7 @@ function NoteGpxTrack({ note, hideLabels, isDarkTheme }: { note: FNote, hideLabe}/**- * A note's drawn shape, where the note carries one — a line written into its `#geoShape` label+ * A note's drawn shape, where the note carries one — a shape written into its `#geoShape` label* (see shapes.ts). A label the shape cannot be read from draws nothing, the same nothing a note* with no shape at all draws: the label is user-editable like any other, and a map is no place to* report a parse error.@@ -433,10 +431,28 @@ function NoteShapeWrapper({ note }: { note: FNote }) {return null;}- return <LineShape+ return <ShapeLayernoteId={note.noteId}- coordinates={shape.coordinates}+ shape={shape}color={color ?? "blue"}/>;}+/** What the instruction toast says while each tool is armed (see the placement toast above). */+function drawingToast(tool: DrawTool): { icon: string; title: string; message: string } {+ switch (tool) {+ case "line":+ return {+ icon: "vector",+ title: t("geo-map.draw-line-toast-title"),+ message: t("geo-map.draw-line-instruction")+ };+ case "polygon":+ return {+ icon: "shape-polygon",+ title: t("geo-map.draw-polygon-toast-title"),+ message: t("geo-map.draw-polygon-instruction")+ };+ }+}+diff --git a/apps/client/src/widgets/collections/geomap/shapes.spec.ts b/apps/client/src/widgets/collections/geomap/shapes.spec.tsindex 037bb3f318..79bc176713 100644--- a/apps/client/src/widgets/collections/geomap/shapes.spec.ts+++ b/apps/client/src/widgets/collections/geomap/shapes.spec.ts@@ -1,13 +1,21 @@import { describe, expect, it } from "vitest";-import { parseGeoShape, serializeLine } from "./shapes";+import { closeRing, parseGeoShape, polygonFromRing, serializeGeoShape } from "./shapes";-describe("serializeLine", () => {- it("writes lat,lng pairs behind the line prefix, rounded but not padded", () => {- expect(serializeLine([- [ 2.2946944444, 48.8580925 ],- [ 2.35, 48.86 ]- ])).toBe("line:48.858093,2.294694 48.86,2.35");+describe("serializeGeoShape", () => {+ it("writes lat,lng pairs behind the kind's prefix, rounded but not padded", () => {+ expect(serializeGeoShape({+ type: "line",+ coordinates: [+ [ 2.2946944444, 48.8580925 ],+ [ 2.35, 48.86 ]+ ]+ })).toBe("line:48.858093,2.294694 48.86,2.35");++ expect(serializeGeoShape({+ type: "polygon",+ coordinates: [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]+ })).toBe("polygon:2,1 4,3 6,5");});it("round-trips through parseGeoShape", () => {@@ -16,12 +24,14 @@ describe("serializeLine", () => {[ 13.412, 52.531 ],[ -0.1276, 51.5072 ]];- expect(parseGeoShape(serializeLine(coordinates))).toEqual({ type: "line", coordinates });+ for (const type of [ "line", "polygon" ] as const) {+ expect(parseGeoShape(serializeGeoShape({ type, coordinates }))).toEqual({ type, coordinates });+ }});});describe("parseGeoShape", () => {- it("reads a line back in GeoJSON lng,lat order", () => {+ it("reads a shape back in GeoJSON lng,lat order", () => {expect(parseGeoShape("line:48.858093,2.294694 48.86,2.35")).toEqual({type: "line",coordinates: [@@ -35,16 +45,37 @@ describe("parseGeoShape", () => {expect(parseGeoShape("line: 1,2 3,4 ")?.coordinates).toEqual([ [ 2, 1 ], [ 4, 3 ] ]);});- it("refuses what is not a line", () => {- // Another kind's prefix, no prefix at all, and plain junk alike.- expect(parseGeoShape("polygon:1,2 3,4 5,6")).toBeNull();+ it("refuses what is not a shape", () => {+ // An unknown kind, no kind at all, and plain junk alike.+ expect(parseGeoShape("blob:1,2 3,4 5,6")).toBeNull();expect(parseGeoShape("1,2 3,4")).toBeNull();expect(parseGeoShape("")).toBeNull();- // Too few points: one point is no line.- expect(parseGeoShape("line:1,2")).toBeNull();- // Malformed vertices: a missing half, a non-number, a stray comma.+ // Malformed points: a missing half, a non-number, a stray comma.expect(parseGeoShape("line:1,2 3")).toBeNull();expect(parseGeoShape("line:1,2 x,4")).toBeNull();expect(parseGeoShape("line:1,2 3,4,5")).toBeNull();});++ it("holds each kind to its own minimum: one point is no line, and two no area", () => {+ expect(parseGeoShape("line:1,2")).toBeNull();+ expect(parseGeoShape("line:1,2 3,4")).not.toBeNull();+ expect(parseGeoShape("polygon:1,2 3,4")).toBeNull();+ expect(parseGeoShape("polygon:1,2 3,4 5,6")).not.toBeNull();+ });+});++describe("rings", () => {+ it("drops the closing repeat a drawing tool spells out, and leaves an open ring alone", () => {+ const open: [number, number][] = [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ];+ expect(polygonFromRing([ ...open, [ 1, 2 ] ]).coordinates).toEqual(open);+ expect(polygonFromRing(open).coordinates).toEqual(open);+ });++ it("closes a ring back up for GeoJSON", () => {+ expect(closeRing([ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ])).toEqual([ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 1, 2 ] ]);+ });++ it("survives a ring with nothing in it", () => {+ expect(polygonFromRing([]).coordinates).toEqual([]);+ });});diff --git a/apps/client/src/widgets/collections/geomap/shapes.ts b/apps/client/src/widgets/collections/geomap/shapes.tsindex ac5000ed30..6d91097f7e 100644--- a/apps/client/src/widgets/collections/geomap/shapes.ts+++ b/apps/client/src/widgets/collections/geomap/shapes.ts@@ -2,9 +2,11 @@* How a drawn shape is written onto its note, and read back off it.** A shape lives in a label the way a marker's location does (see `LOCATION_ATTRIBUTE` in Markers):- * the same `lat,lng` atom, pluralized — one pair per vertex, space-separated, behind a prefix naming- * what the vertices make. `#geoShape=line:48.858093,2.294694 48.860294,2.338629` is the marker- * format anyone has already read, walked along a path.+ * the same `lat,lng` atom, pluralized — a prefix naming what the points make, then the points.+ * `#geoShape=line:48.858093,2.294694 48.860294,2.338629` is the marker format anyone has already+ * read, walked along a path; a polygon is the same walk closed at the end (the closing point is+ * not written — it is the first one again, and writing it twice would only invite the two copies+ * to disagree).** A label rather than the note's content so the shape rides the attribute payload the way* `#geolocation` does: the map draws every shape the moment its children load, with no fetch per@@ -26,35 +28,77 @@ export interface GeoShapeLine {coordinates: [number, number][];}-/** Every kind of shape a note can carry. Only lines yet; the format leaves room in its prefix. */-export type GeoShape = GeoShapeLine;+export interface GeoShapePolygon {+ type: "polygon";+ /** `[lng, lat]` corners of the ring, without the closing repeat of the first — see+ * {@link closeRing} for the ring as GeoJSON wants it. */+ coordinates: [number, number][];+}++/** Every kind of shape a note can carry. */+export type GeoShape = GeoShapeLine | GeoShapePolygon;++/** The fewest points each kind is a shape at all with: one point is no line, and two no area. */+const MINIMUM_POINTS = { line: 2, polygon: 3 } as const;/**- * A line as its label value: `line:` and then each vertex as `lat,lng`, in the order the reader of- * a `#geolocation` label expects, however the coordinates are held in memory.+ * A shape as its label value: the kind, a colon, and each point as `lat,lng` — the order the+ * reader of a `#geolocation` label expects, however the coordinates are held in memory.*/-export function serializeLine(coordinates: [number, number][]): string {- const points = coordinates- .map(([ lng, lat ]) => `${round(lat)},${round(lng)}`)- .join(" ");- return `line:${points}`;+export function serializeGeoShape(shape: GeoShape): string {+ return `${shape.type}:${serializePoints(shape.coordinates)}`;}/*** The shape a label value spells, or null where it spells none.** Null rather than a throw, whatever is wrong with it — the value is user-editable like any label,- * and a shape that cannot be read is a shape the map does not draw, not an error the map falls over- * on. The rules are only what the geometry itself demands: every vertex a finite `lat,lng` pair,- * and at least two of them, one point being no line.+ * and a shape that cannot be read is a shape the map does not draw, not an error the map falls+ * over on. The rules are only what the geometry itself demands: every point a finite `lat,lng`+ * pair, and enough of them for the kind (see {@link MINIMUM_POINTS}).*/export function parseGeoShape(value: string): GeoShape | null {- if (!value.startsWith("line:")) {- return null;- }+ const divide = value.indexOf(":");+ if (divide < 0) return null;+ const type = value.slice(0, divide);+ if (!isPointKind(type)) return null;++ const coordinates = parsePoints(value.slice(divide + 1));+ if (!coordinates || coordinates.length < MINIMUM_POINTS[type]) return null;++ return { type, coordinates };+}++/**+ * A polygon from the ring a drawing tool hands over, which spells the closing point out — GeoJSON+ * rings end where they began, and the label does not (see the module note).+ */+export function polygonFromRing(ring: [number, number][]): GeoShapePolygon {+ const [ firstLng, firstLat ] = ring[0] ?? [];+ const [ lastLng, lastLat ] = ring[ring.length - 1] ?? [];+ const closed = ring.length > 1 && firstLng === lastLng && firstLat === lastLat;+ return { type: "polygon", coordinates: closed ? ring.slice(0, -1) : ring };+}++/** The ring as GeoJSON wants it back: ended where it began. */+export function closeRing(coordinates: [number, number][]): [number, number][] {+ return [ ...coordinates, coordinates[0] ];+}++function isPointKind(type: string): type is keyof typeof MINIMUM_POINTS {+ return Object.hasOwn(MINIMUM_POINTS, type);+}++function serializePoints(coordinates: [number, number][]): string {+ return coordinates+ .map(([ lng, lat ]) => `${round(lat)},${round(lng)}`)+ .join(" ");+}++function parsePoints(value: string): [number, number][] | null {const coordinates: [number, number][] = [];- for (const point of value.slice("line:".length).trim().split(/\s+/)) {+ for (const point of value.trim().split(/\s+/)) {const parts = point.split(",");if (parts.length !== 2) {return null;@@ -69,11 +113,7 @@ export function parseGeoShape(value: string): GeoShape | null {coordinates.push([ lng, lat ]);}- if (coordinates.length < 2) {- return null;- }-- return { type: "line", coordinates };+ return coordinates;}/** A coordinate at the precision the label keeps, without `toFixed`'s trailing zeros. */